diff --git a/.github/workflows/run-tests.yml b/.github/workflows/run-tests.yml index 1b43726a..8aa5ace1 100644 --- a/.github/workflows/run-tests.yml +++ b/.github/workflows/run-tests.yml @@ -9,6 +9,7 @@ on: jobs: run-platform-tests: runs-on: ${{ matrix.os }} + timeout-minutes: 60 strategy: matrix: os: [ubuntu-latest, windows-latest, macOS-latest] @@ -26,4 +27,15 @@ jobs: - name: Build run: dotnet build src/Lumina.sln --no-restore -p:SixLaborsLicenseEnforceBuild=true - name: Run tests - run: dotnet test src/Lumina.sln --no-build --verbosity normal + # blame-hang terminates a test that blocks for 10 minutes and dumps the hang stack, + # turning the recurring 'stuck job' into a failing job that names the culprit test + run: dotnet test src/Lumina.sln --no-build --verbosity normal --blame-hang --blame-hang-timeout 10m + - name: Upload hang diagnostics + if: failure() + uses: actions/upload-artifact@v4 + with: + name: test-hang-diagnostics-${{ matrix.os }} + path: | + **/TestResults/**/*.dmp + **/TestResults/**/*.log + if-no-files-found: ignore diff --git a/plugins/Lumina.Plugins.Calibre/Properties/AssemblyInfo.cs b/plugins/Lumina.Plugins.Calibre/Properties/AssemblyInfo.cs index c7bf9b3a..092349c5 100644 --- a/plugins/Lumina.Plugins.Calibre/Properties/AssemblyInfo.cs +++ b/plugins/Lumina.Plugins.Calibre/Properties/AssemblyInfo.cs @@ -1,4 +1,5 @@ using System.Runtime.CompilerServices; [assembly: InternalsVisibleTo("Lumina.Plugins.Calibre.UnitTests")] +[assembly: InternalsVisibleTo("Lumina.Plugins.Calibre.IntegrationTests")] [assembly: InternalsVisibleTo("Lumina.Plugins.Calibre.Fixtures")] diff --git a/plugins/Lumina.Plugins.Epub/Properties/AssemblyInfo.cs b/plugins/Lumina.Plugins.Epub/Properties/AssemblyInfo.cs index d1808970..895b727d 100644 --- a/plugins/Lumina.Plugins.Epub/Properties/AssemblyInfo.cs +++ b/plugins/Lumina.Plugins.Epub/Properties/AssemblyInfo.cs @@ -1,4 +1,5 @@ using System.Runtime.CompilerServices; [assembly: InternalsVisibleTo("Lumina.Plugins.Epub.UnitTests")] +[assembly: InternalsVisibleTo("Lumina.Plugins.Epub.IntegrationTests")] [assembly: InternalsVisibleTo("Lumina.Plugins.Epub.Fixtures")] diff --git a/plugins/Lumina.Plugins.Pdf/Properties/AssemblyInfo.cs b/plugins/Lumina.Plugins.Pdf/Properties/AssemblyInfo.cs index fdfba7b5..9a133f40 100644 --- a/plugins/Lumina.Plugins.Pdf/Properties/AssemblyInfo.cs +++ b/plugins/Lumina.Plugins.Pdf/Properties/AssemblyInfo.cs @@ -1,4 +1,5 @@ using System.Runtime.CompilerServices; [assembly: InternalsVisibleTo("Lumina.Plugins.Pdf.UnitTests")] +[assembly: InternalsVisibleTo("Lumina.Plugins.Pdf.IntegrationTests")] [assembly: InternalsVisibleTo("Lumina.Plugins.Pdf.Fixtures")] diff --git a/src/Lumina.DataAccess/Properties/AssemblyInfo.cs b/src/Lumina.DataAccess/Properties/AssemblyInfo.cs index d518cb91..ae54e839 100644 --- a/src/Lumina.DataAccess/Properties/AssemblyInfo.cs +++ b/src/Lumina.DataAccess/Properties/AssemblyInfo.cs @@ -17,4 +17,5 @@ using System.Runtime.InteropServices; [assembly: Guid("F50EC9A6-696C-461E-B2F1-95B70BFE3DBF")] [assembly: InternalsVisibleTo("Lumina.DataAccess.UnitTests")] +[assembly: InternalsVisibleTo("Lumina.DataAccess.IntegrationTests")] [assembly: InternalsVisibleTo("DynamicProxyGenAssembly2")] diff --git a/src/Lumina.Domain/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Services/FileProviderService.cs b/src/Lumina.Domain/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Services/FileProviderService.cs index 859295c3..84eb7e05 100644 --- a/src/Lumina.Domain/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Services/FileProviderService.cs +++ b/src/Lumina.Domain/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Services/FileProviderService.cs @@ -100,7 +100,7 @@ internal class FileProviderService : IFileProviderService // check if the user has access permissions to the provided path if (!_fileSystemPermissionsService.CanAccessPath(path, FileAccessMode.ReadContents)) return Errors.Permission.UnauthorizedAccess; - return File.ReadAllBytes(path.Path); + return _fileSystem.File.ReadAllBytes(path.Path); } /// diff --git a/src/Lumina.Infrastructure/Properties/AssemblyInfo.cs b/src/Lumina.Infrastructure/Properties/AssemblyInfo.cs index 10decd96..a78bbb52 100644 --- a/src/Lumina.Infrastructure/Properties/AssemblyInfo.cs +++ b/src/Lumina.Infrastructure/Properties/AssemblyInfo.cs @@ -18,4 +18,5 @@ using System.Runtime.InteropServices; [assembly: InternalsVisibleTo("Lumina.Infrastructure.UnitTests")] [assembly: InternalsVisibleTo("Lumina.Infrastructure.Fixtures")] +[assembly: InternalsVisibleTo("Lumina.Infrastructure.IntegrationTests")] [assembly: InternalsVisibleTo("DynamicProxyGenAssembly2")] diff --git a/src/Lumina.sln b/src/Lumina.sln index a06abc9f..8d9e26fe 100644 --- a/src/Lumina.sln +++ b/src/Lumina.sln @@ -271,6 +271,16 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Lumina.Plugins.Epub.Fixture EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Lumina.Plugins.Pdf.Fixtures", "..\tests\Common\Lumina.Plugins.Pdf.Fixtures\Lumina.Plugins.Pdf.Fixtures.csproj", "{15BB9243-9CF1-4B7C-B150-678F7F6BA3C2}" EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Lumina.DataAccess.IntegrationTests", "..\tests\IntegrationTests\Lumina.DataAccess.IntegrationTests\Lumina.DataAccess.IntegrationTests.csproj", "{AA870A8B-70FA-47F6-8357-70A2E1D25A15}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Lumina.Infrastructure.IntegrationTests", "..\tests\IntegrationTests\Lumina.Infrastructure.IntegrationTests\Lumina.Infrastructure.IntegrationTests.csproj", "{1644B890-B93E-4137-A98A-CC6DD74BE9EA}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Lumina.Plugins.Epub.IntegrationTests", "..\tests\IntegrationTests\Lumina.Plugins.Epub.IntegrationTests\Lumina.Plugins.Epub.IntegrationTests.csproj", "{97F5171D-DF9B-4C2B-B791-1F75A364ED05}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Lumina.Plugins.Pdf.IntegrationTests", "..\tests\IntegrationTests\Lumina.Plugins.Pdf.IntegrationTests\Lumina.Plugins.Pdf.IntegrationTests.csproj", "{1452D457-8C24-4BB5-A45E-794F3240212D}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Lumina.Plugins.Calibre.IntegrationTests", "..\tests\IntegrationTests\Lumina.Plugins.Calibre.IntegrationTests\Lumina.Plugins.Calibre.IntegrationTests.csproj", "{319846E2-F97B-4547-9134-59B5D7BB9E2D}" +EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU @@ -805,6 +815,66 @@ Global {15BB9243-9CF1-4B7C-B150-678F7F6BA3C2}.Release|x64.Build.0 = Release|Any CPU {15BB9243-9CF1-4B7C-B150-678F7F6BA3C2}.Release|x86.ActiveCfg = Release|Any CPU {15BB9243-9CF1-4B7C-B150-678F7F6BA3C2}.Release|x86.Build.0 = Release|Any CPU + {AA870A8B-70FA-47F6-8357-70A2E1D25A15}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {AA870A8B-70FA-47F6-8357-70A2E1D25A15}.Debug|Any CPU.Build.0 = Debug|Any CPU + {AA870A8B-70FA-47F6-8357-70A2E1D25A15}.Debug|x64.ActiveCfg = Debug|Any CPU + {AA870A8B-70FA-47F6-8357-70A2E1D25A15}.Debug|x64.Build.0 = Debug|Any CPU + {AA870A8B-70FA-47F6-8357-70A2E1D25A15}.Debug|x86.ActiveCfg = Debug|Any CPU + {AA870A8B-70FA-47F6-8357-70A2E1D25A15}.Debug|x86.Build.0 = Debug|Any CPU + {AA870A8B-70FA-47F6-8357-70A2E1D25A15}.Release|Any CPU.ActiveCfg = Release|Any CPU + {AA870A8B-70FA-47F6-8357-70A2E1D25A15}.Release|Any CPU.Build.0 = Release|Any CPU + {AA870A8B-70FA-47F6-8357-70A2E1D25A15}.Release|x64.ActiveCfg = Release|Any CPU + {AA870A8B-70FA-47F6-8357-70A2E1D25A15}.Release|x64.Build.0 = Release|Any CPU + {AA870A8B-70FA-47F6-8357-70A2E1D25A15}.Release|x86.ActiveCfg = Release|Any CPU + {AA870A8B-70FA-47F6-8357-70A2E1D25A15}.Release|x86.Build.0 = Release|Any CPU + {1644B890-B93E-4137-A98A-CC6DD74BE9EA}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {1644B890-B93E-4137-A98A-CC6DD74BE9EA}.Debug|Any CPU.Build.0 = Debug|Any CPU + {1644B890-B93E-4137-A98A-CC6DD74BE9EA}.Debug|x64.ActiveCfg = Debug|Any CPU + {1644B890-B93E-4137-A98A-CC6DD74BE9EA}.Debug|x64.Build.0 = Debug|Any CPU + {1644B890-B93E-4137-A98A-CC6DD74BE9EA}.Debug|x86.ActiveCfg = Debug|Any CPU + {1644B890-B93E-4137-A98A-CC6DD74BE9EA}.Debug|x86.Build.0 = Debug|Any CPU + {1644B890-B93E-4137-A98A-CC6DD74BE9EA}.Release|Any CPU.ActiveCfg = Release|Any CPU + {1644B890-B93E-4137-A98A-CC6DD74BE9EA}.Release|Any CPU.Build.0 = Release|Any CPU + {1644B890-B93E-4137-A98A-CC6DD74BE9EA}.Release|x64.ActiveCfg = Release|Any CPU + {1644B890-B93E-4137-A98A-CC6DD74BE9EA}.Release|x64.Build.0 = Release|Any CPU + {1644B890-B93E-4137-A98A-CC6DD74BE9EA}.Release|x86.ActiveCfg = Release|Any CPU + {1644B890-B93E-4137-A98A-CC6DD74BE9EA}.Release|x86.Build.0 = Release|Any CPU + {97F5171D-DF9B-4C2B-B791-1F75A364ED05}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {97F5171D-DF9B-4C2B-B791-1F75A364ED05}.Debug|Any CPU.Build.0 = Debug|Any CPU + {97F5171D-DF9B-4C2B-B791-1F75A364ED05}.Debug|x64.ActiveCfg = Debug|Any CPU + {97F5171D-DF9B-4C2B-B791-1F75A364ED05}.Debug|x64.Build.0 = Debug|Any CPU + {97F5171D-DF9B-4C2B-B791-1F75A364ED05}.Debug|x86.ActiveCfg = Debug|Any CPU + {97F5171D-DF9B-4C2B-B791-1F75A364ED05}.Debug|x86.Build.0 = Debug|Any CPU + {97F5171D-DF9B-4C2B-B791-1F75A364ED05}.Release|Any CPU.ActiveCfg = Release|Any CPU + {97F5171D-DF9B-4C2B-B791-1F75A364ED05}.Release|Any CPU.Build.0 = Release|Any CPU + {97F5171D-DF9B-4C2B-B791-1F75A364ED05}.Release|x64.ActiveCfg = Release|Any CPU + {97F5171D-DF9B-4C2B-B791-1F75A364ED05}.Release|x64.Build.0 = Release|Any CPU + {97F5171D-DF9B-4C2B-B791-1F75A364ED05}.Release|x86.ActiveCfg = Release|Any CPU + {97F5171D-DF9B-4C2B-B791-1F75A364ED05}.Release|x86.Build.0 = Release|Any CPU + {1452D457-8C24-4BB5-A45E-794F3240212D}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {1452D457-8C24-4BB5-A45E-794F3240212D}.Debug|Any CPU.Build.0 = Debug|Any CPU + {1452D457-8C24-4BB5-A45E-794F3240212D}.Debug|x64.ActiveCfg = Debug|Any CPU + {1452D457-8C24-4BB5-A45E-794F3240212D}.Debug|x64.Build.0 = Debug|Any CPU + {1452D457-8C24-4BB5-A45E-794F3240212D}.Debug|x86.ActiveCfg = Debug|Any CPU + {1452D457-8C24-4BB5-A45E-794F3240212D}.Debug|x86.Build.0 = Debug|Any CPU + {1452D457-8C24-4BB5-A45E-794F3240212D}.Release|Any CPU.ActiveCfg = Release|Any CPU + {1452D457-8C24-4BB5-A45E-794F3240212D}.Release|Any CPU.Build.0 = Release|Any CPU + {1452D457-8C24-4BB5-A45E-794F3240212D}.Release|x64.ActiveCfg = Release|Any CPU + {1452D457-8C24-4BB5-A45E-794F3240212D}.Release|x64.Build.0 = Release|Any CPU + {1452D457-8C24-4BB5-A45E-794F3240212D}.Release|x86.ActiveCfg = Release|Any CPU + {1452D457-8C24-4BB5-A45E-794F3240212D}.Release|x86.Build.0 = Release|Any CPU + {319846E2-F97B-4547-9134-59B5D7BB9E2D}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {319846E2-F97B-4547-9134-59B5D7BB9E2D}.Debug|Any CPU.Build.0 = Debug|Any CPU + {319846E2-F97B-4547-9134-59B5D7BB9E2D}.Debug|x64.ActiveCfg = Debug|Any CPU + {319846E2-F97B-4547-9134-59B5D7BB9E2D}.Debug|x64.Build.0 = Debug|Any CPU + {319846E2-F97B-4547-9134-59B5D7BB9E2D}.Debug|x86.ActiveCfg = Debug|Any CPU + {319846E2-F97B-4547-9134-59B5D7BB9E2D}.Debug|x86.Build.0 = Debug|Any CPU + {319846E2-F97B-4547-9134-59B5D7BB9E2D}.Release|Any CPU.ActiveCfg = Release|Any CPU + {319846E2-F97B-4547-9134-59B5D7BB9E2D}.Release|Any CPU.Build.0 = Release|Any CPU + {319846E2-F97B-4547-9134-59B5D7BB9E2D}.Release|x64.ActiveCfg = Release|Any CPU + {319846E2-F97B-4547-9134-59B5D7BB9E2D}.Release|x64.Build.0 = Release|Any CPU + {319846E2-F97B-4547-9134-59B5D7BB9E2D}.Release|x86.ActiveCfg = Release|Any CPU + {319846E2-F97B-4547-9134-59B5D7BB9E2D}.Release|x86.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE @@ -879,6 +949,11 @@ Global {B97069B6-71A8-4D42-87E7-178396E4749F} = {53B1231B-37F5-44BA-80D5-DBA979775F5C} {334D9DE2-AE31-4C2C-9B8B-F3E1A335C11F} = {7E8A2D6B-3F4C-4E5F-9A6B-1C2D3E4F5A6B} {15BB9243-9CF1-4B7C-B150-678F7F6BA3C2} = {7E8A2D6B-3F4C-4E5F-9A6B-1C2D3E4F5A6B} + {AA870A8B-70FA-47F6-8357-70A2E1D25A15} = {3F057926-562F-4EF4-BFC0-EE62372D4551} + {1644B890-B93E-4137-A98A-CC6DD74BE9EA} = {3F057926-562F-4EF4-BFC0-EE62372D4551} + {97F5171D-DF9B-4C2B-B791-1F75A364ED05} = {3F057926-562F-4EF4-BFC0-EE62372D4551} + {1452D457-8C24-4BB5-A45E-794F3240212D} = {3F057926-562F-4EF4-BFC0-EE62372D4551} + {319846E2-F97B-4547-9134-59B5D7BB9E2D} = {3F057926-562F-4EF4-BFC0-EE62372D4551} EndGlobalSection GlobalSection(ExtensibilityGlobals) = postSolution SolutionGuid = {4A55A28E-C657-4A0B-95EA-2931AE66004E} diff --git a/tests/Common/Lumina.Domain.Fixtures/Core/BoundedContexts/UserManagementBoundedContext/UserSettingsAggregate/ValueObjects/UserSettingsIdFixture.cs b/tests/Common/Lumina.Domain.Fixtures/Core/BoundedContexts/UserManagementBoundedContext/UserSettingsAggregate/ValueObjects/UserSettingsIdFixture.cs new file mode 100644 index 00000000..a1f52ae8 --- /dev/null +++ b/tests/Common/Lumina.Domain.Fixtures/Core/BoundedContexts/UserManagementBoundedContext/UserSettingsAggregate/ValueObjects/UserSettingsIdFixture.cs @@ -0,0 +1,36 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Domain.Core.BoundedContexts.UserManagementBoundedContext.UserSettingsAggregate.ValueObjects; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Domain.Fixtures.Core.BoundedContexts.UserManagementBoundedContext.UserSettingsAggregate.ValueObjects; + +/// +/// Fixture class for the value object. +/// +[ExcludeFromCodeCoverage] +public class UserSettingsIdFixture +{ + /// + /// Creates a random valid . + /// + /// Optional. The raw value of the user settings Id. + /// The created . + public UserSettingsId Create(Guid? value = null) + { + return UserSettingsId.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/WrittenContentLibraryBoundedContext/BookLibraryAggregate/BookFixture.cs b/tests/Common/Lumina.Domain.Fixtures/Core/BoundedContexts/WrittenContentLibraryBoundedContext/BookLibraryAggregate/BookFixture.cs index 5b4a81cf..3b9873ed 100644 --- a/tests/Common/Lumina.Domain.Fixtures/Core/BoundedContexts/WrittenContentLibraryBoundedContext/BookLibraryAggregate/BookFixture.cs +++ b/tests/Common/Lumina.Domain.Fixtures/Core/BoundedContexts/WrittenContentLibraryBoundedContext/BookLibraryAggregate/BookFixture.cs @@ -84,8 +84,8 @@ public class BookFixture _fixture.Register(() => { - int originalYear = _fixture.Create>().First(year => year >= 1900 && year <= 2025); - int reReleaseYear = _fixture.Create>().First(year => year >= originalYear && year <= 2025); + int originalYear = Random.Shared.Next(1900, 2026); + int reReleaseYear = Random.Shared.Next(originalYear, 2026); return ReleaseInfo.Create( Optional.Some(DateOnly.FromDateTime(new DateTime(originalYear, 1, 1))), diff --git a/tests/Common/Lumina.Domain.Fixtures/Core/BoundedContexts/WrittenContentLibraryBoundedContext/ExternalIdentifiers/LibraryManagementBoundedContext/LibraryAggregate/LibraryIdFixture.cs b/tests/Common/Lumina.Domain.Fixtures/Core/BoundedContexts/WrittenContentLibraryBoundedContext/ExternalIdentifiers/LibraryManagementBoundedContext/LibraryAggregate/LibraryIdFixture.cs new file mode 100644 index 00000000..82e5d030 --- /dev/null +++ b/tests/Common/Lumina.Domain.Fixtures/Core/BoundedContexts/WrittenContentLibraryBoundedContext/ExternalIdentifiers/LibraryManagementBoundedContext/LibraryAggregate/LibraryIdFixture.cs @@ -0,0 +1,36 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Domain.Core.BoundedContexts.WrittenContentLibraryBoundedContext.ExternalIdentifiers.LibraryManagementBoundedContext.LibraryAggregate; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Domain.Fixtures.Core.BoundedContexts.WrittenContentLibraryBoundedContext.ExternalIdentifiers.LibraryManagementBoundedContext.LibraryAggregate; + +/// +/// 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.Infrastructure.Fixtures/Properties/AssemblyInfo.cs b/tests/Common/Lumina.Infrastructure.Fixtures/Properties/AssemblyInfo.cs index 7903ac6a..e7e3c2c1 100644 --- a/tests/Common/Lumina.Infrastructure.Fixtures/Properties/AssemblyInfo.cs +++ b/tests/Common/Lumina.Infrastructure.Fixtures/Properties/AssemblyInfo.cs @@ -17,4 +17,5 @@ using System.Runtime.InteropServices; [assembly: Guid("A1B2C3D4-0004-4A5B-9C0D-444444444444")] [assembly: InternalsVisibleTo("Lumina.Infrastructure.UnitTests")] +[assembly: InternalsVisibleTo("Lumina.Infrastructure.IntegrationTests")] [assembly: InternalsVisibleTo("DynamicProxyGenAssembly2")] diff --git a/tests/Common/Lumina.Plugins.Calibre.Fixtures/Properties/AssemblyInfo.cs b/tests/Common/Lumina.Plugins.Calibre.Fixtures/Properties/AssemblyInfo.cs index 59eb394e..98b6ab94 100644 --- a/tests/Common/Lumina.Plugins.Calibre.Fixtures/Properties/AssemblyInfo.cs +++ b/tests/Common/Lumina.Plugins.Calibre.Fixtures/Properties/AssemblyInfo.cs @@ -17,4 +17,5 @@ using System.Runtime.InteropServices; [assembly: Guid("B6F9E5D2-3C4D-5E6F-9A7B-8C9D0E1F2A31")] [assembly: InternalsVisibleTo("Lumina.Plugins.Calibre.UnitTests")] +[assembly: InternalsVisibleTo("Lumina.Plugins.Calibre.IntegrationTests")] [assembly: InternalsVisibleTo("DynamicProxyGenAssembly2")] diff --git a/tests/Common/Lumina.Plugins.Epub.Fixtures/Properties/AssemblyInfo.cs b/tests/Common/Lumina.Plugins.Epub.Fixtures/Properties/AssemblyInfo.cs index 8ac590a6..81429e36 100644 --- a/tests/Common/Lumina.Plugins.Epub.Fixtures/Properties/AssemblyInfo.cs +++ b/tests/Common/Lumina.Plugins.Epub.Fixtures/Properties/AssemblyInfo.cs @@ -17,4 +17,5 @@ using System.Runtime.InteropServices; [assembly: Guid("A3C1E9B4-5D7F-4E2A-9B6C-8D1F0E3A2B41")] [assembly: InternalsVisibleTo("Lumina.Plugins.Epub.UnitTests")] +[assembly: InternalsVisibleTo("Lumina.Plugins.Epub.IntegrationTests")] [assembly: InternalsVisibleTo("DynamicProxyGenAssembly2")] diff --git a/tests/Common/Lumina.Plugins.Pdf.Fixtures/Properties/AssemblyInfo.cs b/tests/Common/Lumina.Plugins.Pdf.Fixtures/Properties/AssemblyInfo.cs index bff36898..e18b4e00 100644 --- a/tests/Common/Lumina.Plugins.Pdf.Fixtures/Properties/AssemblyInfo.cs +++ b/tests/Common/Lumina.Plugins.Pdf.Fixtures/Properties/AssemblyInfo.cs @@ -17,4 +17,5 @@ using System.Runtime.InteropServices; [assembly: Guid("7E2A4C8D-9B1F-4E6A-8D3C-2F5A0B9E7C41")] [assembly: InternalsVisibleTo("Lumina.Plugins.Pdf.UnitTests")] +[assembly: InternalsVisibleTo("Lumina.Plugins.Pdf.IntegrationTests")] [assembly: InternalsVisibleTo("DynamicProxyGenAssembly2")] diff --git a/tests/IntegrationTests/Lumina.DataAccess.IntegrationTests/Core/Repositories/Books/BookRepositoryTests.cs b/tests/IntegrationTests/Lumina.DataAccess.IntegrationTests/Core/Repositories/Books/BookRepositoryTests.cs new file mode 100644 index 00000000..0d408200 --- /dev/null +++ b/tests/IntegrationTests/Lumina.DataAccess.IntegrationTests/Core/Repositories/Books/BookRepositoryTests.cs @@ -0,0 +1,138 @@ +#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; +using Lumina.DataAccess.Core.UoW; +using Lumina.Domain.Common.Primitives; +using Lumina.Domain.SharedKernel.Common.Enums.BookLibrary; +using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; +using Microsoft.Data.Sqlite; +using Microsoft.EntityFrameworkCore; +using System; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.DataAccess.IntegrationTests.Core.Repositories.Books; + +/// +/// Contains integration tests for the class, exercising it against a real SQLite database. +/// +[ExcludeFromCodeCoverage] +public class BookRepositoryTests +{ + private readonly BookEntityFixture _bookEntityFixture = new(); + private readonly BookArtworkEntityFixture _bookArtworkEntityFixture = new(); + + [Fact] + public async Task ResetEnrichmentStateForPathsAsync_WhenCalled_ShouldResetTheMetadataAndArtworkStatusesForThePaths() + { + // Arrange + // The reset methods use ExecuteUpdateAsync, which is not supported by the in-memory provider, so a real SQLite database is used. + using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-bookrepo-reset-{Guid.NewGuid()};Mode=Memory;Cache=Shared"); + anchorConnection.Open(); + LuminaDbContext context = new(new DbContextOptionsBuilder().UseSqlite(anchorConnection.ConnectionString).Options); + context.Database.EnsureCreated(); + BookRepository sut = new(context); + + Guid libraryId = Guid.NewGuid(); + BookEntity changedBook = _bookEntityFixture.Create(); + changedBook.LibraryId = libraryId; + changedBook.Path = "/books/changed.epub"; + changedBook.MetadataStatus = MetadataStatus.Enriched; + changedBook.BookArtwork = [_bookArtworkEntityFixture.Create(bookId: changedBook.Id, artworkType: ArtworkType.Cover, ordinal: 0, status: ArtworkStatus.Enriched)]; + BookEntity unchangedBook = _bookEntityFixture.Create(); + unchangedBook.LibraryId = libraryId; + unchangedBook.Path = "/books/unchanged.epub"; + unchangedBook.MetadataStatus = MetadataStatus.Enriched; + unchangedBook.BookArtwork = [_bookArtworkEntityFixture.Create(bookId: unchangedBook.Id, artworkType: ArtworkType.Cover, ordinal: 0, status: ArtworkStatus.Enriched)]; + context.Books.AddRange(changedBook, unchangedBook); + await context.SaveChangesAsync(); + + // Act + Result result = await sut.ResetEnrichmentStateForPathsAsync(libraryId, ["/books/changed.epub"], CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal(Result.Updated, result.Value); + BookEntity? resetBook = await context.Books.AsNoTracking().Include(book => book.BookArtwork).FirstOrDefaultAsync(book => book.Id == changedBook.Id); + Assert.NotNull(resetBook); + Assert.Equal(MetadataStatus.Pending, resetBook!.MetadataStatus); + Assert.Equal(ArtworkStatus.Pending, resetBook.BookArtwork.Single().Status); + BookEntity? keptBook = await context.Books.AsNoTracking().FirstOrDefaultAsync(book => book.Id == unchangedBook.Id); + Assert.NotNull(keptBook); + Assert.Equal(MetadataStatus.Enriched, keptBook!.MetadataStatus); + } + + [Fact] + public async Task ResetMetadataStatusForLibraryAsync_WhenCalled_ShouldResetTheMetadataStatusOfAllBooksOfTheLibrary() + { + // Arrange + // The reset methods use ExecuteUpdateAsync, which is not supported by the in-memory provider, so a real SQLite database is used. + using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-bookrepo-reset-{Guid.NewGuid()};Mode=Memory;Cache=Shared"); + anchorConnection.Open(); + LuminaDbContext context = new(new DbContextOptionsBuilder().UseSqlite(anchorConnection.ConnectionString).Options); + context.Database.EnsureCreated(); + BookRepository sut = new(context); + + Guid libraryId = Guid.NewGuid(); + BookEntity enrichedBook = _bookEntityFixture.Create(); + enrichedBook.LibraryId = libraryId; + enrichedBook.MetadataStatus = MetadataStatus.Enriched; + BookEntity bookOfAnotherLibrary = _bookEntityFixture.Create(); + bookOfAnotherLibrary.LibraryId = Guid.NewGuid(); + bookOfAnotherLibrary.MetadataStatus = MetadataStatus.Enriched; + context.Books.AddRange(enrichedBook, bookOfAnotherLibrary); + await context.SaveChangesAsync(); + + // Act + Result result = await sut.ResetMetadataStatusForLibraryAsync(libraryId, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal(Result.Updated, result.Value); + BookEntity? resetBook = await context.Books.AsNoTracking().FirstOrDefaultAsync(book => book.Id == enrichedBook.Id); + Assert.NotNull(resetBook); + Assert.Equal(MetadataStatus.Pending, resetBook!.MetadataStatus); + BookEntity? keptBook = await context.Books.AsNoTracking().FirstOrDefaultAsync(book => book.Id == bookOfAnotherLibrary.Id); + Assert.NotNull(keptBook); + Assert.Equal(MetadataStatus.Enriched, keptBook!.MetadataStatus); + } + + [Fact] + public async Task ResetArtworkStatusForLibraryAsync_WhenCalled_ShouldResetTheArtworkStatusOfTheLibraryBooks() + { + // Arrange + // The reset methods use ExecuteUpdateAsync, which is not supported by the in-memory provider, so a real SQLite database is used. + using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-bookrepo-reset-{Guid.NewGuid()};Mode=Memory;Cache=Shared"); + anchorConnection.Open(); + LuminaDbContext context = new(new DbContextOptionsBuilder().UseSqlite(anchorConnection.ConnectionString).Options); + context.Database.EnsureCreated(); + BookRepository sut = new(context); + + Guid libraryId = Guid.NewGuid(); + BookEntity book = _bookEntityFixture.Create(); + book.LibraryId = libraryId; + book.BookArtwork = [_bookArtworkEntityFixture.Create(bookId: book.Id, artworkType: ArtworkType.Cover, ordinal: 0, status: ArtworkStatus.Enriched)]; + BookEntity bookOfAnotherLibrary = _bookEntityFixture.Create(); + bookOfAnotherLibrary.LibraryId = Guid.NewGuid(); + bookOfAnotherLibrary.BookArtwork = [_bookArtworkEntityFixture.Create(bookId: bookOfAnotherLibrary.Id, artworkType: ArtworkType.Cover, ordinal: 0, status: ArtworkStatus.Enriched)]; + context.Books.AddRange(book, bookOfAnotherLibrary); + await context.SaveChangesAsync(); + + // Act + Result result = await sut.ResetArtworkStatusForLibraryAsync(libraryId, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal(Result.Updated, result.Value); + BookArtworkEntity? resetArtwork = await context.Set().AsNoTracking().FirstOrDefaultAsync(artwork => artwork.BookId == book.Id); + Assert.NotNull(resetArtwork); + Assert.Equal(ArtworkStatus.Pending, resetArtwork!.Status); + BookArtworkEntity? keptArtwork = await context.Set().AsNoTracking().FirstOrDefaultAsync(artwork => artwork.BookId == bookOfAnotherLibrary.Id); + Assert.NotNull(keptArtwork); + Assert.Equal(ArtworkStatus.Enriched, keptArtwork!.Status); + } +} diff --git a/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Repositories/Libraries/DirectoryScanFingerprintRepositoryTests.cs b/tests/IntegrationTests/Lumina.DataAccess.IntegrationTests/Core/Repositories/Libraries/DirectoryScanFingerprintRepositoryTests.cs similarity index 97% rename from tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Repositories/Libraries/DirectoryScanFingerprintRepositoryTests.cs rename to tests/IntegrationTests/Lumina.DataAccess.IntegrationTests/Core/Repositories/Libraries/DirectoryScanFingerprintRepositoryTests.cs index ca8aeb78..564a4231 100644 --- a/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Repositories/Libraries/DirectoryScanFingerprintRepositoryTests.cs +++ b/tests/IntegrationTests/Lumina.DataAccess.IntegrationTests/Core/Repositories/Libraries/DirectoryScanFingerprintRepositoryTests.cs @@ -17,10 +17,10 @@ using System.Threading; using System.Threading.Tasks; #endregion -namespace Lumina.DataAccess.UnitTests.Core.Repositories.Libraries; +namespace Lumina.DataAccess.IntegrationTests.Core.Repositories.Libraries; /// -/// Contains unit tests for the class. +/// Contains integration 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 diff --git a/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Repositories/Libraries/LibraryScanSnapshotRepositoryTests.cs b/tests/IntegrationTests/Lumina.DataAccess.IntegrationTests/Core/Repositories/Libraries/LibraryScanSnapshotRepositoryTests.cs similarity index 97% rename from tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Repositories/Libraries/LibraryScanSnapshotRepositoryTests.cs rename to tests/IntegrationTests/Lumina.DataAccess.IntegrationTests/Core/Repositories/Libraries/LibraryScanSnapshotRepositoryTests.cs index e3212529..86f9c283 100644 --- a/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Repositories/Libraries/LibraryScanSnapshotRepositoryTests.cs +++ b/tests/IntegrationTests/Lumina.DataAccess.IntegrationTests/Core/Repositories/Libraries/LibraryScanSnapshotRepositoryTests.cs @@ -17,10 +17,10 @@ using System.Threading; using System.Threading.Tasks; #endregion -namespace Lumina.DataAccess.UnitTests.Core.Repositories.Libraries; +namespace Lumina.DataAccess.IntegrationTests.Core.Repositories.Libraries; /// -/// Contains unit tests for the class. +/// Contains integration 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 @@ -174,7 +174,7 @@ public class LibraryScanSnapshotRepositoryTests : IDisposable Assert.False(result.IsFailure); Assert.Equal(Result.Updated, result.Value); - // audit entries: deleted, new and modified items + // Audit entries: deleted, new and modified items. List scanResults = await _context.LibraryScanResults.AsNoTracking() .Where(scanResult => scanResult.LibraryScanId == scanId) .ToListAsync(); @@ -184,7 +184,7 @@ public class LibraryScanSnapshotRepositoryTests : IDisposable 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 + // 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(); @@ -194,7 +194,7 @@ public class LibraryScanSnapshotRepositoryTests : IDisposable 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 + // The staging results of the scan have been cleared. Assert.False(await _context.LibraryScanStagingResults.AsNoTracking().AnyAsync(staging => staging.LibraryScanId == scanId)); } diff --git a/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Repositories/Libraries/LibraryScanStagingResultsRepositoryTests.cs b/tests/IntegrationTests/Lumina.DataAccess.IntegrationTests/Core/Repositories/Libraries/LibraryScanStagingResultsRepositoryTests.cs similarity index 87% rename from tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Repositories/Libraries/LibraryScanStagingResultsRepositoryTests.cs rename to tests/IntegrationTests/Lumina.DataAccess.IntegrationTests/Core/Repositories/Libraries/LibraryScanStagingResultsRepositoryTests.cs index 1fe8bf95..9fdad82a 100644 --- a/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Repositories/Libraries/LibraryScanStagingResultsRepositoryTests.cs +++ b/tests/IntegrationTests/Lumina.DataAccess.IntegrationTests/Core/Repositories/Libraries/LibraryScanStagingResultsRepositoryTests.cs @@ -19,10 +19,10 @@ using System.Threading; using System.Threading.Tasks; #endregion -namespace Lumina.DataAccess.UnitTests.Core.Repositories.Libraries; +namespace Lumina.DataAccess.IntegrationTests.Core.Repositories.Libraries; /// -/// Contains unit tests for the class. +/// Contains integration 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 @@ -143,7 +143,7 @@ public class LibraryScanStagingResultsRepositoryTests : IDisposable { // 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 + // 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(); @@ -225,6 +225,43 @@ public class LibraryScanStagingResultsRepositoryTests : IDisposable Assert.Equal("/books/b.epub", retrievedFile.Path); } + [Fact] + public async Task GetChangedPathsAsync_WhenStagingResultsChanged_ShouldReturnOnlyTheChangedPathsExcludingNewItems() + { + // Arrange + (_, _, Guid scanId) = await SeedScanGraphAsync(); + LibraryScanStagingResultsEntity changedStaging = _libraryScanStagingResultsEntityFixture.Create(libraryScanId: scanId, path: "/books/a.epub", needsRehash: true, isNew: false); + LibraryScanStagingResultsEntity newStaging = _libraryScanStagingResultsEntityFixture.Create(libraryScanId: scanId, path: "/books/b.epub", needsRehash: true, isNew: true); + LibraryScanStagingResultsEntity unchangedStaging = _libraryScanStagingResultsEntityFixture.Create(libraryScanId: scanId, path: "/books/c.epub", needsRehash: false, isNew: false); + _context.LibraryScanStagingResults.AddRange(changedStaging, newStaging, unchangedStaging); + await _context.SaveChangesAsync(); + + // Act + Result> result = await _sut.GetChangedPathsAsync(scanId, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + string changedPath = Assert.Single(result.Value); + Assert.Equal("/books/a.epub", changedPath); + } + + [Fact] + public async Task GetChangedPathsAsync_WhenNoStagingResultsAreChanged_ShouldReturnEmptyList() + { + // Arrange + (_, _, Guid scanId) = await SeedScanGraphAsync(); + LibraryScanStagingResultsEntity newStaging = _libraryScanStagingResultsEntityFixture.Create(libraryScanId: scanId, path: "/books/b.epub", needsRehash: true, isNew: true); + _context.LibraryScanStagingResults.Add(newStaging); + await _context.SaveChangesAsync(); + + // Act + Result> result = await _sut.GetChangedPathsAsync(scanId, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + Assert.Empty(result.Value); + } + [Fact] public async Task UpdateFileHashesAsync_WhenCalled_ShouldUpdateTheContentHashes() { diff --git a/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/UoW/LuminaDbContextTests.cs b/tests/IntegrationTests/Lumina.DataAccess.IntegrationTests/Core/UoW/LuminaDbContextTests.cs similarity index 97% rename from tests/UnitTests/Lumina.DataAccess.UnitTests/Core/UoW/LuminaDbContextTests.cs rename to tests/IntegrationTests/Lumina.DataAccess.IntegrationTests/Core/UoW/LuminaDbContextTests.cs index d1a882a1..ffec9027 100644 --- a/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/UoW/LuminaDbContextTests.cs +++ b/tests/IntegrationTests/Lumina.DataAccess.IntegrationTests/Core/UoW/LuminaDbContextTests.cs @@ -12,10 +12,10 @@ using System.Linq; using System.Threading.Tasks; #endregion -namespace Lumina.DataAccess.UnitTests.Core.UoW; +namespace Lumina.DataAccess.IntegrationTests.Core.UoW; /// -/// Contains unit tests for the class. +/// Contains integration tests for the class. /// [ExcludeFromCodeCoverage] public class LuminaDbContextTests : IDisposable diff --git a/tests/IntegrationTests/Lumina.DataAccess.IntegrationTests/Core/UoW/UnitOfWorkTests.cs b/tests/IntegrationTests/Lumina.DataAccess.IntegrationTests/Core/UoW/UnitOfWorkTests.cs new file mode 100644 index 00000000..c8adc54e --- /dev/null +++ b/tests/IntegrationTests/Lumina.DataAccess.IntegrationTests/Core/UoW/UnitOfWorkTests.cs @@ -0,0 +1,192 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Entities.Authorization; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.Authorization; +using Lumina.DataAccess.Core.UoW; +using Microsoft.Data.Sqlite; +using Microsoft.EntityFrameworkCore; +using System; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.DataAccess.IntegrationTests.Core.UoW; + +/// +/// Contains integration tests for the class, exercising its transaction handling against a real SQLite database. +/// +[ExcludeFromCodeCoverage] +public class UnitOfWorkTests +{ + private readonly RoleEntityFixture _roleEntityFixture = new(); + + [Fact] + public async Task BeginTransactionAsync_WhenCalled_ShouldBeginTransactionOnTheDatabase() + { + // Arrange + (SqliteConnection anchorConnection, LuminaDbContext dbContext) = CreateSqliteContext(); + using (anchorConnection) + { + using (dbContext) + { + UnitOfWork sut = new(dbContext); + + // Act + await sut.BeginTransactionAsync(CancellationToken.None); + + // Assert + Assert.NotNull(dbContext.Database.CurrentTransaction); + } + } + } + + [Fact] + public async Task CommitTransactionAsync_WhenTransactionIsActive_ShouldPersistChangesAndClearCurrentTransaction() + { + // Arrange + (SqliteConnection anchorConnection, LuminaDbContext dbContext) = CreateSqliteContext(); + using (anchorConnection) + { + using (dbContext) + { + UnitOfWork sut = new(dbContext); + RoleEntity role = _roleEntityFixture.Create(roleName: "Admin"); + + // Act + await sut.BeginTransactionAsync(CancellationToken.None); + dbContext.Roles.Add(role); + await sut.SaveChangesAsync(CancellationToken.None); + await sut.CommitTransactionAsync(CancellationToken.None); + + // Assert + Assert.Null(dbContext.Database.CurrentTransaction); + dbContext.ChangeTracker.Clear(); + RoleEntity? persistedRole = await dbContext.Roles.AsNoTracking().FirstOrDefaultAsync(existingRole => existingRole.Id == role.Id); + Assert.NotNull(persistedRole); + Assert.Equal(role.RoleName, persistedRole!.RoleName); + } + } + } + + [Fact] + public async Task CommitTransactionAsync_WhenNoTransactionIsActive_ShouldCompleteWithoutError() + { + // Arrange + (SqliteConnection anchorConnection, LuminaDbContext dbContext) = CreateSqliteContext(); + using (anchorConnection) + { + using (dbContext) + { + UnitOfWork sut = new(dbContext); + + // Act + await sut.CommitTransactionAsync(CancellationToken.None); + + // Assert + Assert.Null(dbContext.Database.CurrentTransaction); + } + } + } + + [Fact] + public async Task RollbackTransactionAsync_WhenTransactionIsActive_ShouldDiscardChangesAndClearCurrentTransaction() + { + // Arrange + (SqliteConnection anchorConnection, LuminaDbContext dbContext) = CreateSqliteContext(); + using (anchorConnection) + { + using (dbContext) + { + UnitOfWork sut = new(dbContext); + RoleEntity role = _roleEntityFixture.Create(roleName: "Admin"); + + // Act + await sut.BeginTransactionAsync(CancellationToken.None); + dbContext.Roles.Add(role); + await sut.SaveChangesAsync(CancellationToken.None); + await sut.RollbackTransactionAsync(CancellationToken.None); + + // Assert + Assert.Null(dbContext.Database.CurrentTransaction); + dbContext.ChangeTracker.Clear(); + RoleEntity? persistedRole = await dbContext.Roles.AsNoTracking().FirstOrDefaultAsync(existingRole => existingRole.Id == role.Id); + Assert.Null(persistedRole); + } + } + } + + [Fact] + public async Task RollbackTransactionAsync_WhenNoTransactionIsActive_ShouldCompleteWithoutError() + { + // Arrange + (SqliteConnection anchorConnection, LuminaDbContext dbContext) = CreateSqliteContext(); + using (anchorConnection) + { + using (dbContext) + { + UnitOfWork sut = new(dbContext); + + // Act + await sut.RollbackTransactionAsync(CancellationToken.None); + + // Assert + Assert.Null(dbContext.Database.CurrentTransaction); + } + } + } + + [Fact] + public async Task Dispose_WhenTransactionIsActive_ShouldDisposeTheTransactionAndTheDbContext() + { + // Arrange + (SqliteConnection anchorConnection, LuminaDbContext dbContext) = CreateSqliteContext(); + using (anchorConnection) + { + using (dbContext) + { + UnitOfWork sut = new(dbContext); + + // Act + await sut.BeginTransactionAsync(CancellationToken.None); + sut.Dispose(); + + // Assert + Assert.Throws(() => dbContext.Roles.Count()); + } + } + } + + [Fact] + public void Dispose_WhenNoTransactionIsActive_ShouldDisposeTheDbContext() + { + // Arrange + (SqliteConnection anchorConnection, LuminaDbContext dbContext) = CreateSqliteContext(); + using (anchorConnection) + { + using (dbContext) + { + UnitOfWork sut = new(dbContext); + + // Act + sut.Dispose(); + + // Assert + Assert.Throws(() => dbContext.Roles.Count()); + } + } + } + + /// + /// Creates a real SQLite in-memory context, kept alive by an anchor connection, because transactions are not supported by the in-memory provider. + /// + /// A tuple containing the anchor connection and the database context. + private static (SqliteConnection AnchorConnection, LuminaDbContext Context) CreateSqliteContext() + { + SqliteConnection anchorConnection = new($"Data Source=luminadataccess-unitofwork-tests-{Guid.NewGuid()};Mode=Memory;Cache=Shared"); + anchorConnection.Open(); + LuminaDbContext dbContext = new(new DbContextOptionsBuilder().UseSqlite(anchorConnection.ConnectionString).Options); + dbContext.Database.EnsureCreated(); + return (anchorConnection, dbContext); + } +} diff --git a/tests/IntegrationTests/Lumina.DataAccess.IntegrationTests/Lumina.DataAccess.IntegrationTests.csproj b/tests/IntegrationTests/Lumina.DataAccess.IntegrationTests/Lumina.DataAccess.IntegrationTests.csproj new file mode 100644 index 00000000..25d7a895 --- /dev/null +++ b/tests/IntegrationTests/Lumina.DataAccess.IntegrationTests/Lumina.DataAccess.IntegrationTests.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/IntegrationTests/Lumina.Infrastructure.IntegrationTests/Core/MediaLibrary/Management/Scanning/Jobs/WrittenContent/Books/BooksFileSystemDiscoveryJobTests.cs b/tests/IntegrationTests/Lumina.Infrastructure.IntegrationTests/Core/MediaLibrary/Management/Scanning/Jobs/WrittenContent/Books/BooksFileSystemDiscoveryJobTests.cs new file mode 100644 index 00000000..85de2f66 --- /dev/null +++ b/tests/IntegrationTests/Lumina.Infrastructure.IntegrationTests/Core/MediaLibrary/Management/Scanning/Jobs/WrittenContent/Books/BooksFileSystemDiscoveryJobTests.cs @@ -0,0 +1,354 @@ +#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.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.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.IntegrationTests.Core.MediaLibrary.Management.Scanning.Jobs.WrittenContent.Books; + +/// +/// Contains integration 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 DirectoryScanFingerprintEntityFixture _directoryScanFingerprintEntityFixture = 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_WhenFastSkipIsEnabledAndDirectoryDidNotChange_ShouldSkipTheDirectoryAndUpsertOnlyChangedFingerprints() + { + // Arrange + using TemporaryLibraryDirectory temporaryLibraryDirectory = new(); + string unchangedDirectoryPath = temporaryLibraryDirectory.CreateSubdirectory("unchanged"); + File.WriteAllText(Path.Combine(unchangedDirectoryPath, "skip.pdf"), "unchanged book content"); + string changedDirectoryPath = temporaryLibraryDirectory.CreateSubdirectory("changed"); + File.WriteAllText(Path.Combine(changedDirectoryPath, "book.pdf"), "changed book content"); + + DirectoryInfo unchangedDirectory = new(unchangedDirectoryPath); + string unchangedDirectoryFullName = unchangedDirectory.FullName; + DateTime unchangedDirectoryLastWriteTimeUtc = unchangedDirectory.LastWriteTimeUtc; + DirectoryInfo changedDirectory = new(changedDirectoryPath); + string changedDirectoryFullName = changedDirectory.FullName; + DirectoryInfo rootDirectory = new(temporaryLibraryDirectory.Path); + string rootDirectoryFullName = rootDirectory.FullName; + + LibraryEntity libraryEntity = _libraryEntityFixture.Create( + id: _libraryId.Value, + userId: _userId.Value, + title: "Test Library", + libraryType: LibraryType.Book, + contentLocations: [temporaryLibraryDirectory.Path], + shouldSkipUnchangedDirectoriesDuringScan: true); + _mockLibraryRepository.GetByIdAsync(_libraryId.Value, Arg.Any()) + .Returns(Result.From(libraryEntity)); + _mockDirectoryScanFingerprintRepository.GetMappedByLibraryIdAsync(_libraryId.Value, Arg.Any()) + .Returns(Result.From(new Dictionary + { + [unchangedDirectoryFullName] = _directoryScanFingerprintEntityFixture.Create( + libraryId: _libraryId.Value, + path: unchangedDirectoryFullName, + lastWriteTimeUtc: unchangedDirectoryLastWriteTimeUtc) + })); + _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); + await _mockStagingResultsRepository.Received(1).InsertRangeAsync( + Arg.Is>(entities => + entities.Count == 1 && Path.GetFileName(entities.Single().Path) == "book.pdf"), + Arg.Any()); + await _mockDirectoryScanFingerprintRepository.Received(1).UpsertRangeAsync( + Arg.Is>(entities => + entities.Count == 2 + && entities.Any(entity => entity.Path == rootDirectoryFullName) + && entities.Any(entity => entity.Path == changedDirectoryFullName) + && entities.All(entity => entity.Path != unchangedDirectoryFullName) + && entities.All(entity => entity.LibraryId == _libraryId.Value)), + Arg.Any()); + } + + [Fact] + public async Task ExecuteAsync_WhenLoadingDirectoryScanFingerprintsFails_ShouldMarkJobAsFailedAndPublishFailureEvent() + { + // Arrange + using TemporaryLibraryDirectory temporaryLibraryDirectory = new(); + LibraryEntity libraryEntity = _libraryEntityFixture.Create( + id: _libraryId.Value, + userId: _userId.Value, + title: "Test Library", + libraryType: LibraryType.Book, + contentLocations: [temporaryLibraryDirectory.Path], + shouldSkipUnchangedDirectoriesDuringScan: true); + _mockLibraryRepository.GetByIdAsync(_libraryId.Value, Arg.Any()) + .Returns(Result.From(libraryEntity)); + _mockDirectoryScanFingerprintRepository.GetMappedByLibraryIdAsync(_libraryId.Value, Arg.Any()) + .Returns(Error.Failure("Database.Error", "Failed to load the directory scan fingerprints")); + + // 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), Arg.Any()); + } + + [Fact] + public async Task ExecuteAsync_WhenUpsertingDirectoryScanFingerprintsFails_ShouldMarkJobAsFailedAndPublishFailureEvent() + { + // Arrange + using TemporaryLibraryDirectory temporaryLibraryDirectory = new(); + temporaryLibraryDirectory.CreateSubdirectory("changed"); + LibraryEntity libraryEntity = _libraryEntityFixture.Create( + id: _libraryId.Value, + userId: _userId.Value, + title: "Test Library", + libraryType: LibraryType.Book, + contentLocations: [temporaryLibraryDirectory.Path], + shouldSkipUnchangedDirectoriesDuringScan: true); + _mockLibraryRepository.GetByIdAsync(_libraryId.Value, Arg.Any()) + .Returns(Result.From(libraryEntity)); + _mockDirectoryScanFingerprintRepository.GetMappedByLibraryIdAsync(_libraryId.Value, Arg.Any()) + .Returns(Result.From(new Dictionary())); + _mockDirectoryScanFingerprintRepository.UpsertRangeAsync(Arg.Any>(), Arg.Any()) + .Returns(Error.Failure("Database.Error", "Failed to upsert the directory scan fingerprints")); + + // 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()); + await _mockDomainEventPublisher.DidNotReceive().PublishAsync(Arg.Is(domainEvent => + domainEvent.LibraryId == _libraryId), Arg.Any()); + } + + [Fact] + public async Task ExecuteAsync_WhenInsertingStagingResultsFails_ShouldMarkJobAsFailedAndPublishFailureEvent() + { + // Arrange + using TemporaryLibraryDirectory temporaryLibraryDirectory = new(); + temporaryLibraryDirectory.CreateFile("book.pdf", "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(Error.Failure("Database.Error", "Failed to insert the staging results")); + + // Act + await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None); + + // Assert + Assert.Equal(LibraryScanJobStatus.Failed, _sut.Status); + await _mockDirectoryScanFingerprintRepository.DidNotReceive().UpsertRangeAsync(Arg.Any>(), Arg.Any()); + await _mockDomainEventPublisher.Received(1).PublishAsync(Arg.Is(domainEvent => + domainEvent.LibraryId == _libraryId), Arg.Any()); + await _mockDomainEventPublisher.DidNotReceive().PublishAsync(Arg.Is(domainEvent => + domainEvent.LibraryId == _libraryId), Arg.Any()); + } + + [Fact] + public async Task ExecuteAsync_WhenJobHasLinkedChildren_ShouldExecuteEachChildAndComplete() + { + // Arrange + using TemporaryLibraryDirectory temporaryLibraryDirectory = new(); + temporaryLibraryDirectory.CreateFile("book1.pdf", "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)); + + IMediaLibraryScanJob mockChild = Substitute.For(); + mockChild.ExecuteAsync(Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(Task.CompletedTask); + _sut.AddChild(mockChild); + object input = new(); + + // Act + await _sut.ExecuteAsync(Guid.NewGuid(), input, CancellationToken.None); + + // Assert + Assert.Equal(LibraryScanJobStatus.Completed, _sut.Status); + await mockChild.Received(1).ExecuteAsync(Arg.Any(), Arg.Is(executedInput => executedInput == input), Arg.Any()); + } + + /// + /// 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/IntegrationTests/Lumina.Infrastructure.IntegrationTests/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Artwork/BookArtworkServiceTests.cs b/tests/IntegrationTests/Lumina.Infrastructure.IntegrationTests/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Artwork/BookArtworkServiceTests.cs new file mode 100644 index 00000000..13b9f52b --- /dev/null +++ b/tests/IntegrationTests/Lumina.Infrastructure.IntegrationTests/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Artwork/BookArtworkServiceTests.cs @@ -0,0 +1,690 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.Infrastructure.Models.DTO.Configuration; +using Lumina.Application.Fixtures.Common.Infrastructure.Models.DTO.Configuration; +using Lumina.Contracts.Fixtures.Core.DTO.Common; +using Lumina.Domain.Common.Errors; +using Lumina.Domain.Common.Primitives; +using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Services; +using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Strategies.Environment; +using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.ValueObjects; +using Lumina.Domain.Fixtures.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.ValueObjects; +using Lumina.Domain.SharedKernel.Common.Enums.PhotoLibrary; +using Lumina.Infrastructure.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Artwork; +using Lumina.Infrastructure.Fixtures.Common.Setup; +using Microsoft.Extensions.Options; +using NSubstitute; +using System; +using System.Collections.Generic; +using System.Diagnostics; +using System.Diagnostics.CodeAnalysis; +using System.IO; +using System.Net; +using System.Net.Http; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Infrastructure.IntegrationTests.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Artwork; + +/// +/// Contains integration tests for the class. +/// +[ExcludeFromCodeCoverage] +public class BookArtworkServiceTests +{ + private const long MAX_ARTWORK_SIZE_BYTES = 10 * 1024 * 1024; + + private readonly IEnvironmentContext _mockEnvironmentContext; + private readonly IFileTypeService _mockFileTypeService; + private readonly IFileProviderService _mockFileProviderService; + private readonly IDirectoryProviderService _mockDirectoryProviderService; + private readonly IPathService _mockPathService; + private readonly IHttpClientFactory _mockHttpClientFactory; + private readonly IOptions _mockMediaSettingsOptions; + private readonly BookArtworkService _sut; + private readonly FileSystemPathIdFixture _fileSystemPathIdFixture = new(); + private readonly PathSegmentFixture _pathSegmentFixture = new(); + private readonly ArtworkDtoFixture _artworkDtoFixture = new(); + private readonly MediaSettingsDtoFixture _mediaSettingsDtoFixture = new(); + private readonly StubHttpMessageHandler _stubHttpMessageHandler = new(); + + /// + /// Initializes a new instance of the class. + /// + public BookArtworkServiceTests() + { + _mockEnvironmentContext = Substitute.For(); + _mockFileTypeService = Substitute.For(); + _mockFileProviderService = Substitute.For(); + _mockDirectoryProviderService = Substitute.For(); + _mockEnvironmentContext.FileTypeService.Returns(_mockFileTypeService); + _mockEnvironmentContext.FileProviderService.Returns(_mockFileProviderService); + _mockEnvironmentContext.DirectoryProviderService.Returns(_mockDirectoryProviderService); + + _mockPathService = Substitute.For(); + _mockPathService.PathSeparator.Returns('\\'); + + _mockHttpClientFactory = Substitute.For(); + _mockHttpClientFactory.CreateClient().Returns(new HttpClient(_stubHttpMessageHandler)); + + MediaSettingsDto mediaSettings = _mediaSettingsDtoFixture.Create(rootDirectory: "media", librariesDirectory: "libraries", booksDirectory: "books"); + _mockMediaSettingsOptions = Substitute.For>(); + _mockMediaSettingsOptions.Value.Returns(mediaSettings); + + _sut = new BookArtworkService(_mockEnvironmentContext, _mockPathService, _mockHttpClientFactory, _mockMediaSettingsOptions); + } + + [Fact] + public async Task SaveBookArtworkAsync_WhenLocalArtworkExists_ShouldCopyItAndReturnARelativePath() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + Guid bookId = Guid.NewGuid(); + string libraryName = "Test Library"; + string authorName = "Test Author"; + string bookTitle = "Test Book"; + + string sourcePath = CreateTempImageFile(smallImageBytes: 1024); + try + { + _mockFileProviderService.FileExists(Arg.Any()).Returns(Result.From(true)); + _mockFileTypeService.GetImageTypeAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From(ImageType.JPEG)); + + string artworkDirectoryPath = BuildArtworkDirectoryPath(libraryId, bookId, libraryName, authorName, bookTitle); + MockArtworkDirectoryStubs(artworkDirectoryPath); + + FileSystemPathId copiedFileId = _fileSystemPathIdFixture.Create(Path.Combine(artworkDirectoryPath, "cover.jpg")); + _mockFileProviderService.CopyFile(Arg.Any(), Arg.Any(), true) + .Returns(Result.From(copiedFileId)); + + string renamedFilePath = Path.Combine(artworkDirectoryPath, "cover.jpeg"); + FileSystemPathId renamedFileId = _fileSystemPathIdFixture.Create(renamedFilePath); + _mockFileProviderService.RenameFile(Arg.Any(), "cover.jpeg") + .Returns(Result.From(renamedFileId)); + + // Act + Result result = await _sut.SaveBookArtworkAsync(libraryId, bookId, libraryName, authorName, bookTitle, _artworkDtoFixture.Create(localPath: sourcePath), CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal(renamedFilePath[AppContext.BaseDirectory.Length..].Insert(0, "\\"), result.Value); + _mockFileProviderService.Received(1).CopyFile( + Arg.Is(pathId => pathId.Path == sourcePath), + Arg.Any(), + true); + _mockFileProviderService.Received(1).RenameFile(Arg.Any(), "cover.jpeg"); + } + finally + { + File.Delete(sourcePath); + } + } + + [Fact] + public async Task SaveBookArtworkAsync_WhenAuthorNameIsMissing_ShouldUseUnknownForTheDirectorySegment() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + Guid bookId = Guid.NewGuid(); + string libraryName = "Test Library"; + string bookTitle = "Test Book"; + + string sourcePath = CreateTempImageFile(smallImageBytes: 1024); + try + { + _mockFileProviderService.FileExists(Arg.Any()).Returns(Result.From(true)); + _mockFileTypeService.GetImageTypeAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From(ImageType.JPEG)); + + string artworkDirectoryPath = BuildArtworkDirectoryPath(libraryId, bookId, libraryName, authorName: "Unknown", bookTitle); + MockArtworkDirectoryStubs(artworkDirectoryPath); + + FileSystemPathId renamedFileId = _fileSystemPathIdFixture.Create(Path.Combine(artworkDirectoryPath, "cover.jpeg")); + _mockFileProviderService.CopyFile(Arg.Any(), Arg.Any(), true) + .Returns(Result.From(_fileSystemPathIdFixture.Create(Path.Combine(artworkDirectoryPath, "cover.jpg")))); + _mockFileProviderService.RenameFile(Arg.Any(), "cover.jpeg") + .Returns(Result.From(renamedFileId)); + + // Act + Result result = await _sut.SaveBookArtworkAsync(libraryId, bookId, libraryName, authorName: " ", bookTitle, _artworkDtoFixture.Create(localPath: sourcePath), CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + _mockPathService.Received(1).SanitizeSegment("Unknown"); + } + finally + { + File.Delete(sourcePath); + } + } + + [Fact] + public async Task SaveBookArtworkAsync_WhenLocalArtworkIsALink_ShouldReturnInvalidPath() + { + // Arrange + string targetDirectory = Path.Combine(Path.GetTempPath(), $"lumina-junction-target-{Guid.NewGuid():N}"); + Directory.CreateDirectory(targetDirectory); + string linkPath = Path.Combine(Path.GetTempPath(), $"lumina-junction-link-{Guid.NewGuid():N}"); + if (!TryCreateJunction(linkPath, targetDirectory)) + { + Directory.Delete(targetDirectory, true); + return; // The environment does not support creating reparse points. + } + + try + { + _mockFileProviderService.FileExists(Arg.Any()).Returns(Result.From(true)); + + // Act + Result result = await _sut.SaveBookArtworkAsync(Guid.NewGuid(), Guid.NewGuid(), "Library", "Author", "Title", _artworkDtoFixture.Create(localPath: linkPath), CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.FileSystemManagement.InvalidPath, result.FirstError); + _mockFileProviderService.DidNotReceive().CopyFile(Arg.Any(), Arg.Any(), true); + } + finally + { + // Windows removes a junction with Directory.Delete, while Unix-like platforms unlink the symbolic link with File.Delete. + if (OperatingSystem.IsWindows()) + Directory.Delete(linkPath, true); + else + File.Delete(linkPath); + Directory.Delete(targetDirectory, true); + } + } + + [Fact] + public async Task SaveBookArtworkAsync_WhenLocalArtworkExceedsMaxSize_ShouldReturnFileTooLarge() + { + // Arrange + string sourcePath = CreateTempImageFile(smallImageBytes: (int)MAX_ARTWORK_SIZE_BYTES + 1); + try + { + _mockFileProviderService.FileExists(Arg.Any()).Returns(Result.From(true)); + + // Act + Result result = await _sut.SaveBookArtworkAsync(Guid.NewGuid(), Guid.NewGuid(), "Library", "Author", "Title", _artworkDtoFixture.Create(localPath: sourcePath), CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.FileSystemManagement.FileTooLarge, result.FirstError); + await _mockFileTypeService.DidNotReceive().GetImageTypeAsync(Arg.Any(), Arg.Any()); + } + finally + { + File.Delete(sourcePath); + } + } + + [Fact] + public async Task SaveBookArtworkAsync_WhenLocalArtworkIsNotAnImage_ShouldReturnCoverFileMustBeAnImage() + { + // Arrange + string sourcePath = CreateTempImageFile(smallImageBytes: 1024); + try + { + _mockFileProviderService.FileExists(Arg.Any()).Returns(Result.From(true)); + _mockFileTypeService.GetImageTypeAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From(ImageType.None)); + + // Act + Result result = await _sut.SaveBookArtworkAsync(Guid.NewGuid(), Guid.NewGuid(), "Library", "Author", "Title", _artworkDtoFixture.Create(localPath: sourcePath), CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.Library.CoverFileMustBeAnImage, result.FirstError); + _mockFileProviderService.DidNotReceive().CopyFile(Arg.Any(), Arg.Any(), true); + } + finally + { + File.Delete(sourcePath); + } + } + + [Fact] + public async Task SaveBookArtworkAsync_WhenRemoteUrlIsProvided_ShouldDownloadAndStoreTheArtwork() + { + // Arrange + byte[] imageBytes = new byte[1024]; + _stubHttpMessageHandler.SetResponse(HttpStatusCode.OK, imageBytes); + Guid libraryId = Guid.NewGuid(); + Guid bookId = Guid.NewGuid(); + string libraryName = "Test Library"; + string authorName = "Test Author"; + string bookTitle = "Test Book"; + + _mockFileProviderService.FileExists(Arg.Any()).Returns(Result.From(true)); + _mockFileTypeService.GetImageTypeAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From(ImageType.JPEG)); + + string artworkDirectoryPath = BuildArtworkDirectoryPath(libraryId, bookId, libraryName, authorName, bookTitle); + MockArtworkDirectoryStubs(artworkDirectoryPath); + + _mockFileProviderService.CopyFile(Arg.Any(), Arg.Any(), true) + .Returns(Result.From(_fileSystemPathIdFixture.Create(Path.Combine(artworkDirectoryPath, "cover.jpg")))); + FileSystemPathId renamedFileId = _fileSystemPathIdFixture.Create(Path.Combine(artworkDirectoryPath, "cover.jpeg")); + _mockFileProviderService.RenameFile(Arg.Any(), "cover.jpeg") + .Returns(Result.From(renamedFileId)); + + // Act + Result result = await _sut.SaveBookArtworkAsync(libraryId, bookId, libraryName, authorName, bookTitle, _artworkDtoFixture.Create(remoteUrl: "http://artwork.example/cover.jpg"), CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + _mockFileProviderService.Received(1).CopyFile( + Arg.Is(pathId => pathId.Path.StartsWith(Path.GetTempPath())), + Arg.Any(), + true); + } + + [Fact] + public async Task SaveBookArtworkAsync_WhenRemoteDownloadReturnsAnErrorStatus_ShouldReturnFileNotFound() + { + // Arrange + _stubHttpMessageHandler.SetResponse(HttpStatusCode.NotFound, []); + + // Act + Result result = await _sut.SaveBookArtworkAsync(Guid.NewGuid(), Guid.NewGuid(), "Library", "Author", "Title", _artworkDtoFixture.Create(remoteUrl: "http://artwork.example/cover.jpg"), CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.FileSystemManagement.FileNotFound, result.FirstError); + } + + [Fact] + public async Task SaveBookArtworkAsync_WhenRemoteDownloadExceedsMaxSize_ShouldReturnFileTooLarge() + { + // Arrange + _stubHttpMessageHandler.SetResponse(HttpStatusCode.OK, new byte[MAX_ARTWORK_SIZE_BYTES + 1]); + + // Act + Result result = await _sut.SaveBookArtworkAsync(Guid.NewGuid(), Guid.NewGuid(), "Library", "Author", "Title", _artworkDtoFixture.Create(remoteUrl: "http://artwork.example/cover.jpg"), CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.FileSystemManagement.FileTooLarge, result.FirstError); + } + + [Fact] + public async Task SaveBookArtworkAsync_WhenArtworkHasBothLocalPathAndRemoteUrl_ShouldUseTheLocalFileWithoutDeletingIt() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + Guid bookId = Guid.NewGuid(); + string libraryName = "Test Library"; + string authorName = "Test Author"; + string bookTitle = "Test Book"; + + string sourcePath = CreateTempImageFile(smallImageBytes: 1024); + try + { + _mockFileProviderService.FileExists(Arg.Any()).Returns(Result.From(true)); + _mockFileTypeService.GetImageTypeAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From(ImageType.JPEG)); + + string artworkDirectoryPath = BuildArtworkDirectoryPath(libraryId, bookId, libraryName, authorName, bookTitle); + MockArtworkDirectoryStubs(artworkDirectoryPath); + + FileSystemPathId renamedFileId = _fileSystemPathIdFixture.Create(Path.Combine(artworkDirectoryPath, "cover.jpeg")); + _mockFileProviderService.CopyFile(Arg.Any(), Arg.Any(), true) + .Returns(Result.From(_fileSystemPathIdFixture.Create(Path.Combine(artworkDirectoryPath, "cover.jpg")))); + _mockFileProviderService.RenameFile(Arg.Any(), "cover.jpeg") + .Returns(Result.From(renamedFileId)); + + // Act + Result result = await _sut.SaveBookArtworkAsync(libraryId, bookId, libraryName, authorName, bookTitle, _artworkDtoFixture.Create(localPath: sourcePath, remoteUrl: "http://artwork.example/cover.jpg"), CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + Assert.True(File.Exists(sourcePath)); + _mockFileProviderService.Received(1).CopyFile( + Arg.Is(pathId => pathId.Path == sourcePath), + Arg.Any(), + true); + } + finally + { + File.Delete(sourcePath); + } + } + + [Fact] + public async Task SaveBookArtworkAsync_WhenRemoteDownloadIsCancelled_ShouldRethrowCancellation() + { + // Arrange + CancellationTokenSource cancellationTokenSource = new(); + cancellationTokenSource.Cancel(); + + // Act + async Task Act() + { + await _sut.SaveBookArtworkAsync(Guid.NewGuid(), Guid.NewGuid(), "Library", "Author", "Title", _artworkDtoFixture.Create(remoteUrl: "http://artwork.example/cover.jpg"), cancellationTokenSource.Token); + } + + // Assert + await Assert.ThrowsAnyAsync(Act); + } + + [Fact] + public async Task SaveBookArtworkAsync_WhenImageTypeDetectionFails_ShouldReturnTheError() + { + // Arrange + string sourcePath = CreateTempImageFile(smallImageBytes: 1024); + try + { + _mockFileProviderService.FileExists(Arg.Any()).Returns(Result.From(true)); + _mockFileTypeService.GetImageTypeAsync(Arg.Any(), Arg.Any()) + .Returns(Error.Failure("FileSystem.Error", "Failed to detect the image type")); + + // Act + Result result = await _sut.SaveBookArtworkAsync(Guid.NewGuid(), Guid.NewGuid(), "Library", "Author", "Title", _artworkDtoFixture.Create(localPath: sourcePath), CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal("FileSystem.Error", result.FirstError.Code); + _mockFileProviderService.DidNotReceive().CopyFile(Arg.Any(), Arg.Any(), true); + } + finally + { + File.Delete(sourcePath); + } + } + + [Fact] + public async Task SaveBookArtworkAsync_WhenCreatingTheArtworkDirectoryFails_ShouldReturnTheError() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + Guid bookId = Guid.NewGuid(); + string libraryName = "Test Library"; + string authorName = "Test Author"; + string bookTitle = "Test Book"; + + string sourcePath = CreateTempImageFile(smallImageBytes: 1024); + try + { + _mockFileProviderService.FileExists(Arg.Any()).Returns(Result.From(true)); + _mockFileTypeService.GetImageTypeAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From(ImageType.JPEG)); + + string artworkDirectoryPath = BuildArtworkDirectoryPath(libraryId, bookId, libraryName, authorName, bookTitle); + MockArtworkDirectoryStubs(artworkDirectoryPath); + _mockDirectoryProviderService.CreateDirectory(Arg.Any(), Arg.Any()) + .Returns(Error.Failure("Directory.Error", "Failed to create the artwork directory")); + + // Act + Result result = await _sut.SaveBookArtworkAsync(libraryId, bookId, libraryName, authorName, bookTitle, _artworkDtoFixture.Create(localPath: sourcePath), CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal("Directory.Error", result.FirstError.Code); + _mockFileProviderService.DidNotReceive().CopyFile(Arg.Any(), Arg.Any(), true); + } + finally + { + File.Delete(sourcePath); + } + } + + [Fact] + public async Task SaveBookArtworkAsync_WhenDirectoryExistenceCheckFails_ShouldReturnTheError() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + Guid bookId = Guid.NewGuid(); + string libraryName = "Test Library"; + string authorName = "Test Author"; + string bookTitle = "Test Book"; + + string sourcePath = CreateTempImageFile(smallImageBytes: 1024); + try + { + _mockFileProviderService.FileExists(Arg.Any()).Returns(Result.From(true)); + _mockFileTypeService.GetImageTypeAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From(ImageType.JPEG)); + + string artworkDirectoryPath = BuildArtworkDirectoryPath(libraryId, bookId, libraryName, authorName, bookTitle); + MockArtworkDirectoryStubs(artworkDirectoryPath); + _mockDirectoryProviderService.DirectoryExists(Arg.Any()) + .Returns(Error.Failure("Directory.Error", "Failed to check the artwork directory")); + + // Act + Result result = await _sut.SaveBookArtworkAsync(libraryId, bookId, libraryName, authorName, bookTitle, _artworkDtoFixture.Create(localPath: sourcePath), CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal("Directory.Error", result.FirstError.Code); + _mockFileProviderService.DidNotReceive().CopyFile(Arg.Any(), Arg.Any(), true); + } + finally + { + File.Delete(sourcePath); + } + } + + [Fact] + public async Task SaveBookArtworkAsync_WhenCopyingTheArtworkFails_ShouldReturnTheError() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + Guid bookId = Guid.NewGuid(); + string libraryName = "Test Library"; + string authorName = "Test Author"; + string bookTitle = "Test Book"; + + string sourcePath = CreateTempImageFile(smallImageBytes: 1024); + try + { + _mockFileProviderService.FileExists(Arg.Any()).Returns(Result.From(true)); + _mockFileTypeService.GetImageTypeAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From(ImageType.JPEG)); + + string artworkDirectoryPath = BuildArtworkDirectoryPath(libraryId, bookId, libraryName, authorName, bookTitle); + MockArtworkDirectoryStubs(artworkDirectoryPath); + _mockFileProviderService.CopyFile(Arg.Any(), Arg.Any(), true) + .Returns(Error.Failure("FileSystem.Error", "Failed to copy the artwork")); + + // Act + Result result = await _sut.SaveBookArtworkAsync(libraryId, bookId, libraryName, authorName, bookTitle, _artworkDtoFixture.Create(localPath: sourcePath), CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal("FileSystem.Error", result.FirstError.Code); + _mockFileProviderService.DidNotReceive().RenameFile(Arg.Any(), Arg.Any()); + } + finally + { + File.Delete(sourcePath); + } + } + + [Fact] + public async Task SaveBookArtworkAsync_WhenRenamingTheCopiedArtworkFails_ShouldReturnTheError() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + Guid bookId = Guid.NewGuid(); + string libraryName = "Test Library"; + string authorName = "Test Author"; + string bookTitle = "Test Book"; + + string sourcePath = CreateTempImageFile(smallImageBytes: 1024); + try + { + _mockFileProviderService.FileExists(Arg.Any()).Returns(Result.From(true)); + _mockFileTypeService.GetImageTypeAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From(ImageType.JPEG)); + + string artworkDirectoryPath = BuildArtworkDirectoryPath(libraryId, bookId, libraryName, authorName, bookTitle); + MockArtworkDirectoryStubs(artworkDirectoryPath); + _mockFileProviderService.CopyFile(Arg.Any(), Arg.Any(), true) + .Returns(Result.From(_fileSystemPathIdFixture.Create(Path.Combine(artworkDirectoryPath, "cover.jpg")))); + _mockFileProviderService.RenameFile(Arg.Any(), "cover.jpeg") + .Returns(Error.Failure("FileSystem.Error", "Failed to rename the artwork")); + + // Act + Result result = await _sut.SaveBookArtworkAsync(libraryId, bookId, libraryName, authorName, bookTitle, _artworkDtoFixture.Create(localPath: sourcePath), CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal("FileSystem.Error", result.FirstError.Code); + _mockFileProviderService.DidNotReceive().DeleteFile(Arg.Any()); + } + finally + { + File.Delete(sourcePath); + } + } + + [Fact] + public async Task SaveBookArtworkAsync_WhenAuthorNameCannotBeSanitized_ShouldReturnInvalidPath() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + Guid bookId = Guid.NewGuid(); + string libraryName = "Test Library"; + string authorName = "Test Author"; + string bookTitle = "Test Book"; + + string sourcePath = CreateTempImageFile(smallImageBytes: 1024); + try + { + _mockFileProviderService.FileExists(Arg.Any()).Returns(Result.From(true)); + _mockFileTypeService.GetImageTypeAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From(ImageType.JPEG)); + + string mediaRoot = Path.Combine(AppContext.BaseDirectory, "media"); + string booksPath = Path.Combine(mediaRoot, "books"); + _mockPathService.CombinePath(AppContext.BaseDirectory, "media").Returns(Result.From(mediaRoot)); + _mockPathService.CombinePath(mediaRoot, "books").Returns(Result.From(booksPath)); + _mockPathService.CombinePath(Arg.Any(), Arg.Any()) + .Returns(callInfo => Result.From(Path.Combine(callInfo.ArgAt(0), callInfo.ArgAt(1)))); + _mockPathService.SanitizeSegment(Arg.Any()) + .Returns(callInfo => + { + string name = callInfo.Arg(); + return name == $"{libraryName}-{libraryId}" + ? Result.From(_pathSegmentFixture.Create(name: name, isDirectory: true, isDrive: false)) + : Errors.FileSystemManagement.InvalidPath; + }); + + // Act + Result result = await _sut.SaveBookArtworkAsync(libraryId, bookId, libraryName, authorName, bookTitle, _artworkDtoFixture.Create(localPath: sourcePath), CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.FileSystemManagement.InvalidPath, result.FirstError); + _mockFileProviderService.DidNotReceive().CopyFile(Arg.Any(), Arg.Any(), true); + } + finally + { + File.Delete(sourcePath); + } + } + + /// + /// Stubs the path and file system services so that the artwork is stored into the given directory. + /// + /// The file system path of the directory into which the artwork is stored. + private void MockArtworkDirectoryStubs(string artworkDirectoryPath) + { + string mediaRoot = Path.Combine(AppContext.BaseDirectory, "media"); + string booksPath = Path.Combine(mediaRoot, "books"); + _mockPathService.CombinePath(AppContext.BaseDirectory, "media").Returns(Result.From(mediaRoot)); + _mockPathService.CombinePath(mediaRoot, "books").Returns(Result.From(booksPath)); + + _mockPathService.SanitizeSegment(Arg.Any()) + .Returns(callInfo => + { + string name = callInfo.Arg(); + return Result.From(_pathSegmentFixture.Create(name: name, isDirectory: true, isDrive: false)); + }); + + _mockPathService.CombinePath(Arg.Any(), Arg.Any()) + .Returns(callInfo => Result.From(Path.Combine(callInfo.ArgAt(0), callInfo.ArgAt(1)))); + + // Every directory except the artwork directory itself already exists, so that only the final directory is created. + _mockDirectoryProviderService.DirectoryExists(Arg.Any()) + .Returns(callInfo => Result.From(!string.Equals(callInfo.Arg().Path, artworkDirectoryPath, StringComparison.OrdinalIgnoreCase))); + _mockDirectoryProviderService.CreateDirectory(Arg.Any(), Arg.Any()) + .Returns(callInfo => Result.From(_fileSystemPathIdFixture.Create(Path.Combine(callInfo.Arg().Path, callInfo.Arg())))); + + _mockFileProviderService.GetFilePaths(Arg.Any(), true) + .Returns(Result.From>([])); + } + + /// + /// Builds the file system path of the directory that the artwork of the book is stored into. + /// + /// The Id of the media library the book belongs to. + /// The Id of the book. + /// The name of the media library the book belongs to. + /// The name of the author of the book. + /// The title of the book. + /// The expected file system path of the book artwork directory. + private static string BuildArtworkDirectoryPath(Guid libraryId, Guid bookId, string libraryName, string authorName, string bookTitle) + { + return Path.Combine( + AppContext.BaseDirectory, + "media", + "books", + $"{libraryName}-{libraryId}", + authorName, + $"{bookTitle}-{bookId}"); + } + + /// + /// Creates a temporary image file with the given size and returns its path. + /// + /// The size of the temporary image file, in bytes. + /// The file system path of the created temporary image file. + private static string CreateTempImageFile(int smallImageBytes) + { + string sourcePath = Path.Combine(Path.GetTempPath(), $"lumina-artwork-source-{Guid.NewGuid():N}.jpg"); + File.WriteAllBytes(sourcePath, new byte[smallImageBytes]); + return sourcePath; + } + + /// + /// Creates a file system link that points to the target directory: a junction on Windows, and a symbolic link on Unix-like platforms. + /// + /// The file system path of the link to create. + /// The file system path of the directory the link points to. + /// when the link was created, otherwise. + private static bool TryCreateJunction(string linkPath, string targetDirectory) + { + try + { + ProcessStartInfo startInfo = OperatingSystem.IsWindows() + ? new() + { + FileName = "cmd.exe", + Arguments = $"/c mklink /J \"{linkPath}\" \"{targetDirectory}\"", + CreateNoWindow = true, + UseShellExecute = false + } + : new() + { + FileName = "ln", + CreateNoWindow = true, + UseShellExecute = false + }; + if (!OperatingSystem.IsWindows()) + { + startInfo.ArgumentList.Add("-s"); + startInfo.ArgumentList.Add(targetDirectory); + startInfo.ArgumentList.Add(linkPath); + } + + Process process = Process.Start(startInfo)!; + process.WaitForExit(5000); + return process.ExitCode == 0; + } + catch (Exception) + { + return false; + } + } +} diff --git a/tests/IntegrationTests/Lumina.Infrastructure.IntegrationTests/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Reading/BookReadingServiceTests.cs b/tests/IntegrationTests/Lumina.Infrastructure.IntegrationTests/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Reading/BookReadingServiceTests.cs new file mode 100644 index 00000000..3fadeb90 --- /dev/null +++ b/tests/IntegrationTests/Lumina.Infrastructure.IntegrationTests/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Reading/BookReadingServiceTests.cs @@ -0,0 +1,782 @@ +#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.Infrastructure.Reading; +using Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Reading; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.Plugins; +using Lumina.Contracts.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary.Reading; +using Lumina.Contracts.Fixtures.Core.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary.Reading; +using Lumina.Contracts.Responses.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Reading; +using Lumina.Domain.Common.Errors; +using Lumina.Domain.Common.Primitives; +using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; +using Lumina.Infrastructure.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Reading; +using Lumina.Plugins.Contracts.Core.Plugins; +using Lumina.Plugins.Contracts.Core.Reading; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Logging; +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.IntegrationTests.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Reading; + +/// +/// Contains integration tests for the class. +/// +[ExcludeFromCodeCoverage] +public class BookReadingServiceTests : IDisposable +{ + private readonly IPluginManager _mockPluginManager; + private readonly IPlugin _mockPlugin; + private readonly IBookReader _mockReader; + private readonly IUnitOfWork _mockUnitOfWork; + private readonly ILibraryBookReaderConfigurationRepository _mockConfigurationRepository; + private readonly IServiceProvider _serviceProvider; + private readonly BookReadingService _sut; + private readonly TestBookReaderEnablementCache _enablementCache = new(); + private readonly Guid _pluginId = Guid.NewGuid(); + private readonly Guid _bookId = Guid.NewGuid(); + private readonly Guid _libraryId = Guid.NewGuid(); + private readonly string _bookPath; + private readonly ReadingDocumentDtoFixture _readingDocumentDtoFixture = new(); + private readonly ReadingSpineItemDtoFixture _readingSpineItemDtoFixture = new(); + private readonly ReadingResourceInfoDtoFixture _readingResourceInfoDtoFixture = new(); + private readonly LibraryBookReaderConfigurationEntityFixture _configurationEntityFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + public BookReadingServiceTests() + { + _mockReader = Substitute.For(); + _mockReader.SupportedExtensions.Returns([".epub"]); + _mockReader.SupportedLibraryTypes.Returns([LibraryType.EBook]); + _mockPlugin = Substitute.For(); + _mockPlugin.Id.Returns(_pluginId); + _mockPlugin.Name.Returns("Test Reader"); + _mockPluginManager = Substitute.For(); + _mockPluginManager.GetPlugins().Returns([_mockPlugin]); + + _mockUnitOfWork = Substitute.For(); + _mockConfigurationRepository = Substitute.For(); + _mockUnitOfWork.LibraryBookReaderConfigurationRepository.Returns(_mockConfigurationRepository); + LibraryBookReaderConfigurationEntity enabledConfiguration = _configurationEntityFixture.Create(libraryId: _libraryId, pluginId: _pluginId, isEnabled: true); + _mockConfigurationRepository.GetByLibraryAndPluginIdAsync(_libraryId, _pluginId, Arg.Any()) + .Returns(Result.From(enabledConfiguration)); + + ServiceCollection services = new(); + services.AddKeyedSingleton(_pluginId, _mockReader); + services.AddSingleton(_mockUnitOfWork); + _serviceProvider = services.BuildServiceProvider(); + IServiceScopeFactory serviceScopeFactory = _serviceProvider.GetRequiredService(); + + _bookPath = Path.Combine(Path.GetTempPath(), $"lumina-test-book-{Guid.NewGuid():N}.epub"); + File.WriteAllText(_bookPath, "test epub content"); + + _sut = new BookReadingService(_serviceProvider, _mockPluginManager, _enablementCache, serviceScopeFactory, Substitute.For>()); + } + + [Fact] + public async Task GetManifestAsync_WhenBookIsNotCached_ShouldExtractAndReturnTheManifest() + { + // Arrange + ReadingDocumentDto document = CreateExtractableDocument(); + StubOpenAsyncToExtract(document); + CancellationToken cancellationToken = CancellationToken.None; + + // Act + Result result = await _sut.GetManifestAsync(_bookId, _libraryId, _bookPath, LibraryType.EBook, shouldRenderPdfAsImages: false, cancellationToken); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal(document.Title, result.Value.Title); + Assert.Equal(document.Author, result.Value.Author); + await _mockReader.Received(1).OpenAsync(_bookPath, Arg.Any(), Arg.Any(), cancellationToken); + } + + [Fact] + public async Task GetManifestAsync_WhenFileIsUnchanged_ShouldReuseTheCachedDocument() + { + // Arrange + ReadingDocumentDto document = CreateExtractableDocument(); + StubOpenAsyncToExtract(document); + CancellationToken cancellationToken = CancellationToken.None; + + // Act + await _sut.GetManifestAsync(_bookId, _libraryId, _bookPath, LibraryType.EBook, shouldRenderPdfAsImages: false, cancellationToken); + Result secondResult = await _sut.GetManifestAsync(_bookId, _libraryId, _bookPath, LibraryType.EBook, shouldRenderPdfAsImages: false, cancellationToken); + + // Assert + Assert.False(secondResult.IsFailure); + await _mockReader.Received(1).OpenAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()); + } + + [Fact] + public async Task GetManifestAsync_WhenFileChanged_ShouldReExtractTheBook() + { + // Arrange + ReadingDocumentDto document = CreateExtractableDocument(); + StubOpenAsyncToExtract(document); + CancellationToken cancellationToken = CancellationToken.None; + + // Act + await _sut.GetManifestAsync(_bookId, _libraryId, _bookPath, LibraryType.EBook, shouldRenderPdfAsImages: false, cancellationToken); + File.WriteAllText(_bookPath, "modified epub content, longer than before"); + Result secondResult = await _sut.GetManifestAsync(_bookId, _libraryId, _bookPath, LibraryType.EBook, shouldRenderPdfAsImages: false, cancellationToken); + + // Assert + Assert.False(secondResult.IsFailure); + await _mockReader.Received(2).OpenAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()); + } + + [Fact] + public async Task GetManifestAsync_WhenRenderingPreferenceDiffers_ShouldExtractTheBookTwice() + { + // Arrange + ReadingDocumentDto document = CreateExtractableDocument(); + StubOpenAsyncToExtract(document); + CancellationToken cancellationToken = CancellationToken.None; + + // Act + await _sut.GetManifestAsync(_bookId, _libraryId, _bookPath, LibraryType.EBook, shouldRenderPdfAsImages: false, cancellationToken); + Result secondResult = await _sut.GetManifestAsync(_bookId, _libraryId, _bookPath, LibraryType.EBook, shouldRenderPdfAsImages: true, cancellationToken); + + // Assert + Assert.False(secondResult.IsFailure); + await _mockReader.Received(2).OpenAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()); + await _mockReader.Received(1).OpenAsync(Arg.Any(), Arg.Any(), false, Arg.Any()); + await _mockReader.Received(1).OpenAsync(Arg.Any(), Arg.Any(), true, Arg.Any()); + } + + [Fact] + public async Task GetManifestAsync_WhenBothRenderingPreferencesAreExtracted_ShouldKeepTheirWorkingDirectoriesSeparate() + { + // Arrange + ReadingDocumentDto document = CreateExtractableDocument(); + StubOpenAsyncToExtract(document); + CancellationToken cancellationToken = CancellationToken.None; + + // Act + await _sut.GetManifestAsync(_bookId, _libraryId, _bookPath, LibraryType.EBook, shouldRenderPdfAsImages: false, cancellationToken); + await _sut.GetManifestAsync(_bookId, _libraryId, _bookPath, LibraryType.EBook, shouldRenderPdfAsImages: true, cancellationToken); + // The text extraction must survive the image extraction of the same book, and still be served from the cache. + Result thirdResult = await _sut.GetManifestAsync(_bookId, _libraryId, _bookPath, LibraryType.EBook, shouldRenderPdfAsImages: false, cancellationToken); + + // Assert + Assert.False(thirdResult.IsFailure); + string textWorkingDirectory = Path.Combine(ReadingCachePaths.GetRootDirectory(), _bookId.ToString("N"), "text"); + string imageWorkingDirectory = Path.Combine(ReadingCachePaths.GetRootDirectory(), _bookId.ToString("N"), "images"); + Assert.True(File.Exists(Path.Combine(textWorkingDirectory, "sections", "0.html"))); + Assert.True(File.Exists(Path.Combine(imageWorkingDirectory, "sections", "0.html"))); + await _mockReader.Received(2).OpenAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()); + } + + [Fact] + public async Task GetManifestAsync_WhenConcurrentRequests_ShouldShareASingleExtraction() + { + // Arrange + ReadingDocumentDto document = CreateExtractableDocument(); + TaskCompletionSource extractionStarted = new(); + TaskCompletionSource allowExtractionToFinish = new(); + _mockReader.OpenAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(callInfo => Task.Run(async () => + { + extractionStarted.SetResult(true); + await allowExtractionToFinish.Task; + return document; + })); + + // Act + Task> firstTask = _sut.GetManifestAsync(_bookId, _libraryId, _bookPath, LibraryType.EBook, shouldRenderPdfAsImages: false, CancellationToken.None); + await extractionStarted.Task; + Task> secondTask = _sut.GetManifestAsync(_bookId, _libraryId, _bookPath, LibraryType.EBook, shouldRenderPdfAsImages: false, CancellationToken.None); + allowExtractionToFinish.SetResult(true); + Result firstResult = await firstTask; + Result secondResult = await secondTask; + + // Assert + Assert.False(firstResult.IsFailure); + Assert.False(secondResult.IsFailure); + await _mockReader.Received(1).OpenAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()); + } + + [Fact] + public async Task GetSectionAsync_WhenSectionExists_ShouldReturnSanitizedContent() + { + // Arrange + ReadingDocumentDto document = CreateExtractableDocument(); + StubOpenAsyncToExtract(document); + CancellationToken cancellationToken = CancellationToken.None; + + // Act + Result result = await _sut.GetSectionAsync(_bookId, _libraryId, _bookPath, LibraryType.EBook, "section-1", shouldRenderPdfAsImages: false, shouldPreserveStyles: false, cancellationToken); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal("section-1", result.Value.LocationRef); + Assert.Contains("Chapter 1", result.Value.ContentHtml, StringComparison.Ordinal); + } + + [Fact] + public async Task GetSectionAsync_WhenSectionDoesNotExist_ShouldReturnSectionNotFoundError() + { + // Arrange + ReadingDocumentDto document = CreateExtractableDocument(); + StubOpenAsyncToExtract(document); + + // Act + Result result = await _sut.GetSectionAsync(_bookId, _libraryId, _bookPath, LibraryType.EBook, "missing-section", shouldRenderPdfAsImages: false, shouldPreserveStyles: false, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.Reading.SectionNotFound, result.FirstError); + } + + [Fact] + public async Task GetSectionAsync_WhenSectionFileDoesNotExist_ShouldReturnSectionNotFoundError() + { + // Arrange + ReadingDocumentDto document = _readingDocumentDtoFixture.Create( + title: "Test Book", + tableOfContents: [], + spine: + [ + _readingSpineItemDtoFixture.Create(locationRef: "section-1", title: "Chapter 1", relativeSectionFilePath: "sections/missing.html") + ], + resources: new Dictionary() + ); + StubOpenAsyncToExtract(document); + + // Act + Result result = await _sut.GetSectionAsync(_bookId, _libraryId, _bookPath, LibraryType.EBook, "section-1", shouldRenderPdfAsImages: false, shouldPreserveStyles: false, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.Reading.SectionNotFound, result.FirstError); + } + + [Fact] + public async Task GetSectionAsync_WhenSectionPathEscapesTheWorkingDirectory_ShouldReturnSectionNotFoundError() + { + // Arrange + ReadingDocumentDto document = _readingDocumentDtoFixture.Create( + title: "Test Book", + tableOfContents: [], + spine: + [ + _readingSpineItemDtoFixture.Create(locationRef: "section-1", title: "Chapter 1", relativeSectionFilePath: "../../escape.html") + ], + resources: new Dictionary() + ); + StubOpenAsyncToExtract(document); + + // Act + Result result = await _sut.GetSectionAsync(_bookId, _libraryId, _bookPath, LibraryType.EBook, "section-1", shouldRenderPdfAsImages: false, shouldPreserveStyles: false, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.Reading.SectionNotFound, result.FirstError); + } + + [Fact] + public async Task GetResourceAsync_WhenResourceDoesNotExistInTheDocument_ShouldReturnResourceNotFoundError() + { + // Arrange + ReadingDocumentDto document = CreateExtractableDocument(); + StubOpenAsyncToExtract(document); + + // Act + Result result = await _sut.GetResourceAsync(_bookId, _libraryId, _bookPath, LibraryType.EBook, "missing-key", shouldRenderPdfAsImages: false, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.Reading.ResourceNotFound, result.FirstError); + await _mockReader.DidNotReceive().GetResourceAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()); + } + + [Fact] + public async Task GetResourceAsync_WhenResourcePathEscapesTheWorkingDirectory_ShouldReturnResourceNotFoundError() + { + // Arrange + ReadingDocumentDto document = _readingDocumentDtoFixture.Create( + title: "Test Book", + tableOfContents: [], + spine: [], + resources: new Dictionary + { + ["escaping"] = _readingResourceInfoDtoFixture.Create(relativeFilePath: "../../escape.png", mimeType: "image/png") + } + ); + StubOpenAsyncToExtract(document); + + // Act + Result result = await _sut.GetResourceAsync(_bookId, _libraryId, _bookPath, LibraryType.EBook, "escaping", shouldRenderPdfAsImages: false, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.Reading.ResourceNotFound, result.FirstError); + await _mockReader.DidNotReceive().GetResourceAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()); + } + + [Fact] + public async Task GetResourceAsync_WhenResourceFileAlreadyExists_ShouldServeItFromDiskWithoutCallingTheReader() + { + // Arrange + ReadingDocumentDto document = CreateExtractableDocument(); + StubOpenAsyncToExtract(document); + await _sut.GetManifestAsync(_bookId, _libraryId, _bookPath, LibraryType.EBook, shouldRenderPdfAsImages: false, CancellationToken.None); + string workingDirectory = Path.Combine(ReadingCachePaths.GetRootDirectory(), _bookId.ToString("N"), "text"); + string resourceFilePath = Path.Combine(workingDirectory, "resources", "cover.png"); + Directory.CreateDirectory(Path.GetDirectoryName(resourceFilePath)!); + File.WriteAllBytes(resourceFilePath, [1, 2, 3]); + + // Act + Result result = await _sut.GetResourceAsync(_bookId, _libraryId, _bookPath, LibraryType.EBook, "cover", shouldRenderPdfAsImages: false, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal(new byte[] { 1, 2, 3 }, result.Value.Data); + Assert.Equal("image/png", result.Value.MimeType); + await _mockReader.DidNotReceive().GetResourceAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()); + } + + [Fact] + public async Task GetResourceAsync_WhenResourceFileDoesNotExist_ShouldProduceItAndCacheItToDisk() + { + // Arrange + ReadingDocumentDto document = CreateExtractableDocument(); + StubOpenAsyncToExtract(document); + byte[] producedResource = [4, 5, 6]; + _mockReader.GetResourceAsync(Arg.Any(), Arg.Any(), "cover", Arg.Any()).Returns(producedResource); + + // Act + Result firstResult = await _sut.GetResourceAsync(_bookId, _libraryId, _bookPath, LibraryType.EBook, "cover", shouldRenderPdfAsImages: false, CancellationToken.None); + Result secondResult = await _sut.GetResourceAsync(_bookId, _libraryId, _bookPath, LibraryType.EBook, "cover", shouldRenderPdfAsImages: false, CancellationToken.None); + + // Assert + Assert.False(firstResult.IsFailure); + Assert.Equal(new byte[] { 4, 5, 6 }, firstResult.Value.Data); + Assert.Equal("image/png", firstResult.Value.MimeType); + Assert.False(secondResult.IsFailure); + Assert.Equal(new byte[] { 4, 5, 6 }, secondResult.Value.Data); + Assert.Equal("image/png", secondResult.Value.MimeType); + await _mockReader.Received(1).GetResourceAsync(_bookPath, Arg.Any(), "cover", Arg.Any()); + string cachedFilePath = Path.Combine(ReadingCachePaths.GetRootDirectory(), _bookId.ToString("N"), "text", "resources", "cover.png"); + Assert.True(File.Exists(cachedFilePath)); + Assert.Equal(new byte[] { 4, 5, 6 }, File.ReadAllBytes(cachedFilePath)); + } + + [Fact] + public async Task GetResourceAsync_WhenReaderIsDisabledForTheLibrary_ShouldReturnReaderDisabledError() + { + // Arrange + ReadingDocumentDto document = CreateExtractableDocument(); + StubOpenAsyncToExtract(document); + _mockConfigurationRepository.GetByLibraryAndPluginIdAsync(_libraryId, _pluginId, Arg.Any()) + .Returns(Result.From(null)); + // The resource already exists on disk, from an earlier extraction, but the enablement is read on every request, so it must not be served. + string workingDirectory = Path.Combine(ReadingCachePaths.GetRootDirectory(), _bookId.ToString("N"), "text"); + string resourceFilePath = Path.Combine(workingDirectory, "resources", "cover.png"); + Directory.CreateDirectory(Path.GetDirectoryName(resourceFilePath)!); + File.WriteAllBytes(resourceFilePath, [1, 2, 3]); + + // Act + Result result = await _sut.GetResourceAsync(_bookId, _libraryId, _bookPath, LibraryType.EBook, "cover", shouldRenderPdfAsImages: false, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.Reading.ReaderDisabled, result.FirstError); + await _mockReader.DidNotReceive().GetResourceAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()); + } + + [Fact] + public async Task GetResourceAsync_WhenEnablementCacheSaysDisabledAndResourceFileAlreadyExists_ShouldNotServeTheResource() + { + // Arrange + ReadingDocumentDto document = CreateExtractableDocument(); + StubOpenAsyncToExtract(document); + // The reader was disabled after the book was extracted, so the enablement cache already knows it; the request must be cut + // off before the already extracted resource on disk is considered, and without consulting the database again. + _enablementCache.Set(_libraryId, _pluginId, isEnabled: false); + string workingDirectory = Path.Combine(ReadingCachePaths.GetRootDirectory(), _bookId.ToString("N"), "text"); + string resourceFilePath = Path.Combine(workingDirectory, "resources", "cover.png"); + Directory.CreateDirectory(Path.GetDirectoryName(resourceFilePath)!); + File.WriteAllBytes(resourceFilePath, [1, 2, 3]); + + // Act + Result result = await _sut.GetResourceAsync(_bookId, _libraryId, _bookPath, LibraryType.EBook, "cover", shouldRenderPdfAsImages: false, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.Reading.ReaderDisabled, result.FirstError); + await _mockReader.DidNotReceive().GetResourceAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()); + await _mockConfigurationRepository.DidNotReceive().GetByLibraryAndPluginIdAsync(Arg.Any(), Arg.Any(), Arg.Any()); + } + + [Fact] + public async Task GetResourceAsync_WhenReaderThrowsWhileProducingTheResource_ShouldReturnResourceProductionFailedError() + { + // Arrange + ReadingDocumentDto document = CreateExtractableDocument(); + StubOpenAsyncToExtract(document); + _mockReader.GetResourceAsync(Arg.Any(), Arg.Any(), "cover", Arg.Any()) + .Returns(Task.FromException(new InvalidOperationException("The page renderer failed"))); + + // Act + Result result = await _sut.GetResourceAsync(_bookId, _libraryId, _bookPath, LibraryType.EBook, "cover", shouldRenderPdfAsImages: false, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal("Reading.ResourceProductionFailed", result.FirstError.Code); + await _mockReader.Received(1).GetResourceAsync(Arg.Any(), Arg.Any(), "cover", Arg.Any()); + } + + [Fact] + public async Task GetResourceAsync_WhenReaderProductionIsCancelled_ShouldPropagateTheCancellation() + { + // Arrange + ReadingDocumentDto document = CreateExtractableDocument(); + StubOpenAsyncToExtract(document); + _mockReader.GetResourceAsync(Arg.Any(), Arg.Any(), "cover", Arg.Any()) + .Returns(Task.FromException(new OperationCanceledException())); + + // Act + Task> operationTask = _sut.GetResourceAsync(_bookId, _libraryId, _bookPath, LibraryType.EBook, "cover", shouldRenderPdfAsImages: false, CancellationToken.None); + + // Assert + await Assert.ThrowsAnyAsync(() => operationTask); + } + + [Fact] + public async Task GetSectionAsync_WhenStylesArePreserved_ShouldKeepTheStyleAttributeInTheContent() + { + // Arrange + ReadingDocumentDto document = CreateExtractableDocument(); + StubOpenAsyncToExtractStyledContent(document); + CancellationToken cancellationToken = CancellationToken.None; + + // Act + Result result = await _sut.GetSectionAsync(_bookId, _libraryId, _bookPath, LibraryType.EBook, "section-1", shouldRenderPdfAsImages: false, shouldPreserveStyles: true, cancellationToken); + + // Assert + Assert.False(result.IsFailure); + Assert.Contains("style", result.Value.ContentHtml, StringComparison.OrdinalIgnoreCase); + } + + [Fact] + public async Task GetSectionAsync_WhenStylesAreNotPreserved_ShouldStripTheStyleAttributeFromTheContent() + { + // Arrange + ReadingDocumentDto document = CreateExtractableDocument(); + StubOpenAsyncToExtractStyledContent(document); + CancellationToken cancellationToken = CancellationToken.None; + + // Act + Result result = await _sut.GetSectionAsync(_bookId, _libraryId, _bookPath, LibraryType.EBook, "section-1", shouldRenderPdfAsImages: false, shouldPreserveStyles: false, cancellationToken); + + // Assert + Assert.False(result.IsFailure); + Assert.DoesNotContain("style", result.Value.ContentHtml, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("color:red", result.Value.ContentHtml, StringComparison.OrdinalIgnoreCase); + Assert.Contains("Chapter 1", result.Value.ContentHtml, StringComparison.Ordinal); + } + + [Fact] + public async Task GetManifestAsync_WhenReaderOpenThrowsFileNotFoundException_ShouldReturnBookFileNotFoundError() + { + // Arrange + _mockReader.OpenAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(Task.FromException(new FileNotFoundException("book missing"))); + + // Act + Result result = await _sut.GetManifestAsync(_bookId, _libraryId, _bookPath, LibraryType.EBook, shouldRenderPdfAsImages: false, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.Reading.BookFileNotFound, result.FirstError); + } + + [Fact] + public async Task GetManifestAsync_WhenReaderOpenThrowsDirectoryNotFoundException_ShouldReturnBookFileNotFoundError() + { + // Arrange + _mockReader.OpenAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(Task.FromException(new DirectoryNotFoundException("directory missing"))); + + // Act + Result result = await _sut.GetManifestAsync(_bookId, _libraryId, _bookPath, LibraryType.EBook, shouldRenderPdfAsImages: false, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.Reading.BookFileNotFound, result.FirstError); + } + + [Fact] + public async Task GetManifestAsync_WhenReaderOpenThrowsOtherException_ShouldReturnExtractionFailedError() + { + // Arrange + _mockReader.OpenAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(Task.FromException(new InvalidDataException("broken book"))); + + // Act + Result result = await _sut.GetManifestAsync(_bookId, _libraryId, _bookPath, LibraryType.EBook, shouldRenderPdfAsImages: false, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal("Reading.ExtractionFailed", result.FirstError.Code); + } + + [Fact] + public async Task GetManifestAsync_WhenReaderOpenIsCancelled_ShouldPropagateTheCancellation() + { + // Arrange + _mockReader.OpenAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(Task.FromException(new OperationCanceledException())); + + // Act + Task> operationTask = _sut.GetManifestAsync(_bookId, _libraryId, _bookPath, LibraryType.EBook, shouldRenderPdfAsImages: false, CancellationToken.None); + + // Assert + await Assert.ThrowsAnyAsync(() => operationTask); + } + + [Fact] + public async Task GetManifestAsync_WhenBookFileIsDeletedAfterExtraction_ShouldReExtractAndFail() + { + // Arrange + ReadingDocumentDto document = CreateExtractableDocument(); + StubOpenAsyncToExtract(document); + await _sut.GetManifestAsync(_bookId, _libraryId, _bookPath, LibraryType.EBook, shouldRenderPdfAsImages: false, CancellationToken.None); + _mockReader.OpenAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(Task.FromException(new FileNotFoundException("book missing"))); + File.Delete(_bookPath); + + // Act + Result result = await _sut.GetManifestAsync(_bookId, _libraryId, _bookPath, LibraryType.EBook, shouldRenderPdfAsImages: false, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.Reading.BookFileNotFound, result.FirstError); + await _mockReader.Received(2).OpenAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()); + } + + [Fact] + public async Task GetManifestAsync_WhenReaderMatchesExtensionCaseInsensitively_ShouldResolveIt() + { + // Arrange + string uppercaseExtensionPath = Path.Combine(Path.GetTempPath(), $"lumina-test-book-{Guid.NewGuid():N}.EPUB"); + File.WriteAllText(uppercaseExtensionPath, "test epub content"); + try + { + ReadingDocumentDto document = CreateExtractableDocument(); + StubOpenAsyncToExtract(document); + + // Act + Result result = await _sut.GetManifestAsync(_bookId, _libraryId, uppercaseExtensionPath, LibraryType.EBook, shouldRenderPdfAsImages: false, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + } + finally + { + File.Delete(uppercaseExtensionPath); + } + } + + [Fact] + public async Task GetManifestAsync_WhenReaderSupportsTheLibraryTypeButNotTheExtension_ShouldReturnNoReaderAvailableError() + { + // Arrange + string unsupportedExtensionPath = Path.Combine(Path.GetTempPath(), $"lumina-test-book-{Guid.NewGuid():N}.txt"); + File.WriteAllText(unsupportedExtensionPath, "test content"); + try + { + // Act + Result result = await _sut.GetManifestAsync(_bookId, _libraryId, unsupportedExtensionPath, LibraryType.EBook, shouldRenderPdfAsImages: false, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.Reading.NoReaderAvailable, result.FirstError); + await _mockReader.DidNotReceive().OpenAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()); + } + finally + { + File.Delete(unsupportedExtensionPath); + } + } + + [Fact] + public async Task GetManifestAsync_WhenAReaderDeclaresABlankExtension_ShouldSkipItAndStillResolveTheFormat() + { + // Arrange + ReadingDocumentDto document = CreateExtractableDocument(); + StubOpenAsyncToExtract(document); + IBookReader blankExtensionReader = Substitute.For(); + blankExtensionReader.SupportedExtensions.Returns([" "]); + blankExtensionReader.SupportedLibraryTypes.Returns([LibraryType.EBook]); + ServiceCollection services = new(); + services.AddKeyedSingleton(_pluginId, blankExtensionReader); + services.AddKeyedSingleton(_pluginId, _mockReader); + services.AddSingleton(_mockUnitOfWork); + using (ServiceProvider serviceProvider = services.BuildServiceProvider()) + { + IServiceScopeFactory serviceScopeFactory = serviceProvider.GetRequiredService(); + BookReadingService sut = new(serviceProvider, _mockPluginManager, _enablementCache, serviceScopeFactory, Substitute.For>()); + + // Act + Result result = await sut.GetManifestAsync(_bookId, _libraryId, _bookPath, LibraryType.EBook, shouldRenderPdfAsImages: false, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal(document.Title, result.Value.Title); + } + } + + [Fact] + public async Task GetResourceAsync_WhenTwoRequestsMissTheSameResourceConcurrently_ShouldProduceItOnceAndBothServeIt() + { + // Arrange + ReadingDocumentDto document = CreateExtractableDocument(); + StubOpenAsyncToExtract(document); + byte[] producedResource = [7, 8, 9]; + TaskCompletionSource productionStarted = new(); + TaskCompletionSource allowProductionToFinish = new(); + _mockReader.GetResourceAsync(Arg.Any(), Arg.Any(), "cover", Arg.Any()) + .Returns(async callInfo => + { + productionStarted.SetResult(true); + await allowProductionToFinish.Task; + return producedResource; + }); + + // Act + Task> firstTask = _sut.GetResourceAsync(_bookId, _libraryId, _bookPath, LibraryType.EBook, "cover", shouldRenderPdfAsImages: false, CancellationToken.None); + await productionStarted.Task; + Task> secondTask = _sut.GetResourceAsync(_bookId, _libraryId, _bookPath, LibraryType.EBook, "cover", shouldRenderPdfAsImages: false, CancellationToken.None); + allowProductionToFinish.SetResult(true); + Result firstResult = await firstTask; + Result secondResult = await secondTask; + + // Assert + Assert.False(firstResult.IsFailure); + Assert.False(secondResult.IsFailure); + Assert.Equal(new byte[] { 7, 8, 9 }, firstResult.Value.Data); + Assert.Equal(new byte[] { 7, 8, 9 }, secondResult.Value.Data); + await _mockReader.Received(1).GetResourceAsync(_bookPath, Arg.Any(), "cover", Arg.Any()); + } + + /// + /// Creates a reading document whose spine and resources are extractable into the working directory. + /// + /// The created reading document. + private ReadingDocumentDto CreateExtractableDocument() + { + return _readingDocumentDtoFixture.Create( + title: "Test Book", + author: "Test Author", + tableOfContents: [], + spine: + [ + _readingSpineItemDtoFixture.Create(locationRef: "section-1", title: "Chapter 1", relativeSectionFilePath: "sections/0.html") + ], + resources: new Dictionary + { + ["cover"] = _readingResourceInfoDtoFixture.Create(relativeFilePath: "resources/cover.png", mimeType: "image/png") + }, + hasTextContent: true + ); + } + + /// + /// Stubs the reader's OpenAsync to create the extractable files of the document into the working directory. + /// + /// The document returned by the extraction. + private void StubOpenAsyncToExtract(ReadingDocumentDto document) + { + _mockReader.OpenAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(callInfo => + { + string workingDirectory = callInfo.ArgAt(1); + Directory.CreateDirectory(Path.Combine(workingDirectory, "sections")); + File.WriteAllText(Path.Combine(workingDirectory, "sections", "0.html"), "

Chapter 1

Some text.

"); + return Task.FromResult(document); + }); + } + + /// + /// Stubs the reader's OpenAsync to create a section whose content carries a style attribute, so that the sanitization + /// preference of the service is observable. + /// + /// The document returned by the extraction. + private void StubOpenAsyncToExtractStyledContent(ReadingDocumentDto document) + { + _mockReader.OpenAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(callInfo => + { + string workingDirectory = callInfo.ArgAt(1); + Directory.CreateDirectory(Path.Combine(workingDirectory, "sections")); + File.WriteAllText(Path.Combine(workingDirectory, "sections", "0.html"), "

Chapter 1

Some text.

"); + return Task.FromResult(document); + }); + } + + /// + public void Dispose() + { + if (Directory.Exists(ReadingCachePaths.GetRootDirectory())) + Directory.Delete(ReadingCachePaths.GetRootDirectory(), recursive: true); + if (File.Exists(_bookPath)) + File.Delete(_bookPath); + (_serviceProvider as IDisposable)?.Dispose(); + } + + /// + /// In-memory test double for the used by the service under test. + /// + [ExcludeFromCodeCoverage] + private sealed class TestBookReaderEnablementCache : IBookReaderEnablementCache + { + private readonly Dictionary<(Guid LibraryId, Guid PluginId), bool> _enablements = []; + + /// + public bool? Get(Guid libraryId, Guid pluginId) + { + return _enablements.TryGetValue((libraryId, pluginId), out bool isEnabled) ? isEnabled : null; + } + + /// + public void Set(Guid libraryId, Guid pluginId, bool isEnabled) + { + _enablements[(libraryId, pluginId)] = isEnabled; + } + + /// + public void Invalidate(Guid libraryId, Guid pluginId) + { + _enablements.Remove((libraryId, pluginId)); + } + + /// + public void InvalidateLibrary(Guid libraryId) + { + foreach (Guid cachedPluginId in _enablements.Keys.Where(cachedPair => cachedPair.LibraryId == libraryId).Select(cachedPair => cachedPair.PluginId).ToList()) + _enablements.Remove((libraryId, cachedPluginId)); + } + + /// + public void InvalidatePlugin(Guid pluginId) + { + foreach (Guid cachedLibraryId in _enablements.Keys.Where(cachedPair => cachedPair.PluginId == pluginId).Select(cachedPair => cachedPair.LibraryId).ToList()) + _enablements.Remove((cachedLibraryId, pluginId)); + } + } +} diff --git a/tests/IntegrationTests/Lumina.Infrastructure.IntegrationTests/Core/Plugins/PluginInstallerTests.cs b/tests/IntegrationTests/Lumina.Infrastructure.IntegrationTests/Core/Plugins/PluginInstallerTests.cs new file mode 100644 index 00000000..d28c1c94 --- /dev/null +++ b/tests/IntegrationTests/Lumina.Infrastructure.IntegrationTests/Core/Plugins/PluginInstallerTests.cs @@ -0,0 +1,159 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.Infrastructure.Models.DTO.Configuration; +using Lumina.Domain.Common.Errors; +using Lumina.Domain.Common.Primitives; +using Lumina.Infrastructure.Core.Plugins; +using Lumina.Infrastructure.Fixtures.Common.Models.DTO.Configuration; +using Microsoft.Extensions.Logging; +using Microsoft.Extensions.Options; +using NSubstitute; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.IO; +using System.IO.Compression; +using System.Text; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Infrastructure.IntegrationTests.Core.Plugins; + +/// +/// Contains integration tests for the class. +/// +[ExcludeFromCodeCoverage] +public class PluginInstallerTests : IDisposable +{ + private readonly string _pluginsDirectory; + private readonly PluginInstaller _sut; + private readonly PluginsSettingsDtoFixture _pluginsSettingsDtoFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + public PluginInstallerTests() + { + _pluginsDirectory = Path.Combine(AppContext.BaseDirectory, $".test-plugins-{Guid.NewGuid():N}"); + ILogger mockLogger = Substitute.For>(); + IOptions mockOptions = Substitute.For>(); + mockOptions.Value.Returns(_pluginsSettingsDtoFixture.Create(directory: Path.GetFileName(_pluginsDirectory))); + _sut = new PluginInstaller(mockOptions, mockLogger); + } + + [Fact] + public async Task InstallAsync_WhenUploadingSingleAssembly_ShouldCopyAssemblyToPluginsDirectory() + { + // Arrange + string assemblyName = "Lumina.TestPlugin.dll"; + await using FileStream stream = File.OpenRead(Path.Combine(AppContext.BaseDirectory, assemblyName)); + + // Act + Result result = await _sut.InstallAsync(stream, assemblyName, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + Assert.True(File.Exists(Path.Combine(_pluginsDirectory, assemblyName))); + } + + [Fact] + public async Task InstallAsync_WhenUploadingZipWithAssemblies_ShouldExtractAssembliesFlattenedToPluginsDirectory() + { + // Arrange + await using MemoryStream zipStream = new(); + CreateZipArchive(zipStream, [("nested/plugin/Lumina.TestPlugin.dll", ReadTestAssembly()), ("readme.txt", Encoding.UTF8.GetBytes("not an assembly"))]); + zipStream.Position = 0; + + // Act + Result result = await _sut.InstallAsync(zipStream, "plugin.zip", CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + Assert.True(File.Exists(Path.Combine(_pluginsDirectory, "Lumina.TestPlugin.dll"))); + Assert.False(File.Exists(Path.Combine(_pluginsDirectory, "readme.txt"))); + } + + [Fact] + public async Task InstallAsync_WhenUploadingZipWithBackslashTraversalEntry_ShouldFlattenItInsidePluginsDirectory() + { + // Arrange + await using MemoryStream zipStream = new(); + // A backslash is not a directory separator on non-Windows platforms, so it must be neutralized explicitly. + CreateZipArchive(zipStream, [(@"..\evil.dll", ReadTestAssembly())]); + zipStream.Position = 0; + + // Act + Result result = await _sut.InstallAsync(zipStream, "plugin.zip", CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + Assert.True(File.Exists(Path.Combine(_pluginsDirectory, "evil.dll"))); + Assert.False(File.Exists(Path.Combine(AppContext.BaseDirectory, "evil.dll"))); + } + + [Fact] + public async Task InstallAsync_WhenUploadingSingleAssemblyWithTraversalFileName_ShouldFlattenItInsidePluginsDirectory() + { + // Arrange + const string TRAVERSAL_FILE_NAME = "traversal-test-plugin.dll"; + await using FileStream stream = File.OpenRead(Path.Combine(AppContext.BaseDirectory, "Lumina.TestPlugin.dll")); + + // Act + Result result = await _sut.InstallAsync(stream, $@"..\{TRAVERSAL_FILE_NAME}", CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + Assert.True(File.Exists(Path.Combine(_pluginsDirectory, TRAVERSAL_FILE_NAME))); + Assert.False(File.Exists(Path.Combine(AppContext.BaseDirectory, TRAVERSAL_FILE_NAME))); + } + + [Fact] + public async Task InstallAsync_WhenUploadingZipWithoutAssemblies_ShouldReturnError() + { + // Arrange + await using MemoryStream zipStream = new(); + CreateZipArchive(zipStream, [("readme.txt", Encoding.UTF8.GetBytes("not an assembly"))]); + zipStream.Position = 0; + + // Act + Result result = await _sut.InstallAsync(zipStream, "plugin.zip", CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.Plugins.PluginArchiveContainsNoAssemblies, result.FirstError); + } + + /// + /// Deletes the temporary plugins directory created by the tests. + /// + public void Dispose() + { + if (Directory.Exists(_pluginsDirectory)) + Directory.Delete(_pluginsDirectory, recursive: true); + } + + /// + /// Creates an in-memory ZIP archive containing the provided entries. + /// + /// The stream to write the archive into. + /// The entries to add, as pairs of entry name and content. + private static void CreateZipArchive(MemoryStream zipStream, IEnumerable<(string Name, byte[] Content)> entries) + { + using ZipArchive zipArchive = new(zipStream, ZipArchiveMode.Create, leaveOpen: true); + foreach ((string name, byte[] content) in entries) + { + ZipArchiveEntry entry = zipArchive.CreateEntry(name); + using Stream entryStream = entry.Open(); + entryStream.Write(content); + } + } + + /// + /// Reads the bytes of the Lumina.TestPlugin.dll assembly from the test output directory. + /// + /// The assembly bytes. + private static byte[] ReadTestAssembly() + { + return File.ReadAllBytes(Path.Combine(AppContext.BaseDirectory, "Lumina.TestPlugin.dll")); + } +} diff --git a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Plugins/PluginLoadContextTests.cs b/tests/IntegrationTests/Lumina.Infrastructure.IntegrationTests/Core/Plugins/PluginLoadContextTests.cs similarity index 91% rename from tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Plugins/PluginLoadContextTests.cs rename to tests/IntegrationTests/Lumina.Infrastructure.IntegrationTests/Core/Plugins/PluginLoadContextTests.cs index 4a1d9810..4f46a6e2 100644 --- a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Plugins/PluginLoadContextTests.cs +++ b/tests/IntegrationTests/Lumina.Infrastructure.IntegrationTests/Core/Plugins/PluginLoadContextTests.cs @@ -6,10 +6,10 @@ using System.IO; using System.Reflection; #endregion -namespace Lumina.Infrastructure.UnitTests.Core.Plugins; +namespace Lumina.Infrastructure.IntegrationTests.Core.Plugins; /// -/// Contains unit tests for the class. +/// Contains integration tests for the class. /// [ExcludeFromCodeCoverage] public class PluginLoadContextTests @@ -93,11 +93,11 @@ public class PluginLoadContextTests } catch (IOException) { - // best effort cleanup of the temporary plugins directory + // Best effort cleanup of the temporary plugins directory. } catch (UnauthorizedAccessException) { - // the plugin assemblies are still locked by their load contexts, best effort cleanup only + // 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/IntegrationTests/Lumina.Infrastructure.IntegrationTests/Core/Plugins/PluginLoaderTests.cs similarity index 97% rename from tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Plugins/PluginLoaderTests.cs rename to tests/IntegrationTests/Lumina.Infrastructure.IntegrationTests/Core/Plugins/PluginLoaderTests.cs index 840be123..3dd45486 100644 --- a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Plugins/PluginLoaderTests.cs +++ b/tests/IntegrationTests/Lumina.Infrastructure.IntegrationTests/Core/Plugins/PluginLoaderTests.cs @@ -9,10 +9,10 @@ using System.IO; using System.Linq; #endregion -namespace Lumina.Infrastructure.UnitTests.Core.Plugins; +namespace Lumina.Infrastructure.IntegrationTests.Core.Plugins; /// -/// Contains unit tests for the class. +/// Contains integration tests for the class. /// [ExcludeFromCodeCoverage] public class PluginLoaderTests @@ -266,11 +266,11 @@ public class PluginLoaderTests } catch (IOException) { - // best effort cleanup of the temporary plugins directory + // Best effort cleanup of the temporary plugins directory. } catch (UnauthorizedAccessException) { - // the plugin assemblies are still locked by their load contexts, best effort cleanup only + // 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/Security/FileHashServiceTests.cs b/tests/IntegrationTests/Lumina.Infrastructure.IntegrationTests/Core/Security/FileHashServiceTests.cs similarity index 79% rename from tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Security/FileHashServiceTests.cs rename to tests/IntegrationTests/Lumina.Infrastructure.IntegrationTests/Core/Security/FileHashServiceTests.cs index 0b32baa0..bdd99113 100644 --- a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Security/FileHashServiceTests.cs +++ b/tests/IntegrationTests/Lumina.Infrastructure.IntegrationTests/Core/Security/FileHashServiceTests.cs @@ -12,10 +12,10 @@ using System.Threading; using System.Threading.Tasks; #endregion -namespace Lumina.Infrastructure.UnitTests.Core.Security; +namespace Lumina.Infrastructure.IntegrationTests.Core.Security; /// -/// Contains unit tests for the class. +/// Contains integration tests for the class. /// [ExcludeFromCodeCoverage] public class FileHashServiceTests @@ -51,7 +51,7 @@ public class FileHashServiceTests 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 + // 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)); @@ -144,6 +144,52 @@ public class FileHashServiceTests await Assert.ThrowsAnyAsync(() => operation); } + [Fact] + public void ComputeFileHash_WhenFileIsEmpty_ShouldReturnEmptyFileHash() + { + // Arrange + using TemporaryTestDirectory temporaryTestDirectory = new(); + string filePath = temporaryTestDirectory.CreateFile("empty.pdf", string.Empty); + + // Act + ulong hash = _sut.ComputeFileHash(filePath); + + // Assert + Assert.Equal(BitConverter.ToUInt64(new XxHash64().GetCurrentHash()), hash); + } + + [Fact] + public void ComputeFileHash_WhenFileHasContent_ShouldReturnNonZeroHash() + { + // Arrange + using TemporaryTestDirectory temporaryTestDirectory = new(); + string filePath = temporaryTestDirectory.CreateFile("book.pdf", "content of the book"); + + // Act + ulong hash = _sut.ComputeFileHash(filePath); + + // Assert + Assert.NotEqual(0UL, hash); + } + + [Fact] + public async Task HashFilesAsync_WhenFileIsLargerThanTheSamplingThreshold_ShouldSampleTheWholeFile() + { + // Arrange + using TemporaryTestDirectory temporaryTestDirectory = new(); + string filePath = Path.Combine(temporaryTestDirectory.Path, "large.pdf"); + File.WriteAllBytes(filePath, new byte[500_000]); + 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.NotEqual(0UL, hashedFile.CurrentHash); + } + /// /// Test helper managing a temporary directory, deleted when the test finishes. /// @@ -176,7 +222,7 @@ public class FileHashServiceTests } catch (IOException) { - // best effort cleanup of the temporary test directory + // Best effort cleanup of the temporary test directory. } _disposed = true; } diff --git a/tests/IntegrationTests/Lumina.Infrastructure.IntegrationTests/Core/Themes/ThemeServiceTests.cs b/tests/IntegrationTests/Lumina.Infrastructure.IntegrationTests/Core/Themes/ThemeServiceTests.cs new file mode 100644 index 00000000..f8607f53 --- /dev/null +++ b/tests/IntegrationTests/Lumina.Infrastructure.IntegrationTests/Core/Themes/ThemeServiceTests.cs @@ -0,0 +1,1455 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.Infrastructure.Models.DTO.Themes; +using Lumina.Domain.Common.Errors; +using Lumina.Domain.Common.Primitives; +using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Services; +using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.ValueObjects; +using Lumina.Infrastructure.Common.Models.DTO.Configuration; +using Lumina.Infrastructure.Core.Themes; +using Lumina.Infrastructure.Fixtures.Common.Models.DTO.Configuration; +using Lumina.Infrastructure.Fixtures.Core.Themes; +using Microsoft.Extensions.Logging; +using Microsoft.Extensions.Options; +using NSubstitute; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.IO; +using System.IO.Compression; +using System.Linq; +using System.Text; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Infrastructure.IntegrationTests.Core.Themes; + +/// +/// Contains integration tests for the class. +/// +[ExcludeFromCodeCoverage] +public class ThemeServiceTests : IDisposable +{ + private const string DEFAULT_TEMPLATE = "default template"; + private const string HOME_TEMPLATE = "home template"; + private const string LIBRARY_TEMPLATE = "library template"; + + private readonly string _testRootPath; + private readonly ThemeEngineOptionsDto _options; + private readonly ThemeService _sut; + private readonly ThemePackFixture _themePackFixture = new(); + private readonly ThemeEngineOptionsDtoFixture _themeEngineOptionsDtoFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + public ThemeServiceTests() + { + _testRootPath = Path.Combine(Path.GetTempPath(), $"lumina-themes-{Guid.NewGuid():N}"); + Directory.CreateDirectory(_testRootPath); + _options = _themeEngineOptionsDtoFixture.Create( + storagePath: Path.Combine(_testRootPath, "themes"), + bundledThemesPath: Path.Combine(_testRootPath, "bundled"), + defaultThemeId: "lumina-default", + maxArchiveBytes: 8 * 1024 * 1024, + maxExpandedBytes: 24 * 1024 * 1024, + maxSingleFileBytes: 6 * 1024 * 1024, + maxEntries: 250); + _sut = CreateSut(_options); + } + + [Fact] + public void GetBundledThemeArchivePaths_WhenBundledDirectoryDoesNotExist_ShouldReturnEmptyList() + { + // Arrange + // The bundled directory of the default options never exists. + + // Act + IReadOnlyList result = _sut.GetBundledThemeArchivePaths(); + + // Assert + Assert.Empty(result); + } + + [Fact] + public void GetBundledThemeArchivePaths_WhenBundledDirectoryContainsZips_ShouldReturnSortedZipPaths() + { + // Arrange + string bundledPath = Path.Combine(_testRootPath, "bundled"); + Directory.CreateDirectory(bundledPath); + File.WriteAllBytes(Path.Combine(bundledPath, "zeta.zip"), _themePackFixture.Create()); + File.WriteAllBytes(Path.Combine(bundledPath, "alpha.zip"), _themePackFixture.Create()); + File.WriteAllBytes(Path.Combine(bundledPath, "notes.txt"), Encoding.UTF8.GetBytes("not a theme archive")); + + // Act + IReadOnlyList result = _sut.GetBundledThemeArchivePaths(); + + // Assert + Assert.Equal(2, result.Count); + Assert.Equal(Path.Combine(bundledPath, "alpha.zip"), result[0]); + Assert.Equal(Path.Combine(bundledPath, "zeta.zip"), result[1]); + } + + [Fact] + public async Task HasThemePack_WhenThemeIsInstalled_ShouldReturnTrue() + { + // Arrange + await InstallValidThemeAsync(_themePackFixture.Create()); + + // Act + bool result = _sut.HasThemePack("test-theme"); + + // Assert + Assert.True(result); + } + + [Fact] + public void HasThemePack_WhenThemeIsNotInstalled_ShouldReturnFalse() + { + // Arrange + // nothing is installed + + // Act + bool result = _sut.HasThemePack("test-theme"); + + // Assert + Assert.False(result); + } + + [Fact] + public void HasThemePack_WhenThemeDirectoryExistsButManifestIsMissing_ShouldReturnFalse() + { + // Arrange + Directory.CreateDirectory(Path.Combine(_options.StoragePath, "test-theme")); + + // Act + bool result = _sut.HasThemePack("test-theme"); + + // Assert + Assert.False(result); + } + + [Fact] + public async Task InstallAsync_WhenArchiveIsValid_ShouldExtractThemeAndReturnManifest() + { + // Arrange + byte[] archive = _themePackFixture.Create(defaultTemplateContent: DEFAULT_TEMPLATE); + + // Act + Result result = await _sut.InstallAsync(new MemoryStream(archive), CancellationToken.None); + + // Assert + Assert.True(result.IsSuccess); + Assert.Equal("test-theme", result.Value.Id); + Assert.Equal("Test Theme", result.Value.Name); + Assert.True(File.Exists(Path.Combine(_options.StoragePath, "test-theme", "theme.json"))); + Assert.True(File.Exists(Path.Combine(_options.StoragePath, "test-theme", "templates", "default.html"))); + Assert.True(File.Exists(Path.Combine(_options.StoragePath, "test-theme", "assets", "preview.png"))); + } + + [Fact] + public async Task InstallAsync_WhenThemeIsAlreadyInstalled_ShouldReplaceExistingThemeFiles() + { + // Arrange + byte[] firstArchive = _themePackFixture.Create(defaultTemplateContent: "first version"); + byte[] secondArchive = _themePackFixture.Create(defaultTemplateContent: "second version"); + + // Act + await InstallValidThemeAsync(firstArchive); + await InstallValidThemeAsync(secondArchive); + Result templateResult = await _sut.GetTemplateAsync("test-theme", "default", CancellationToken.None); + + // Assert + Assert.True(templateResult.IsSuccess); + Assert.Equal("second version", templateResult.Value); + string[] themeDirectories = [.. Directory.GetDirectories(_options.StoragePath).Where(path => Path.GetFileName(path) != ".staging")]; + Assert.Single(themeDirectories); + Assert.Equal("test-theme", Path.GetFileName(themeDirectories[0])); + } + + [Fact] + public async Task InstallAsync_WhenThemeDestinationIsBlocked_ShouldReturnThemeFilesUnreadableInsteadOfThrowing() + { + // Arrange + byte[] archive = _themePackFixture.Create(themeId: "test-theme"); + // The destination path is blocked by an existing file, so the extracted pack cannot be moved into place. + Directory.CreateDirectory(_options.StoragePath); + File.WriteAllText(Path.Combine(_options.StoragePath, "test-theme"), "blocked"); + + // Act + Result result = await _sut.InstallAsync(new MemoryStream(archive), CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal("ThemeFilesUnreadable", result.FirstError.Description); + } + + [Fact] + public async Task InstallAsync_WhenArchiveExceedsMaxArchiveBytes_ShouldReturnArchiveTooLargeError() + { + // Arrange + ThemeEngineOptionsDto options = _themeEngineOptionsDtoFixture.Create( + storagePath: Path.Combine(_testRootPath, "themes"), + bundledThemesPath: Path.Combine(_testRootPath, "bundled"), + defaultThemeId: "lumina-default", + maxArchiveBytes: 8 * 1024 * 1024, + maxExpandedBytes: 24 * 1024 * 1024, + maxSingleFileBytes: 6 * 1024 * 1024, + maxEntries: 250); + options.MaxArchiveBytes = 128; + ThemeService sut = CreateSut(options); + byte[] archive = _themePackFixture.Create(); + + // Act + Result result = await sut.InstallAsync(new MemoryStream(archive), CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal("Theme.Archive.TooLarge", result.FirstError.Code); + Assert.False(sut.HasThemePack("test-theme")); + } + + [Fact] + public async Task InstallAsync_WhenArchiveStreamIsEmpty_ShouldReturnPackageInvalidError() + { + // Arrange + using MemoryStream emptyStream = new(); + + // Act + Result result = await _sut.InstallAsync(emptyStream, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal("Theme.Package.Invalid", result.FirstError.Code); + Assert.Contains("empty", result.FirstError.Description); + } + + [Fact] + public async Task InstallAsync_WhenArchiveContainsNoEntries_ShouldReturnPackageInvalidError() + { + // Arrange + byte[] archive = _themePackFixture.CreateArchive(); + + // Act + Result result = await _sut.InstallAsync(new MemoryStream(archive), CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal("Theme.Package.Invalid", result.FirstError.Code); + Assert.Contains("no files", result.FirstError.Description); + } + + [Fact] + public async Task InstallAsync_WhenArchiveIsNotAZip_ShouldReturnThemeArchiveNotReadable() + { + // Arrange + byte[] archive = Encoding.UTF8.GetBytes("this is not a valid zip archive"); + + // Act + Result result = await _sut.InstallAsync(new MemoryStream(archive), CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal("ThemeArchiveNotReadable", result.FirstError.Description); + Assert.False(_sut.HasThemePack("test-theme")); + } + + [Fact] + public async Task InstallAsync_WhenArchiveContainsPathTraversalEntry_ShouldReturnPackageInvalidError() + { + // Arrange + string manifestJson = _themePackFixture.CreateManifestJson(); + byte[] archive = _themePackFixture.CreateArchive( + new("theme.json", manifestJson), + new("templates/default.html", DEFAULT_TEMPLATE), + new("../evil.txt", "should not escape the package")); + + // Act + Result result = await _sut.InstallAsync(new MemoryStream(archive), CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal("Theme.Package.Invalid", result.FirstError.Code); + Assert.False(_sut.HasThemePack("test-theme")); + } + + [Fact] + public async Task InstallAsync_WhenArchiveContainsBackslashPathEntry_ShouldReturnPackageInvalidError() + { + // Arrange + string manifestJson = _themePackFixture.CreateManifestJson(); + byte[] archive = _themePackFixture.CreateArchive( + new("theme.json", manifestJson), + new("templates/default.html", DEFAULT_TEMPLATE), + new("assets\\..\\evil.txt", "should not escape the package")); + + // Act + Result result = await _sut.InstallAsync(new MemoryStream(archive), CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal("Theme.Package.Invalid", result.FirstError.Code); + } + + [Fact] + public async Task InstallAsync_WhenArchiveEntryIsOutsideAllowedLocations_ShouldReturnPackageInvalidError() + { + // Arrange + string manifestJson = _themePackFixture.CreateManifestJson(); + byte[] archive = _themePackFixture.CreateArchive( + new("theme.json", manifestJson), + new("templates/default.html", DEFAULT_TEMPLATE), + new("notes/readme.txt", "files must live under templates or assets")); + + // Act + Result result = await _sut.InstallAsync(new MemoryStream(archive), CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal("Theme.Package.Invalid", result.FirstError.Code); + Assert.Contains("outside the allowed", result.FirstError.Description); + } + + [Fact] + public async Task InstallAsync_WhenArchiveContainsSymbolicLinkEntry_ShouldReturnPackageInvalidError() + { + // Arrange + string manifestJson = _themePackFixture.CreateManifestJson(); + byte[] archive = _themePackFixture.CreateArchive( + new("theme.json", manifestJson), + new("templates/default.html", DEFAULT_TEMPLATE), + new("assets/link.png", "symlink target", UnixFileType: 0xA000)); + + // Act + Result result = await _sut.InstallAsync(new MemoryStream(archive), CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal("Theme.Package.Invalid", result.FirstError.Code); + Assert.Contains("Symbolic links", result.FirstError.Description); + } + + [Fact] + public async Task InstallAsync_WhenArchiveContainsDuplicateEntryPaths_ShouldReturnPackageInvalidError() + { + // Arrange + string manifestJson = _themePackFixture.CreateManifestJson(); + byte[] archive = _themePackFixture.CreateArchive( + new("theme.json", manifestJson), + new("templates/default.html", DEFAULT_TEMPLATE), + new("templates/default.html", "duplicate")); + + // Act + Result result = await _sut.InstallAsync(new MemoryStream(archive), CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal("Theme.Package.Invalid", result.FirstError.Code); + Assert.Contains("duplicate path", result.FirstError.Description); + } + + [Fact] + public async Task InstallAsync_WhenArchiveExceedsMaxEntries_ShouldReturnTooManyEntriesError() + { + // Arrange + ThemeEngineOptionsDto options = _themeEngineOptionsDtoFixture.Create( + storagePath: Path.Combine(_testRootPath, "themes"), + bundledThemesPath: Path.Combine(_testRootPath, "bundled"), + defaultThemeId: "lumina-default", + maxArchiveBytes: 8 * 1024 * 1024, + maxExpandedBytes: 24 * 1024 * 1024, + maxSingleFileBytes: 6 * 1024 * 1024, + maxEntries: 250); + options.MaxEntries = 2; + ThemeService sut = CreateSut(options); + byte[] archive = _themePackFixture.Create(); + + // Act + Result result = await sut.InstallAsync(new MemoryStream(archive), CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal("Theme.Archive.TooManyEntries", result.FirstError.Code); + } + + [Fact] + public async Task InstallAsync_WhenArchiveFileExceedsMaxSingleFileBytes_ShouldReturnFileTooLargeError() + { + // Arrange + ThemeEngineOptionsDto options = _themeEngineOptionsDtoFixture.Create( + storagePath: Path.Combine(_testRootPath, "themes"), + bundledThemesPath: Path.Combine(_testRootPath, "bundled"), + defaultThemeId: "lumina-default", + maxArchiveBytes: 8 * 1024 * 1024, + maxExpandedBytes: 24 * 1024 * 1024, + maxSingleFileBytes: 6 * 1024 * 1024, + maxEntries: 250); + options.MaxSingleFileBytes = 10; + ThemeService sut = CreateSut(options); + string manifestJson = _themePackFixture.CreateManifestJson(); + byte[] archive = _themePackFixture.CreateArchive( + new("theme.json", manifestJson), + new("templates/default.html", new string('a', 64))); + + // Act + Result result = await sut.InstallAsync(new MemoryStream(archive), CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal("Theme.File.TooLarge", result.FirstError.Code); + } + + [Fact] + public async Task InstallAsync_WhenExpandedSizeExceedsMaxExpandedBytes_ShouldReturnExpandedTooLargeError() + { + // Arrange + ThemeEngineOptionsDto options = _themeEngineOptionsDtoFixture.Create( + storagePath: Path.Combine(_testRootPath, "themes"), + bundledThemesPath: Path.Combine(_testRootPath, "bundled"), + defaultThemeId: "lumina-default", + maxArchiveBytes: 8 * 1024 * 1024, + maxExpandedBytes: 24 * 1024 * 1024, + maxSingleFileBytes: 6 * 1024 * 1024, + maxEntries: 250); + options.MaxSingleFileBytes = 400; + options.MaxExpandedBytes = 300; + ThemeService sut = CreateSut(options); + byte[] archive = _themePackFixture.CreateArchive( + new("templates/default.html", new string('a', 200)), + new("templates/other.html", new string('b', 200))); + + // Act + Result result = await sut.InstallAsync(new MemoryStream(archive), CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal("Theme.Archive.ExpandedTooLarge", result.FirstError.Code); + } + + [Fact] + public async Task InstallAsync_WhenSchemaVersionIsUnsupported_ShouldReturnPackageInvalidError() + { + // Arrange + byte[] archive = _themePackFixture.Create(schemaVersion: 2); + + // Act + Result result = await _sut.InstallAsync(new MemoryStream(archive), CancellationToken.None); + + // Assert + AssertPackageInvalid(result, "schemaVersion"); + } + + [Fact] + public async Task InstallAsync_WhenThemeIdIsNotKebabCase_ShouldReturnPackageInvalidError() + { + // Arrange + byte[] archive = _themePackFixture.Create(themeId: "Test_Theme"); + + // Act + Result result = await _sut.InstallAsync(new MemoryStream(archive), CancellationToken.None); + + // Assert + AssertPackageInvalid(result, "kebab-case"); + } + + [Fact] + public async Task InstallAsync_WhenThemeIdIsTooLong_ShouldReturnPackageInvalidError() + { + // Arrange + string longThemeId = string.Join('-', Enumerable.Repeat("a", 33)); + byte[] archive = _themePackFixture.Create(themeId: longThemeId); + + // Act + Result result = await _sut.InstallAsync(new MemoryStream(archive), CancellationToken.None); + + // Assert + AssertPackageInvalid(result, "kebab-case"); + } + + [Fact] + public async Task InstallAsync_WhenNameIsMissing_ShouldReturnPackageInvalidError() + { + // Arrange + byte[] archive = _themePackFixture.Create(name: string.Empty); + + // Act + Result result = await _sut.InstallAsync(new MemoryStream(archive), CancellationToken.None); + + // Assert + AssertPackageInvalid(result, "name"); + } + + [Fact] + public async Task InstallAsync_WhenDescriptionIsMissing_ShouldReturnPackageInvalidError() + { + // Arrange + byte[] archive = _themePackFixture.Create(description: string.Empty); + + // Act + Result result = await _sut.InstallAsync(new MemoryStream(archive), CancellationToken.None); + + // Assert + AssertPackageInvalid(result, "description"); + } + + [Fact] + public async Task InstallAsync_WhenAuthorIsMissing_ShouldReturnPackageInvalidError() + { + // Arrange + byte[] archive = _themePackFixture.Create(author: string.Empty); + + // Act + Result result = await _sut.InstallAsync(new MemoryStream(archive), CancellationToken.None); + + // Assert + AssertPackageInvalid(result, "author"); + } + + [Fact] + public async Task InstallAsync_WhenVersionIsMissing_ShouldReturnPackageInvalidError() + { + // Arrange + byte[] archive = _themePackFixture.Create(version: string.Empty); + + // Act + Result result = await _sut.InstallAsync(new MemoryStream(archive), CancellationToken.None); + + // Assert + AssertPackageInvalid(result, "version"); + } + + [Fact] + public async Task InstallAsync_WhenVersionIsNotSemanticVersion_ShouldReturnPackageInvalidError() + { + // Arrange + byte[] archive = _themePackFixture.Create(version: "1.0"); + + // Act + Result result = await _sut.InstallAsync(new MemoryStream(archive), CancellationToken.None); + + // Assert + AssertPackageInvalid(result, "semantic version"); + } + + [Fact] + public async Task InstallAsync_WhenManifestDeclaresNoTemplates_ShouldInstallSuccessfully() + { + // Arrange + byte[] archive = _themePackFixture.Create(templates: new Dictionary(StringComparer.OrdinalIgnoreCase)); + + // Act + Result result = await _sut.InstallAsync(new MemoryStream(archive), CancellationToken.None); + + // Assert + Assert.True(result.IsSuccess); + } + + [Fact] + public async Task InstallAsync_WhenManifestDeclaresTooManyTemplates_ShouldReturnPackageInvalidError() + { + // Arrange + Dictionary manyTemplates = new(StringComparer.OrdinalIgnoreCase); + for (int index = 0; index < 33; index++) + manyTemplates[$"template-{index}"] = $"templates/template-{index}.html"; + byte[] archive = _themePackFixture.Create(templates: manyTemplates); + + // Act + Result result = await _sut.InstallAsync(new MemoryStream(archive), CancellationToken.None); + + // Assert + AssertPackageInvalid(result, "at most 32"); + } + + [Fact] + public async Task InstallAsync_WhenTemplateKeyIsInvalid_ShouldReturnPackageInvalidError() + { + // Arrange + Dictionary templates = new(StringComparer.OrdinalIgnoreCase) + { + ["default"] = "templates/default.html", + ["Bad Key"] = "templates/bad-key.html" + }; + byte[] archive = _themePackFixture.Create(templates: templates); + + // Act + Result result = await _sut.InstallAsync(new MemoryStream(archive), CancellationToken.None); + + // Assert + AssertPackageInvalid(result, "Template key"); + } + + [Fact] + public async Task InstallAsync_WhenTemplatePathIsOutsideTemplatesDirectory_ShouldReturnPackageInvalidError() + { + // Arrange + string manifestJson = _themePackFixture.CreateManifestJson(templates: new Dictionary(StringComparer.OrdinalIgnoreCase) + { + ["default"] = "assets/not-a-template.html" + }); + byte[] archive = _themePackFixture.CreateArchive( + new("theme.json", manifestJson), + new("assets/not-a-template.html", DEFAULT_TEMPLATE)); + + // Act + Result result = await _sut.InstallAsync(new MemoryStream(archive), CancellationToken.None); + + // Assert + AssertPackageInvalid(result, "under templates"); + } + + [Fact] + public async Task InstallAsync_WhenTemplateFileIsMissing_ShouldReturnPackageInvalidError() + { + // Arrange + string manifestJson = _themePackFixture.CreateManifestJson(templates: new Dictionary(StringComparer.OrdinalIgnoreCase) + { + ["default"] = "templates/missing.html" + }); + byte[] archive = _themePackFixture.CreateArchive(new ThemeArchiveEntry("theme.json", manifestJson)); + + // Act + Result result = await _sut.InstallAsync(new MemoryStream(archive), CancellationToken.None); + + // Assert + AssertPackageInvalid(result, "missing file"); + } + + [Fact] + public async Task InstallAsync_WhenManifestLacksDefaultTemplate_ShouldInstallSuccessfully() + { + // Arrange + Dictionary templates = new(StringComparer.OrdinalIgnoreCase) + { + ["home"] = "templates/home.html" + }; + byte[] archive = _themePackFixture.Create(templates: templates); + + // Act + Result result = await _sut.InstallAsync(new MemoryStream(archive), CancellationToken.None); + + // Assert + Assert.True(result.IsSuccess); + } + + [Fact] + public async Task InstallAsync_WhenPreviewIsOutsideAssetsDirectory_ShouldReturnPackageInvalidError() + { + // Arrange + byte[] archive = _themePackFixture.Create(preview: "templates/default.html"); + + // Act + Result result = await _sut.InstallAsync(new MemoryStream(archive), CancellationToken.None); + + // Assert + AssertPackageInvalid(result, "preview"); + } + + [Fact] + public async Task InstallAsync_WhenPreviewFileIsMissing_ShouldReturnPackageInvalidError() + { + // Arrange + byte[] archive = _themePackFixture.Create(preview: "assets/missing.png", includePreviewAsset: false); + + // Act + Result result = await _sut.InstallAsync(new MemoryStream(archive), CancellationToken.None); + + // Assert + AssertPackageInvalid(result, "preview"); + } + + [Fact] + public async Task InstallAsync_WhenManifestIsNotValidJson_ShouldReturnInvalidJsonError() + { + // Arrange + byte[] archive = _themePackFixture.CreateArchive(new ThemeArchiveEntry("theme.json", "this is not json")); + + // Act + Result result = await _sut.InstallAsync(new MemoryStream(archive), CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal("Theme.Manifest.InvalidJson", result.FirstError.Code); + } + + [Fact] + public async Task InstallAsync_WhenManifestExceedsMaximumSize_ShouldReturnManifestTooLargeError() + { + // Arrange + byte[] archive = _themePackFixture.Create(description: new string('a', 70 * 1024)); + + // Act + Result result = await _sut.InstallAsync(new MemoryStream(archive), CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal("Theme.Manifest.TooLarge", result.FirstError.Code); + } + + [Fact] + public async Task ReadManifestFromArchiveAsync_WhenArchiveIsValid_ShouldReturnManifest() + { + // Arrange + string archivePath = Path.Combine(_testRootPath, "valid-theme.zip"); + File.WriteAllBytes(archivePath, _themePackFixture.Create(themeId: "manifest-theme")); + + // Act + Result result = await _sut.ReadManifestFromArchiveAsync(archivePath, CancellationToken.None); + + // Assert + Assert.True(result.IsSuccess); + Assert.Equal("manifest-theme", result.Value.Id); + } + + [Fact] + public async Task ReadManifestFromArchiveAsync_WhenManifestEntryIsMissing_ShouldReturnPackageInvalidError() + { + // Arrange + string archivePath = Path.Combine(_testRootPath, "no-manifest.zip"); + File.WriteAllBytes(archivePath, _themePackFixture.CreateArchive(new ThemeArchiveEntry("templates/default.html", DEFAULT_TEMPLATE))); + + // Act + Result result = await _sut.ReadManifestFromArchiveAsync(archivePath, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal("Theme.Package.Invalid", result.FirstError.Code); + Assert.Contains("missing theme.json", result.FirstError.Description); + } + + [Fact] + public async Task ReadManifestFromArchiveAsync_WhenManifestIsNotValidJson_ShouldReturnInvalidJsonError() + { + // Arrange + string archivePath = Path.Combine(_testRootPath, "invalid-json.zip"); + File.WriteAllBytes(archivePath, _themePackFixture.CreateArchive(new ThemeArchiveEntry("theme.json", "not json"))); + + // Act + Result result = await _sut.ReadManifestFromArchiveAsync(archivePath, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal("Theme.Manifest.InvalidJson", result.FirstError.Code); + } + + [Fact] + public async Task ReadManifestFromArchiveAsync_WhenArchiveIsNotAZip_ShouldReturnThemeArchiveNotReadable() + { + // Arrange + string archivePath = Path.Combine(_testRootPath, "not-a-zip.zip"); + File.WriteAllBytes(archivePath, Encoding.UTF8.GetBytes("plain text file")); + + // Act + Result result = await _sut.ReadManifestFromArchiveAsync(archivePath, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal("ThemeArchiveNotReadable", result.FirstError.Description); + } + + [Fact] + public async Task ReadManifestFromArchiveAsync_WhenArchiveFileDoesNotExist_ShouldReturnThemeFilesUnreadable() + { + // Arrange + string archivePath = Path.Combine(_testRootPath, "does-not-exist.zip"); + + // Act + Result result = await _sut.ReadManifestFromArchiveAsync(archivePath, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal("ThemeFilesUnreadable", result.FirstError.Description); + } + + [Fact] + public async Task DeleteAsync_WhenThemeIsInstalled_ShouldRemoveThemePack() + { + // Arrange + await InstallValidThemeAsync(_themePackFixture.Create()); + + // Act + Result result = await _sut.DeleteAsync("test-theme", CancellationToken.None); + + // Assert + Assert.True(result.IsSuccess); + Assert.False(_sut.HasThemePack("test-theme")); + Assert.False(Directory.Exists(Path.Combine(_options.StoragePath, "test-theme"))); + } + + [Fact] + public async Task DeleteAsync_WhenThemeIsNotInstalled_ShouldReturnSuccess() + { + // Arrange + // Nothing is installed. + + // Act + Result result = await _sut.DeleteAsync("test-theme", CancellationToken.None); + + // Assert + Assert.True(result.IsSuccess); + } + + [Fact] + public async Task LoadManifestAsync_WhenThemeIsNotInstalled_ShouldReturnThemeFilesUnreadable() + { + // Arrange + // Nothing is installed. + + // Act + Result result = await _sut.LoadManifestAsync("test-theme", CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal("ThemeFilesUnreadable", result.FirstError.Description); + } + + [Fact] + public async Task LoadManifestAsync_WhenThemeIsInstalled_ShouldReturnManifest() + { + // Arrange + await InstallValidThemeAsync(_themePackFixture.Create(themeId: "loaded-theme")); + + // Act + Result result = await _sut.LoadManifestAsync("loaded-theme", CancellationToken.None); + + // Assert + Assert.True(result.IsSuccess); + Assert.Equal("loaded-theme", result.Value.Id); + Assert.Equal("Test Theme", result.Value.Name); + } + + [Fact] + public async Task GetTemplateAsync_WhenPageKeyHasExplicitManifestTemplate_ShouldReturnExplicitTemplate() + { + // Arrange + byte[] archive = CreateThemeWithTemplates(); + await InstallValidThemeAsync(archive); + + // Act + Result result = await _sut.GetTemplateAsync("test-theme", "home", CancellationToken.None); + + // Assert + Assert.True(result.IsSuccess); + Assert.Equal(HOME_TEMPLATE, result.Value); + } + + [Fact] + public async Task GetTemplateAsync_WhenPageKeyHasNoExplicitTemplate_ShouldUseMirroredTemplate() + { + // Arrange + byte[] archive = CreateThemeWithTemplates(); + await InstallValidThemeAsync(archive); + + // Act + Result result = await _sut.GetTemplateAsync("test-theme", "library", CancellationToken.None); + + // Assert + Assert.True(result.IsSuccess); + Assert.Equal(LIBRARY_TEMPLATE, result.Value); + } + + [Fact] + public async Task GetTemplateAsync_WhenMirroredTemplateIsMissing_ShouldWalkUpToParentScope() + { + // Arrange + byte[] archive = CreateThemeWithTemplates(); + await InstallValidThemeAsync(archive); + + // Act + Result result = await _sut.GetTemplateAsync("test-theme", "library/book", CancellationToken.None); + + // Assert + Assert.True(result.IsSuccess); + Assert.Equal(LIBRARY_TEMPLATE, result.Value); + } + + [Fact] + public async Task GetTemplateAsync_WhenNoTemplateResolves_ShouldReturnThemeTemplateNotFound() + { + // Arrange + byte[] archive = CreateThemeWithTemplates(); + await InstallValidThemeAsync(archive); + + // Act + Result result = await _sut.GetTemplateAsync("test-theme", "unknown-page", CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.Themes.ThemeTemplateNotFound, result.FirstError); + } + + [Theory] + [InlineData("../secret")] // parent scope traversal attempt + [InlineData("/etc/passwd")] // rooted path attempt + [InlineData("templates//nested")] // empty segment attempt + public async Task GetTemplateAsync_WhenPageKeyAttemptsToEscapeTheThemePack_ShouldReturnThemeTemplateNotFound(string pageKey) + { + // Arrange + byte[] archive = CreateThemeWithTemplates(); + await InstallValidThemeAsync(archive); + + // Act + Result result = await _sut.GetTemplateAsync("test-theme", pageKey, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.Themes.ThemeTemplateNotFound, result.FirstError); + } + + [Fact] + public async Task GetTemplateAsync_WhenSharedLayoutTemplateIsMissing_ShouldReturnThemeTemplateNotFound() + { + // Arrange + byte[] archive = CreateThemeWithTemplates(); + await InstallValidThemeAsync(archive); + + // Act + Result result = await _sut.GetTemplateAsync("test-theme", "shared/layout", CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.Themes.ThemeTemplateNotFound, result.FirstError); + } + + [Fact] + public async Task GetTemplateAsync_WhenSharedNavMenuTemplateIsMissing_ShouldReturnThemeTemplateNotFound() + { + // Arrange + byte[] archive = CreateThemeWithTemplates(); + await InstallValidThemeAsync(archive); + + // Act + Result result = await _sut.GetTemplateAsync("test-theme", "shared/nav-menu", CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.Themes.ThemeTemplateNotFound, result.FirstError); + } + + [Fact] + public async Task GetTemplateAsync_WhenSharedNavMenuMirrorExists_ShouldReturnTheMirroredTemplate() + { + // Arrange + const string NAV_TEMPLATE = "nav menu"; + byte[] archive = _themePackFixture.Create(additionalFiles: new Dictionary + { + ["templates/shared/nav-menu.html"] = NAV_TEMPLATE + }); + await InstallValidThemeAsync(archive); + + // Act + Result result = await _sut.GetTemplateAsync("test-theme", "shared/nav-menu", CancellationToken.None); + + // Assert + Assert.True(result.IsSuccess); + Assert.Equal(NAV_TEMPLATE, result.Value); + } + + [Fact] + public async Task GetTemplateAsync_WhenThemeIsNotInstalled_ShouldReturnThemeFilesUnreadable() + { + // Arrange + // Nothing is installed. + + // Act + Result result = await _sut.GetTemplateAsync("test-theme", "home", CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal("ThemeFilesUnreadable", result.FirstError.Description); + } + + [Fact] + public async Task GetTemplateAsync_WhenManifestTemplateFileWasRemoved_ShouldReturnPackageInvalidError() + { + // Arrange + byte[] archive = CreateThemeWithTemplates(); + await InstallValidThemeAsync(archive); + File.Delete(Path.Combine(_options.StoragePath, "test-theme", "templates", "default.html")); + + // Act + Result result = await _sut.GetTemplateAsync("test-theme", "unknown-page", CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal("Theme.Package.Invalid", result.FirstError.Code); + Assert.Contains("missing file", result.FirstError.Description); + } + + [Fact] + public async Task GetTemplateAsync_WhenMirroredTemplateFileWasRemoved_ShouldReturnThemeTemplateNotFound() + { + // Arrange + byte[] archive = CreateThemeWithTemplates(); + await InstallValidThemeAsync(archive); + File.Delete(Path.Combine(_options.StoragePath, "test-theme", "templates", "library.html")); + + // Act + Result result = await _sut.GetTemplateAsync("test-theme", "library/book", CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.Themes.ThemeTemplateNotFound, result.FirstError); + } + + [Fact] + public async Task GetAssetAsync_WhenAssetExists_ShouldReturnFileBytesAndContentType() + { + // Arrange + byte[] archive = _themePackFixture.Create(additionalFiles: new Dictionary + { + ["assets/style.css"] = "body { color: red; }" + }); + await InstallValidThemeAsync(archive); + + // Act + Result result = await _sut.GetAssetAsync("test-theme", "assets/style.css", CancellationToken.None); + + // Assert + Assert.True(result.IsSuccess); + Assert.Equal("text/css", result.Value.ContentType); + Assert.Equal("body { color: red; }", Encoding.UTF8.GetString(result.Value.Bytes)); + } + + [Fact] + public async Task GetAssetAsync_WhenAssetPathIsOutsideAssetsDirectory_ShouldReturnPackageInvalidError() + { + // Arrange + byte[] archive = CreateThemeWithTemplates(); + await InstallValidThemeAsync(archive); + + // Act + Result result = await _sut.GetAssetAsync("test-theme", "templates/default.html", CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal("Theme.Package.Invalid", result.FirstError.Code); + } + + [Fact] + public async Task GetAssetAsync_WhenAssetPathAttemptsTraversal_ShouldReturnPackageInvalidError() + { + // Arrange + byte[] archive = _themePackFixture.Create(); + await InstallValidThemeAsync(archive); + + // Act + Result result = await _sut.GetAssetAsync("test-theme", "../secret.txt", CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal("Theme.Package.Invalid", result.FirstError.Code); + } + + [Fact] + public async Task GetAssetAsync_WhenAssetFileIsMissing_ShouldReturnThemeFilesUnreadable() + { + // Arrange + byte[] archive = _themePackFixture.Create(); + await InstallValidThemeAsync(archive); + + // Act + Result result = await _sut.GetAssetAsync("test-theme", "assets/missing.png", CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal("ThemeFilesUnreadable", result.FirstError.Description); + } + + [Fact] + public async Task GetAssetAsync_WhenAssetIsJavaScript_ShouldReturnJavaScriptContentType() + { + // Arrange + byte[] archive = _themePackFixture.Create(additionalFiles: new Dictionary + { + ["assets/app.js"] = "console.log('hello');" + }); + await InstallValidThemeAsync(archive); + + // Act + Result result = await _sut.GetAssetAsync("test-theme", "assets/app.js", CancellationToken.None); + + // Assert + Assert.True(result.IsSuccess); + Assert.Equal("application/javascript", result.Value.ContentType); + } + + [Fact] + public async Task BuildArchiveAsync_WhenThemeIsInstalled_ShouldReturnDownloadableZipArchive() + { + // Arrange + byte[] archive = _themePackFixture.Create(); + await InstallValidThemeAsync(archive); + + // Act + Result result = await _sut.BuildArchiveAsync("test-theme", CancellationToken.None); + + // Assert + Assert.True(result.IsSuccess); + Assert.Equal("test-theme.zip", result.Value.FileName); + Assert.Equal("application/zip", result.Value.ContentType); + using MemoryStream stream = new(result.Value.Bytes); + using ZipArchive rebuiltArchive = new(stream, ZipArchiveMode.Read); + Assert.Contains(rebuiltArchive.Entries, entry => entry.FullName == "theme.json"); + Assert.Contains(rebuiltArchive.Entries, entry => entry.FullName == "templates/default.html"); + } + + [Fact] + public async Task BuildArchiveAsync_WhenThemeIsNotInstalled_ShouldReturnThemeFilesUnreadable() + { + // Arrange + // Nothing is installed. + + // Act + Result result = await _sut.BuildArchiveAsync("test-theme", CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal("ThemeFilesUnreadable", result.FirstError.Description); + } + + [Fact] + public async Task RestoreBundledThemeAsync_WhenBundledArchiveMatchesThemeId_ShouldInstallTheme() + { + // Arrange + string bundledPath = Path.Combine(_testRootPath, "bundled"); + Directory.CreateDirectory(bundledPath); + File.WriteAllBytes(Path.Combine(bundledPath, "bundled-theme.zip"), _themePackFixture.Create(themeId: "bundled-theme")); + + // Act + Result result = await _sut.RestoreBundledThemeAsync("bundled-theme", CancellationToken.None); + + // Assert + Assert.True(result.IsSuccess); + Assert.True(_sut.HasThemePack("bundled-theme")); + } + + [Fact] + public async Task RestoreBundledThemeAsync_WhenNoBundledArchiveMatches_ShouldReturnThemeFilesUnreadable() + { + // Arrange + string bundledPath = Path.Combine(_testRootPath, "bundled"); + Directory.CreateDirectory(bundledPath); + File.WriteAllBytes(Path.Combine(bundledPath, "other-theme.zip"), _themePackFixture.Create(themeId: "other-theme")); + + // Act + Result result = await _sut.RestoreBundledThemeAsync("bundled-theme", CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal("ThemeFilesUnreadable", result.FirstError.Description); + } + + [Fact] + public async Task RestoreBundledThemeAsync_WhenBundledArchiveManifestIsInvalid_ShouldSkipArchiveAndReturnThemeFilesUnreadable() + { + // Arrange + string bundledPath = Path.Combine(_testRootPath, "bundled"); + Directory.CreateDirectory(bundledPath); + File.WriteAllBytes(Path.Combine(bundledPath, "broken.zip"), _themePackFixture.CreateArchive(new ThemeArchiveEntry("templates/default.html", DEFAULT_TEMPLATE))); + + // Act + Result result = await _sut.RestoreBundledThemeAsync("bundled-theme", CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal("ThemeFilesUnreadable", result.FirstError.Description); + Assert.False(_sut.HasThemePack("bundled-theme")); + } + + [Fact] + public async Task InstallAsync_WhenArchiveContainsAllowedDirectoryEntries_ShouldInstallSuccessfully() + { + // Arrange + string manifestJson = _themePackFixture.CreateManifestJson(); + byte[] archive = _themePackFixture.CreateArchive( + new("templates/", string.Empty), + new("theme.json", manifestJson), + new("templates/default.html", DEFAULT_TEMPLATE), + new("assets/preview.png", "preview-image-bytes")); + + // Act + Result result = await _sut.InstallAsync(new MemoryStream(archive), CancellationToken.None); + + // Assert + Assert.True(result.IsSuccess); + Assert.True(_sut.HasThemePack("test-theme")); + } + + [Fact] + public async Task InstallAsync_WhenArchiveContainsDisallowedDirectoryEntry_ShouldReturnPackageInvalidError() + { + // Arrange + byte[] archive = _themePackFixture.CreateArchive(new ThemeArchiveEntry("notes/", string.Empty)); + + // Act + Result result = await _sut.InstallAsync(new MemoryStream(archive), CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal("Theme.Package.Invalid", result.FirstError.Code); + Assert.Contains("not allowed", result.FirstError.Description); + } + + [Fact] + public async Task InstallAsync_WhenArchiveDoesNotContainThemeJson_ShouldReturnPackageInvalidError() + { + // Arrange + byte[] archive = _themePackFixture.CreateArchive(new ThemeArchiveEntry("templates/default.html", DEFAULT_TEMPLATE)); + + // Act + Result result = await _sut.InstallAsync(new MemoryStream(archive), CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal("Theme.Package.Invalid", result.FirstError.Code); + Assert.Contains("theme.json", result.FirstError.Description); + } + + [Fact] + public async Task InstallAsync_WhenTemplatePathFailsNormalization_ShouldReturnPackageInvalidError() + { + // Arrange + string manifestJson = _themePackFixture.CreateManifestJson(templates: new Dictionary(StringComparer.OrdinalIgnoreCase) + { + ["default"] = "templates/../../escape.html" + }); + byte[] archive = _themePackFixture.CreateArchive(new ThemeArchiveEntry("theme.json", manifestJson)); + + // Act + Result result = await _sut.InstallAsync(new MemoryStream(archive), CancellationToken.None); + + // Assert + AssertPackageInvalid(result, "Theme path segment"); + } + + [Fact] + public async Task InstallAsync_WhenPreviewPathFailsNormalization_ShouldReturnPackageInvalidError() + { + // Arrange + string manifestJson = _themePackFixture.CreateManifestJson(preview: "../../outside.png"); + byte[] archive = _themePackFixture.CreateArchive( + new("theme.json", manifestJson), + new("templates/default.html", DEFAULT_TEMPLATE)); + + // Act + Result result = await _sut.InstallAsync(new MemoryStream(archive), CancellationToken.None); + + // Assert + AssertPackageInvalid(result, "Theme path segment"); + } + + [Fact] + public async Task InstallAsync_WhenManifestContainsNullLiteral_ShouldReturnInvalidJsonError() + { + // Arrange + byte[] archive = _themePackFixture.CreateArchive(new ThemeArchiveEntry("theme.json", "null")); + + // Act + Result result = await _sut.InstallAsync(new MemoryStream(archive), CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal("Theme.Manifest.InvalidJson", result.FirstError.Code); + Assert.Contains("no manifest object", result.FirstError.Description); + } + + [Fact] + public async Task InstallAsync_WhenStorageRootCannotBeCreated_ShouldReturnThemeFilesUnreadable() + { + // Arrange + string blockedRootPath = Path.Combine(_testRootPath, "blocked-storage"); + File.WriteAllText(blockedRootPath, "a file occupies the storage root path"); + ThemeEngineOptionsDto options = _themeEngineOptionsDtoFixture.Create( + storagePath: blockedRootPath, + bundledThemesPath: Path.Combine(_testRootPath, "bundled"), + defaultThemeId: "lumina-default", + maxArchiveBytes: 8 * 1024 * 1024, + maxExpandedBytes: 24 * 1024 * 1024, + maxSingleFileBytes: 6 * 1024 * 1024, + maxEntries: 250); + ThemeService sut = CreateSut(options); + byte[] archive = _themePackFixture.Create(); + + // Act + Result result = await sut.InstallAsync(new MemoryStream(archive), CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal("ThemeFilesUnreadable", result.FirstError.Description); + } + + [Fact] + public async Task InstallAsync_WhenStagingDirectoryContainsStaleEntries_ShouldRemoveThemBeforeInstalling() + { + // Arrange + Directory.CreateDirectory(_options.StoragePath); + Directory.CreateDirectory(Path.Combine(_options.StoragePath, ".staging")); + File.WriteAllText(Path.Combine(_options.StoragePath, ".staging", "stale.txt"), "stale"); + Directory.CreateDirectory(Path.Combine(_options.StoragePath, ".staging", "old")); + File.WriteAllText(Path.Combine(_options.StoragePath, ".staging", "old", "inner.txt"), "stale"); + byte[] archive = _themePackFixture.Create(); + + // Act + await InstallValidThemeAsync(archive); + + // Assert + Assert.True(_sut.HasThemePack("test-theme")); + Assert.False(File.Exists(Path.Combine(_options.StoragePath, ".staging", "stale.txt"))); + Assert.False(Directory.Exists(Path.Combine(_options.StoragePath, ".staging", "old"))); + } + + [Fact] + public async Task LoadManifestAsync_WhenThemeDirectoryExistsButManifestWasRemoved_ShouldReturnMissingManifestError() + { + // Arrange + await InstallValidThemeAsync(_themePackFixture.Create(themeId: "removed-manifest-theme")); + File.Delete(Path.Combine(_options.StoragePath, "removed-manifest-theme", "theme.json")); + + // Act + Result result = await _sut.LoadManifestAsync("removed-manifest-theme", CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal("Theme.Package.Invalid", result.FirstError.Code); + Assert.Contains("missing theme.json", result.FirstError.Description); + } + + [Fact] + public async Task ReadManifestFromArchiveAsync_WhenManifestContainsNullLiteral_ShouldReturnInvalidJsonError() + { + // Arrange + string archivePath = Path.Combine(_testRootPath, "null-manifest.zip"); + File.WriteAllBytes(archivePath, _themePackFixture.CreateArchive(new ThemeArchiveEntry("theme.json", "null"))); + + // Act + Result result = await _sut.ReadManifestFromArchiveAsync(archivePath, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal("Theme.Manifest.InvalidJson", result.FirstError.Code); + Assert.Contains("no manifest object", result.FirstError.Description); + } + + [Fact] + public async Task RestoreBundledThemeAsync_WhenThemeDestinationIsBlocked_ShouldReturnThemeFilesUnreadable() + { + // Arrange + string bundledPath = Path.Combine(_testRootPath, "bundled"); + Directory.CreateDirectory(bundledPath); + File.WriteAllBytes(Path.Combine(bundledPath, "restore-blocked.zip"), _themePackFixture.Create(themeId: "restore-blocked")); + Directory.CreateDirectory(_options.StoragePath); + File.WriteAllText(Path.Combine(_options.StoragePath, "restore-blocked"), "blocked"); + + // Act + Result result = await _sut.RestoreBundledThemeAsync("restore-blocked", CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal("ThemeFilesUnreadable", result.FirstError.Description); + Assert.False(_sut.HasThemePack("restore-blocked")); + } + + [Fact] + public void Constructor_WhenConfiguredPathsAreRelative_ShouldResolveThemAgainstTheBaseDirectory() + { + // Arrange + ThemeEngineOptionsDto options = _themeEngineOptionsDtoFixture.Create( + storagePath: Path.Combine(_testRootPath, "themes"), + bundledThemesPath: Path.Combine(_testRootPath, "bundled"), + defaultThemeId: "lumina-default", + maxArchiveBytes: 8 * 1024 * 1024, + maxExpandedBytes: 24 * 1024 * 1024, + maxSingleFileBytes: 6 * 1024 * 1024, + maxEntries: 250); + options.StoragePath = $"relative-themes-{Guid.NewGuid():N}"; + options.BundledThemesPath = $"relative-bundled-{Guid.NewGuid():N}"; + + // Act + ThemeService sut = CreateSut(options); + + // Assert + Assert.False(sut.HasThemePack("not-installed")); + } + + /// + /// Cleans up the temporary storage used by the tests. + /// + public void Dispose() + { + try + { + if (Directory.Exists(_testRootPath)) + Directory.Delete(_testRootPath, recursive: true); + } + catch (IOException) + { + // Best effort cleanup of the per-test temp directory. + } + catch (UnauthorizedAccessException) + { + // Best effort cleanup of the per-test temp directory. + } + } + + /// + /// Creates a valid theme pack that declares the default, home and library templates and their files. + /// + /// The created theme pack ZIP archive. + private byte[] CreateThemeWithTemplates() + { + Dictionary templates = new(StringComparer.OrdinalIgnoreCase) + { + ["default"] = "templates/default.html", + ["home"] = "templates/home.html" + }; + + return _themePackFixture.Create( + templates: templates, + additionalFiles: new Dictionary + { + ["templates/library.html"] = LIBRARY_TEMPLATE + }); + } + + /// + /// Installs the provided theme archive using the provided service and asserts that the install succeeds. + /// + /// The theme pack ZIP archive to install. + /// The service to install with, defaults to the shared system under test. + /// The task representing the asynchronous operation. + private async Task InstallValidThemeAsync(byte[] archive, ThemeService? service = null) + { + ThemeService themeService = service ?? _sut; + using MemoryStream stream = new(archive); + Result result = await themeService.InstallAsync(stream, CancellationToken.None); + Assert.True(result.IsSuccess, result.Match( + success => string.Empty, + errors => $"Expected a successful install but got: {errors.First().Code}: {errors.First().Description}")); + } + + /// + /// Asserts that the result is a package invalid failure whose description contains the provided fragment. + /// + /// The result to assert on. + /// The fragment the error description must contain. + private static void AssertPackageInvalid(Result result, string expectedDescriptionFragment) + { + Assert.True(result.IsFailure); + Assert.Equal("Theme.Package.Invalid", result.FirstError.Code); + Assert.Contains(expectedDescriptionFragment, result.FirstError.Description); + } + + /// + /// Creates a instance using the provided options. + /// + /// The theme engine options to configure the service with. + /// The created service. + private static ThemeService CreateSut(ThemeEngineOptionsDto options) + { + ILogger logger = Substitute.For>(); + IPathService pathService = Substitute.For(); + pathService.SanitizeSegment(Arg.Any()) + .Returns(callInfo => PathSegment.Create(callInfo.Arg(), isDirectory: true, isDrive: false)); + return new ThemeService(Options.Create(options), logger, pathService); + } +} diff --git a/tests/IntegrationTests/Lumina.Infrastructure.IntegrationTests/Lumina.Infrastructure.IntegrationTests.csproj b/tests/IntegrationTests/Lumina.Infrastructure.IntegrationTests/Lumina.Infrastructure.IntegrationTests.csproj new file mode 100644 index 00000000..f442a0d8 --- /dev/null +++ b/tests/IntegrationTests/Lumina.Infrastructure.IntegrationTests/Lumina.Infrastructure.IntegrationTests.csproj @@ -0,0 +1,51 @@ + + + + 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/IntegrationTests/Lumina.Plugins.Calibre.IntegrationTests/Core/CalibreArtworkProviderTests.cs b/tests/IntegrationTests/Lumina.Plugins.Calibre.IntegrationTests/Core/CalibreArtworkProviderTests.cs new file mode 100644 index 00000000..e337b06b --- /dev/null +++ b/tests/IntegrationTests/Lumina.Plugins.Calibre.IntegrationTests/Core/CalibreArtworkProviderTests.cs @@ -0,0 +1,188 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Contracts.DTO.Common; +using Lumina.Contracts.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary; +using Lumina.Contracts.Fixtures.Core.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary; +using Lumina.Plugins.Calibre.Core; +using System; +using System.Diagnostics.CodeAnalysis; +using System.IO; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Plugins.Calibre.IntegrationTests.Core; + +/// +/// Contains integration tests for the class. +/// +[ExcludeFromCodeCoverage] +public class CalibreArtworkProviderTests +{ + private readonly BookMetadataLookupDtoFixture _bookMetadataLookupDtoFixture = new(); + private readonly CalibreArtworkProvider _sut = new(); + + [Fact] + public async Task GetArtworkAsync_WhenCoverHrefIsABareFileName_ShouldReturnTheLocalCoverPath() + { + // Arrange + string bookDirectory = CreateTempDirectory(); + try + { + string bookPath = Path.Combine(bookDirectory, "book.epub"); + WriteOpf(bookDirectory, coverHref: "cover.jpg"); + File.WriteAllText(Path.Combine(bookDirectory, "cover.jpg"), "image-bytes"); + BookMetadataLookupDto lookup = _bookMetadataLookupDtoFixture.Create(path: bookPath); + + // Act + ArtworkDto? result = await _sut.GetArtworkAsync(lookup, CancellationToken.None); + + // Assert + Assert.NotNull(result); + Assert.Equal(Path.Combine(bookDirectory, "cover.jpg"), result!.LocalPath); + Assert.Null(result.RemoteUrl); + } + finally + { + Directory.Delete(bookDirectory, true); + } + } + + [Fact] + public async Task GetArtworkAsync_WhenCoverHrefIsAnAbsolutePath_ShouldReturnNull() + { + // Arrange + string bookDirectory = CreateTempDirectory(); + try + { + string bookPath = Path.Combine(bookDirectory, "book.epub"); + WriteOpf(bookDirectory, coverHref: @"C:\Windows\System32\drivers\etc\hosts"); + BookMetadataLookupDto lookup = _bookMetadataLookupDtoFixture.Create(path: bookPath); + + // Act + ArtworkDto? result = await _sut.GetArtworkAsync(lookup, CancellationToken.None); + + // Assert + Assert.Null(result); + } + finally + { + Directory.Delete(bookDirectory, true); + } + } + + [Theory] + [InlineData("../cover.jpg")] // parent directory escape + [InlineData("sub/cover.jpg")] // path with a separator + [InlineData("sub\\cover.jpg")] // path with a backslash separator + public async Task GetArtworkAsync_WhenCoverHrefContainsPathTraversalOrSeparators_ShouldReturnNull(string coverHref) + { + // Arrange + string bookDirectory = CreateTempDirectory(); + try + { + string bookPath = Path.Combine(bookDirectory, "book.epub"); + WriteOpf(bookDirectory, coverHref); + BookMetadataLookupDto lookup = _bookMetadataLookupDtoFixture.Create(path: bookPath); + + // Act + ArtworkDto? result = await _sut.GetArtworkAsync(lookup, CancellationToken.None); + + // Assert + Assert.Null(result); + } + finally + { + Directory.Delete(bookDirectory, true); + } + } + + [Fact] + public async Task GetArtworkAsync_WhenCoverFileIsMissing_ShouldReturnNull() + { + // Arrange + string bookDirectory = CreateTempDirectory(); + try + { + string bookPath = Path.Combine(bookDirectory, "book.epub"); + WriteOpf(bookDirectory, coverHref: "cover.jpg"); + BookMetadataLookupDto lookup = _bookMetadataLookupDtoFixture.Create(path: bookPath); + + // Act + ArtworkDto? result = await _sut.GetArtworkAsync(lookup, CancellationToken.None); + + // Assert + Assert.Null(result); + } + finally + { + Directory.Delete(bookDirectory, true); + } + } + + [Fact] + public async Task GetArtworkAsync_WhenOpfFileDoesNotExist_ShouldReturnNull() + { + // Arrange + string bookDirectory = CreateTempDirectory(); + try + { + string bookPath = Path.Combine(bookDirectory, "book.epub"); + BookMetadataLookupDto lookup = _bookMetadataLookupDtoFixture.Create(path: bookPath); + + // Act + ArtworkDto? result = await _sut.GetArtworkAsync(lookup, CancellationToken.None); + + // Assert + Assert.Null(result); + } + finally + { + Directory.Delete(bookDirectory, true); + } + } + + [Fact] + public async Task GetArtworkAsync_WhenOpfHasNoCoverReference_ShouldReturnNull() + { + // Arrange + string bookDirectory = CreateTempDirectory(); + try + { + string bookPath = Path.Combine(bookDirectory, "book.epub"); + File.WriteAllText(Path.Combine(bookDirectory, "metadata.opf"), """Test"""); + BookMetadataLookupDto lookup = _bookMetadataLookupDtoFixture.Create(path: bookPath); + + // Act + ArtworkDto? result = await _sut.GetArtworkAsync(lookup, CancellationToken.None); + + // Assert + Assert.Null(result); + } + finally + { + Directory.Delete(bookDirectory, true); + } + } + + /// + /// Writes an OPF file that references the given cover into the book directory. + /// + /// The file system path of the directory the OPF file is written into. + /// The href of the cover the OPF file references. + private static void WriteOpf(string bookDirectory, string coverHref) + { + string opf = $$"""Test"""; + File.WriteAllText(Path.Combine(bookDirectory, "metadata.opf"), opf); + } + + /// + /// Creates a unique temporary directory for the book. + /// + /// The file system path of the created temporary directory. + private static string CreateTempDirectory() + { + string directoryPath = Path.Combine(Path.GetTempPath(), $"lumina-calibre-artwork-{Guid.NewGuid():N}"); + Directory.CreateDirectory(directoryPath); + return directoryPath; + } +} diff --git a/tests/IntegrationTests/Lumina.Plugins.Calibre.IntegrationTests/Core/CalibreBookMetadataProviderTests.cs b/tests/IntegrationTests/Lumina.Plugins.Calibre.IntegrationTests/Core/CalibreBookMetadataProviderTests.cs new file mode 100644 index 00000000..41868f69 --- /dev/null +++ b/tests/IntegrationTests/Lumina.Plugins.Calibre.IntegrationTests/Core/CalibreBookMetadataProviderTests.cs @@ -0,0 +1,128 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Contracts.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary; +using Lumina.Contracts.Fixtures.Core.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary; +using Lumina.Plugins.Calibre.Core; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.IO; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Plugins.Calibre.IntegrationTests.Core; + +/// +/// Contains integration tests for the class. +/// +[ExcludeFromCodeCoverage] +public class CalibreBookMetadataProviderTests +{ + private readonly BookMetadataLookupDtoFixture _bookMetadataLookupDtoFixture = new(); + private readonly CalibreBookMetadataProvider _sut = new(); + + private const string OPF_DOCUMENT = """Test Book TitleTest Author"""; + + [Fact] + public async Task GetMetadataAsync_WhenOpfFileExistsNextToTheBook_ShouldReturnTheMappedMetadata() + { + // Arrange + string bookDirectory = CreateTempDirectory(); + try + { + string bookPath = Path.Combine(bookDirectory, "book.epub"); + File.WriteAllText(Path.Combine(bookDirectory, "metadata.opf"), OPF_DOCUMENT); + BookMetadataLookupDto lookup = _bookMetadataLookupDtoFixture.Create(path: bookPath); + + // Act + BookMetadataDto? result = await _sut.GetMetadataAsync(lookup, CancellationToken.None); + + // Assert + Assert.NotNull(result); + Assert.Equal("Test Book Title", result!.Title); + } + finally + { + Directory.Delete(bookDirectory, true); + } + } + + [Fact] + public async Task GetMetadataAsync_WhenOpfFileDoesNotExist_ShouldReturnNull() + { + // Arrange + string bookDirectory = CreateTempDirectory(); + try + { + string bookPath = Path.Combine(bookDirectory, "book.epub"); + BookMetadataLookupDto lookup = _bookMetadataLookupDtoFixture.Create(path: bookPath); + + // Act + BookMetadataDto? result = await _sut.GetMetadataAsync(lookup, CancellationToken.None); + + // Assert + Assert.Null(result); + } + finally + { + Directory.Delete(bookDirectory, true); + } + } + + [Fact] + public async Task GetSearchResultsAsync_WhenOpfFileExistsNextToTheBook_ShouldReturnASingleMetadataCandidate() + { + // Arrange + string bookDirectory = CreateTempDirectory(); + try + { + string bookPath = Path.Combine(bookDirectory, "book.epub"); + File.WriteAllText(Path.Combine(bookDirectory, "metadata.opf"), OPF_DOCUMENT); + BookMetadataLookupDto lookup = _bookMetadataLookupDtoFixture.Create(path: bookPath); + + // Act + IReadOnlyList result = await _sut.GetSearchResultsAsync(lookup, CancellationToken.None); + + // Assert + BookMetadataDto metadata = Assert.IsType(Assert.Single(result)); + Assert.Equal("Test Book Title", metadata.Title); + } + finally + { + Directory.Delete(bookDirectory, true); + } + } + + [Fact] + public async Task GetSearchResultsAsync_WhenOpfFileDoesNotExist_ShouldReturnAnEmptyList() + { + // Arrange + string bookDirectory = CreateTempDirectory(); + try + { + string bookPath = Path.Combine(bookDirectory, "book.epub"); + BookMetadataLookupDto lookup = _bookMetadataLookupDtoFixture.Create(path: bookPath); + + // Act + IReadOnlyList result = await _sut.GetSearchResultsAsync(lookup, CancellationToken.None); + + // Assert + Assert.Empty(result); + } + finally + { + Directory.Delete(bookDirectory, true); + } + } + + /// + /// Creates a unique temporary directory for the book. + /// + /// The file system path of the created temporary directory. + private static string CreateTempDirectory() + { + string directoryPath = Path.Combine(Path.GetTempPath(), $"lumina-calibre-metadata-{Guid.NewGuid():N}"); + Directory.CreateDirectory(directoryPath); + return directoryPath; + } +} diff --git a/tests/UnitTests/Lumina.Plugins.Calibre.UnitTests/Core/Opf/OpfReaderTests.cs b/tests/IntegrationTests/Lumina.Plugins.Calibre.IntegrationTests/Core/Opf/OpfReaderTests.cs similarity index 97% rename from tests/UnitTests/Lumina.Plugins.Calibre.UnitTests/Core/Opf/OpfReaderTests.cs rename to tests/IntegrationTests/Lumina.Plugins.Calibre.IntegrationTests/Core/Opf/OpfReaderTests.cs index b5435fcb..d92084fe 100644 --- a/tests/UnitTests/Lumina.Plugins.Calibre.UnitTests/Core/Opf/OpfReaderTests.cs +++ b/tests/IntegrationTests/Lumina.Plugins.Calibre.IntegrationTests/Core/Opf/OpfReaderTests.cs @@ -6,10 +6,10 @@ using System.Diagnostics.CodeAnalysis; using System.IO; #endregion -namespace Lumina.Plugins.Calibre.UnitTests.Core.Opf; +namespace Lumina.Plugins.Calibre.IntegrationTests.Core.Opf; /// -/// Contains unit tests for the class. +/// Contains integration tests for the class. /// [ExcludeFromCodeCoverage] public class OpfReaderTests @@ -117,7 +117,7 @@ public class OpfReaderTests public void Read_WhenOpfFileDeclaresADoctypeWithEntities_ShouldNotExpandThem() { // Arrange - // the DTD is prohibited, so the document must not be parsed and the entity must not be expanded into the title + // The DTD is prohibited, so the document must not be parsed and the entity must not be expanded into the title. string opfFilePath = CreateOpfFile("""]>&xxe;"""); try diff --git a/tests/IntegrationTests/Lumina.Plugins.Calibre.IntegrationTests/Lumina.Plugins.Calibre.IntegrationTests.csproj b/tests/IntegrationTests/Lumina.Plugins.Calibre.IntegrationTests/Lumina.Plugins.Calibre.IntegrationTests.csproj new file mode 100644 index 00000000..4309ec26 --- /dev/null +++ b/tests/IntegrationTests/Lumina.Plugins.Calibre.IntegrationTests/Lumina.Plugins.Calibre.IntegrationTests.csproj @@ -0,0 +1,48 @@ + + + + net10.0 + disable + enable + + false + true + + + + + <_Parameter1>DisableTestParallelization = true + <_Parameter1_IsLiteral>true + + + + + + + + + all + runtime; build; native; contentfiles; analyzers; buildtransitive + + + + + + + all + runtime; build; native; contentfiles; analyzers; buildtransitive + + + + + + + + + + + + + + + diff --git a/tests/UnitTests/Lumina.Plugins.Epub.UnitTests/Core/Epub/EpubDocumentParserTests.cs b/tests/IntegrationTests/Lumina.Plugins.Epub.IntegrationTests/Core/Epub/EpubDocumentParserTests.cs similarity index 99% rename from tests/UnitTests/Lumina.Plugins.Epub.UnitTests/Core/Epub/EpubDocumentParserTests.cs rename to tests/IntegrationTests/Lumina.Plugins.Epub.IntegrationTests/Core/Epub/EpubDocumentParserTests.cs index db0d339b..1a29cf59 100644 --- a/tests/UnitTests/Lumina.Plugins.Epub.UnitTests/Core/Epub/EpubDocumentParserTests.cs +++ b/tests/IntegrationTests/Lumina.Plugins.Epub.IntegrationTests/Core/Epub/EpubDocumentParserTests.cs @@ -13,10 +13,10 @@ using System.Text; using System.Threading; #endregion -namespace Lumina.Plugins.Epub.UnitTests.Core.Epub; +namespace Lumina.Plugins.Epub.IntegrationTests.Core.Epub; /// -/// Contains unit tests for the class. +/// Contains integration tests for the class. /// [ExcludeFromCodeCoverage] public class EpubDocumentParserTests : IDisposable diff --git a/tests/IntegrationTests/Lumina.Plugins.Epub.IntegrationTests/Core/EpubReaderTests.cs b/tests/IntegrationTests/Lumina.Plugins.Epub.IntegrationTests/Core/EpubReaderTests.cs new file mode 100644 index 00000000..9fa33a7a --- /dev/null +++ b/tests/IntegrationTests/Lumina.Plugins.Epub.IntegrationTests/Core/EpubReaderTests.cs @@ -0,0 +1,72 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Contracts.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary.Reading; +using Lumina.Plugins.Epub.Core; +using Lumina.Plugins.Epub.Fixtures.Core.Epub; +using System; +using System.Diagnostics.CodeAnalysis; +using System.IO; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Plugins.Epub.IntegrationTests.Core; + +/// +/// Contains integration tests for the class. +/// +[ExcludeFromCodeCoverage] +public class EpubReaderTests : IDisposable +{ + private readonly string _temporaryDirectory = Path.Combine(Path.GetTempPath(), $"lumina-epub-reader-{Guid.NewGuid():N}"); + private readonly string _epubPath; + private readonly EpubReader _sut = new(); + + /// + /// Initializes a new instance of the class. + /// + public EpubReaderTests() + { + Directory.CreateDirectory(_temporaryDirectory); + _epubPath = Path.Combine(_temporaryDirectory, "minimal.epub"); + TestEpubFileFactory.CreateMinimalEpub(_epubPath); + } + + [Fact] + public async Task OpenAsync_WhenCalled_ShouldReturnTheParsedDocument() + { + // Arrange + string workingDirectory = Path.Combine(_temporaryDirectory, "work"); + + // Act + ReadingDocumentDto result = await _sut.OpenAsync(_epubPath, workingDirectory, shouldRenderPdfAsImages: false, CancellationToken.None); + + // Assert + Assert.Equal("Minimal EPUB Book", result.Title); + Assert.Equal(2, result.Spine.Count); + } + + [Fact] + public async Task GetResourceAsync_WhenResourceWasExtracted_ShouldReturnItsBytes() + { + // Arrange + string workingDirectory = Path.Combine(_temporaryDirectory, "work"); + ReadingDocumentDto document = await _sut.OpenAsync(_epubPath, workingDirectory, shouldRenderPdfAsImages: false, CancellationToken.None); + string resourceKey = document.Resources.Keys.Single(); + + // Act + byte[] result = await _sut.GetResourceAsync(_epubPath, workingDirectory, resourceKey, CancellationToken.None); + + // Assert + Assert.NotNull(result); + Assert.NotEmpty(result); + } + + /// + public void Dispose() + { + if (Directory.Exists(_temporaryDirectory)) + Directory.Delete(_temporaryDirectory, recursive: true); + } +} + diff --git a/tests/IntegrationTests/Lumina.Plugins.Epub.IntegrationTests/Lumina.Plugins.Epub.IntegrationTests.csproj b/tests/IntegrationTests/Lumina.Plugins.Epub.IntegrationTests/Lumina.Plugins.Epub.IntegrationTests.csproj new file mode 100644 index 00000000..0abab51d --- /dev/null +++ b/tests/IntegrationTests/Lumina.Plugins.Epub.IntegrationTests/Lumina.Plugins.Epub.IntegrationTests.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/IntegrationTests/Lumina.Plugins.Pdf.IntegrationTests/Core/Pdf/PdfDocumentParserTests.cs b/tests/IntegrationTests/Lumina.Plugins.Pdf.IntegrationTests/Core/Pdf/PdfDocumentParserTests.cs new file mode 100644 index 00000000..94434e21 --- /dev/null +++ b/tests/IntegrationTests/Lumina.Plugins.Pdf.IntegrationTests/Core/Pdf/PdfDocumentParserTests.cs @@ -0,0 +1,218 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Contracts.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary.Reading; +using Lumina.Plugins.Pdf.Core.Pdf; +using Lumina.Plugins.Pdf.Fixtures.Core.Pdf; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.IO; +using System.Runtime.Versioning; +using System.Threading; +#endregion + +namespace Lumina.Plugins.Pdf.IntegrationTests.Core.Pdf; + +/// +/// Contains integration tests for the class. +/// +[ExcludeFromCodeCoverage] +public class PdfDocumentParserTests : IDisposable +{ + private readonly string _temporaryDirectory = Path.Combine(Path.GetTempPath(), $"lumina-pdf-tests-{Guid.NewGuid():N}"); + private readonly string _pdfPath; + + /// + /// Initializes a new instance of the class. + /// + public PdfDocumentParserTests() + { + Directory.CreateDirectory(_temporaryDirectory); + _pdfPath = Path.Combine(_temporaryDirectory, "minimal.pdf"); + TestPdfFileFactory.CreateMinimalPdf(_pdfPath); + } + + [Fact] + public void Parse_WhenCalledOnPdfWithTextLayer_ShouldReturnDocumentWithTextSections() + { + // Arrange + string workingDirectory = Path.Combine(_temporaryDirectory, "work"); + + // Act + ReadingDocumentDto result = PdfDocumentParser.Parse(_pdfPath, workingDirectory, shouldRenderPdfAsImages: false, CancellationToken.None); + + // Assert + Assert.Equal("minimal", result.Title); + Assert.True(result.HasTextContent); + ReadingSpineItemDto spineItem = Assert.Single(result.Spine); + Assert.Equal("page:1", spineItem.LocationRef); + string sectionContent = File.ReadAllText(Path.Combine(workingDirectory, spineItem.RelativeSectionFilePath)); + Assert.Contains("

Hello PDF Page 1

", sectionContent, StringComparison.Ordinal); + Assert.Empty(result.Resources); + } + + [Fact] + public void Parse_WhenCalledWithRenderAsImages_ShouldReturnDocumentWithImageSectionsAndNoTextContent() + { + // Arrange + string workingDirectory = Path.Combine(_temporaryDirectory, "work"); + + // Act + ReadingDocumentDto result = PdfDocumentParser.Parse(_pdfPath, workingDirectory, shouldRenderPdfAsImages: true, CancellationToken.None); + + // Assert + Assert.Equal("minimal", result.Title); + Assert.False(result.HasTextContent); + ReadingSpineItemDto spineItem = Assert.Single(result.Spine); + Assert.Equal("page:1", spineItem.LocationRef); + KeyValuePair resource = Assert.Single(result.Resources); + Assert.Equal("page:1", resource.Key); + Assert.Equal("image/png", resource.Value.MimeType); + string sectionContent = File.ReadAllText(Path.Combine(workingDirectory, spineItem.RelativeSectionFilePath)); + Assert.Contains("data-lumina-resource=\"page:1\"", sectionContent, StringComparison.Ordinal); + } + + [Fact] + public void Parse_WhenPdfFileDoesNotExist_ShouldThrowFileNotFoundException() + { + // Arrange + string missingPdfPath = Path.Combine(_temporaryDirectory, "missing.pdf"); + string workingDirectory = Path.Combine(_temporaryDirectory, "work"); + + // Act + Action act = () => PdfDocumentParser.Parse(missingPdfPath, workingDirectory, shouldRenderPdfAsImages: false, CancellationToken.None); + + // Assert + Assert.Throws(act); + } + + [SupportedOSPlatform("windows")] + [Fact] + public void RenderResource_WhenResourceKeyNamesAPageBeyondTheDocument_ShouldThrowInvalidDataException() + { + // Act + // The minimal PDF has a single page, so page 2 is rejected against the page count of the document without rendering it. + Action act = () => PdfDocumentParser.RenderResource(_pdfPath, "page:2", CancellationToken.None); + + // Assert + Assert.Throws(act); + } + + [Fact] + public void Parse_WhenPdfHasBookmarks_ShouldBuildTableOfContentsFromTheOutline() + { + // Arrange + string outlinedPdfPath = Path.Combine(_temporaryDirectory, "outlined.pdf"); + TestPdfFileFactory.CreatePdfWithOutline(outlinedPdfPath); + string workingDirectory = Path.Combine(_temporaryDirectory, "work"); + + // Act + ReadingDocumentDto result = PdfDocumentParser.Parse(outlinedPdfPath, workingDirectory, shouldRenderPdfAsImages: false, CancellationToken.None); + + // Assert + // PdfPig does not surface a bookmark without a title, so only the three titled top-level entries appear. + Assert.Equal(3, result.TableOfContents.Count); + ReadingTocEntryDto chapterOne = result.TableOfContents[0]; + Assert.Equal("Chapter One", chapterOne.Label); + Assert.Equal("page:1", chapterOne.LocationRef); + ReadingTocEntryDto partOne = Assert.Single(chapterOne.Children); + Assert.Equal("Part One", partOne.Label); + Assert.Equal("page:1", partOne.LocationRef); + Assert.Equal("Chapter Two", result.TableOfContents[1].Label); + Assert.Equal("page:2", result.TableOfContents[1].LocationRef); + // A bookmark pointing at a URI instead of a page yields an entry that is not navigable. + Assert.Equal("External Link", result.TableOfContents[2].Label); + Assert.Equal(string.Empty, result.TableOfContents[2].LocationRef); + } + + [Fact] + public void Parse_WhenPdfIsTooLarge_ShouldThrowInvalidDataException() + { + // Arrange + string oversizedPdfPath = Path.Combine(_temporaryDirectory, "oversized.pdf"); + // A sparse file larger than the 500 MB cap, without allocating disk space. + using (FileStream fileStream = new(oversizedPdfPath, FileMode.Create, FileAccess.Write)) + fileStream.SetLength(501L * 1024 * 1024); + string workingDirectory = Path.Combine(_temporaryDirectory, "work"); + + // Act + Action act = () => PdfDocumentParser.Parse(oversizedPdfPath, workingDirectory, shouldRenderPdfAsImages: false, CancellationToken.None); + + // Assert + Assert.Throws(act); + } + + [Fact] + public void Parse_WhenPdfHasABlankTextLine_ShouldSkipTheBlankLineAndKeepTheOthers() + { + // Arrange + string blankLinePdfPath = Path.Combine(_temporaryDirectory, "blankline.pdf"); + TestPdfFileFactory.CreatePdfWithBlankLine(blankLinePdfPath); + string workingDirectory = Path.Combine(_temporaryDirectory, "work"); + + // Act + ReadingDocumentDto result = PdfDocumentParser.Parse(blankLinePdfPath, workingDirectory, shouldRenderPdfAsImages: false, CancellationToken.None); + + // Assert + string sectionContent = File.ReadAllText(Path.Combine(workingDirectory, result.Spine[0].RelativeSectionFilePath)); + Assert.Contains("

First line

", sectionContent, StringComparison.Ordinal); + Assert.Contains("

Third line

", sectionContent, StringComparison.Ordinal); + Assert.DoesNotContain("

", sectionContent, StringComparison.Ordinal); + } + + [Fact] + public void Parse_WhenPdfOutlineIsMalformed_ShouldSkipTheTableOfContentsAndKeepThePages() + { + // Arrange + string malformedOutlinePdfPath = Path.Combine(_temporaryDirectory, "malformed-outline.pdf"); + TestPdfFileFactory.CreatePdfWithMalformedOutline(malformedOutlinePdfPath); + string workingDirectory = Path.Combine(_temporaryDirectory, "work"); + + // Act + ReadingDocumentDto result = PdfDocumentParser.Parse(malformedOutlinePdfPath, workingDirectory, shouldRenderPdfAsImages: false, CancellationToken.None); + + // Assert + // The malformed bookmarks are best effort: the table of contents is skipped, but the pages are still readable. + Assert.Empty(result.TableOfContents); + Assert.Single(result.Spine); + } + + [Fact] + public void Parse_WhenPdfExceedsThePageCap_ShouldStopAtTheCap() + { + // Arrange + string manyPagesPdfPath = Path.Combine(_temporaryDirectory, "many-pages.pdf"); + TestPdfFileFactory.CreatePdfWithMorePagesThanAllowed(manyPagesPdfPath); + string workingDirectory = Path.Combine(_temporaryDirectory, "work"); + + // Act + ReadingDocumentDto result = PdfDocumentParser.Parse(manyPagesPdfPath, workingDirectory, shouldRenderPdfAsImages: false, CancellationToken.None); + + // Assert + // The parser stops enumerating after the page cap instead of reading every page. + Assert.Equal(10_000, result.Spine.Count); + } + + [Fact] + public void ParseAsImages_WhenPdfExceedsThePageCap_ShouldStopAtTheCap() + { + // Arrange + string manyPagesPdfPath = Path.Combine(_temporaryDirectory, "many-pages-images.pdf"); + TestPdfFileFactory.CreatePdfWithMorePagesThanAllowed(manyPagesPdfPath); + string workingDirectory = Path.Combine(_temporaryDirectory, "work"); + + // Act + ReadingDocumentDto result = PdfDocumentParser.Parse(manyPagesPdfPath, workingDirectory, shouldRenderPdfAsImages: true, CancellationToken.None); + + // Assert + Assert.Equal(10_000, result.Spine.Count); + Assert.Equal(10_000, result.Resources.Count); + } + + /// + public void Dispose() + { + if (Directory.Exists(_temporaryDirectory)) + Directory.Delete(_temporaryDirectory, recursive: true); + } +} + diff --git a/tests/IntegrationTests/Lumina.Plugins.Pdf.IntegrationTests/Core/PdfReaderTests.cs b/tests/IntegrationTests/Lumina.Plugins.Pdf.IntegrationTests/Core/PdfReaderTests.cs new file mode 100644 index 00000000..782279ab --- /dev/null +++ b/tests/IntegrationTests/Lumina.Plugins.Pdf.IntegrationTests/Core/PdfReaderTests.cs @@ -0,0 +1,71 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Contracts.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary.Reading; +using Lumina.Plugins.Pdf.Core; +using Lumina.Plugins.Pdf.Fixtures.Core.Pdf; +using System; +using System.Diagnostics.CodeAnalysis; +using System.IO; +using System.Runtime.Versioning; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Plugins.Pdf.IntegrationTests.Core; + +/// +/// Contains integration tests for the class. +/// +[ExcludeFromCodeCoverage] +public class PdfReaderTests : IDisposable +{ + private readonly string _temporaryDirectory = Path.Combine(Path.GetTempPath(), $"lumina-pdf-reader-{Guid.NewGuid():N}"); + private readonly string _pdfPath; + private readonly PdfReader _sut = new(); + + /// + /// Initializes a new instance of the class. + /// + public PdfReaderTests() + { + Directory.CreateDirectory(_temporaryDirectory); + _pdfPath = Path.Combine(_temporaryDirectory, "minimal.pdf"); + TestPdfFileFactory.CreateMinimalPdf(_pdfPath); + } + + [Fact] + public async Task OpenAsync_WhenCalled_ShouldReturnTheParsedDocument() + { + // Arrange + string workingDirectory = Path.Combine(_temporaryDirectory, "work"); + + // Act + ReadingDocumentDto result = await _sut.OpenAsync(_pdfPath, workingDirectory, shouldRenderPdfAsImages: false, CancellationToken.None); + + // Assert + Assert.Equal("minimal", result.Title); + Assert.Single(result.Spine); + } + + [SupportedOSPlatform("windows")] + [Fact] + public async Task GetResourceAsync_WhenCalledForAPage_ShouldRenderThePageImage() + { + // Arrange + string workingDirectory = Path.Combine(_temporaryDirectory, "work"); + + // Act + byte[] result = await _sut.GetResourceAsync(_pdfPath, workingDirectory, "page:1", CancellationToken.None); + + // Assert + Assert.NotNull(result); + Assert.NotEmpty(result); + } + + /// + public void Dispose() + { + if (Directory.Exists(_temporaryDirectory)) + Directory.Delete(_temporaryDirectory, recursive: true); + } +} + diff --git a/tests/IntegrationTests/Lumina.Plugins.Pdf.IntegrationTests/Lumina.Plugins.Pdf.IntegrationTests.csproj b/tests/IntegrationTests/Lumina.Plugins.Pdf.IntegrationTests/Lumina.Plugins.Pdf.IntegrationTests.csproj new file mode 100644 index 00000000..e5717587 --- /dev/null +++ b/tests/IntegrationTests/Lumina.Plugins.Pdf.IntegrationTests/Lumina.Plugins.Pdf.IntegrationTests.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/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 9fad8b58..09d95c44 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 @@ -196,7 +196,7 @@ public class GetBooksLiteEndpointTests : IClassFixture? paginatedBooks = await response.Content.ReadFromJsonAsync>(_jsonOptions); Assert.NotNull(paginatedBooks); Assert.Equal(2, paginatedBooks!.Count); - Assert.Contains(paginatedBooks.Data, book => book.Title == ""); // the empty title book matches the filter through its original title + Assert.Contains(paginatedBooks.Data, book => book.Title == ""); // The empty title book matches the filter through its original title. Assert.Contains(paginatedBooks.Data, book => book.Title == "Racing"); } @@ -222,6 +222,28 @@ public class GetBooksLiteEndpointTests : IClassFixture? paginatedBooks = await response.Content.ReadFromJsonAsync>(_jsonOptions); + Assert.NotNull(paginatedBooks); + Assert.Empty(paginatedBooks!.Data); + Assert.Equal(0, paginatedBooks.Count); + } + [Fact] public async Task GetBooksLite_WhenCalledWithPaginationData_ShouldReturnRequestedPage() { diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/Management/CancelLibraryScanRequestMappingTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/Management/CancelLibraryScanRequestMappingTests.cs new file mode 100644 index 00000000..ece6fcb4 --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/Management/CancelLibraryScanRequestMappingTests.cs @@ -0,0 +1,33 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.Mapping.MediaLibrary.Management; +using Lumina.Application.Core.MediaLibrary.Management.Commands.CancelLibraryScan; +using Lumina.Contracts.Fixtures.Core.Requests.MediaLibrary.Management; +using Lumina.Contracts.Requests.MediaLibrary.Management; +using System; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Application.UnitTests.Common.Mapping.MediaLibrary.Management; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class CancelLibraryScanRequestMappingTests +{ + private readonly CancelLibraryScanRequestFixture _cancelLibraryScanRequestFixture = new(); + + [Fact] + public void ToCommand_WhenMappingValidRequest_ShouldMapCorrectly() + { + // Arrange + CancelLibraryScanRequest request = _cancelLibraryScanRequestFixture.Create(); + + // Act + CancelLibraryScanCommand result = request.ToCommand(); + + // Assert + Assert.Equal(request.LibraryId, result.LibraryId); + Assert.Equal(request.ScanId, result.ScanId); + } +} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/Management/DeleteLibraryRequestMappingTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/Management/DeleteLibraryRequestMappingTests.cs new file mode 100644 index 00000000..1720e82f --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/Management/DeleteLibraryRequestMappingTests.cs @@ -0,0 +1,33 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.Mapping.MediaLibrary.Management; +using Lumina.Application.Core.MediaLibrary.Management.Commands.DeleteLibrary; +using Lumina.Contracts.Fixtures.Core.Requests.MediaLibrary.Management; +using Lumina.Contracts.Requests.MediaLibrary.Management; +using System; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Application.UnitTests.Common.Mapping.MediaLibrary.Management; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class DeleteLibraryRequestMappingTests +{ + private readonly DeleteLibraryRequestFixture _deleteLibraryRequestFixture = new(); + + [Fact] + public void ToCommand_WhenMappingValidRequest_ShouldMapCorrectly() + { + // Arrange + Guid id = Guid.NewGuid(); + DeleteLibraryRequest request = _deleteLibraryRequestFixture.Create(id); + + // Act + DeleteLibraryCommand result = request.ToCommand(); + + // Assert + Assert.Equal(request.Id, result.Id); + } +} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/Management/GetLibraryRequestMappingTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/Management/GetLibraryRequestMappingTests.cs new file mode 100644 index 00000000..071861c3 --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/Management/GetLibraryRequestMappingTests.cs @@ -0,0 +1,33 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.Mapping.MediaLibrary.Management; +using Lumina.Application.Core.MediaLibrary.Management.Queries.GetLibrary; +using Lumina.Contracts.Fixtures.Core.Requests.MediaLibrary.Management; +using Lumina.Contracts.Requests.MediaLibrary.Management; +using System; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Application.UnitTests.Common.Mapping.MediaLibrary.Management; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class GetLibraryRequestMappingTests +{ + private readonly GetLibraryRequestFixture _getLibraryRequestFixture = new(); + + [Fact] + public void ToQuery_WhenMappingValidRequest_ShouldMapCorrectly() + { + // Arrange + Guid id = Guid.NewGuid(); + GetLibraryRequest request = _getLibraryRequestFixture.Create(id); + + // Act + GetLibraryQuery result = request.ToQuery(); + + // Assert + Assert.Equal(request.Id, result.Id); + } +} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/Management/GetLibraryScanProgressRequestMappingTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/Management/GetLibraryScanProgressRequestMappingTests.cs new file mode 100644 index 00000000..2c5f651a --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/Management/GetLibraryScanProgressRequestMappingTests.cs @@ -0,0 +1,32 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.Mapping.MediaLibrary.Management; +using Lumina.Application.Core.MediaLibrary.Management.Queries.GetLibraryScanProgress; +using Lumina.Contracts.Fixtures.Core.Requests.MediaLibrary.Management; +using Lumina.Contracts.Requests.MediaLibrary.Management; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Application.UnitTests.Common.Mapping.MediaLibrary.Management; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class GetLibraryScanProgressRequestMappingTests +{ + private readonly GetLibraryScanProgressRequestFixture _getLibraryScanProgressRequestFixture = new(); + + [Fact] + public void ToQuery_WhenMappingValidRequest_ShouldMapCorrectly() + { + // Arrange + GetLibraryScanProgressRequest request = _getLibraryScanProgressRequestFixture.Create(); + + // Act + GetLibraryScanProgressQuery result = request.ToQuery(); + + // Assert + Assert.Equal(request.LibraryId, result.LibraryId); + Assert.Equal(request.ScanId, result.ScanId); + } +} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/Management/MediaLibraryScanJobProgressMappingTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/Management/MediaLibraryScanJobProgressMappingTests.cs new file mode 100644 index 00000000..b0573e66 --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/Management/MediaLibraryScanJobProgressMappingTests.cs @@ -0,0 +1,37 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.Mapping.MediaLibrary.Management; +using Lumina.Contracts.Responses.MediaLibrary.Management; +using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects; +using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Application.UnitTests.Common.Mapping.MediaLibrary.Management; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class MediaLibraryScanJobProgressMappingTests +{ + private readonly MediaLibraryScanJobProgressFixture _mediaLibraryScanJobProgressFixture = new(); + + [Fact] + public void ToResponse_WhenMappingValidValueObject_ShouldMapCorrectly() + { + // Arrange + MediaLibraryScanJobProgress progress = _mediaLibraryScanJobProgressFixture.Create( + completedItems: 3, + totalItems: 10, + currentOperation: "Hashing files"); + + // Act + MediaLibraryScanJobProgressResponse result = progress.ToResponse(); + + // Assert + Assert.Equal(progress.CompletedItems, result.CompletedItems); + Assert.Equal(progress.TotalItems, result.TotalItems); + Assert.Equal(progress.CurrentOperation, result.CurrentOperation); + Assert.Equal(progress.ProgressPercentage, result.ProgressPercentage); + } +} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/Management/ScanLibraryRequestMappingTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/Management/ScanLibraryRequestMappingTests.cs new file mode 100644 index 00000000..62acce21 --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/Management/ScanLibraryRequestMappingTests.cs @@ -0,0 +1,33 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.Mapping.MediaLibrary.Management; +using Lumina.Application.Core.MediaLibrary.Management.Commands.ScanLibrary; +using Lumina.Contracts.Fixtures.Core.Requests.MediaLibrary.Management; +using Lumina.Contracts.Requests.MediaLibrary.Management; +using System; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Application.UnitTests.Common.Mapping.MediaLibrary.Management; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class ScanLibraryRequestMappingTests +{ + private readonly ScanLibraryRequestFixture _scanLibraryRequestFixture = new(); + + [Fact] + public void ToCommand_WhenMappingValidRequest_ShouldMapCorrectly() + { + // Arrange + Guid id = Guid.NewGuid(); + ScanLibraryRequest request = _scanLibraryRequestFixture.Create(id); + + // Act + ScanLibraryCommand result = request.ToCommand(); + + // Assert + Assert.Equal(request.Id, result.Id); + } +} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/Management/UpdateLibraryRequestMappingTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/Management/UpdateLibraryRequestMappingTests.cs new file mode 100644 index 00000000..cf7be28a --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/Management/UpdateLibraryRequestMappingTests.cs @@ -0,0 +1,49 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.Mapping.MediaLibrary.Management; +using Lumina.Application.Core.MediaLibrary.Management.Commands.UpdateLibrary; +using Lumina.Contracts.Fixtures.Core.Requests.MediaLibrary.Management; +using Lumina.Contracts.Requests.MediaLibrary.Management; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Application.UnitTests.Common.Mapping.MediaLibrary.Management; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class UpdateLibraryRequestMappingTests +{ + private readonly UpdateLibraryRequestFixture _updateLibraryRequestFixture = new(); + + [Fact] + public void ToCommand_WhenMappingValidRequest_ShouldMapCorrectly() + { + // Arrange + UpdateLibraryRequest request = _updateLibraryRequestFixture.Create( + title: "My Library", + libraryType: "Book", + contentLocations: ["C:/Books", "D:/Media/Books"], + coverImage: "D:/poster.jpg", + isEnabled: true, + isLocked: false, + canDownloadMetadataFromWeb: true, + shouldSaveMetadataInMediaDirectories: false, + shouldSkipUnchangedDirectoriesDuringScan: false); + + // Act + UpdateLibraryCommand result = request.ToCommand(); + + // Assert + Assert.Equal(request.Id, result.Id); + Assert.Equal(request.Title, result.Title); + Assert.Equal(request.LibraryType, result.LibraryType); + Assert.Equal(request.ContentLocations, result.ContentLocations); + Assert.Equal(request.CoverImage, result.CoverImage); + Assert.Equal(request.IsEnabled, result.IsEnabled); + Assert.Equal(request.IsLocked, result.IsLocked); + Assert.Equal(request.CanDownloadMetadataFromWeb, result.CanDownloadMetadataFromWeb); + Assert.Equal(request.ShouldSaveMetadataInMediaDirectories, result.ShouldSaveMetadataInMediaDirectories); + Assert.Equal(request.ShouldSkipUnchangedDirectoriesDuringScan, result.ShouldSkipUnchangedDirectoriesDuringScan); + } +} 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 159942c5..8131f3a8 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 @@ -3,8 +3,10 @@ using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentL using Lumina.Application.Common.Mapping.Common.Metadata; using Lumina.Application.Common.Mapping.MediaLibrary.WrittenContentLibrary.BookLibrary.Books; using Lumina.Application.Common.Mapping.MediaLibrary.WrittenContentLibrary.BookLibrary.Common; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary; using Lumina.Domain.Core.BoundedContexts.WrittenContentLibraryBoundedContext.BookLibraryAggregate; using Lumina.Domain.Fixtures.Core.BoundedContexts.WrittenContentLibraryBoundedContext.BookLibraryAggregate; +using System; using System.Diagnostics.CodeAnalysis; using System.Linq; #endregion @@ -18,6 +20,7 @@ namespace Lumina.Application.UnitTests.Common.Mapping.MediaLibrary.WrittenConten public class BookMappingTests { private readonly BookFixture _bookFixture = new(); + private readonly BookEntityFixture _bookEntityFixture = new(); [Fact] public void ToRepositoryEntity_WhenMappingCompleteBook_ShouldMapAllPropertiesCorrectly() @@ -67,4 +70,73 @@ public class BookMappingTests Assert.Equal(book.CreatedOnUtc, result.CreatedOnUtc); Assert.Equal(book.UpdatedOnUtc.HasValue ? book.UpdatedOnUtc.Value : null, result.UpdatedOnUtc); } + + [Fact] + public void ApplyMetadataToEntity_WhenApplyingCompleteBook_ShouldOverwriteTheMetadataFields() + { + // Arrange + Book book = _bookFixture.Create(); + BookEntity entity = _bookEntityFixture.Create(); + BookEntity expectedEntity = book.ToRepositoryEntity(); + + // Act + entity.ApplyMetadataToEntity(book); + + // Assert + Assert.Equal(book.Metadata.Title, entity.Title); + Assert.Equal(expectedEntity.OriginalTitle, entity.OriginalTitle); + Assert.Equal(expectedEntity.Description, entity.Description); + Assert.Equal(expectedEntity.OriginalReleaseDate, entity.OriginalReleaseDate); + Assert.Equal(expectedEntity.OriginalReleaseYear, entity.OriginalReleaseYear); + Assert.Equal(expectedEntity.ReReleaseDate, entity.ReReleaseDate); + Assert.Equal(expectedEntity.ReReleaseYear, entity.ReReleaseYear); + Assert.Equal(expectedEntity.ReleaseCountry, entity.ReleaseCountry); + Assert.Equal(expectedEntity.ReleaseVersion, entity.ReleaseVersion); + Assert.Equal(expectedEntity.LanguageCode, entity.LanguageCode); + Assert.Equal(expectedEntity.LanguageName, entity.LanguageName); + Assert.Equal(expectedEntity.LanguageNativeName, entity.LanguageNativeName); + Assert.Equal(expectedEntity.OriginalLanguageCode, entity.OriginalLanguageCode); + Assert.Equal(expectedEntity.OriginalLanguageName, entity.OriginalLanguageName); + Assert.Equal(expectedEntity.OriginalLanguageNativeName, entity.OriginalLanguageNativeName); + Assert.Equal(expectedEntity.Publisher, entity.Publisher); + Assert.Equal(expectedEntity.PageCount, entity.PageCount); + Assert.Equal(expectedEntity.Format, entity.Format); + Assert.Equal(expectedEntity.Edition, entity.Edition); + Assert.Equal(expectedEntity.VolumeNumber, entity.VolumeNumber); + Assert.Equal(expectedEntity.ASIN, entity.ASIN); + Assert.Equal(expectedEntity.GoodreadsId, entity.GoodreadsId); + Assert.Equal(expectedEntity.LCCN, entity.LCCN); + Assert.Equal(expectedEntity.OCLCNumber, entity.OCLCNumber); + Assert.Equal(expectedEntity.OpenLibraryId, entity.OpenLibraryId); + Assert.Equal(expectedEntity.LibraryThingId, entity.LibraryThingId); + Assert.Equal(expectedEntity.GoogleBooksId, entity.GoogleBooksId); + Assert.Equal(expectedEntity.BarnesAndNobleId, entity.BarnesAndNobleId); + Assert.Equal(expectedEntity.AppleBooksId, entity.AppleBooksId); + Assert.NotNull(entity.UpdatedOnUtc); + Assert.NotNull(entity.UpdatedBy); + } + + [Fact] + public void ApplyMetadataToEntity_WhenApplyingBook_ShouldPreserveIdentityAndCollectionColumns() + { + // Arrange + Book book = _bookFixture.Create(); + BookEntity entity = _bookEntityFixture.Create(); + Guid entityId = entity.Id; + Guid libraryId = entity.LibraryId; + string path = entity.Path; + int isbnsCount = entity.ISBNs.Count; + int ratingsCount = entity.Ratings.Count; + + // Act + entity.ApplyMetadataToEntity(book); + + // Assert + // the identity and the collection columns are not part of the metadata application + Assert.Equal(entityId, entity.Id); + Assert.Equal(libraryId, entity.LibraryId); + Assert.Equal(path, entity.Path); + Assert.Equal(isbnsCount, entity.ISBNs.Count); + Assert.Equal(ratingsCount, entity.Ratings.Count); + } } diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/BookMetadataDtoMappingTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/BookMetadataDtoMappingTests.cs index ad0cd120..5dcf533a 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/BookMetadataDtoMappingTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/BookMetadataDtoMappingTests.cs @@ -1,12 +1,15 @@ #region ========================================================================= USING ===================================================================================== using Lumina.Application.Common.Mapping.MediaLibrary.WrittenContentLibrary.BookLibrary.Books; +using Lumina.Contracts.DTO.Common; using Lumina.Contracts.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary; using Lumina.Contracts.Fixtures.Core.DTO.Common; using Lumina.Contracts.Fixtures.Core.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary; +using Lumina.Domain.Common.Errors; using Lumina.Domain.Common.Primitives; using Lumina.Domain.Core.BoundedContexts.WrittenContentLibraryBoundedContext.BookLibraryAggregate; using Lumina.Domain.Fixtures.Core.BoundedContexts.WrittenContentLibraryBoundedContext.BookLibraryAggregate; using Lumina.Domain.SharedKernel.Common.Enums.BookLibrary; +using System; using System.Diagnostics.CodeAnalysis; #endregion @@ -66,4 +69,171 @@ public class BookMetadataDtoMappingTests Assert.True(result.IsFailure); Assert.NotEqual("The Fellowship of the Ring", book.Metadata.Title); } + + [Theory] + [InlineData(null)] // missing title + [InlineData("")] // empty title + [InlineData(" ")] // whitespace title + public void ApplyMetadata_WhenTitleIsNullOrWhitespace_ShouldReturnTitleCannotBeEmptyError(string? title) + { + // Arrange + Book book = _bookFixture.Create(); + BookMetadataDto metadata = _bookMetadataDtoFixture.Create(title: title, includeOptionalProperties: false); + + // Act + Result result = book.ApplyMetadata(metadata); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.Metadata.TitleCannotBeEmpty, result.FirstError); + } + + [Fact] + public void ApplyMetadata_WhenReleaseInfoIsNull_ShouldReturnReleaseInfoCannotBeNullError() + { + // Arrange + Book book = _bookFixture.Create(); + BookMetadataDto metadata = _bookMetadataDtoFixture.Create(title: "A valid title", includeOptionalProperties: false); + + // Act + Result result = book.ApplyMetadata(metadata); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.Metadata.ReleaseInfoCannotBeNull, result.FirstError); + } + + [Fact] + public void ApplyMetadata_WhenReleaseInfoIsInvalid_ShouldReturnError() + { + // Arrange + Book book = _bookFixture.Create(); + BookMetadataDto metadata = _bookMetadataDtoFixture.Create( + title: "A valid title", + releaseInfo: new ReleaseInfoDto(new DateOnly(2000, 1, 1), 1999, null, null, null, null)); + + // Act + Result result = book.ApplyMetadata(metadata); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.Metadata.OriginalReleaseDateAndYearMustMatch, result.FirstError); + } + + [Fact] + public void ApplyMetadata_WhenTagsAreInvalid_ShouldReturnError() + { + // Arrange + Book book = _bookFixture.Create(); + BookMetadataDto metadata = _bookMetadataDtoFixture.Create( + title: "A valid title", + tags: [new TagDto(" ")]); + + // Act + Result result = book.ApplyMetadata(metadata); + + // Assert + Assert.True(result.IsFailure); + } + + [Fact] + public void ApplyMetadata_WhenLanguageIsInvalid_ShouldReturnError() + { + // Arrange + Book book = _bookFixture.Create(); + BookMetadataDto metadata = _bookMetadataDtoFixture.Create( + title: "A valid title", + language: new LanguageInfoDto("", "English", "English")); + + // Act + Result result = book.ApplyMetadata(metadata); + + // Assert + Assert.True(result.IsFailure); + } + + [Fact] + public void ApplyMetadata_WhenOriginalLanguageIsInvalid_ShouldReturnError() + { + // Arrange + Book book = _bookFixture.Create(); + BookMetadataDto metadata = _bookMetadataDtoFixture.Create( + title: "A valid title", + originalLanguage: new LanguageInfoDto("", "English", "English")); + + // Act + Result result = book.ApplyMetadata(metadata); + + // Assert + Assert.True(result.IsFailure); + } + + [Fact] + public void ApplyMetadata_WhenIsbnIsInvalid_ShouldReturnError() + { + // Arrange + Book book = _bookFixture.Create(); + BookMetadataDto metadata = _bookMetadataDtoFixture.Create( + title: "A valid title", + isbns: [new IsbnDto("not-an-isbn", IsbnFormat.Isbn13)]); + + // Act + Result result = book.ApplyMetadata(metadata); + + // Assert + Assert.True(result.IsFailure); + } + + [Fact] + public void ApplyMetadata_WhenRatingIsInvalid_ShouldReturnError() + { + // Arrange + Book book = _bookFixture.Create(); + BookMetadataDto metadata = _bookMetadataDtoFixture.Create( + title: "A valid title", + ratings: [new BookRatingDto(-1m, 5m, null, null)]); + + // Act + Result result = book.ApplyMetadata(metadata); + + // Assert + Assert.True(result.IsFailure); + } + + [Fact] + public void ApplyMetadata_WhenOptionalCollectionsAreNull_ShouldApplyMetadataWithoutCollections() + { + // Arrange + Book book = _bookFixture.Create(); + BookMetadataDto metadata = _bookMetadataDtoFixture.Create( + title: "A valid title", + releaseInfo: new ReleaseInfoDto(new DateOnly(2000, 1, 1), 2000, null, null, null, null), + includeOptionalProperties: false); + + // Act + Result result = book.ApplyMetadata(metadata); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal("A valid title", book.Metadata.Title); + } + + [Fact] + public void ApplyMetadata_WhenIsbnsAndRatingsAreValid_ShouldApplyMetadataWithTheCollections() + { + // Arrange + Book book = _bookFixture.Create(); + BookMetadataDto metadata = _bookMetadataDtoFixture.Create( + title: "A valid title", + isbns: [new IsbnDto("9780306406157", IsbnFormat.Isbn13)], + ratings: [new BookRatingDto(4m, 5m, null, 10)]); + + // Act + Result result = book.ApplyMetadata(metadata); + + // Assert + Assert.False(result.IsFailure); + Assert.Single(book.ISBNs); + Assert.Single(book.Ratings); + } } diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/GetReadingAvailabilityRequestMappingTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/GetReadingAvailabilityRequestMappingTests.cs new file mode 100644 index 00000000..697d16a1 --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/GetReadingAvailabilityRequestMappingTests.cs @@ -0,0 +1,32 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.Mapping.MediaLibrary.WrittenContentLibrary.BookLibrary.Books; +using Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Reading.Queries.GetReadingAvailability; +using Lumina.Contracts.Fixtures.Core.Requests.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Reading; +using Lumina.Contracts.Requests.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Reading; +using System; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Application.UnitTests.Common.Mapping.MediaLibrary.WrittenContentLibrary.BookLibrary.Books; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class GetReadingAvailabilityRequestMappingTests +{ + private readonly GetReadingAvailabilityRequestFixture _getReadingAvailabilityRequestFixture = new(); + + [Fact] + public void ToQuery_WhenMappingValidRequest_ShouldMapCorrectly() + { + // Arrange + GetReadingAvailabilityRequest request = _getReadingAvailabilityRequestFixture.Create(); + + // Act + GetReadingAvailabilityQuery result = request.ToQuery(); + + // Assert + Assert.Equal(request.BookId, result.BookId); + } +} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Plugins/GetLibraryArtworkProvidersRequestMappingTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Plugins/GetLibraryArtworkProvidersRequestMappingTests.cs new file mode 100644 index 00000000..d2cec660 --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Plugins/GetLibraryArtworkProvidersRequestMappingTests.cs @@ -0,0 +1,31 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.Mapping.Plugins; +using Lumina.Application.Core.Plugins.Queries.GetLibraryArtworkProviders; +using Lumina.Contracts.Fixtures.Core.Requests.Plugins; +using Lumina.Contracts.Requests.Plugins; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Application.UnitTests.Common.Mapping.Plugins; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class GetLibraryArtworkProvidersRequestMappingTests +{ + private readonly GetLibraryArtworkProvidersRequestFixture _getLibraryArtworkProvidersRequestFixture = new(); + + [Fact] + public void ToQuery_WhenMappingValidRequest_ShouldMapCorrectly() + { + // Arrange + GetLibraryArtworkProvidersRequest request = _getLibraryArtworkProvidersRequestFixture.Create(); + + // Act + GetLibraryArtworkProvidersQuery result = request.ToQuery(); + + // Assert + Assert.Equal(request.LibraryId, result.LibraryId); + } +} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Plugins/ReorderLibraryArtworkProvidersRequestMappingTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Plugins/ReorderLibraryArtworkProvidersRequestMappingTests.cs new file mode 100644 index 00000000..eb922a18 --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Plugins/ReorderLibraryArtworkProvidersRequestMappingTests.cs @@ -0,0 +1,32 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.Mapping.Plugins; +using Lumina.Application.Core.Plugins.Commands.ReorderLibraryArtworkProviders; +using Lumina.Contracts.Fixtures.Core.Requests.Plugins; +using Lumina.Contracts.Requests.Plugins; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Application.UnitTests.Common.Mapping.Plugins; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class ReorderLibraryArtworkProvidersRequestMappingTests +{ + private readonly ReorderLibraryArtworkProvidersRequestFixture _reorderLibraryArtworkProvidersRequestFixture = new(); + + [Fact] + public void ToCommand_WhenMappingValidRequest_ShouldMapCorrectly() + { + // Arrange + ReorderLibraryArtworkProvidersRequest request = _reorderLibraryArtworkProvidersRequestFixture.Create(); + + // Act + ReorderLibraryArtworkProvidersCommand result = request.ToCommand(); + + // Assert + Assert.Equal(request.LibraryId, result.LibraryId); + Assert.Equal(request.PluginIds, result.PluginIds); + } +} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Plugins/SetLibraryArtworkProviderEnabledRequestMappingTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Plugins/SetLibraryArtworkProviderEnabledRequestMappingTests.cs new file mode 100644 index 00000000..b4ce861a --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Plugins/SetLibraryArtworkProviderEnabledRequestMappingTests.cs @@ -0,0 +1,33 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.Mapping.Plugins; +using Lumina.Application.Core.Plugins.Commands.SetLibraryArtworkProviderEnabled; +using Lumina.Contracts.Fixtures.Core.Requests.Plugins; +using Lumina.Contracts.Requests.Plugins; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Application.UnitTests.Common.Mapping.Plugins; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class SetLibraryArtworkProviderEnabledRequestMappingTests +{ + private readonly SetLibraryArtworkProviderEnabledRequestFixture _setLibraryArtworkProviderEnabledRequestFixture = new(); + + [Fact] + public void ToCommand_WhenMappingValidRequest_ShouldMapCorrectly() + { + // Arrange + SetLibraryArtworkProviderEnabledRequest request = _setLibraryArtworkProviderEnabledRequestFixture.Create(isEnabled: true); + + // Act + SetLibraryArtworkProviderEnabledCommand result = request.ToCommand(); + + // Assert + 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/Telemetry/HandlerOutcomeDetectorTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Common/Telemetry/HandlerOutcomeDetectorTests.cs new file mode 100644 index 00000000..d12d4c79 --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Common/Telemetry/HandlerOutcomeDetectorTests.cs @@ -0,0 +1,93 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.Telemetry; +using Lumina.Domain.Common.Primitives; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Application.UnitTests.Common.Telemetry; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class HandlerOutcomeDetectorTests +{ + [Fact] + public void IsSuccessful_WhenResultIsNull_ShouldReturnTrue() + { + // Act + bool result = HandlerOutcomeDetector.IsSuccessful(null); + + // Assert + Assert.True(result); + } + + [Fact] + public void IsSuccessful_WhenResultExposesNoSuccessFlag_ShouldReturnTrue() + { + // Act + bool result = HandlerOutcomeDetector.IsSuccessful("a plain dto"); + + // Assert + Assert.True(result); + } + + [Fact] + public void IsSuccessful_WhenResultIsSuccessful_ShouldReturnTrue() + { + // Arrange + Result resultValue = Result.Success("value"); + + // Act + bool result = HandlerOutcomeDetector.IsSuccessful(resultValue); + + // Assert + Assert.True(result); + } + + [Fact] + public void IsSuccessful_WhenResultIsFailed_ShouldReturnFalse() + { + // Arrange + Result resultValue = Result.Failure(Error.Validation("Test.Code", "Test description")); + + // Act + bool result = HandlerOutcomeDetector.IsSuccessful(resultValue); + + // Assert + Assert.False(result); + } + + [Fact] + public void GetErrorDescription_WhenResultIsNull_ShouldReturnNull() + { + // Act + string? result = HandlerOutcomeDetector.GetErrorDescription(null); + + // Assert + Assert.Null(result); + } + + [Fact] + public void GetErrorDescription_WhenResultExposesNoFirstError_ShouldReturnNull() + { + // Act + string? result = HandlerOutcomeDetector.GetErrorDescription("a plain dto"); + + // Assert + Assert.Null(result); + } + + [Fact] + public void GetErrorDescription_WhenResultIsFailed_ShouldReturnFirstErrorDescription() + { + // Arrange + Result resultValue = Result.Failure(Error.Validation("Test.Code", "Test description")); + + // Act + string? result = HandlerOutcomeDetector.GetErrorDescription(resultValue); + + // Assert + Assert.Equal("Test description", result); + } +} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Common/Telemetry/TelemetryDecoratorFactoryTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Common/Telemetry/TelemetryDecoratorFactoryTests.cs new file mode 100644 index 00000000..82a142f6 --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Common/Telemetry/TelemetryDecoratorFactoryTests.cs @@ -0,0 +1,72 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.CQRS; +using Lumina.Application.Common.Telemetry; +using Lumina.Application.Core.Admin.Authorization.Roles.Commands.AddRole; +using Lumina.Application.Core.Admin.Authorization.Roles.Queries.GetRolePermissions; +using Lumina.Contracts.Responses.Authorization; +using Lumina.Domain.Common.Events; +using Lumina.Domain.Common.Primitives; +using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.Events; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Application.UnitTests.Common.Telemetry; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class TelemetryDecoratorFactoryTests +{ + [Fact] + public void GetDecoratorType_WhenContractIsQueryHandler_ShouldReturnQueryDecoratorType() + { + // Arrange + Type contract = typeof(IQueryHandler>); + + // Act + Type result = TelemetryDecoratorFactory.GetDecoratorType(contract); + + // Assert + Assert.Equal(typeof(TelemetryQueryHandlerDecorator>), result); + } + + [Fact] + public void GetDecoratorType_WhenContractIsCommandHandler_ShouldReturnCommandDecoratorType() + { + // Arrange + Type contract = typeof(ICommandHandler>); + + // Act + Type result = TelemetryDecoratorFactory.GetDecoratorType(contract); + + // Assert + Assert.Equal(typeof(TelemetryCommandHandlerDecorator>), result); + } + + [Fact] + public void GetDecoratorType_WhenContractIsDomainEventHandler_ShouldReturnDomainEventHandlerDecoratorType() + { + // Arrange + Type contract = typeof(IDomainEventHandler); + + // Act + Type result = TelemetryDecoratorFactory.GetDecoratorType(contract); + + // Assert + Assert.Equal(typeof(TelemetryDomainEventHandlerDecorator), result); + } + + [Fact] + public void GetDecoratorType_WhenContractIsNotSupported_ShouldThrowArgumentException() + { + // Arrange + Type contract = typeof(IEnumerable); + + // Act & Assert + ArgumentException exception = Assert.Throws(() => TelemetryDecoratorFactory.GetDecoratorType(contract)); + Assert.Contains("No telemetry decorator is defined", exception.Message); + } +} diff --git a/tests/UnitTests/Lumina.DataAccess.UnitTests/Common/Dapper/SqliteGuidTypeHandlerTests.cs b/tests/UnitTests/Lumina.DataAccess.UnitTests/Common/Dapper/SqliteGuidTypeHandlerTests.cs new file mode 100644 index 00000000..605d437e --- /dev/null +++ b/tests/UnitTests/Lumina.DataAccess.UnitTests/Common/Dapper/SqliteGuidTypeHandlerTests.cs @@ -0,0 +1,81 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.DataAccess.Common.Dapper; +using NSubstitute; +using System; +using System.Data; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.DataAccess.UnitTests.Common.Dapper; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class SqliteGuidTypeHandlerTests +{ + private readonly SqliteGuidTypeHandler _sut; + + /// + /// Initializes a new instance of the class. + /// + public SqliteGuidTypeHandlerTests() + { + _sut = new SqliteGuidTypeHandler(); + } + + [Fact] + public void SetValue_WhenCalled_ShouldStoreTheGuidAsItsTextRepresentation() + { + // Arrange + IDbDataParameter parameter = Substitute.For(); + Guid guid = Guid.NewGuid(); + + // Act + _sut.SetValue(parameter, guid); + + // Assert + Assert.Equal(guid.ToString(), (string?)parameter.Value); + } + + [Fact] + public void Parse_WhenValueIsGuid_ShouldReturnTheSameGuid() + { + // Arrange + Guid guid = Guid.NewGuid(); + object value = guid; + + // Act + Guid parsed = _sut.Parse(value); + + // Assert + Assert.Equal(guid, parsed); + } + + [Fact] + public void Parse_WhenValueIsGuidText_ShouldReturnTheParsedGuid() + { + // Arrange + Guid guid = Guid.NewGuid(); + object value = guid.ToString(); + + // Act + Guid parsed = _sut.Parse(value); + + // Assert + Assert.Equal(guid, parsed); + } + + [Fact] + public void Parse_WhenValueIsNotValidGuidText_ShouldThrowFormatException() + { + // Arrange + object value = "not-a-guid"; + + // Act + Action act = () => _sut.Parse(value); + + // Assert + Assert.Throws(act); + } +} diff --git a/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Repositories/Books/BookRepositoryTests.cs b/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Repositories/Books/BookRepositoryTests.cs index b6fd72d0..e80bfb33 100644 --- a/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Repositories/Books/BookRepositoryTests.cs +++ b/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Repositories/Books/BookRepositoryTests.cs @@ -18,7 +18,6 @@ using Lumina.Domain.SharedKernel.Common.Enums.BookLibrary; using Lumina.Domain.SharedKernel.Common.Enums.Common; using Lumina.Domain.SharedKernel.Common.Enums.MediaContributors; using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; -using Microsoft.Data.Sqlite; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.ChangeTracking; using System; @@ -73,7 +72,7 @@ public class BookRepositoryTests Assert.False(result.IsFailure); Assert.Equal(Result.Created, result.Value); - // check if the book was added to the context's ChangeTracker + // Check if the book was added to the context's ChangeTracker. EntityEntry? addedBook = _mockContext.ChangeTracker.Entries() .FirstOrDefault(e => e.State == EntityState.Added && e.Entity.Id == bookModel.Id); Assert.NotNull(addedBook); @@ -94,7 +93,7 @@ public class BookRepositoryTests // Assert Assert.True(result.IsFailure); Assert.Equal(Errors.WrittenContent.BookAlreadyExists, result.FirstError); - Assert.Single(_mockContext.ChangeTracker.Entries()); // only the existing book should be in the context + Assert.Single(_mockContext.ChangeTracker.Entries()); // Only the existing book should be in the context. } [Fact] @@ -595,116 +594,6 @@ public class BookRepositoryTests Assert.Equal(1, result.Value); } - [Fact] - public async Task ResetEnrichmentStateForPathsAsync_WhenCalled_ShouldResetTheMetadataAndArtworkStatusesForThePaths() - { - // Arrange - // the reset methods use ExecuteUpdateAsync, which is not supported by the in-memory provider, so a real SQLite database is used - using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-bookrepo-reset-{Guid.NewGuid()};Mode=Memory;Cache=Shared"); - anchorConnection.Open(); - LuminaDbContext context = new(new DbContextOptionsBuilder().UseSqlite(anchorConnection.ConnectionString).Options); - context.Database.EnsureCreated(); - BookRepository sut = new(context); - - Guid libraryId = Guid.NewGuid(); - BookEntity changedBook = _bookEntityFixture.Create(); - changedBook.LibraryId = libraryId; - changedBook.Path = "/books/changed.epub"; - changedBook.MetadataStatus = MetadataStatus.Enriched; - changedBook.BookArtwork = [_bookArtworkEntityFixture.Create(bookId: changedBook.Id, artworkType: ArtworkType.Cover, ordinal: 0, status: ArtworkStatus.Enriched)]; - BookEntity unchangedBook = _bookEntityFixture.Create(); - unchangedBook.LibraryId = libraryId; - unchangedBook.Path = "/books/unchanged.epub"; - unchangedBook.MetadataStatus = MetadataStatus.Enriched; - unchangedBook.BookArtwork = [_bookArtworkEntityFixture.Create(bookId: unchangedBook.Id, artworkType: ArtworkType.Cover, ordinal: 0, status: ArtworkStatus.Enriched)]; - context.Books.AddRange(changedBook, unchangedBook); - await context.SaveChangesAsync(); - - // Act - Result result = await sut.ResetEnrichmentStateForPathsAsync(libraryId, ["/books/changed.epub"], CancellationToken.None); - - // Assert - Assert.False(result.IsFailure); - Assert.Equal(Result.Updated, result.Value); - BookEntity? resetBook = await context.Books.AsNoTracking().Include(book => book.BookArtwork).FirstOrDefaultAsync(book => book.Id == changedBook.Id); - Assert.NotNull(resetBook); - Assert.Equal(MetadataStatus.Pending, resetBook!.MetadataStatus); - Assert.Equal(ArtworkStatus.Pending, resetBook.BookArtwork.Single().Status); - BookEntity? keptBook = await context.Books.AsNoTracking().FirstOrDefaultAsync(book => book.Id == unchangedBook.Id); - Assert.NotNull(keptBook); - Assert.Equal(MetadataStatus.Enriched, keptBook!.MetadataStatus); - } - - [Fact] - public async Task ResetMetadataStatusForLibraryAsync_WhenCalled_ShouldResetTheMetadataStatusOfAllBooksOfTheLibrary() - { - // Arrange - // the reset methods use ExecuteUpdateAsync, which is not supported by the in-memory provider, so a real SQLite database is used - using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-bookrepo-reset-{Guid.NewGuid()};Mode=Memory;Cache=Shared"); - anchorConnection.Open(); - LuminaDbContext context = new(new DbContextOptionsBuilder().UseSqlite(anchorConnection.ConnectionString).Options); - context.Database.EnsureCreated(); - BookRepository sut = new(context); - - Guid libraryId = Guid.NewGuid(); - BookEntity enrichedBook = _bookEntityFixture.Create(); - enrichedBook.LibraryId = libraryId; - enrichedBook.MetadataStatus = MetadataStatus.Enriched; - BookEntity bookOfAnotherLibrary = _bookEntityFixture.Create(); - bookOfAnotherLibrary.LibraryId = Guid.NewGuid(); - bookOfAnotherLibrary.MetadataStatus = MetadataStatus.Enriched; - context.Books.AddRange(enrichedBook, bookOfAnotherLibrary); - await context.SaveChangesAsync(); - - // Act - Result result = await sut.ResetMetadataStatusForLibraryAsync(libraryId, CancellationToken.None); - - // Assert - Assert.False(result.IsFailure); - Assert.Equal(Result.Updated, result.Value); - BookEntity? resetBook = await context.Books.AsNoTracking().FirstOrDefaultAsync(book => book.Id == enrichedBook.Id); - Assert.NotNull(resetBook); - Assert.Equal(MetadataStatus.Pending, resetBook!.MetadataStatus); - BookEntity? keptBook = await context.Books.AsNoTracking().FirstOrDefaultAsync(book => book.Id == bookOfAnotherLibrary.Id); - Assert.NotNull(keptBook); - Assert.Equal(MetadataStatus.Enriched, keptBook!.MetadataStatus); - } - - [Fact] - public async Task ResetArtworkStatusForLibraryAsync_WhenCalled_ShouldResetTheArtworkStatusOfTheLibraryBooks() - { - // Arrange - // the reset methods use ExecuteUpdateAsync, which is not supported by the in-memory provider, so a real SQLite database is used - using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-bookrepo-reset-{Guid.NewGuid()};Mode=Memory;Cache=Shared"); - anchorConnection.Open(); - LuminaDbContext context = new(new DbContextOptionsBuilder().UseSqlite(anchorConnection.ConnectionString).Options); - context.Database.EnsureCreated(); - BookRepository sut = new(context); - - Guid libraryId = Guid.NewGuid(); - BookEntity book = _bookEntityFixture.Create(); - book.LibraryId = libraryId; - book.BookArtwork = [_bookArtworkEntityFixture.Create(bookId: book.Id, artworkType: ArtworkType.Cover, ordinal: 0, status: ArtworkStatus.Enriched)]; - BookEntity bookOfAnotherLibrary = _bookEntityFixture.Create(); - bookOfAnotherLibrary.LibraryId = Guid.NewGuid(); - bookOfAnotherLibrary.BookArtwork = [_bookArtworkEntityFixture.Create(bookId: bookOfAnotherLibrary.Id, artworkType: ArtworkType.Cover, ordinal: 0, status: ArtworkStatus.Enriched)]; - context.Books.AddRange(book, bookOfAnotherLibrary); - await context.SaveChangesAsync(); - - // Act - Result result = await sut.ResetArtworkStatusForLibraryAsync(libraryId, CancellationToken.None); - - // Assert - Assert.False(result.IsFailure); - Assert.Equal(Result.Updated, result.Value); - BookArtworkEntity? resetArtwork = await context.Set().AsNoTracking().FirstOrDefaultAsync(artwork => artwork.BookId == book.Id); - Assert.NotNull(resetArtwork); - Assert.Equal(ArtworkStatus.Pending, resetArtwork!.Status); - BookArtworkEntity? keptArtwork = await context.Set().AsNoTracking().FirstOrDefaultAsync(artwork => artwork.BookId == bookOfAnotherLibrary.Id); - Assert.NotNull(keptArtwork); - Assert.Equal(ArtworkStatus.Enriched, keptArtwork!.Status); - } - [Fact] public async Task GetAuthorsDisplayNamesByBookIdsAsync_WhenCalled_ShouldReturnTheAuthorDisplayNames() { @@ -730,7 +619,7 @@ public class BookRepositoryTests // Assert Assert.False(result.IsFailure); - // only the author contributor of the first book is returned; the book with no author is not included + // Only the author contributor of the first book is returned; the book with no author is not included. Assert.Single(result.Value); Assert.Equal("Frank Herbert", result.Value[firstBook.Id]); } @@ -764,4 +653,258 @@ public class BookRepositoryTests Assert.True(result.IsFailure); Assert.Equal(Errors.WrittenContent.BookNotFound, result.FirstError); } + + [Fact] + public async Task GetByIdAsync_WhenBookExists_ShouldReturnTheBook() + { + // Arrange + BookEntity book = _bookEntityFixture.Create(); + _mockContext.Books.Add(book); + await _mockContext.SaveChangesAsync(); + + // Act + Result result = await _sut.GetByIdAsync(book.Id, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal(book.Id, result.Value!.Id); + } + + [Fact] + public async Task GetByIdAsync_WhenBookDoesNotExist_ShouldReturnNull() + { + // Act + Result result = await _sut.GetByIdAsync(Guid.NewGuid(), CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + Assert.Null(result.Value); + } + + [Fact] + public async Task GetByIdAsync_WhenBookExists_ShouldIncludeRelatedEntities() + { + // Arrange + BookEntity book = _bookEntityFixture.Create(); + book.Tags = [_tagEntityFixture.Create(name: "Tag1"), _tagEntityFixture.Create(name: "Tag2")]; + book.Genres = [_genreEntityFixture.Create(name: "Genre1"), _genreEntityFixture.Create(name: "Genre2")]; + book.ISBNs = [_isbnEntityFixture.Create(value: "1234567890", format: IsbnFormat.Isbn10), _isbnEntityFixture.Create(value: "1234567890123", format: IsbnFormat.Isbn13)]; + book.BookArtwork = [_bookArtworkEntityFixture.Create(bookId: book.Id, artworkType: ArtworkType.Cover, ordinal: 0, status: ArtworkStatus.Enriched)]; + _mockContext.Books.Add(book); + await _mockContext.SaveChangesAsync(); + + // Act + Result result = await _sut.GetByIdAsync(book.Id, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + BookEntity retrievedBook = result.Value!; + Assert.Equal(2, retrievedBook.Tags.Count); + Assert.Equal(2, retrievedBook.Genres.Count); + Assert.Equal(2, retrievedBook.ISBNs.Count); + Assert.Single(retrievedBook.BookArtwork); + } + + [Fact] + public async Task GetBooksNeedingMetadataCountAsync_WhenCalled_ShouldCountOnlyBooksWhoseMetadataIsNotEnriched() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + BookEntity pendingBook = _bookEntityFixture.Create(); + pendingBook.LibraryId = libraryId; + pendingBook.MetadataStatus = MetadataStatus.Pending; + BookEntity enrichedBook = _bookEntityFixture.Create(); + enrichedBook.LibraryId = libraryId; + enrichedBook.MetadataStatus = MetadataStatus.Enriched; + BookEntity failedBook = _bookEntityFixture.Create(); + failedBook.LibraryId = libraryId; + failedBook.MetadataStatus = MetadataStatus.Failed; + BookEntity bookOfAnotherLibrary = _bookEntityFixture.Create(); + bookOfAnotherLibrary.LibraryId = Guid.NewGuid(); + bookOfAnotherLibrary.MetadataStatus = MetadataStatus.Pending; + _mockContext.Books.AddRange(pendingBook, enrichedBook, failedBook, bookOfAnotherLibrary); + await _mockContext.SaveChangesAsync(); + + // Act + Result result = await _sut.GetBooksNeedingMetadataCountAsync(libraryId, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal(2, result.Value); + } + + [Fact] + public async Task GetPaginatedAsync_WhenSortByLanguageCodeAscending_ShouldReturnBooksInAscendingOrder() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + BookEntity frenchBook = _bookEntityFixture.Create(title: "French Book"); + frenchBook.LibraryId = libraryId; + frenchBook.LanguageCode = "fr"; + BookEntity englishBook = _bookEntityFixture.Create(title: "English Book"); + englishBook.LibraryId = libraryId; + englishBook.LanguageCode = "en"; + _mockContext.Books.AddRange(frenchBook, englishBook); + await _mockContext.SaveChangesAsync(); + + PaginationDataDto paginationData = _paginationDataDtoFixture.Create(currentPage: 1, perPage: 10); + LibraryFilterDto filter = _libraryFilterDtoFixture.Create(libraryId: libraryId); + + // Act + Result> result = await _sut.GetPaginatedAsync(paginationData, "languageCode", SortOrder.Ascending, filter, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal(["English Book", "French Book"], result.Value.Data.Select(book => book.Title)); + } + + [Fact] + public async Task GetPaginatedAsync_WhenSortByLanguageCodeDescending_ShouldReturnBooksInDescendingOrder() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + BookEntity englishBook = _bookEntityFixture.Create(title: "English Book"); + englishBook.LibraryId = libraryId; + englishBook.LanguageCode = "en"; + BookEntity frenchBook = _bookEntityFixture.Create(title: "French Book"); + frenchBook.LibraryId = libraryId; + frenchBook.LanguageCode = "fr"; + _mockContext.Books.AddRange(englishBook, frenchBook); + await _mockContext.SaveChangesAsync(); + + PaginationDataDto paginationData = _paginationDataDtoFixture.Create(currentPage: 1, perPage: 10); + LibraryFilterDto filter = _libraryFilterDtoFixture.Create(libraryId: libraryId); + + // Act + Result> result = await _sut.GetPaginatedAsync(paginationData, "languageCode", SortOrder.Descending, filter, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal(["French Book", "English Book"], result.Value.Data.Select(book => book.Title)); + } + + [Fact] + public async Task GetPaginatedAsync_WhenSortByFormatAscending_ShouldReturnBooksInAscendingOrder() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + BookEntity paperbackBook = _bookEntityFixture.Create(title: "Paperback Book"); + paperbackBook.LibraryId = libraryId; + paperbackBook.Format = BookFormat.Paperback; + BookEntity hardcoverBook = _bookEntityFixture.Create(title: "Hardcover Book"); + hardcoverBook.LibraryId = libraryId; + hardcoverBook.Format = BookFormat.Hardcover; + _mockContext.Books.AddRange(paperbackBook, hardcoverBook); + await _mockContext.SaveChangesAsync(); + + PaginationDataDto paginationData = _paginationDataDtoFixture.Create(currentPage: 1, perPage: 10); + LibraryFilterDto filter = _libraryFilterDtoFixture.Create(libraryId: libraryId); + + // Act + Result> result = await _sut.GetPaginatedAsync(paginationData, "format", SortOrder.Ascending, filter, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal(["Hardcover Book", "Paperback Book"], result.Value.Data.Select(book => book.Title)); + } + + [Fact] + public async Task GetPaginatedAsync_WhenSortByFormatDescending_ShouldReturnBooksInDescendingOrder() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + BookEntity hardcoverBook = _bookEntityFixture.Create(title: "Hardcover Book"); + hardcoverBook.LibraryId = libraryId; + hardcoverBook.Format = BookFormat.Hardcover; + BookEntity paperbackBook = _bookEntityFixture.Create(title: "Paperback Book"); + paperbackBook.LibraryId = libraryId; + paperbackBook.Format = BookFormat.Paperback; + _mockContext.Books.AddRange(hardcoverBook, paperbackBook); + await _mockContext.SaveChangesAsync(); + + PaginationDataDto paginationData = _paginationDataDtoFixture.Create(currentPage: 1, perPage: 10); + LibraryFilterDto filter = _libraryFilterDtoFixture.Create(libraryId: libraryId); + + // Act + Result> result = await _sut.GetPaginatedAsync(paginationData, "format", SortOrder.Descending, filter, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal(["Paperback Book", "Hardcover Book"], result.Value.Data.Select(book => book.Title)); + } + + [Fact] + public async Task GetPaginatedAsync_WhenSortByMetadataProviderAscending_ShouldReturnBooksInAscendingOrder() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + BookEntity openLibraryBook = _bookEntityFixture.Create(title: "OpenLibrary Book"); + openLibraryBook.LibraryId = libraryId; + openLibraryBook.MetadataProvider = "OpenLibrary"; + BookEntity calibreBook = _bookEntityFixture.Create(title: "Calibre Book"); + calibreBook.LibraryId = libraryId; + calibreBook.MetadataProvider = "Calibre"; + _mockContext.Books.AddRange(openLibraryBook, calibreBook); + await _mockContext.SaveChangesAsync(); + + PaginationDataDto paginationData = _paginationDataDtoFixture.Create(currentPage: 1, perPage: 10); + LibraryFilterDto filter = _libraryFilterDtoFixture.Create(libraryId: libraryId); + + // Act + Result> result = await _sut.GetPaginatedAsync(paginationData, "metadataProvider", SortOrder.Ascending, filter, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal(["Calibre Book", "OpenLibrary Book"], result.Value.Data.Select(book => book.Title)); + } + + [Fact] + public async Task GetPaginatedAsync_WhenSortByMetadataProviderDescending_ShouldReturnBooksInDescendingOrder() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + BookEntity calibreBook = _bookEntityFixture.Create(title: "Calibre Book"); + calibreBook.LibraryId = libraryId; + calibreBook.MetadataProvider = "Calibre"; + BookEntity openLibraryBook = _bookEntityFixture.Create(title: "OpenLibrary Book"); + openLibraryBook.LibraryId = libraryId; + openLibraryBook.MetadataProvider = "OpenLibrary"; + _mockContext.Books.AddRange(calibreBook, openLibraryBook); + await _mockContext.SaveChangesAsync(); + + PaginationDataDto paginationData = _paginationDataDtoFixture.Create(currentPage: 1, perPage: 10); + LibraryFilterDto filter = _libraryFilterDtoFixture.Create(libraryId: libraryId); + + // Act + Result> result = await _sut.GetPaginatedAsync(paginationData, "metadataProvider", SortOrder.Descending, filter, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal(["OpenLibrary Book", "Calibre Book"], result.Value.Data.Select(book => book.Title)); + } + + [Fact] + public async Task GetPaginatedAsync_WhenIgnoringTheTitlePrefixForSorting_ShouldSortByTitleStrippedOfItsPrefix() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + BookEntity beneathBook = _bookEntityFixture.Create(title: "Beneath the Surface", includeMetadata: false); + beneathBook.LibraryId = libraryId; + BookEntity artOfWarBook = _bookEntityFixture.Create(title: "The Art of War", includeMetadata: false); + artOfWarBook.LibraryId = libraryId; + _mockContext.Books.AddRange(beneathBook, artOfWarBook); + await _mockContext.SaveChangesAsync(); + + PaginationDataDto paginationData = _paginationDataDtoFixture.Create(currentPage: 1, perPage: 10); + LibraryFilterDto filter = _libraryFilterDtoFixture.Create(libraryId: libraryId, shouldIgnoreThePrefixForAlphaPicker: true); + + // Act + Result> result = await _sut.GetPaginatedAsync(paginationData, null, null, filter, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + // Without stripping the prefix, "The Art of War" would be sorted after "Beneath the Surface", since its sort key would start with "the" instead of "art". + Assert.Equal(["The Art of War", "Beneath the Surface"], result.Value.Data.Select(book => book.Title)); + } + } 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 deleted file mode 100644 index bdfb1169..00000000 --- a/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Repositories/Books/Specifications/BookAlphaFilterSpecificationTests.cs +++ /dev/null @@ -1,198 +0,0 @@ -#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", includeMetadata: false), - _bookEntityFixture.Create(title: "1984", includeMetadata: false), - _bookEntityFixture.Create(title: "@home", includeMetadata: false)); - 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", includeMetadata: false), - _bookEntityFixture.Create(title: "1984", includeMetadata: false), - _bookEntityFixture.Create(title: "Zoo", includeMetadata: false)); - 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", includeMetadata: false), - _bookEntityFixture.Create(title: "moby dick", includeMetadata: false)); - 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", includeMetadata: false), - _bookEntityFixture.Create(title: "The Fellowship of the Ring", includeMetadata: false)); - 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", includeMetadata: false), - _bookEntityFixture.Create(title: "1984", includeMetadata: false), - _bookEntityFixture.Create(title: "Zoo", includeMetadata: false)); - 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", includeMetadata: false), - _bookEntityFixture.Create(title: "To Kill a Mockingbird", includeMetadata: false)); - 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", includeMetadata: false), - _bookEntityFixture.Create(title: "To Kill a Mockingbird", includeMetadata: false)); - 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", includeMetadata: false)); - 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/MediaContributors/MediaContributorRepositoryTests.cs b/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Repositories/MediaContributors/MediaContributorRepositoryTests.cs index 3f0c4b72..641fa0b8 100644 --- a/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Repositories/MediaContributors/MediaContributorRepositoryTests.cs +++ b/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Repositories/MediaContributors/MediaContributorRepositoryTests.cs @@ -1,14 +1,12 @@ #region ========================================================================= USING ===================================================================================== using EntityFrameworkCore.Testing.NSubstitute; using Lumina.Application.Common.DataAccess.Entities.MediaContributors; -using Lumina.Application.Common.DataAccess.Repositories.MediaContributors; using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaContributors; using Lumina.DataAccess.Core.Repositories.MediaContributors; using Lumina.DataAccess.Core.UoW; 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; @@ -50,7 +48,7 @@ public class MediaContributorRepositoryTests // Assert Assert.False(result.IsFailure); - // the comparison is case-insensitive, so the existing contributor is returned and no new one is created + // The comparison is case-insensitive, so the existing contributor is returned and no new one is created. Assert.Equal(existingContributor.Id, result.Value.Id); Assert.Equal("Stephen King", result.Value.DisplayName); Assert.Single(_mockContext.ChangeTracker.Entries()); @@ -112,4 +110,22 @@ public class MediaContributorRepositoryTests Assert.Contains(result.Value, contributor => contributor.Id == firstContributor.Id); Assert.Contains(result.Value, contributor => contributor.Id == thirdContributor.Id); } + + [Fact] + public async Task InsertAsync_WhenCalled_ShouldAddContributorToContextAndReturnCreated() + { + // Arrange + MediaContributorEntity contributor = _mediaContributorEntityFixture.Create(); + + // Act + Result result = await _sut.InsertAsync(contributor, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal(Result.Created, result.Value); + + EntityEntry? addedContributor = _mockContext.ChangeTracker.Entries() + .FirstOrDefault(entityEntry => entityEntry.State == EntityState.Added && entityEntry.Entity.Id == contributor.Id); + Assert.NotNull(addedContributor); + } } diff --git a/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Repositories/Plugins/PluginRepositoryTests.cs b/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Repositories/Plugins/PluginRepositoryTests.cs index a0ae9321..32264bd7 100644 --- a/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Repositories/Plugins/PluginRepositoryTests.cs +++ b/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Repositories/Plugins/PluginRepositoryTests.cs @@ -6,7 +6,10 @@ using Lumina.DataAccess.Core.Repositories.Plugins; 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; @@ -76,7 +79,7 @@ public class PluginRepositoryTests PluginEntity updatedPlugin = _pluginFixture.Create(plugin.Id); updatedPlugin.Name = "Updated Name"; - updatedPlugin.SettingsJson = null; // the stored settings must be preserved + updatedPlugin.SettingsJson = null; // The stored settings must be preserved. // Act Result result = await _sut.UpsertAsync(updatedPlugin, CancellationToken.None); @@ -116,4 +119,71 @@ public class PluginRepositoryTests Assert.True(result.IsFailure); Assert.Equal(Errors.Plugins.PluginNotFound, result.FirstError); } + + [Fact] + public async Task GetAllAsync_WhenPluginsExist_ShouldReturnAllPlugins() + { + // Arrange + List plugins = _pluginFixture.CreateMany(2); + + _mockContext.Plugins.AddRange(plugins); + await _mockContext.SaveChangesAsync(); + + // Act + Result> result = await _sut.GetAllAsync(CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + Assert.NotNull(result.Value); + Assert.Equal(2, result.Value.Count()); + Assert.Contains(result.Value, plugin => plugin.Id == plugins[0].Id); + Assert.Contains(result.Value, plugin => plugin.Id == plugins[1].Id); + } + + [Fact] + public async Task GetAllAsync_WhenNoPluginsExist_ShouldReturnEmptyList() + { + // Act + Result> result = await _sut.GetAllAsync(CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + Assert.NotNull(result.Value); + Assert.Empty(result.Value); + } + + [Fact] + public async Task DeleteByIdAsync_WhenPluginExists_ShouldRemovePluginAndReturnDeleted() + { + // Arrange + PluginEntity existingPlugin = _pluginFixture.Create(); + _mockContext.Plugins.Add(existingPlugin); + await _mockContext.SaveChangesAsync(); + + // Act + Result result = await _sut.DeleteByIdAsync(existingPlugin.Id, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal(Result.Deleted, result.Value); + + EntityEntry? deletedEntry = _mockContext.ChangeTracker.Entries() + .FirstOrDefault(entityEntry => entityEntry.Entity.Id == existingPlugin.Id); + Assert.NotNull(deletedEntry); + Assert.Equal(EntityState.Deleted, deletedEntry!.State); + } + + [Fact] + public async Task DeleteByIdAsync_WhenPluginDoesNotExist_ShouldReturnError() + { + // Arrange + Guid nonExistentId = Guid.NewGuid(); + + // Act + Result result = await _sut.DeleteByIdAsync(nonExistentId, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.Plugins.PluginNotFound, result.FirstError); + } } diff --git a/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Repositories/Themes/ThemeRepositoryTests.cs b/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Repositories/Themes/ThemeRepositoryTests.cs new file mode 100644 index 00000000..e91ccef7 --- /dev/null +++ b/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Repositories/Themes/ThemeRepositoryTests.cs @@ -0,0 +1,237 @@ +#region ========================================================================= USING ===================================================================================== +using EntityFrameworkCore.Testing.NSubstitute; +using Lumina.Application.Common.DataAccess.Entities.Themes; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.Themes; +using Lumina.DataAccess.Core.Repositories.Themes; +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.Themes; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class ThemeRepositoryTests +{ + private readonly LuminaDbContext _mockContext; + private readonly ThemeRepository _sut; + private readonly ThemeEntityFixture _themeEntityFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + public ThemeRepositoryTests() + { + _mockContext = Create.MockedDbContextFor(); + _sut = new ThemeRepository(_mockContext); + } + + [Fact] + public async Task InsertAsync_WhenThemeDoesNotExist_ShouldAddThemeToContextAndReturnCreated() + { + // Arrange + ThemeEntity theme = _themeEntityFixture.Create(); + + // Act + Result result = await _sut.InsertAsync(theme, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal(Result.Created, result.Value); + + EntityEntry? addedTheme = _mockContext.ChangeTracker.Entries() + .FirstOrDefault(entry => entry.State == EntityState.Added && entry.Entity.Id == theme.Id); + Assert.NotNull(addedTheme); + Assert.Equal(theme.ThemeId, addedTheme.Entity.ThemeId); + } + + [Fact] + public async Task InsertAsync_WhenThemeAlreadyExists_ShouldReturnError() + { + // Arrange + ThemeEntity theme = _themeEntityFixture.Create(); + _mockContext.Themes.Add(theme); + await _mockContext.SaveChangesAsync(); + + // Act + Result result = await _sut.InsertAsync(theme, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.Themes.ThemeNotFound, result.FirstError); + Assert.Single(_mockContext.ChangeTracker.Entries()); + } + + [Fact] + public async Task GetAllAsync_WhenCalled_ShouldReturnAllThemes() + { + // Arrange + List themes = _themeEntityFixture.CreateMany(); + _mockContext.Themes.AddRange(themes); + await _mockContext.SaveChangesAsync(); + + // Act + Result> result = await _sut.GetAllAsync(CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + Assert.NotNull(result.Value); + Assert.Equal(3, result.Value.Count()); + Assert.Equal(themes, result.Value); + } + + [Fact] + public async Task GetAllAsync_WhenNoThemesExist_ShouldReturnEmptyList() + { + // Act + Result> result = await _sut.GetAllAsync(CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + Assert.NotNull(result.Value); + Assert.Empty(result.Value); + } + + [Fact] + public async Task GetByThemeIdAsync_WhenThemeExists_ShouldReturnTheme() + { + // Arrange + ThemeEntity theme = _themeEntityFixture.Create(themeId: "my-theme"); + _mockContext.Themes.Add(theme); + await _mockContext.SaveChangesAsync(); + + // Act + Result result = await _sut.GetByThemeIdAsync(theme.ThemeId, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + Assert.NotNull(result.Value); + Assert.Equal(theme, result.Value); + } + + [Fact] + public async Task GetByThemeIdAsync_WhenThemeDoesNotExist_ShouldReturnNull() + { + // Act + Result result = await _sut.GetByThemeIdAsync("nonexistent-theme", CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + Assert.Null(result.Value); + } + + [Fact] + public async Task UpdateAsync_WhenThemeExists_ShouldUpdateThemeAndReturnUpdated() + { + // Arrange + ThemeEntity existingTheme = _themeEntityFixture.Create(name: "Existing Theme"); + _mockContext.Themes.Add(existingTheme); + await _mockContext.SaveChangesAsync(); + + ThemeEntity updatedTheme = _themeEntityFixture.Create(id: existingTheme.Id, themeId: existingTheme.ThemeId, name: "Updated Theme", includeIsCurrent: true, isCurrent: true); + updatedTheme.CreatedOnUtc = existingTheme.CreatedOnUtc; + updatedTheme.CreatedBy = existingTheme.CreatedBy; + + // Act + Result result = await _sut.UpdateAsync(updatedTheme, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal(Result.Updated, result.Value); + + ThemeEntity? modifiedTheme = await _mockContext.Themes.FirstOrDefaultAsync(theme => theme.Id == existingTheme.Id); + Assert.NotNull(modifiedTheme); + Assert.Equal("Updated Theme", modifiedTheme.Name); + Assert.True(modifiedTheme.IsCurrent); + } + + [Fact] + public async Task UpdateAsync_WhenThemeDoesNotExist_ShouldReturnError() + { + // Arrange + ThemeEntity theme = _themeEntityFixture.Create(); + + // Act + Result result = await _sut.UpdateAsync(theme, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.Themes.ThemeNotFound, result.FirstError); + } + + [Fact] + public async Task DeleteByIdAsync_WhenThemeExists_ShouldRemoveThemeFromContextAndReturnDeleted() + { + // Arrange + ThemeEntity theme = _themeEntityFixture.Create(); + _mockContext.Themes.Add(theme); + await _mockContext.SaveChangesAsync(); + + // Act + Result result = await _sut.DeleteByIdAsync(theme.Id, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal(Result.Deleted, result.Value); + + EntityEntry? deletedTheme = _mockContext.ChangeTracker.Entries() + .FirstOrDefault(entry => entry.State == EntityState.Deleted && entry.Entity.Id == theme.Id); + Assert.NotNull(deletedTheme); + } + + [Fact] + public async Task DeleteByIdAsync_WhenThemeDoesNotExist_ShouldReturnError() + { + // Act + Result result = await _sut.DeleteByIdAsync(Guid.NewGuid(), CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.Themes.ThemeNotFound, result.FirstError); + } + + [Fact] + public async Task GetCurrentAsync_WhenCurrentThemeExists_ShouldReturnCurrentTheme() + { + // Arrange + ThemeEntity currentTheme = _themeEntityFixture.Create(includeIsCurrent: true, isCurrent: true); + ThemeEntity nonCurrentTheme = _themeEntityFixture.Create(includeIsCurrent: true, isCurrent: false); + _mockContext.Themes.AddRange(currentTheme, nonCurrentTheme); + await _mockContext.SaveChangesAsync(); + + // Act + Result result = await _sut.GetCurrentAsync(CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + Assert.NotNull(result.Value); + Assert.Equal(currentTheme, result.Value); + } + + [Fact] + public async Task GetCurrentAsync_WhenNoCurrentThemeExists_ShouldReturnNull() + { + // Arrange + ThemeEntity nonCurrentTheme = _themeEntityFixture.Create(includeIsCurrent: true, isCurrent: false); + _mockContext.Themes.Add(nonCurrentTheme); + await _mockContext.SaveChangesAsync(); + + // Act + Result result = await _sut.GetCurrentAsync(CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + Assert.Null(result.Value); + } +} diff --git a/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/UoW/UnitOfWorkTests.cs b/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/UoW/UnitOfWorkTests.cs index 928ae81d..4ae099c4 100644 --- a/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/UoW/UnitOfWorkTests.cs +++ b/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/UoW/UnitOfWorkTests.cs @@ -14,6 +14,7 @@ using NSubstitute; using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; +using System.Linq; using System.Threading; using System.Threading.Tasks; #endregion @@ -54,14 +55,19 @@ public class UnitOfWorkTests yield return new object[] { nameof(IUnitOfWork.RoleRepository), (Func)(unitOfWork => unitOfWork.RoleRepository) }; yield return new object[] { nameof(IUnitOfWork.UserRoleRepository), (Func)(unitOfWork => unitOfWork.UserRoleRepository) }; yield return new object[] { nameof(IUnitOfWork.BookRepository), (Func)(unitOfWork => unitOfWork.BookRepository) }; + yield return new object[] { nameof(IUnitOfWork.MediaContributorRepository), (Func)(unitOfWork => unitOfWork.MediaContributorRepository) }; yield return new object[] { nameof(IUnitOfWork.DirectoryScanFingerprintRepository), (Func)(unitOfWork => unitOfWork.DirectoryScanFingerprintRepository) }; yield return new object[] { nameof(IUnitOfWork.LibraryRepository), (Func)(unitOfWork => unitOfWork.LibraryRepository) }; yield return new object[] { nameof(IUnitOfWork.LibraryScanRepository), (Func)(unitOfWork => unitOfWork.LibraryScanRepository) }; yield return new object[] { nameof(IUnitOfWork.LibraryScanSnapshotRepository), (Func)(unitOfWork => unitOfWork.LibraryScanSnapshotRepository) }; yield return new object[] { nameof(IUnitOfWork.LibraryScanStagingResultsRepository), (Func)(unitOfWork => unitOfWork.LibraryScanStagingResultsRepository) }; yield return new object[] { nameof(IUnitOfWork.LibraryMetadataProviderConfigurationRepository), (Func)(unitOfWork => unitOfWork.LibraryMetadataProviderConfigurationRepository) }; + yield return new object[] { nameof(IUnitOfWork.ArtworkProviderConfigurationRepository), (Func)(unitOfWork => unitOfWork.ArtworkProviderConfigurationRepository) }; + yield return new object[] { nameof(IUnitOfWork.LibraryBookReaderConfigurationRepository), (Func)(unitOfWork => unitOfWork.LibraryBookReaderConfigurationRepository) }; yield return new object[] { nameof(IUnitOfWork.PluginRepository), (Func)(unitOfWork => unitOfWork.PluginRepository) }; + yield return new object[] { nameof(IUnitOfWork.ThemeRepository), (Func)(unitOfWork => unitOfWork.ThemeRepository) }; yield return new object[] { nameof(IUnitOfWork.UserRepository), (Func)(unitOfWork => unitOfWork.UserRepository) }; + yield return new object[] { nameof(IUnitOfWork.UserSettingsRepository), (Func)(unitOfWork => unitOfWork.UserSettingsRepository) }; } [Theory] diff --git a/tests/UnitTests/Lumina.Domain.UnitTests/Common/Errors/ErrorsTests.cs b/tests/UnitTests/Lumina.Domain.UnitTests/Common/Errors/ErrorsTests.cs index 2cc0c0af..986db136 100644 --- a/tests/UnitTests/Lumina.Domain.UnitTests/Common/Errors/ErrorsTests.cs +++ b/tests/UnitTests/Lumina.Domain.UnitTests/Common/Errors/ErrorsTests.cs @@ -82,62 +82,168 @@ public class ErrorsTests } [Fact] - public void Metadata_WhenAccessed_ShouldExposeRepresentativeErrorsWithExpectedTypes() + public void Metadata_WhenAccessed_ShouldExposeErrorsWithExpectedTypes() { // Assert + // The count assertion fails when an error is added or removed, reminding to update the assertions below. + Assert.Equal(31, typeof(DomainErrors.Metadata).GetProperties().Length); AssertError(DomainErrors.Metadata.MetadataCannotBeNull, ErrorType.Validation); AssertError(DomainErrors.Metadata.TitleCannotBeEmpty, ErrorType.Validation); + AssertError(DomainErrors.Metadata.TitleMustBeMaximum255CharactersLong, ErrorType.Validation); + AssertError(DomainErrors.Metadata.OriginalTitleMustBeMaximum255CharactersLong, ErrorType.Validation); + AssertError(DomainErrors.Metadata.DescriptionMustBeMaximum2000CharactersLong, ErrorType.Validation); + AssertError(DomainErrors.Metadata.GenresListCannotBeNull, ErrorType.Validation); + AssertError(DomainErrors.Metadata.GenreNameCannotBeEmpty, ErrorType.Validation); + AssertError(DomainErrors.Metadata.GenreNameMustBeMaximum50CharactersLong, ErrorType.Validation); + AssertError(DomainErrors.Metadata.TagsListCannotBeNull, ErrorType.Validation); + AssertError(DomainErrors.Metadata.TagNameCannotBeEmpty, ErrorType.Validation); + AssertError(DomainErrors.Metadata.TagNameMustBeMaximum50CharactersLong, ErrorType.Validation); + AssertError(DomainErrors.Metadata.LanguageCodeCannotBeEmpty, ErrorType.Validation); + AssertError(DomainErrors.Metadata.LanguageNameCannotBeEmpty, ErrorType.Validation); + AssertError(DomainErrors.Metadata.LanguageCodeMustBe2CharactersLong, ErrorType.Validation); + AssertError(DomainErrors.Metadata.LanguageNameMustBeMaximum50CharactersLong, ErrorType.Validation); + AssertError(DomainErrors.Metadata.LanguageNativeNameMustBeMaximum50CharactersLong, ErrorType.Validation); AssertError(DomainErrors.Metadata.OriginalReleaseYearMustBeBetween1And9999, ErrorType.Validation); + AssertError(DomainErrors.Metadata.ReReleaseYearMustBeBetween1And9999, ErrorType.Validation); AssertError(DomainErrors.Metadata.ReReleaseYearCannotBeEarlierThanOriginalReleaseYear, ErrorType.Validation); + AssertError(DomainErrors.Metadata.CountryCodeMustBe2CharactersLong, ErrorType.Validation); + AssertError(DomainErrors.Metadata.ReleaseVersionMustBeMaximum50CharactersLong, ErrorType.Validation); AssertError(DomainErrors.Metadata.OriginalReleaseDateAndYearMustMatch, ErrorType.Validation); + AssertError(DomainErrors.Metadata.ReReleaseDateAndYearMustMatch, ErrorType.Validation); + AssertError(DomainErrors.Metadata.ReReleaseDateCannotBeEarlierThanOriginalReleaseDate, ErrorType.Validation); + AssertError(DomainErrors.Metadata.ReleaseInfoCannotBeNull, ErrorType.Validation); AssertError(DomainErrors.Metadata.RatingValueMustBePositive, ErrorType.Validation); + AssertError(DomainErrors.Metadata.RatingMaxValueMustBePositive, ErrorType.Validation); AssertError(DomainErrors.Metadata.RatingValueCannotBeGreaterThanMaxValue, ErrorType.Validation); AssertError(DomainErrors.Metadata.RatingVoteCountMustBePositive, ErrorType.Validation); + AssertError(DomainErrors.Metadata.RatingsListCannotBeNull, 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() + public void WrittenContent_WhenAccessed_ShouldExposeErrorsWithExpectedTypes() { // Assert + // The count assertion fails when an error is added or removed, reminding to update the assertions below. + Assert.Equal(27, typeof(DomainErrors.WrittenContent).GetProperties().Length); AssertError(DomainErrors.WrittenContent.BookAlreadyExists, ErrorType.Conflict); AssertError(DomainErrors.WrittenContent.IsbnValueCannotBeEmpty, ErrorType.Validation); + AssertError(DomainErrors.WrittenContent.IsbnListCannotBeNull, 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.AsinMustBe10CharactersLong, ErrorType.Validation); + AssertError(DomainErrors.WrittenContent.GoodreadsIdMustBeNumeric, ErrorType.Validation); + AssertError(DomainErrors.WrittenContent.InvalidLccnFormat, ErrorType.Validation); + AssertError(DomainErrors.WrittenContent.InvalidOclcFormat, ErrorType.Validation); + AssertError(DomainErrors.WrittenContent.InvalidOpenLibraryId, ErrorType.Validation); + AssertError(DomainErrors.WrittenContent.LibraryThingIdMustBeMaximum50CharactersLong, ErrorType.Validation); + AssertError(DomainErrors.WrittenContent.GoogleBooksIdMustBe12CharactersLong, ErrorType.Validation); + AssertError(DomainErrors.WrittenContent.InvalidGoogleBooksIdFormat, ErrorType.Validation); + AssertError(DomainErrors.WrittenContent.BarnesAndNoblesIdMustBe10CharactersLong, ErrorType.Validation); + AssertError(DomainErrors.WrittenContent.InvalidBarnesAndNoblesIdFormat, ErrorType.Validation); + AssertError(DomainErrors.WrittenContent.InvalidAppleBooksIdFormat, ErrorType.Validation); + AssertError(DomainErrors.WrittenContent.PublisherMustBeMaximum100CharactersLong, ErrorType.Validation); AssertError(DomainErrors.WrittenContent.PageCountMustBeGreaterThanZero, ErrorType.Validation); + AssertError(DomainErrors.WrittenContent.UnknownBookFormat, ErrorType.Validation); + AssertError(DomainErrors.WrittenContent.EditionMustBeMaximum50CharactersLong, ErrorType.Validation); + AssertError(DomainErrors.WrittenContent.VolumeNumberMustBeGreaterThanZero, ErrorType.Validation); + AssertError(DomainErrors.WrittenContent.BookLibraryCannotBeNull, ErrorType.Validation); + AssertError(DomainErrors.WrittenContent.BookPathCannotBeEmpty, ErrorType.Validation); + AssertError(DomainErrors.WrittenContent.BookNotFound, ErrorType.NotFound); } [Fact] - public void MediaContributor_WhenAccessed_ShouldExposeRepresentativeErrorsWithExpectedTypes() + public void MediaContributor_WhenAccessed_ShouldExposeErrorsWithExpectedTypes() { // Assert + // The count assertion fails when an error is added or removed, reminding to update the assertions below. + Assert.Equal(9, typeof(DomainErrors.MediaContributor).GetProperties().Length); 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.ContributorLegalNameMustBeMaximum100CharactersLong, ErrorType.Validation); AssertError(DomainErrors.MediaContributor.RoleNameCannotBeEmpty, ErrorType.Validation); + AssertError(DomainErrors.MediaContributor.RoleNameMustBeMaximum50CharactersLong, ErrorType.Validation); AssertError(DomainErrors.MediaContributor.RoleCategoryCannotBeEmpty, ErrorType.Validation); AssertError(DomainErrors.MediaContributor.ContributorRoleCannotBeNull, ErrorType.Validation); } [Fact] - public void FileSystemManagement_WhenAccessed_ShouldExposeRepresentativeErrorsWithExpectedTypes() + public void MediaContributors_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.MediaContributors).GetProperties().Length); + AssertError(DomainErrors.MediaContributors.MediaContributorNameCannotBeEmpty, ErrorType.Validation); + AssertError(DomainErrors.MediaContributors.MediaContributorRoleNameCannotBeEmpty, ErrorType.Validation); + } + + [Fact] + public void FileSystemManagement_WhenAccessed_ShouldExposeErrorsWithExpectedTypes() + { + // Assert + // The count assertion fails when an error is added or removed, reminding to update the assertions below. + Assert.Equal(19, typeof(DomainErrors.FileSystemManagement).GetProperties().Length); AssertError(DomainErrors.FileSystemManagement.ParentNodeCannotBeNull, ErrorType.Failure); + AssertError(DomainErrors.FileSystemManagement.PathMustBeMaximum260CharactersLong, ErrorType.Failure); + AssertError(DomainErrors.FileSystemManagement.FileCopyError, ErrorType.Failure); + AssertError(DomainErrors.FileSystemManagement.FileMoveError, ErrorType.Failure); + AssertError(DomainErrors.FileSystemManagement.DirectoryCopyError, ErrorType.Failure); + AssertError(DomainErrors.FileSystemManagement.DirectoryMoveError, ErrorType.Failure); + AssertError(DomainErrors.FileSystemManagement.FileNotFound, ErrorType.NotFound); 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.ExtensionCannotBeEmpty, ErrorType.Validation); + AssertError(DomainErrors.FileSystemManagement.StreamIdCannotBeEmpty, ErrorType.Validation); + AssertError(DomainErrors.FileSystemManagement.CodecCannotBeEmpty, ErrorType.Validation); + AssertError(DomainErrors.FileSystemManagement.BitrateMustBeAPositiveNumber, ErrorType.Validation); + AssertError(DomainErrors.FileSystemManagement.CannotNavigateUp, ErrorType.Failure); AssertError(DomainErrors.FileSystemManagement.NameCannotBeEmpty, ErrorType.Validation); + AssertError(DomainErrors.FileSystemManagement.FileAlreadyExists, ErrorType.Conflict); + AssertError(DomainErrors.FileSystemManagement.DirectoryNotFound, ErrorType.NotFound); + AssertError(DomainErrors.FileSystemManagement.DirectoryAlreadyExists, ErrorType.Conflict); + AssertError(DomainErrors.FileSystemManagement.FileTooLarge, ErrorType.Validation); + } + + [Fact] + public void Reading_WhenAccessed_ShouldExposeErrorsWithExpectedTypes() + { + // Assert + // The count assertion fails when an error is added or removed, reminding to update the assertions below. + Assert.Equal(9, typeof(DomainErrors.Reading).GetProperties().Length); + AssertError(DomainErrors.Reading.BookIdCannotBeEmpty, ErrorType.Validation); + AssertError(DomainErrors.Reading.LocationRefCannotBeEmpty, ErrorType.Validation); + AssertError(DomainErrors.Reading.ResourceKeyCannotBeEmpty, ErrorType.Validation); + AssertError(DomainErrors.Reading.BookNotFound, ErrorType.NotFound); + AssertError(DomainErrors.Reading.NoReaderAvailable, ErrorType.NotFound); + AssertError(DomainErrors.Reading.ReaderDisabled, ErrorType.NotFound); + AssertError(DomainErrors.Reading.BookFileNotFound, ErrorType.NotFound); + AssertError(DomainErrors.Reading.SectionNotFound, ErrorType.NotFound); + AssertError(DomainErrors.Reading.ResourceNotFound, ErrorType.NotFound); + } + + [Fact] + public void Themes_WhenAccessed_ShouldExposeErrorsWithExpectedTypes() + { + // Assert + // The count assertion fails when an error is added or removed, reminding to update the assertions below. + Assert.Equal(12, typeof(DomainErrors.Themes).GetProperties().Length); + AssertError(DomainErrors.Themes.ThemeNotFound, ErrorType.NotFound); + AssertError(DomainErrors.Themes.ThemeIdCannotBeEmpty, ErrorType.Validation); + AssertError(DomainErrors.Themes.PageKeyCannotBeEmpty, ErrorType.Validation); + AssertError(DomainErrors.Themes.ThemeAssetPathCannotBeEmpty, ErrorType.Validation); + AssertError(DomainErrors.Themes.ThemeArchiveCannotBeNull, ErrorType.Validation); + AssertError(DomainErrors.Themes.LastBundledThemeCannotBeDeleted, ErrorType.Forbidden); + AssertError(DomainErrors.Themes.ThemeCannotBeDeleted, ErrorType.Forbidden); + AssertError(DomainErrors.Themes.ThemeCannotBeRestored, ErrorType.Forbidden); + AssertError(DomainErrors.Themes.ThemeArchiveNotReadable, ErrorType.Failure); + AssertError(DomainErrors.Themes.ThemeFilesUnreadable, ErrorType.Failure); + AssertError(DomainErrors.Themes.ThemeTemplateNotFound, ErrorType.NotFound); + AssertError(DomainErrors.Themes.ThemeNotAvailable, ErrorType.Failure); } [Fact] @@ -160,14 +266,23 @@ public class ErrorsTests } [Fact] - public void Plugins_WhenAccessed_ShouldExposeRepresentativeErrorsWithExpectedTypes() + public void Plugins_WhenAccessed_ShouldExposeErrorsWithExpectedTypes() { // Assert + // The count assertion fails when an error is added or removed, reminding to update the assertions below. + Assert.Equal(12, typeof(DomainErrors.Plugins).GetProperties().Length); AssertError(DomainErrors.Plugins.PluginNotFound, ErrorType.NotFound); AssertError(DomainErrors.Plugins.PluginIdCannotBeEmpty, ErrorType.Validation); + AssertError(DomainErrors.Plugins.PluginSettingsCannotBeNull, ErrorType.Validation); + AssertError(DomainErrors.Plugins.LibraryIdCannotBeEmpty, ErrorType.Validation); AssertError(DomainErrors.Plugins.PluginIdsListCannotBeNull, ErrorType.Validation); AssertError(DomainErrors.Plugins.PluginIdsListCannotBeEmpty, ErrorType.Validation); AssertError(DomainErrors.Plugins.LibraryMetadataProviderConfigurationNotFound, ErrorType.NotFound); + AssertError(DomainErrors.Plugins.PluginArchiveCannotBeNull, ErrorType.Validation); + AssertError(DomainErrors.Plugins.PluginFileNameCannotBeEmpty, ErrorType.Validation); + AssertError(DomainErrors.Plugins.UnsupportedPluginFileType, ErrorType.Validation); + AssertError(DomainErrors.Plugins.PluginArchiveNotReadable, ErrorType.Failure); + AssertError(DomainErrors.Plugins.PluginArchiveContainsNoAssemblies, ErrorType.Failure); } private static void AssertError(Error error, ErrorType expectedType) diff --git a/tests/UnitTests/Lumina.Domain.UnitTests/Common/Models/Core/EntityIdTests.cs b/tests/UnitTests/Lumina.Domain.UnitTests/Common/Models/Core/EntityIdTests.cs index eb8794ac..a1dbba3e 100644 --- a/tests/UnitTests/Lumina.Domain.UnitTests/Common/Models/Core/EntityIdTests.cs +++ b/tests/UnitTests/Lumina.Domain.UnitTests/Common/Models/Core/EntityIdTests.cs @@ -85,6 +85,31 @@ public class EntityIdTests Assert.Equal(firstHashCode, secondHashCode); } + [Fact] + public void GetEqualityComponents_WhenNotOverridden_ShouldYieldOnlyTheValue() + { + // Arrange + Guid value = Guid.NewGuid(); + DefaultEntityId entityId = new(value); + + // Act + IEnumerable components = entityId.GetEqualityComponents(); + + // Assert + object? component = Assert.Single(components); + Assert.Equal(value, component); + } + + [Fact] + public void Constructor_WhenCalledWithoutArguments_ShouldLeaveValueAsDefault() + { + // Act + DefaultEntityId entityId = new(); + + // Assert + Assert.Equal(default, entityId.Value); + } + /// /// Concrete test implementation of the abstract class. /// @@ -107,4 +132,25 @@ public class EntityIdTests yield return Value; } } + + /// + /// Concrete test implementation of the abstract class that relies on the base equality components. + /// + private sealed class DefaultEntityId : EntityId + { + /// + /// Initializes a new instance of the class. + /// + /// The value representing this object. + public DefaultEntityId(Guid value) : base(value) + { + } + + /// + /// Initializes a new instance of the class. + /// + public DefaultEntityId() : base() + { + } + } } diff --git a/tests/UnitTests/Lumina.Domain.UnitTests/Common/Primitives/ResultTests.cs b/tests/UnitTests/Lumina.Domain.UnitTests/Common/Primitives/ResultTests.cs index 00d40cc9..47583c5e 100644 --- a/tests/UnitTests/Lumina.Domain.UnitTests/Common/Primitives/ResultTests.cs +++ b/tests/UnitTests/Lumina.Domain.UnitTests/Common/Primitives/ResultTests.cs @@ -295,6 +295,39 @@ public class ResultTests Assert.True(firstResult.Equals(secondResult)); } + [Fact] + public void Equals_WhenOneResultIsSuccessfulAndTheOtherIsFailed_ShouldReturnFalse() + { + // Act + Result successResult = Result.Success("test"); + Result failureResult = Result.Failure(Error.Validation("Code", "Description")); + + // Assert + Assert.False(successResult.Equals(failureResult)); + } + + [Fact] + public void Equals_WhenCalledWithBoxedResult_ShouldReturnTrue() + { + // Act + Result firstResult = Result.Success("test"); + object boxedResult = Result.Success("test"); + + // Assert + Assert.True(firstResult.Equals(boxedResult)); + } + + [Fact] + public void Equals_WhenCalledWithNonResultObject_ShouldReturnFalse() + { + // Act + Result result = Result.Success("test"); + object nonResultObject = new(); + + // Assert + Assert.False(result.Equals(nonResultObject)); + } + [Fact] public void EqualityOperator_WhenResultsAreEqual_ShouldReturnTrue() { diff --git a/tests/UnitTests/Lumina.Domain.UnitTests/Common/ValueObjects/Metadata/LanguageInfoTests.cs b/tests/UnitTests/Lumina.Domain.UnitTests/Common/ValueObjects/Metadata/LanguageInfoTests.cs index 61ac9093..12cd4adb 100644 --- a/tests/UnitTests/Lumina.Domain.UnitTests/Common/ValueObjects/Metadata/LanguageInfoTests.cs +++ b/tests/UnitTests/Lumina.Domain.UnitTests/Common/ValueObjects/Metadata/LanguageInfoTests.cs @@ -87,4 +87,65 @@ public class LanguageInfoTests // Assert Assert.Equal("en - English", result); } + + [Fact] + public void Equals_WithSameValues_ShouldReturnTrue() + { + // Arrange + LanguageInfo firstLanguageInfo = _languageInfoFixture.Create( + languageCode: "en", + languageName: "English", + nativeName: Optional.Some("English")); + LanguageInfo secondLanguageInfo = _languageInfoFixture.Create( + languageCode: "en", + languageName: "English", + nativeName: Optional.Some("English")); + + // Act + bool result = firstLanguageInfo.Equals(secondLanguageInfo); + + // Assert + Assert.True(result); + } + + [Fact] + public void GetHashCode_WithSameValues_ShouldReturnSameHashCode() + { + // Arrange + LanguageInfo firstLanguageInfo = _languageInfoFixture.Create( + languageCode: "en", + languageName: "English", + nativeName: Optional.Some("English")); + LanguageInfo secondLanguageInfo = _languageInfoFixture.Create( + languageCode: "en", + languageName: "English", + nativeName: Optional.Some("English")); + + // Act + int firstHashCode = firstLanguageInfo.GetHashCode(); + int secondHashCode = secondLanguageInfo.GetHashCode(); + + // Assert + Assert.Equal(firstHashCode, secondHashCode); + } + + [Fact] + public void Equals_WithDifferentLanguageName_ShouldReturnFalse() + { + // Arrange + LanguageInfo firstLanguageInfo = _languageInfoFixture.Create( + languageCode: "en", + languageName: "English", + nativeName: Optional.None()); + LanguageInfo secondLanguageInfo = _languageInfoFixture.Create( + languageCode: "en", + languageName: "French", + nativeName: Optional.None()); + + // Act + bool result = firstLanguageInfo.Equals(secondLanguageInfo); + + // Assert + Assert.False(result); + } } 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 1d827fa3..b1d236ce 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 @@ -597,6 +597,90 @@ public class DirectoryProviderServiceTests Assert.Equal(Errors.FileSystemManagement.DirectoryCopyError, result.FirstError); } + [Fact] + public void CopyDirectory_WhenNestedSubdirectoryPathIsInvalid_ShouldReturnError() + { + // Arrange + FileSystemPathId sourcePath = _fileSystemPathIdFixture.Create(_pathSource); + FileSystemPathId destinationPath = _fileSystemPathIdFixture.Create(_pathDestination); + bool overrideExisting = false; + + _mockFileSystem.Directory.Exists(_pathSource).Returns(true); + _mockFileSystem.Directory.Exists(_pathSourceSubDir).Returns(true); + _mockFileSystem.Directory.Exists(_pathDestination).Returns(false); + + _mockFileSystem.Directory.CreateDirectory(Arg.Any()).Returns(callInfo => + { + IDirectoryInfo mockDirInfo = Substitute.For(); + mockDirInfo.FullName.Returns(callInfo.Arg()); + return mockDirInfo; + }); + + IDirectoryInfo invalidNestedDir = Substitute.For(); + invalidNestedDir.FullName.Returns(" "); + + IDirectoryInfo nestedDirInfo = Substitute.For(); + nestedDirInfo.GetFiles().Returns([]); + nestedDirInfo.GetDirectories().Returns([invalidNestedDir]); + _mockFileSystem.DirectoryInfo.New(_pathSourceSubDir).Returns(nestedDirInfo); + + IDirectoryInfo subDirInfo = Substitute.For(); + subDirInfo.Name.Returns("SubDir"); + subDirInfo.FullName.Returns(_pathSourceSubDir); + + IDirectoryInfo sourceDirectoryInfo = Substitute.For(); + sourceDirectoryInfo.GetFiles().Returns([]); + sourceDirectoryInfo.GetDirectories().Returns([subDirInfo]); + _mockFileSystem.DirectoryInfo.New(_pathSource).Returns(sourceDirectoryInfo); + + _mockFileSystem.Path.Combine(Arg.Any(), Arg.Any()) + .Returns(callInfo => Path.Combine(callInfo.ArgAt(0), callInfo.ArgAt(1))); + + // Act + Result result = _sut.CopyDirectory(sourcePath, destinationPath, overrideExisting); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.FileSystemManagement.InvalidPath, result.FirstError); + } + + [Fact] + public void CopyDirectory_WhenDestinationSubdirectoryPathIsInvalid_ShouldReturnError() + { + // Arrange + FileSystemPathId sourcePath = _fileSystemPathIdFixture.Create(_pathSource); + FileSystemPathId destinationPath = _fileSystemPathIdFixture.Create(_pathDestination); + bool overrideExisting = false; + + _mockFileSystem.Directory.Exists(_pathSource).Returns(true); + _mockFileSystem.Directory.Exists(_pathDestination).Returns(false); + + _mockFileSystem.Directory.CreateDirectory(Arg.Any()).Returns(callInfo => + { + IDirectoryInfo mockDirInfo = Substitute.For(); + mockDirInfo.FullName.Returns(callInfo.Arg()); + return mockDirInfo; + }); + + IDirectoryInfo subDirInfo = Substitute.For(); + subDirInfo.Name.Returns("SubDir"); + subDirInfo.FullName.Returns(_pathSourceSubDir); + + IDirectoryInfo sourceDirectoryInfo = Substitute.For(); + sourceDirectoryInfo.GetFiles().Returns([]); + sourceDirectoryInfo.GetDirectories().Returns([subDirInfo]); + _mockFileSystem.DirectoryInfo.New(_pathSource).Returns(sourceDirectoryInfo); + + _mockFileSystem.Path.Combine(Arg.Any(), Arg.Any()).Returns(" "); + + // Act + Result result = _sut.CopyDirectory(sourcePath, destinationPath, overrideExisting); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.FileSystemManagement.InvalidPath, result.FirstError); + } + [Fact] public void MoveDirectory_WhenSourceDirectoryDoesNotExist_ShouldReturnDirectoryNotFoundError() { @@ -969,6 +1053,52 @@ public class DirectoryProviderServiceTests _mockFileSystem.Directory.DidNotReceive().Move(Arg.Any(), Arg.Any()); } + [Fact] + public void RenameDirectory_WhenParentDirectoryPathIsWhitespace_ShouldReturnInvalidPathError() + { + // Arrange + FileSystemPathId path = _fileSystemPathIdFixture.Create( + s_isUnix ? "/OldName" : @"C:\OldName" + ); + string newName = "NewName"; + + IDirectoryInfo parentDirectoryInfo = Substitute.For(); + parentDirectoryInfo.FullName.Returns(" "); + _mockFileSystem.Directory.GetParent(path.Path).Returns(parentDirectoryInfo); + + // Act + Result result = _sut.RenameDirectory(path, newName); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.FileSystemManagement.InvalidPath, result.FirstError); + _mockFileSystem.Directory.DidNotReceive().Move(Arg.Any(), Arg.Any()); + } + + [Fact] + public void RenameDirectory_WhenNewPathIsWhitespace_ShouldReturnInvalidPathError() + { + // Arrange + FileSystemPathId path = _fileSystemPathIdFixture.Create( + s_isUnix ? "/OldName" : @"C:\OldName" + ); + string newName = "NewName"; + string parentPath = s_isUnix ? "/" : @"C:\"; + + IDirectoryInfo parentDirectoryInfo = Substitute.For(); + parentDirectoryInfo.FullName.Returns(parentPath); + _mockFileSystem.Directory.GetParent(path.Path).Returns(parentDirectoryInfo); + _mockFileSystem.Path.Combine(parentPath, newName).Returns(" "); + + // Act + Result result = _sut.RenameDirectory(path, newName); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.FileSystemManagement.InvalidPath, result.FirstError); + _mockFileSystem.Directory.DidNotReceive().Move(Arg.Any(), Arg.Any()); + } + [Fact] public void DeleteDirectory_WhenDirectoryExistsAndHasDeletePermission_ShouldDeleteSuccessfully() { diff --git a/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Services/DirectoryServiceTests.cs b/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Services/DirectoryServiceTests.cs index 1ec2e417..4cf8069e 100644 --- a/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Services/DirectoryServiceTests.cs +++ b/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Services/DirectoryServiceTests.cs @@ -36,6 +36,7 @@ public class DirectoryServiceTests private readonly string _pathDirTest = s_isUnix ? "/TestDir" : @"C:\TestDir"; private readonly string _pathDirTestSubDir1 = s_isUnix ? "/TestDir/Sub1" : @"C:\TestDir\Sub1"; private readonly string _pathDirTestSubDir2 = s_isUnix ? "/TestDir/Sub2" : @"C:\TestDir\Sub2"; + private readonly char _dirSeparator = s_isUnix ? '/' : '\\'; /// /// Initializes a new instance of the class. @@ -497,6 +498,150 @@ public class DirectoryServiceTests _mockEnvironmentContext.DirectoryProviderService.DidNotReceive().CreateDirectory(Arg.Any(), Arg.Any()); } + [Fact] + public void CopyDirectory_WhenSourceAndDestinationDoNotEndWithSeparator_ShouldAppendSeparatorAndReturnDirectoryNotFoundError() + { + // Arrange + string sourcePath = s_isUnix ? "/TestDir/Source" : @"C:\TestDir\Source"; + string destinationPath = s_isUnix ? "/TestDir/Destination" : @"C:\TestDir\Destination"; + bool overrideExisting = true; + _mockPlatformContext.PathStrategy.PathSeparator.Returns(_dirSeparator); + _mockEnvironmentContext.DirectoryProviderService.DirectoryExists(Arg.Any()) + .Returns(Result.From(false)); + + // Act + Result result = _sut.CopyDirectory(sourcePath, destinationPath, overrideExisting); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.FileSystemManagement.DirectoryNotFound, result.FirstError); + } + + [Fact] + public void CopyDirectory_WhenSourceAndDestinationEndWithSeparator_ShouldReturnDirectoryNotFoundError() + { + // Arrange + string sourcePath = s_isUnix ? "/TestDir/Source/" : @"C:\TestDir\Source\"; + string destinationPath = s_isUnix ? "/TestDir/Destination/" : @"C:\TestDir\Destination\"; + bool overrideExisting = true; + _mockPlatformContext.PathStrategy.PathSeparator.Returns(_dirSeparator); + _mockEnvironmentContext.DirectoryProviderService.DirectoryExists(Arg.Any()) + .Returns(Result.From(false)); + + // Act + Result result = _sut.CopyDirectory(sourcePath, destinationPath, overrideExisting); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.FileSystemManagement.DirectoryNotFound, result.FirstError); + } + + [Fact] + public void CopyDirectory_WhenDirectoryExistsReturnsError_ShouldPropagateError() + { + // Arrange + string sourcePath = s_isUnix ? "/TestDir/Source" : @"C:\TestDir\Source"; + string destinationPath = s_isUnix ? "/TestDir/Destination" : @"C:\TestDir\Destination"; + bool overrideExisting = true; + _mockPlatformContext.PathStrategy.PathSeparator.Returns(_dirSeparator); + _mockEnvironmentContext.DirectoryProviderService.DirectoryExists(Arg.Any()) + .Returns(Errors.Permission.UnauthorizedAccess); + + // Act + Result result = _sut.CopyDirectory(sourcePath, destinationPath, overrideExisting); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.Permission.UnauthorizedAccess, result.FirstError); + } + + [Fact] + public void CopyDirectory_WhenSourceDirectoryExists_ShouldThrowNotImplementedException() + { + // Arrange + string sourcePath = s_isUnix ? "/TestDir/Source" : @"C:\TestDir\Source"; + string destinationPath = s_isUnix ? "/TestDir/Destination" : @"C:\TestDir\Destination"; + bool overrideExisting = true; + _mockPlatformContext.PathStrategy.PathSeparator.Returns(_dirSeparator); + _mockEnvironmentContext.DirectoryProviderService.DirectoryExists(Arg.Any()) + .Returns(Result.From(true)); + + // Act & Assert + Assert.Throws(() => _sut.CopyDirectory(sourcePath, destinationPath, overrideExisting)); + } + + [Fact] + public void MoveDirectory_WhenSourceAndDestinationDoNotEndWithSeparator_ShouldAppendSeparatorAndReturnDirectoryNotFoundError() + { + // Arrange + string sourcePath = s_isUnix ? "/TestDir/Source" : @"C:\TestDir\Source"; + string destinationPath = s_isUnix ? "/TestDir/Destination" : @"C:\TestDir\Destination"; + bool overrideExisting = true; + _mockPlatformContext.PathStrategy.PathSeparator.Returns(_dirSeparator); + _mockEnvironmentContext.DirectoryProviderService.DirectoryExists(Arg.Any()) + .Returns(Result.From(false)); + + // Act + Result result = _sut.MoveDirectory(sourcePath, destinationPath, overrideExisting); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.FileSystemManagement.DirectoryNotFound, result.FirstError); + } + + [Fact] + public void MoveDirectory_WhenSourceAndDestinationEndWithSeparator_ShouldReturnDirectoryNotFoundError() + { + // Arrange + string sourcePath = s_isUnix ? "/TestDir/Source/" : @"C:\TestDir\Source\"; + string destinationPath = s_isUnix ? "/TestDir/Destination/" : @"C:\TestDir\Destination\"; + bool overrideExisting = true; + _mockPlatformContext.PathStrategy.PathSeparator.Returns(_dirSeparator); + _mockEnvironmentContext.DirectoryProviderService.DirectoryExists(Arg.Any()) + .Returns(Result.From(false)); + + // Act + Result result = _sut.MoveDirectory(sourcePath, destinationPath, overrideExisting); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.FileSystemManagement.DirectoryNotFound, result.FirstError); + } + + [Fact] + public void MoveDirectory_WhenDirectoryExistsReturnsError_ShouldPropagateError() + { + // Arrange + string sourcePath = s_isUnix ? "/TestDir/Source" : @"C:\TestDir\Source"; + string destinationPath = s_isUnix ? "/TestDir/Destination" : @"C:\TestDir\Destination"; + bool overrideExisting = true; + _mockPlatformContext.PathStrategy.PathSeparator.Returns(_dirSeparator); + _mockEnvironmentContext.DirectoryProviderService.DirectoryExists(Arg.Any()) + .Returns(Errors.Permission.UnauthorizedAccess); + + // Act + Result result = _sut.MoveDirectory(sourcePath, destinationPath, overrideExisting); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.Permission.UnauthorizedAccess, result.FirstError); + } + + [Fact] + public void MoveDirectory_WhenSourceDirectoryExists_ShouldThrowNotImplementedException() + { + // Arrange + string sourcePath = s_isUnix ? "/TestDir/Source" : @"C:\TestDir\Source"; + string destinationPath = s_isUnix ? "/TestDir/Destination" : @"C:\TestDir\Destination"; + bool overrideExisting = true; + _mockPlatformContext.PathStrategy.PathSeparator.Returns(_dirSeparator); + _mockEnvironmentContext.DirectoryProviderService.DirectoryExists(Arg.Any()) + .Returns(Result.From(true)); + + // Act & Assert + Assert.Throws(() => _sut.MoveDirectory(sourcePath, destinationPath, overrideExisting)); + } + [Fact] public void RenameDirectory_WithValidStringPath_ShouldReturnRenamedDirectory() { diff --git a/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Services/DriveServiceTests.cs b/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Services/DriveServiceTests.cs index 132aef7f..f5e78cc9 100644 --- a/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Services/DriveServiceTests.cs +++ b/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Services/DriveServiceTests.cs @@ -76,6 +76,27 @@ public class DriveServiceTests Assert.Equal(["C:\\", "D:\\"], result.Value.Select(d => d.Name)); } + [Fact] + public void GetDrives_OnWindowsPlatformWithDriveWithInvalidName_ShouldExcludeThatDrive() + { + // Arrange + _mockPlatformContext.Platform.Returns(PlatformType.Windows); + IDriveInfo[] mockDrives = + [ + CreateMockDriveInfo("C:\\", true), + CreateMockDriveInfo("", true) // drive whose name cannot be turned into a valid path + ]; + _mockFileSystem.DriveInfo.GetDrives().Returns(mockDrives); + + // Act + Result> result = _sut.GetDrives(); + + // Assert + Assert.False(result.IsFailure); + Assert.Single(result.Value); + Assert.Equal("C:\\", result.Value.First().Name); + } + private static IDriveInfo CreateMockDriveInfo(string name, bool isReady) { IDriveInfo mockDriveInfo = Substitute.For(); 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 686ca380..ab1424a5 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 @@ -255,30 +255,17 @@ public class FileProviderServiceTests public void GetFileAsync_WhenUserHasAccess_ShouldReturnFileContents() { // Arrange - string tempFilePath = Path.GetTempFileName(); - try - { - byte[] expectedContents = [1, 2, 3, 4, 5]; - File.WriteAllBytes(tempFilePath, expectedContents); + FileSystemPathId path = _fileSystemPathIdFixture.Create(); + byte[] expectedContents = [1, 2, 3, 4, 5]; + _mockFileSystemPermissionsService.CanAccessPath(path, FileAccessMode.ReadContents).Returns(true); + _mockFileSystem.File.ReadAllBytes(path.Path).Returns(expectedContents); - FileSystemPathId path = _fileSystemPathIdFixture.Create(tempFilePath); - _mockFileSystemPermissionsService.CanAccessPath(path, FileAccessMode.ReadContents).Returns(true); + // Act + Result result = _sut.GetFileAsync(path); - // We need to update the _fileSystem mock to use the real file system for this method - _mockFileSystem.File.ReadAllBytes(tempFilePath).Returns(x => File.ReadAllBytes(x.Arg())); - - // Act - Result result = _sut.GetFileAsync(path); - - // Assert - Assert.False(result.IsFailure); - Assert.Equal(expectedContents, result.Value); - } - finally - { - // clean up - File.Delete(tempFilePath); - } + // Assert + Assert.False(result.IsFailure); + Assert.Equal(expectedContents, result.Value); } [Fact] @@ -300,52 +287,34 @@ public class FileProviderServiceTests public void GetFileAsync_WhenFileIsEmpty_ShouldReturnEmptyByteArray() { // Arrange - string tempFilePath = Path.GetTempFileName(); - try - { - FileSystemPathId path = _fileSystemPathIdFixture.Create(tempFilePath); - _mockFileSystemPermissionsService.CanAccessPath(path, FileAccessMode.ReadContents).Returns(true); + FileSystemPathId path = _fileSystemPathIdFixture.Create(); + _mockFileSystemPermissionsService.CanAccessPath(path, FileAccessMode.ReadContents).Returns(true); + _mockFileSystem.File.ReadAllBytes(path.Path).Returns([]); - // Act - Result result = _sut.GetFileAsync(path); + // Act + Result result = _sut.GetFileAsync(path); - // Assert - Assert.False(result.IsFailure); - Assert.Empty(result.Value); - } - finally - { - // clean up - File.Delete(tempFilePath); - } + // Assert + Assert.False(result.IsFailure); + Assert.Empty(result.Value); } [Fact] public void GetLastWriteTime_WhenUserHasAccess_ShouldReturnLastWriteTime() { // Arrange - string tempFilePath = Path.GetTempFileName(); - try - { - File.WriteAllText(tempFilePath, "Test content"); - FileSystemPathId path = _fileSystemPathIdFixture.Create(tempFilePath); - DateTime expectedDateTime = File.GetLastWriteTime(tempFilePath); + FileSystemPathId path = _fileSystemPathIdFixture.Create(); + DateTime expectedDateTime = new(2024, 1, 2, 3, 4, 5); + _mockFileSystemPermissionsService.CanAccessPath(path, FileAccessMode.ReadProperties).Returns(true); + _mockFileSystem.File.GetLastWriteTime(path.Path).Returns(expectedDateTime); - _mockFileSystemPermissionsService.CanAccessPath(path, FileAccessMode.ReadProperties).Returns(true); - _mockFileSystem.File.GetLastWriteTime(path.Path).Returns(expectedDateTime); + // Act + Result> result = _sut.GetLastWriteTime(path); - // Act - Result> result = _sut.GetLastWriteTime(path); - - // Assert - Assert.False(result.IsFailure); - Assert.True(result.Value.HasValue); - Assert.Equal(expectedDateTime, result.Value.Value, TimeSpan.FromSeconds(1)); - } - finally - { - File.Delete(tempFilePath); - } + // Assert + Assert.False(result.IsFailure); + Assert.True(result.Value.HasValue); + Assert.Equal(expectedDateTime, result.Value.Value, TimeSpan.FromSeconds(1)); } [Fact] @@ -367,28 +336,18 @@ public class FileProviderServiceTests public void GetCreationTime_WhenUserHasAccess_ShouldReturnCreationTime() { // Arrange - string tempFilePath = Path.GetTempFileName(); - try - { - File.WriteAllText(tempFilePath, "Test content"); - FileSystemPathId path = _fileSystemPathIdFixture.Create(tempFilePath); - DateTime expectedDateTime = File.GetCreationTime(tempFilePath); + FileSystemPathId path = _fileSystemPathIdFixture.Create(); + DateTime expectedDateTime = new(2024, 1, 2, 3, 4, 5); + _mockFileSystemPermissionsService.CanAccessPath(path, FileAccessMode.ReadProperties).Returns(true); + _mockFileSystem.File.GetCreationTime(path.Path).Returns(expectedDateTime); - _mockFileSystemPermissionsService.CanAccessPath(path, FileAccessMode.ReadProperties).Returns(true); - _mockFileSystem.File.GetCreationTime(path.Path).Returns(expectedDateTime); + // Act + Result> result = _sut.GetCreationTime(path); - // Act - Result> result = _sut.GetCreationTime(path); - - // Assert - Assert.False(result.IsFailure); - Assert.True(result.Value.HasValue); - Assert.Equal(expectedDateTime, result.Value.Value, TimeSpan.FromSeconds(1)); - } - finally - { - File.Delete(tempFilePath); - } + // Assert + Assert.False(result.IsFailure); + Assert.True(result.Value.HasValue); + Assert.Equal(expectedDateTime, result.Value.Value, TimeSpan.FromSeconds(1)); } [Fact] @@ -410,29 +369,20 @@ public class FileProviderServiceTests public void GetSize_WhenUserHasAccess_ShouldReturnFileSize() { // Arrange - string tempFilePath = Path.GetTempFileName(); - try - { - string content = "Test content"; - File.WriteAllText(tempFilePath, content); - FileSystemPathId path = _fileSystemPathIdFixture.Create(tempFilePath); - long expectedSize = new FileInfo(tempFilePath).Length; + FileSystemPathId path = _fileSystemPathIdFixture.Create(); + long expectedSize = 42; + IFileInfo mockFileInfo = Substitute.For(); + mockFileInfo.Length.Returns(expectedSize); + _mockFileSystemPermissionsService.CanAccessPath(path, FileAccessMode.ReadProperties).Returns(true); + _mockFileSystem.FileInfo.New(path.Path).Returns(mockFileInfo); - _mockFileSystemPermissionsService.CanAccessPath(path, FileAccessMode.ReadProperties).Returns(true); - _mockFileSystem.FileInfo.New(path.Path).Returns(new FileInfoWrapper(_mockFileSystem, new FileInfo(tempFilePath))); + // Act + Result result = _sut.GetSize(path); - // Act - Result result = _sut.GetSize(path); - - // Assert - Assert.False(result.IsFailure); - Assert.NotNull(result.Value); - Assert.Equal(expectedSize, result.Value); - } - finally - { - File.Delete(tempFilePath); - } + // Assert + Assert.False(result.IsFailure); + Assert.NotNull(result.Value); + Assert.Equal(expectedSize, result.Value); } [Fact] @@ -601,7 +551,7 @@ public class FileProviderServiceTests _mockFileSystem.Path.Combine(Arg.Any(), Arg.Any()) .Returns(callInfo => Path.Combine(callInfo.ArgAt(0), callInfo.ArgAt(1))); - // Simulate the behavior of CreateUniqueFilePath + // Simulate the behavior of CreateUniqueFilePath. int copyNumber = 1; _mockFileSystem.File.Exists(Arg.Any()) .Returns(x => @@ -858,6 +808,52 @@ public class FileProviderServiceTests _mockFileSystem.File.DidNotReceive().Move(Arg.Any(), Arg.Any()); } + [Fact] + public void RenameFile_WhenParentDirectoryPathIsWhitespace_ShouldReturnInvalidPathError() + { + // Arrange + FileSystemPathId path = _fileSystemPathIdFixture.Create( + s_isUnix ? "/OldName.txt" : @"C:\OldName.txt" + ); + string newName = "NewName.txt"; + + IFileInfo fileInfo = Substitute.For(); + fileInfo.DirectoryName.Returns(" "); + _mockFileSystem.FileInfo.New(path.Path).Returns(fileInfo); + + // Act + Result result = _sut.RenameFile(path, newName); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.FileSystemManagement.InvalidPath, result.FirstError); + _mockFileSystem.File.DidNotReceive().Move(Arg.Any(), Arg.Any()); + } + + [Fact] + public void RenameFile_WhenNewPathIsWhitespace_ShouldReturnInvalidPathError() + { + // Arrange + FileSystemPathId path = _fileSystemPathIdFixture.Create( + s_isUnix ? "/OldName.txt" : @"C:\OldName.txt" + ); + string newName = "NewName.txt"; + string parentPath = s_isUnix ? "/" : @"C:\"; + + IFileInfo fileInfo = Substitute.For(); + fileInfo.DirectoryName.Returns(parentPath); + _mockFileSystem.FileInfo.New(path.Path).Returns(fileInfo); + _mockFileSystem.Path.Combine(parentPath, newName).Returns(" "); + + // Act + Result result = _sut.RenameFile(path, newName); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.FileSystemManagement.InvalidPath, result.FirstError); + _mockFileSystem.File.DidNotReceive().Move(Arg.Any(), Arg.Any()); + } + [Fact] public void RenameFile_WhenParentDirectoryExistsButNotWritable_ShouldReturnUnauthorizedAccessError() { @@ -874,11 +870,11 @@ public class FileProviderServiceTests _mockFileSystem.FileInfo.New(path.Path).Returns(fileInfo); _mockFileSystem.Path.Combine(parentPath, newName).Returns(newPath); - // Mock successful creation of parent directory FileSystemPathId + // Mock successful creation of parent directory FileSystemPathId. 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 + // Mock permissions: executable for the file, but not writable for the parent directory. _mockFileSystemPermissionsService.CanAccessPath(path, FileAccessMode.Execute).Returns(true); _mockFileSystemPermissionsService.CanAccessPath(Arg.Is(x => x.Path == parentPath), FileAccessMode.Write).Returns(false); diff --git a/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Services/FileServiceTests.cs b/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Services/FileServiceTests.cs index 1efdd9be..a2782531 100644 --- a/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Services/FileServiceTests.cs +++ b/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Services/FileServiceTests.cs @@ -326,6 +326,35 @@ public class FileServiceTests Assert.Equal(FileSystemItemStatus.Inaccessible, result.Value.First().Status); } + [Fact] + public void GetFilesWithFileSystemPathId_WhenSizeRetrievalFails_ShouldReturnInaccessibleFileWithZeroSize() + { + // Arrange + FileSystemPathId pathId = _fileSystemPathIdFixture.Create(_pathTestDir); + bool includeHiddenElements = false; + FileSystemPathId filePath = _fileSystemPathIdFixture.Create(_pathTestDirFile1); + + _mockEnvironmentContext.FileProviderService.GetFilePaths(pathId, includeHiddenElements) + .Returns(Result.From(new[] { filePath }.AsEnumerable())); + _mockEnvironmentContext.FileProviderService.GetFileName(filePath) + .Returns(Result.From("File1.txt")); + _mockEnvironmentContext.FileProviderService.GetLastWriteTime(filePath) + .Returns(Result.From(Optional.FromNullable(DateTime.Now))); + _mockEnvironmentContext.FileProviderService.GetCreationTime(filePath) + .Returns(Result.From(Optional.FromNullable(DateTime.Now.AddDays(-1)))); + _mockEnvironmentContext.FileProviderService.GetSize(filePath) + .Returns(Errors.Permission.UnauthorizedAccess); + + // Act + Result> result = _sut.GetFiles(pathId, includeHiddenElements); + + // Assert + Assert.False(result.IsFailure); + Assert.Single(result.Value); + Assert.Equal(FileSystemItemStatus.Inaccessible, result.Value.First().Status); + Assert.Equal(0, result.Value.First().Size); + } + [Fact] public void CopyFile_WithValidPaths_ShouldReturnCopiedFile() { @@ -432,6 +461,27 @@ public class FileServiceTests Assert.Equal(FileSystemItemStatus.Inaccessible, result.Value.Status); } + [Fact] + public void CopyFile_WhenFileExistsReturnsError_ShouldPropagateError() + { + // Arrange + string sourcePath = _pathSourceFile; + string destinationPath = _pathDestination1; + bool overrideExisting = true; + FileSystemPathId sourcePathId = _fileSystemPathIdFixture.Create(sourcePath); + + _mockPlatformContext.PathStrategy.PathSeparator.Returns(_dirSeparator); + _mockEnvironmentContext.FileProviderService.FileExists(sourcePathId) + .Returns(Errors.Permission.UnauthorizedAccess); + + // Act + Result result = _sut.CopyFile(sourcePath, destinationPath, overrideExisting); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.Permission.UnauthorizedAccess, result.FirstError); + } + [Fact] public void CopyFile_WithInvalidSourcePath_ShouldReturnError() { @@ -559,6 +609,55 @@ public class FileServiceTests Assert.Equal(FileSystemItemStatus.Inaccessible, result.Value.Status); } + [Fact] + public void CopyFileWithFileSystemPathIds_WhenFileExistsReturnsError_ShouldPropagateError() + { + // Arrange + FileSystemPathId sourcePathId = _fileSystemPathIdFixture.Create(_pathSourceFile); + FileSystemPathId destinationPathId = _fileSystemPathIdFixture.Create(_pathDestination2); + bool overrideExisting = true; + + _mockEnvironmentContext.FileProviderService.FileExists(sourcePathId) + .Returns(Errors.Permission.UnauthorizedAccess); + + // Act + Result result = _sut.CopyFile(sourcePathId, destinationPathId, overrideExisting); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.Permission.UnauthorizedAccess, result.FirstError); + } + + [Fact] + public void CopyFileWithFileSystemPathIds_WhenSizeRetrievalFails_ShouldReturnInaccessibleFileWithZeroSize() + { + // Arrange + FileSystemPathId sourcePathId = _fileSystemPathIdFixture.Create(_pathSourceFile); + FileSystemPathId destinationPathId = _fileSystemPathIdFixture.Create(_pathDestination2); + FileSystemPathId copiedFilePathId = _fileSystemPathIdFixture.Create(_pathDestinationFile); + bool overrideExisting = true; + + _mockEnvironmentContext.FileProviderService.FileExists(sourcePathId).Returns(true); + _mockEnvironmentContext.FileProviderService.CopyFile(sourcePathId, destinationPathId, overrideExisting) + .Returns(copiedFilePathId); + _mockEnvironmentContext.FileProviderService.GetFileName(copiedFilePathId).Returns("file.txt"); + _mockEnvironmentContext.FileProviderService.GetLastWriteTime(copiedFilePathId) + .Returns(Optional.FromNullable(DateTime.Now)); + _mockEnvironmentContext.FileProviderService.GetCreationTime(copiedFilePathId) + .Returns(Optional.FromNullable(DateTime.Now.AddDays(-1))); + _mockEnvironmentContext.FileProviderService.GetSize(copiedFilePathId) + .Returns(Errors.Permission.UnauthorizedAccess); + + // Act + Result result = _sut.CopyFile(sourcePathId, destinationPathId, overrideExisting); + + // Assert + Assert.False(result.IsFailure); + Assert.NotNull(result.Value); + Assert.Equal(FileSystemItemStatus.Inaccessible, result.Value.Status); + Assert.Equal(0, result.Value.Size); + } + [Fact] public void MoveFile_WithValidPaths_ShouldReturnMovedFile() { @@ -800,6 +899,36 @@ public class FileServiceTests Assert.Equal(FileSystemItemStatus.Inaccessible, result.Value.Status); } + [Fact] + public void MoveFileWithFileSystemPathIds_WhenSizeRetrievalFails_ShouldReturnInaccessibleFileWithZeroSize() + { + // Arrange + FileSystemPathId sourcePathId = _fileSystemPathIdFixture.Create(_pathSourceFile); + FileSystemPathId destinationPathId = _fileSystemPathIdFixture.Create(_pathDestination1); + FileSystemPathId movedFilePathId = _fileSystemPathIdFixture.Create(_pathDestinationFile); + bool overrideExisting = true; + + _mockEnvironmentContext.FileProviderService.FileExists(sourcePathId).Returns(true); + _mockEnvironmentContext.FileProviderService.MoveFile(sourcePathId, destinationPathId, overrideExisting) + .Returns(movedFilePathId); + _mockEnvironmentContext.FileProviderService.GetFileName(movedFilePathId).Returns("file.txt"); + _mockEnvironmentContext.FileProviderService.GetLastWriteTime(movedFilePathId) + .Returns(Optional.FromNullable(DateTime.Now)); + _mockEnvironmentContext.FileProviderService.GetCreationTime(movedFilePathId) + .Returns(Optional.FromNullable(DateTime.Now.AddDays(-1))); + _mockEnvironmentContext.FileProviderService.GetSize(movedFilePathId) + .Returns(Errors.Permission.UnauthorizedAccess); + + // Act + Result result = _sut.MoveFile(sourcePathId, destinationPathId, overrideExisting); + + // Assert + Assert.False(result.IsFailure); + Assert.NotNull(result.Value); + Assert.Equal(FileSystemItemStatus.Inaccessible, result.Value.Status); + Assert.Equal(0, result.Value.Size); + } + [Fact] public void MoveFile_WhenFileExistsReturnsError_ShouldPropagateError() { @@ -1045,6 +1174,37 @@ public class FileServiceTests Assert.Equal(FileSystemItemStatus.Inaccessible, result.Value.Status); } + [Fact] + public void RenameFileWithFileSystemPathId_WhenSizeRetrievalFails_ShouldReturnInaccessibleFileWithZeroSize() + { + // Arrange + FileSystemPathId pathId = _fileSystemPathIdFixture.Create(_pathSourceOldFile); + string newName = "newfile.txt"; + FileSystemPathId newPathId = _fileSystemPathIdFixture.Create(_pathSourceNewFile); + + _mockPlatformContext.PathStrategy.CombinePath(Arg.Any(), newName) + .Returns(Result.From(newPathId)); + _mockEnvironmentContext.FileProviderService.FileExists(newPathId).Returns(false); + _mockEnvironmentContext.FileProviderService.RenameFile(pathId, newName) + .Returns(Result.From(newPathId)); + _mockEnvironmentContext.FileProviderService.GetFileName(newPathId).Returns(Result.From(newName)); + _mockEnvironmentContext.FileProviderService.GetLastWriteTime(newPathId) + .Returns(Result.From(Optional.FromNullable(DateTime.Now))); + _mockEnvironmentContext.FileProviderService.GetCreationTime(newPathId) + .Returns(Result.From(Optional.FromNullable(DateTime.Now.AddDays(-1)))); + _mockEnvironmentContext.FileProviderService.GetSize(newPathId) + .Returns(Errors.Permission.UnauthorizedAccess); + + // Act + Result result = _sut.RenameFile(pathId, newName); + + // Assert + Assert.False(result.IsFailure); + Assert.NotNull(result.Value); + Assert.Equal(FileSystemItemStatus.Inaccessible, result.Value.Status); + Assert.Equal(0, result.Value.Size); + } + [Fact] public void RenameFile_WhenCombinePathReturnsError_ShouldPropagateError() { @@ -1208,4 +1368,18 @@ public class FileServiceTests Assert.True(result.IsFailure); Assert.Equal(Errors.Permission.UnauthorizedAccess, result.FirstError); } + + [Fact] + public void ReadFile_WithFileSystemPathId_ShouldReturnTrue() + { + // Arrange + FileSystemPathId pathId = _fileSystemPathIdFixture.Create(_pathSourceFile); + + // Act + Result result = _sut.ReadFile(pathId); + + // Assert + Assert.False(result.IsFailure); + Assert.True(result.Value); + } } diff --git a/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Services/FileSystemStructureSeedServiceTests.cs b/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Services/FileSystemStructureSeedServiceTests.cs new file mode 100644 index 00000000..8bf0cae6 --- /dev/null +++ b/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Services/FileSystemStructureSeedServiceTests.cs @@ -0,0 +1,137 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Domain.Common.Errors; +using Lumina.Domain.Common.Primitives; +using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Services; +using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Strategies.Environment; +using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.ValueObjects; +using NSubstitute; +using System; +using System.Diagnostics.CodeAnalysis; +using System.IO; +using System.Runtime.InteropServices; +#endregion + +namespace Lumina.Domain.UnitTests.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Services; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class FileSystemStructureSeedServiceTests +{ + private readonly IEnvironmentContext _mockEnvironmentContext; + private readonly IDirectoryProviderService _mockDirectoryProviderService; + private readonly IPathService _mockPathService; + private readonly FileSystemStructureSeedService _sut; + private static readonly bool s_isUnix = RuntimeInformation.IsOSPlatform(OSPlatform.Linux) || RuntimeInformation.IsOSPlatform(OSPlatform.OSX); + private readonly string _rootPath = s_isUnix ? "/Lumina" : @"C:\Lumina"; + + /// + /// Initializes a new instance of the class. + /// + public FileSystemStructureSeedServiceTests() + { + _mockEnvironmentContext = Substitute.For(); + _mockDirectoryProviderService = Substitute.For(); + _mockPathService = Substitute.For(); + _mockEnvironmentContext.DirectoryProviderService.Returns(_mockDirectoryProviderService); + _sut = new FileSystemStructureSeedService(_mockEnvironmentContext, _mockPathService); + } + + [Fact] + public void SetDefaultDirectories_WhenDirectoriesDoNotExist_ShouldCreateThem() + { + // Arrange + _mockPathService.CombinePath(_rootPath, "libraries").Returns(Path.Combine(_rootPath, "libraries")); + _mockPathService.CombinePath(_rootPath, "books").Returns(Path.Combine(_rootPath, "books")); + _mockDirectoryProviderService.DirectoryExists(Arg.Any()).Returns(false); + _mockDirectoryProviderService.CreateDirectory(Arg.Any(), Arg.Any()) + .Returns(callInfo => Result.Success(FileSystemPathId.Create(Path.Combine(_rootPath, callInfo.ArgAt(1))).Value)); + + // Act + Result result = _sut.SetDefaultDirectories(_rootPath); + + // Assert + Assert.True(result.IsSuccess); + _mockDirectoryProviderService.Received(2).DirectoryExists(Arg.Any()); + _mockDirectoryProviderService.Received(2).CreateDirectory(Arg.Any(), Arg.Any()); + } + + [Fact] + public void SetDefaultDirectories_WhenDirectoriesAlreadyExist_ShouldNotCreateThem() + { + // Arrange + _mockPathService.CombinePath(_rootPath, "libraries").Returns(Path.Combine(_rootPath, "libraries")); + _mockPathService.CombinePath(_rootPath, "books").Returns(Path.Combine(_rootPath, "books")); + _mockDirectoryProviderService.DirectoryExists(Arg.Any()).Returns(true); + + // Act + Result result = _sut.SetDefaultDirectories(_rootPath); + + // Assert + Assert.True(result.IsSuccess); + _mockDirectoryProviderService.Received(2).DirectoryExists(Arg.Any()); + _mockDirectoryProviderService.DidNotReceive().CreateDirectory(Arg.Any(), Arg.Any()); + } + + [Fact] + public void SetDefaultDirectories_WhenRootPathIsInvalid_ShouldReturnInvalidPathError() + { + // Act + Result result = _sut.SetDefaultDirectories(" "); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.FileSystemManagement.InvalidPath, result.FirstError); + _mockPathService.DidNotReceive().CombinePath(Arg.Any(), Arg.Any()); + _mockDirectoryProviderService.DidNotReceive().DirectoryExists(Arg.Any()); + } + + [Fact] + public void SetDefaultDirectories_WhenCombiningPathFails_ShouldReturnTheError() + { + // Arrange + _mockPathService.CombinePath(_rootPath, "libraries").Returns(Errors.FileSystemManagement.InvalidPath); + + // Act + Result result = _sut.SetDefaultDirectories(_rootPath); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.FileSystemManagement.InvalidPath, result.FirstError); + _mockDirectoryProviderService.DidNotReceive().DirectoryExists(Arg.Any()); + } + + [Fact] + public void SetDefaultDirectories_WhenCheckingDirectoryExistenceFails_ShouldReturnTheError() + { + // Arrange + _mockPathService.CombinePath(_rootPath, "libraries").Returns(Path.Combine(_rootPath, "libraries")); + _mockDirectoryProviderService.DirectoryExists(Arg.Any()).Returns(Errors.FileSystemManagement.DirectoryNotFound); + + // Act + Result result = _sut.SetDefaultDirectories(_rootPath); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.FileSystemManagement.DirectoryNotFound, result.FirstError); + _mockDirectoryProviderService.DidNotReceive().CreateDirectory(Arg.Any(), Arg.Any()); + } + + [Fact] + public void SetDefaultDirectories_WhenCreatingDirectoryFails_ShouldReturnTheError() + { + // Arrange + _mockPathService.CombinePath(_rootPath, "libraries").Returns(Path.Combine(_rootPath, "libraries")); + _mockDirectoryProviderService.DirectoryExists(Arg.Any()).Returns(false); + _mockDirectoryProviderService.CreateDirectory(Arg.Any(), Arg.Any()) + .Returns(Errors.FileSystemManagement.DirectoryAlreadyExists); + + // Act + Result result = _sut.SetDefaultDirectories(_rootPath); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.FileSystemManagement.DirectoryAlreadyExists, result.FirstError); + } +} 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 cf0803aa..f87eaacc 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 @@ -40,6 +40,20 @@ public class PathServiceTests _sut = new PathService(_mockPlatformContextManager); } + [Fact] + public void PathSeparator_WhenAccessed_ShouldReturnPathStrategySeparator() + { + // Arrange + char expectedSeparator = '\\'; + _mockPathStrategy.PathSeparator.Returns(expectedSeparator); + + // Act + char result = _sut.PathSeparator; + + // Assert + Assert.Equal(expectedSeparator, result); + } + [Fact] public void IsValidPath_WithValidPath_ShouldReturnTrue() { diff --git a/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Services/ThumbnailServiceTests.cs b/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Services/ThumbnailServiceTests.cs index 83d75cf0..fbf57350 100644 --- a/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Services/ThumbnailServiceTests.cs +++ b/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Services/ThumbnailServiceTests.cs @@ -9,6 +9,7 @@ using Lumina.Domain.Fixtures.Core.BoundedContexts.FileSystemManagementBoundedCon using Lumina.Domain.SharedKernel.Common.Enums.PhotoLibrary; using NSubstitute; using SixLabors.ImageSharp; +using SixLabors.ImageSharp.Formats; using SixLabors.ImageSharp.Formats.Jpeg; using SixLabors.ImageSharp.PixelFormats; using System.Diagnostics.CodeAnalysis; @@ -168,6 +169,67 @@ public class ThumbnailServiceTests } } + [Theory] + [InlineData(ImageType.JPEG2000)] // resolution adjustment switch branch for JPEG2000 + [InlineData(ImageType.JPEG_CANON)] // resolution adjustment switch branch for Canon JPEG + [InlineData(ImageType.JPEG_UNKNOWN)] // resolution adjustment switch branch for unknown JPEG + [InlineData(ImageType.TIFF)] // resolution adjustment switch branch for TIFF + [InlineData(ImageType.WEBP)] // resolution adjustment switch branch for WEBP + [InlineData(ImageType.TGA)] // resolution adjustment switch branch for TGA + public async Task GetThumbnailAsync_WithAdditionalSupportedImageTypes_ShouldReturnAdjustedThumbnail(ImageType imageType) + { + // Arrange + FileSystemPathId pathId = _fileSystemPathIdFixture.Create(@"C:\TestImage"); + int quality = 80; + byte[] imageBytes = CreateImageBytes(new JpegEncoder()); + + _mockEnvironmentContext.FileTypeService.GetImageTypeAsync(pathId, Arg.Any()) + .Returns(Result.From(imageType)); + _mockEnvironmentContext.FileProviderService.GetFileAsync(pathId) + .Returns(Result.From(imageBytes)); + + // Act + Result result = await _sut.GetThumbnailAsync(pathId, quality, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal(imageType, result.Value.Type); + Assert.NotEmpty(result.Value.Bytes); + + using (MemoryStream ms = new(result.Value.Bytes)) + { + Image loadedImage = Image.Load(ms); + Assert.NotNull(loadedImage); + } + } + + [Theory] + [InlineData(ImageType.SVG)] // SVG is not resized, original bytes are returned + [InlineData(ImageType.PICT)] // PICT is not resized, original bytes are returned + [InlineData(ImageType.ICO)] // ICO is not resized, original bytes are returned + [InlineData(ImageType.PSD)] // PSD is not resized, original bytes are returned + [InlineData(ImageType.AVIF)] // AVIF is not resized, original bytes are returned + public async Task GetThumbnailAsync_WithUnsupportedNonNoneImageType_ShouldReturnOriginalBytes(ImageType imageType) + { + // Arrange + FileSystemPathId pathId = _fileSystemPathIdFixture.Create(@"C:\TestImage"); + int quality = 80; + byte[] imageBytes = CreateImageBytes(new JpegEncoder()); + + _mockEnvironmentContext.FileTypeService.GetImageTypeAsync(pathId, Arg.Any()) + .Returns(Result.From(imageType)); + _mockEnvironmentContext.FileProviderService.GetFileAsync(pathId) + .Returns(Result.From(imageBytes)); + + // Act + Result result = await _sut.GetThumbnailAsync(pathId, quality, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal(imageType, result.Value.Type); + Assert.Equal(imageBytes, result.Value.Bytes); + } + [Fact] public async Task GetThumbnailAsync_WithCancellation_ShouldThrowTaskCanceledException() { @@ -184,4 +246,17 @@ public class ThumbnailServiceTests await Assert.ThrowsAsync(() => _sut.GetThumbnailAsync(pathId, quality, cts.Token)); } + + /// + /// Creates the bytes of a small image encoded with the specified encoder. + /// + /// The encoder used to encode the image. + /// The bytes of the created image. + private static byte[] CreateImageBytes(IImageEncoder encoder) + { + using Image image = new(10, 10); + using MemoryStream memoryStream = new(); + image.Save(memoryStream, encoder); + return memoryStream.ToArray(); + } } diff --git a/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Strategies/Path/UnixPathStrategyTests.cs b/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Strategies/Path/UnixPathStrategyTests.cs index c79f6fc3..ee30f141 100644 --- a/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Strategies/Path/UnixPathStrategyTests.cs +++ b/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Strategies/Path/UnixPathStrategyTests.cs @@ -376,6 +376,20 @@ public class UnixPathStrategyTests Assert.Equal(Errors.FileSystemManagement.InvalidPath, result.FirstError); } + [Fact] + public void ParsePath_WhenPathContainsWhitespaceSegment_ShouldReturnError() + { + // Arrange + FileSystemPathId path = _fileSystemPathIdFixture.Create("/home/ /user"); + + // Act + Result> result = _sut.ParsePath(path); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.FileSystemManagement.NameCannotBeEmpty, result.FirstError); + } + [Fact] public void ParsePath_WithPathContainingDots_ShouldParseCorrectly() { diff --git a/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Strategies/Path/WindowsPathStrategyTests.cs b/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Strategies/Path/WindowsPathStrategyTests.cs index a01a5f9b..1e915b96 100644 --- a/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Strategies/Path/WindowsPathStrategyTests.cs +++ b/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Strategies/Path/WindowsPathStrategyTests.cs @@ -419,6 +419,20 @@ public class WindowsPathStrategyTests Assert.Equal(Errors.FileSystemManagement.InvalidPath, result.FirstError); } + [Fact] + public void ParsePath_WhenPathContainsWhitespaceSegment_ShouldReturnError() + { + // Arrange + FileSystemPathId path = _fileSystemPathIdFixture.Create(@"C:\ \folder"); + + // Act + Result> result = _sut.ParsePath(path); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.FileSystemManagement.NameCannotBeEmpty, result.FirstError); + } + [Fact] public void ParsePath_WithPathContainingDots_ShouldParseCorrectly() { diff --git a/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryAggregate/LibraryTests.cs b/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryAggregate/LibraryTests.cs index ca069f9b..e6e9d88e 100644 --- a/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryAggregate/LibraryTests.cs +++ b/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryAggregate/LibraryTests.cs @@ -95,6 +95,45 @@ public class LibraryTests Assert.Equal(id, result.Value.Id.Value); } + [Fact] + public void Create_WhenGivenPreExistingIdAndInvalidContentLocation_ShouldReturnError() + { + // Arrange + Guid id = Guid.NewGuid(); + + // Act + Result result = Library.Create( + _libraryIdFixture.Create(id), + _userIdFixture.Create(), + "My Library", + LibraryType.Book, + [""], + null, + isEnabled: true, + isLocked: false, + canDownloadMetadataFromWeb: true, + shouldSaveMetadataInMediaDirectories: false, + shouldSkipUnchangedDirectoriesDuringScan: false, + []); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Lumina.Domain.Common.Errors.Errors.FileSystemManagement.InvalidPath, result.FirstError); + } + + [Fact] + public void Create_WhenCalledWithValidData_ShouldLeaveCoverImageSourcePathUnset() + { + // Arrange + Library library = _libraryFixture.Create(); + + // Act + string? coverImageSourcePath = library.CoverImageSourcePath; + + // Assert + Assert.Null(coverImageSourcePath); + } + [Fact] public void Create_WhenCalledWithContentLocations_ShouldCreateFileSystemPathIdForEachLocation() { 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 index 2f189b6b..ffa634d3 100644 --- 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 @@ -100,6 +100,23 @@ public class MediaLibrariesScanProgressTrackerTests Assert.Equal(100, progressResult.Value.OverallProgressPercentage); } + [Fact] + public void UpdateScanProgress_WhenScanIsAlreadyCompleted_ShouldReturnError() + { + // Arrange + LibraryId libraryId = _libraryIdFixture.Create(); + MediaLibraryScanCompositeId compositeId = _mediaLibraryScanCompositeIdFixture.Create(); + _sut.InitializeScanProgress(libraryId, compositeId, totalJobs: 1); + _sut.UpdateScanProgress(libraryId, compositeId); + + // Act + Result result = _sut.UpdateScanProgress(libraryId, compositeId); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.LibraryScanning.CompletedScanJobsCountCantExceedTotalScanJobsCount, result.FirstError); + } + [Fact] public void UpdateScanJobProgress_WhenScanExists_ShouldUpdateCurrentJobProgress() { 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 index 33356182..9a3f743b 100644 --- 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 @@ -35,9 +35,39 @@ public class MediaLibraryScannerFactoryTests [Theory] [InlineData(LibraryType.EBook)] // eBook scanner is not implemented + [InlineData(LibraryType.ComicBook)] // comic book scanner is not implemented + [InlineData(LibraryType.Magazine)] // magazine scanner is not implemented + [InlineData(LibraryType.Newspaper)] // newspaper scanner is not implemented + [InlineData(LibraryType.Manga)] // manga scanner is not implemented + [InlineData(LibraryType.GraphicNovel)] // graphic novel scanner is not implemented + [InlineData(LibraryType.AcademicPaper)] // academic paper scanner is not implemented + [InlineData(LibraryType.SheetMusic)] // sheet music scanner is not implemented [InlineData(LibraryType.Movie)] // movie scanner is not implemented + [InlineData(LibraryType.TvShow)] // TV show scanner is not implemented + [InlineData(LibraryType.Documentary)] // documentary scanner is not implemented + [InlineData(LibraryType.Anime)] // anime scanner is not implemented + [InlineData(LibraryType.ConcertVideo)] // concert video scanner is not implemented + [InlineData(LibraryType.TutorialVideo)] // tutorial video scanner is not implemented + [InlineData(LibraryType.HomeVideo)] // home video scanner is not implemented + [InlineData(LibraryType.YouTubeVideo)] // YouTube video scanner is not implemented + [InlineData(LibraryType.MusicVideo)] // music video scanner is not implemented + [InlineData(LibraryType.LiveRecordingVideo)] // live recording video scanner is not implemented + [InlineData(LibraryType.InterviewVideo)] // interview video scanner is not implemented + [InlineData(LibraryType.CoverSongVideo)] // cover song video scanner is not implemented + [InlineData(LibraryType.PodcastVideo)] // podcast video scanner is not implemented [InlineData(LibraryType.Music)] // music scanner is not implemented + [InlineData(LibraryType.Audiobook)] // audiobook scanner is not implemented + [InlineData(LibraryType.LiveRecordingAudio)] // live recording audio scanner is not implemented + [InlineData(LibraryType.InterviewAudio)] // interview audio scanner is not implemented + [InlineData(LibraryType.CoverSongAudio)] // cover song audio scanner is not implemented + [InlineData(LibraryType.Remix)] // remix scanner is not implemented + [InlineData(LibraryType.SoundEffect)] // sound effect scanner is not implemented + [InlineData(LibraryType.PodcastAudio)] // podcast audio scanner is not implemented [InlineData(LibraryType.Photo)] // photo scanner is not implemented + [InlineData(LibraryType.Playlist)] // playlist scanner is not implemented + [InlineData(LibraryType.Collection)] // collection scanner is not implemented + [InlineData(LibraryType.Subtitles)] // subtitles scanner is not implemented + [InlineData(LibraryType.Lyrics)] // lyrics scanner is not implemented public void CreateLibraryScanner_WhenLibraryTypeIsNotImplemented_ShouldThrowNotImplementedException(LibraryType libraryType) { // Arrange 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 index d271dab9..8a3c3ee7 100644 --- 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 @@ -197,4 +197,22 @@ public class MediaLibraryScanProgressTests // Assert Assert.NotEqual(firstResult, secondResult); } + + [Fact] + public void ToString_WhenCalled_ShouldReturnFormattedProgressString() + { + // Arrange + MediaLibraryScanJobProgress currentJobProgress = _mediaLibraryScanJobProgressFixture.Create(completedItems: 3, totalItems: 10, currentOperation: "Hashing files"); + MediaLibraryScanProgress scanProgress = _mediaLibraryScanProgressFixture.Create( + completedJobs: 2, + totalJobs: 5, + status: LibraryScanJobStatus.Running, + currentJobProgress: Optional.Some(currentJobProgress)); + + // Act + string result = scanProgress.ToString(); + + // Assert + Assert.Equal("CompletedJobs: 2; TotalJobs: 5; CurrentJobProgress: CompletedItems: 3; TotalItems: 10; CurrentOperation: Hashing files", 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 index 5ff0c4d6..c1777268 100644 --- 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 @@ -1,4 +1,5 @@ #region ========================================================================= USING ===================================================================================== +using Lumina.Domain.Common.Errors; using Lumina.Domain.Common.Primitives; using Lumina.Domain.Core.BoundedContexts.MediaContributorBoundedContext.MediaContributorAggregate.ValueObjects; using Lumina.Domain.Fixtures.Core.BoundedContexts.MediaContributorBoundedContext.MediaContributorAggregate.ValueObjects; @@ -40,6 +41,20 @@ public class MediaContributorNameTests Assert.False(result.Value.LegalName.HasValue); } + [Theory] + [InlineData(null)] // null display name + [InlineData("")] // empty display name + [InlineData(" ")] // whitespace display name + public void Create_WhenDisplayNameIsNullOrWhitespace_ShouldReturnError(string? displayName) + { + // Act + Result result = MediaContributorName.Create(displayName!, Optional.None()); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.MediaContributors.MediaContributorNameCannotBeEmpty, result.FirstError); + } + [Fact] public void Equals_WithSameValues_ShouldReturnTrue() { 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 ba156551..27de1b25 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,8 +3,10 @@ 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.Core.BoundedContexts.UserManagementBoundedContext.UserSettingsAggregate.ValueObjects; using Lumina.Domain.Fixtures.Core.BoundedContexts.UserManagementBoundedContext.UserAggregate.ValueObjects; using Lumina.Domain.Fixtures.Core.BoundedContexts.UserManagementBoundedContext.UserSettingsAggregate; +using Lumina.Domain.Fixtures.Core.BoundedContexts.UserManagementBoundedContext.UserSettingsAggregate.ValueObjects; using System.Diagnostics.CodeAnalysis; #endregion @@ -18,6 +20,7 @@ public class UserSettingsTests { private readonly UserIdFixture _userIdFixture = new(); private readonly UserSettingsFixture _userSettingsFixture = new(); + private readonly UserSettingsIdFixture _userSettingsIdFixture = new(); [Fact] public void Create_WhenCalledWithoutValues_ShouldCreateSettingsWithDefaultValues() @@ -121,6 +124,38 @@ public class UserSettingsTests Assert.Equal(Errors.UserSettings.ItemsPerPageMustBeGreaterThanZero, result.FirstError); } + [Fact] + public void Create_WhenCalledWithPreExistingIdAndValidValues_ShouldCreateSettingsWithThatId() + { + // Arrange + UserId userId = _userIdFixture.Create(); + UserSettingsId id = _userSettingsIdFixture.Create(); + + // Act + Result result = UserSettings.Create(id, userId, isPaginationEnabled: true, itemsPerPage: 24, shouldIgnoreThePrefixForAlphaPicker: false, isThemeCachingEnabled: true, shouldAggregateMetadataWhenMissing: false, shouldRenderPdfAsImages: false, shouldPreserveBookStyles: true); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal(id, result.Value.Id); + Assert.Equal(userId, result.Value.UserId); + Assert.Equal(24, result.Value.ItemsPerPage); + } + + [Fact] + public void Create_WhenCalledWithPreExistingIdAndNonPositiveItemsPerPage_ShouldReturnError() + { + // Arrange + UserId userId = _userIdFixture.Create(); + UserSettingsId id = _userSettingsIdFixture.Create(); + + // Act + Result result = UserSettings.Create(id, userId, isPaginationEnabled: true, itemsPerPage: 0, shouldIgnoreThePrefixForAlphaPicker: false, isThemeCachingEnabled: true, shouldAggregateMetadataWhenMissing: false, shouldRenderPdfAsImages: false, shouldPreserveBookStyles: false); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.UserSettings.ItemsPerPageMustBeGreaterThanZero, result.FirstError); + } + [Fact] public void UpdateSettings_WhenCalledWithValidValues_ShouldUpdateSettings() { diff --git a/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/UserManagementBoundedContext/UserSettingsAggregate/ValueObjects/UserSettingsIdTests.cs b/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/UserManagementBoundedContext/UserSettingsAggregate/ValueObjects/UserSettingsIdTests.cs new file mode 100644 index 00000000..b26c901e --- /dev/null +++ b/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/UserManagementBoundedContext/UserSettingsAggregate/ValueObjects/UserSettingsIdTests.cs @@ -0,0 +1,86 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Domain.Core.BoundedContexts.UserManagementBoundedContext.UserSettingsAggregate.ValueObjects; +using Lumina.Domain.Fixtures.Core.BoundedContexts.UserManagementBoundedContext.UserSettingsAggregate.ValueObjects; +using System; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Domain.UnitTests.Core.BoundedContexts.UserManagementBoundedContext.UserSettingsAggregate.ValueObjects; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class UserSettingsIdTests +{ + private readonly UserSettingsIdFixture _userSettingsIdFixture = new(); + + [Fact] + public void CreateUnique_WhenCalled_ShouldReturnIdWithNonEmptyValue() + { + // Act + UserSettingsId userSettingsId = UserSettingsId.CreateUnique(); + + // Assert + Assert.NotNull(userSettingsId); + Assert.NotEqual(default, userSettingsId.Value); + } + + [Fact] + public void Create_WhenCalledWithValue_ShouldReturnIdWithThatValue() + { + // Arrange + Guid value = Guid.NewGuid(); + + // Act + UserSettingsId userSettingsId = UserSettingsId.Create(value); + + // Assert + Assert.Equal(value, userSettingsId.Value); + } + + [Fact] + public void Equals_WithSameValue_ShouldReturnTrue() + { + // Arrange + Guid value = Guid.NewGuid(); + UserSettingsId firstId = _userSettingsIdFixture.Create(value); + UserSettingsId secondId = _userSettingsIdFixture.Create(value); + + // Act + bool result = firstId.Equals(secondId); + + // Assert + Assert.True(result); + } + + [Fact] + public void GetHashCode_WithSameValue_ShouldReturnSameHashCode() + { + // Arrange + Guid value = Guid.NewGuid(); + UserSettingsId firstId = _userSettingsIdFixture.Create(value); + UserSettingsId secondId = _userSettingsIdFixture.Create(value); + + // Act + int firstHashCode = firstId.GetHashCode(); + int secondHashCode = secondId.GetHashCode(); + + // Assert + Assert.Equal(firstHashCode, secondHashCode); + } + + [Fact] + public void Equals_WithDifferentValue_ShouldReturnFalse() + { + // Arrange + UserSettingsId firstId = _userSettingsIdFixture.Create(); + UserSettingsId secondId = _userSettingsIdFixture.Create(); + + // Act + bool result = firstId.Equals(secondId); + + // Assert + Assert.False(result); + } +} diff --git a/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/WrittenContentLibraryBoundedContext/BookLibraryAggregate/BookTests.cs b/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/WrittenContentLibraryBoundedContext/BookLibraryAggregate/BookTests.cs index e90f14cf..6bb62492 100644 --- a/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/WrittenContentLibraryBoundedContext/BookLibraryAggregate/BookTests.cs +++ b/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/WrittenContentLibraryBoundedContext/BookLibraryAggregate/BookTests.cs @@ -67,6 +67,148 @@ public class BookTests Assert.Equal(replacementContributorId, contributorId); } + [Fact] + public void Create_WhenCalledWithPreExistingIdAndTimestamps_ShouldPreserveIdentityAndTimestamps() + { + // Arrange + Book sourceBook = _bookFixture.Create(); + DateTime createdOnUtc = DateTime.UtcNow.AddDays(-1); + DateTime updatedOnUtc = DateTime.UtcNow; + + // Act + Result result = Book.Create( + sourceBook.Id, + sourceBook.LibraryId, + sourceBook.Path, + sourceBook.Metadata, + sourceBook.Format, + sourceBook.Edition, + sourceBook.VolumeNumber, + sourceBook.Series, + sourceBook.ASIN, + sourceBook.GoodreadsId, + sourceBook.LCCN, + sourceBook.OCLCNumber, + sourceBook.OpenLibraryId, + sourceBook.LibraryThingId, + sourceBook.GoogleBooksId, + sourceBook.BarnesAndNobleId, + sourceBook.AppleBooksId, + createdOnUtc, + Optional.Some(updatedOnUtc), + [.. sourceBook.ISBNs], + [.. sourceBook.Contributors], + [.. sourceBook.Ratings]); + + // Assert + Book book = result.Value; + Assert.Equal(sourceBook.Id, book.Id); + Assert.Equal(sourceBook.LibraryId, book.LibraryId); + Assert.Equal(sourceBook.Path, book.Path); + Assert.Equal(sourceBook.Metadata, book.Metadata); + Assert.Equal(createdOnUtc, book.CreatedOnUtc); + Assert.Equal(updatedOnUtc, book.UpdatedOnUtc); + Assert.Equal(sourceBook.ISBNs, book.ISBNs); + Assert.Equal(sourceBook.Ratings, book.Ratings); + } + + [Fact] + public void ApplyEnrichedMetadata_WhenCalled_ShouldReplaceMetadataAndRelatedFields() + { + // Arrange + Book book = _bookFixture.Create(); + Book enrichedSource = _bookFixture.Create(); + + // Act + book.ApplyEnrichedMetadata( + enrichedSource.Metadata, + enrichedSource.Format, + enrichedSource.Edition, + enrichedSource.VolumeNumber, + enrichedSource.Series, + enrichedSource.ASIN, + enrichedSource.GoodreadsId, + enrichedSource.LCCN, + enrichedSource.OCLCNumber, + enrichedSource.OpenLibraryId, + enrichedSource.LibraryThingId, + enrichedSource.GoogleBooksId, + enrichedSource.BarnesAndNobleId, + enrichedSource.AppleBooksId, + [.. enrichedSource.ISBNs], + [.. enrichedSource.Ratings]); + + // Assert + // the metadata and related fields are replaced with the enriched values + Assert.Equal(enrichedSource.Metadata, book.Metadata); + Assert.Equal(enrichedSource.Format, book.Format); + Assert.Equal(enrichedSource.Edition, book.Edition); + Assert.Equal(enrichedSource.VolumeNumber, book.VolumeNumber); + Assert.Equal(enrichedSource.Series, book.Series); + Assert.Equal(enrichedSource.ASIN, book.ASIN); + Assert.Equal(enrichedSource.GoodreadsId, book.GoodreadsId); + Assert.Equal(enrichedSource.LCCN, book.LCCN); + Assert.Equal(enrichedSource.OCLCNumber, book.OCLCNumber); + Assert.Equal(enrichedSource.OpenLibraryId, book.OpenLibraryId); + Assert.Equal(enrichedSource.LibraryThingId, book.LibraryThingId); + Assert.Equal(enrichedSource.GoogleBooksId, book.GoogleBooksId); + Assert.Equal(enrichedSource.BarnesAndNobleId, book.BarnesAndNobleId); + Assert.Equal(enrichedSource.AppleBooksId, book.AppleBooksId); + Assert.Equal(enrichedSource.ISBNs, book.ISBNs); + Assert.Equal(enrichedSource.Ratings, book.Ratings); + } + + [Fact] + public void ApplyEnrichedMetadata_WhenCalledAgain_ShouldReplaceCollectionsWithoutAppending() + { + // Arrange + Book book = _bookFixture.Create(); + Book firstEnrichmentSource = _bookFixture.Create(); + Book secondEnrichmentSource = _bookFixture.Create(); + book.ApplyEnrichedMetadata( + firstEnrichmentSource.Metadata, + firstEnrichmentSource.Format, + firstEnrichmentSource.Edition, + firstEnrichmentSource.VolumeNumber, + firstEnrichmentSource.Series, + firstEnrichmentSource.ASIN, + firstEnrichmentSource.GoodreadsId, + firstEnrichmentSource.LCCN, + firstEnrichmentSource.OCLCNumber, + firstEnrichmentSource.OpenLibraryId, + firstEnrichmentSource.LibraryThingId, + firstEnrichmentSource.GoogleBooksId, + firstEnrichmentSource.BarnesAndNobleId, + firstEnrichmentSource.AppleBooksId, + [.. firstEnrichmentSource.ISBNs], + [.. firstEnrichmentSource.Ratings]); + + // Act + book.ApplyEnrichedMetadata( + secondEnrichmentSource.Metadata, + secondEnrichmentSource.Format, + secondEnrichmentSource.Edition, + secondEnrichmentSource.VolumeNumber, + secondEnrichmentSource.Series, + secondEnrichmentSource.ASIN, + secondEnrichmentSource.GoodreadsId, + secondEnrichmentSource.LCCN, + secondEnrichmentSource.OCLCNumber, + secondEnrichmentSource.OpenLibraryId, + secondEnrichmentSource.LibraryThingId, + secondEnrichmentSource.GoogleBooksId, + secondEnrichmentSource.BarnesAndNobleId, + secondEnrichmentSource.AppleBooksId, + [.. secondEnrichmentSource.ISBNs], + [.. secondEnrichmentSource.Ratings]); + + // Assert + // the second enrichment replaces the first, it is not appended to it + Assert.Equal(secondEnrichmentSource.ISBNs.Count, book.ISBNs.Count); + Assert.Equal(secondEnrichmentSource.ISBNs, book.ISBNs); + Assert.Equal(secondEnrichmentSource.Ratings, book.Ratings); + } + [Fact] public void Create_WhenCalled_ShouldNotExposeEnrichmentTracking() { diff --git a/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/WrittenContentLibraryBoundedContext/ExternalIdentifiers/LibraryManagementBoundedContext/LibraryAggregate/LibraryIdTests.cs b/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/WrittenContentLibraryBoundedContext/ExternalIdentifiers/LibraryManagementBoundedContext/LibraryAggregate/LibraryIdTests.cs new file mode 100644 index 00000000..4c93e1ab --- /dev/null +++ b/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/WrittenContentLibraryBoundedContext/ExternalIdentifiers/LibraryManagementBoundedContext/LibraryAggregate/LibraryIdTests.cs @@ -0,0 +1,86 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Domain.Core.BoundedContexts.WrittenContentLibraryBoundedContext.ExternalIdentifiers.LibraryManagementBoundedContext.LibraryAggregate; +using Lumina.Domain.Fixtures.Core.BoundedContexts.WrittenContentLibraryBoundedContext.ExternalIdentifiers.LibraryManagementBoundedContext.LibraryAggregate; +using System; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Domain.UnitTests.Core.BoundedContexts.WrittenContentLibraryBoundedContext.ExternalIdentifiers.LibraryManagementBoundedContext.LibraryAggregate; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class LibraryIdTests +{ + private readonly LibraryIdFixture _libraryIdFixture = new(); + + [Fact] + public void CreateUnique_WhenCalled_ShouldReturnIdWithNonEmptyValue() + { + // Act + LibraryId libraryId = LibraryId.CreateUnique(); + + // Assert + Assert.NotNull(libraryId); + Assert.NotEqual(default, libraryId.Value); + } + + [Fact] + public void Create_WhenCalledWithValue_ShouldReturnIdWithThatValue() + { + // Arrange + Guid value = Guid.NewGuid(); + + // Act + LibraryId libraryId = LibraryId.Create(value); + + // Assert + Assert.Equal(value, libraryId.Value); + } + + [Fact] + public void Equals_WithSameValue_ShouldReturnTrue() + { + // Arrange + Guid value = Guid.NewGuid(); + LibraryId firstId = _libraryIdFixture.Create(value); + LibraryId secondId = _libraryIdFixture.Create(value); + + // Act + bool result = firstId.Equals(secondId); + + // Assert + Assert.True(result); + } + + [Fact] + public void GetHashCode_WithSameValue_ShouldReturnSameHashCode() + { + // Arrange + Guid value = Guid.NewGuid(); + LibraryId firstId = _libraryIdFixture.Create(value); + LibraryId secondId = _libraryIdFixture.Create(value); + + // Act + int firstHashCode = firstId.GetHashCode(); + int secondHashCode = secondId.GetHashCode(); + + // Assert + Assert.Equal(firstHashCode, secondHashCode); + } + + [Fact] + public void Equals_WithDifferentValue_ShouldReturnFalse() + { + // Arrange + LibraryId firstId = _libraryIdFixture.Create(); + LibraryId secondId = _libraryIdFixture.Create(); + + // Act + bool result = firstId.Equals(secondId); + + // Assert + Assert.False(result); + } +} diff --git a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/MediaLibrary/Management/Scanning/Jobs/Common/MediaLibraryScanArtworkEnrichmentJobTests.cs b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/MediaLibrary/Management/Scanning/Jobs/Common/MediaLibraryScanArtworkEnrichmentJobTests.cs index 0f511bba..0a23ca9f 100644 --- a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/MediaLibrary/Management/Scanning/Jobs/Common/MediaLibraryScanArtworkEnrichmentJobTests.cs +++ b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/MediaLibrary/Management/Scanning/Jobs/Common/MediaLibraryScanArtworkEnrichmentJobTests.cs @@ -17,6 +17,7 @@ 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.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; @@ -253,6 +254,538 @@ public class MediaLibraryScanArtworkEnrichmentJobTests Assert.Equal(LibraryScanJobStatus.Canceled, _sut.Status); } + [Fact] + public async Task ExecuteAsync_WhenReadingArtworkProviderConfigurationsFails_ShouldLogWarningAndSkipEnrichment() + { + // Arrange + _mockArtworkConfigurationRepository.GetByLibraryIdAsync(_libraryId.Value, Arg.Any()) + .Returns(Error.Failure("Database.Error", "Failed to read the artwork provider configurations")); + + // Act + await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None); + + // Assert + // a failure to read the artwork configurations is best-effort, so the enrichment is skipped without touching the books + Assert.Equal(LibraryScanJobStatus.Completed, _sut.Status); + await _mockBookRepository.DidNotReceive().GetBooksNeedingArtworkCountAsync(Arg.Any(), Arg.Any()); + } + + [Fact] + public async Task ExecuteAsync_WhenTheConfiguredArtworkProviderIsNotRegistered_ShouldLogWarningAndSkipEnrichment() + { + // Arrange + Guid artworkPluginId = Guid.NewGuid(); + IArtworkProvider artworkProvider = Substitute.For(); + artworkProvider.Name.Returns("Artwork Provider"); + artworkProvider.SupportedLibraryTypes.Returns([LibraryType.Book]); + + IBookArtworkService mockBookArtworkService = Substitute.For(); + IFileHashService mockFileHashService = Substitute.For(); + SetupRealServiceProvider(artworkPluginId, artworkProvider, mockBookArtworkService, mockFileHashService); + + // the configuration references a plugin that is not registered in the dependency injection container + _mockArtworkConfigurationRepository.GetByLibraryIdAsync(_libraryId.Value, Arg.Any()) + .Returns(Result.From>([_artworkConfigurationEntityFixture.Create(_libraryId.Value, Guid.NewGuid(), 1)])); + + // Act + await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None); + + // Assert + Assert.Equal(LibraryScanJobStatus.Completed, _sut.Status); + await _mockBookRepository.DidNotReceive().GetBooksNeedingArtworkCountAsync(Arg.Any(), Arg.Any()); + } + + [Fact] + public async Task ExecuteAsync_WhenTheLibraryForbidsWebDownloads_ShouldSkipArtworkProvidersThatRequireWebAccess() + { + // Arrange + Guid webPluginId = Guid.NewGuid(); + Guid localPluginId = Guid.NewGuid(); + IArtworkProvider webProvider = Substitute.For(); + webProvider.Name.Returns("Web Provider"); + webProvider.SupportedLibraryTypes.Returns([LibraryType.Book]); + webProvider.RequiresWebAccess.Returns(true); + IArtworkProvider localProvider = Substitute.For(); + localProvider.Name.Returns("Local Provider"); + localProvider.SupportedLibraryTypes.Returns([LibraryType.Book]); + localProvider.GetArtworkAsync(Arg.Any(), Arg.Any()) + .Returns(_artworkDtoFixture.Create(localPath: "/some/local-cover.jpg")); + + IBookArtworkService mockBookArtworkService = Substitute.For(); + mockBookArtworkService.SaveBookArtworkAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(Result.From("\\media\\books\\Library\\Author\\Title\\cover.jpeg")); + IFileHashService mockFileHashService = Substitute.For(); + mockFileHashService.ComputeFileHash("/some/local-cover.jpg").Returns(111UL); + + ServiceCollection services = new(); + services.AddKeyedSingleton(webPluginId, webProvider); + services.AddKeyedSingleton(localPluginId, localProvider); + services.AddSingleton(_mockUnitOfWork); + services.AddSingleton(_mockDomainEventPublisher); + services.AddSingleton(mockBookArtworkService); + services.AddSingleton(mockFileHashService); + // the provider is intentionally not disposed here, so that the async service scope used by the job stays alive for the whole test + ServiceProvider realServiceProvider = services.BuildServiceProvider(); + AsyncServiceScope asyncServiceScope = realServiceProvider.CreateAsyncScope(); + _mockServiceScopeFactory.CreateAsyncScope().Returns(asyncServiceScope); + + ILibraryRepository mockLibraryRepository = Substitute.For(); + mockLibraryRepository.GetByIdAsync(_libraryId.Value, Arg.Any()) + .Returns(Result.From(_libraryEntityFixture.Create(id: _libraryId.Value, title: "My Library", canDownloadMetadataFromWeb: false))); + _mockUnitOfWork.LibraryRepository.Returns(mockLibraryRepository); + + BookEntity book = _bookEntityFixture.Create(libraryId: _libraryId.Value, path: "/books/test.epub"); + _mockArtworkConfigurationRepository.GetByLibraryIdAsync(_libraryId.Value, Arg.Any()) + .Returns(Result.From>([ + _artworkConfigurationEntityFixture.Create(_libraryId.Value, webPluginId, 1), + _artworkConfigurationEntityFixture.Create(_libraryId.Value, localPluginId, 2) + ])); + _mockBookRepository.GetBooksNeedingArtworkCountAsync(_libraryId.Value, Arg.Any()) + .Returns(Result.From(1)); + _mockBookRepository.GetBooksNeedingArtworkAsync(_libraryId.Value, Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(Result.From>([book]), Result.From>([])); + _mockBookRepository.GetAuthorsDisplayNamesByBookIdsAsync(Arg.Any>(), Arg.Any()) + .Returns(Result.From>(new Dictionary { [book.Id] = "Frank Herbert" })); + _mockUnitOfWork.SaveChangesAsync(Arg.Any()).Returns(Task.CompletedTask); + + // Act + await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None); + + // Assert + // the provider that requires access to the web is skipped when the library does not permit web downloads + await webProvider.DidNotReceive().GetArtworkAsync(Arg.Any(), Arg.Any()); + BookArtworkEntity coverArtwork = Assert.Single(book.BookArtwork); + Assert.Equal(ArtworkStatus.Enriched, coverArtwork.Status); + Assert.Equal("Local Provider", coverArtwork.Provider); + Assert.Equal(LibraryScanJobStatus.Completed, _sut.Status); + } + + [Fact] + public async Task ExecuteAsync_WhenCountingTheBooksNeedingArtworkFails_ShouldMarkJobAsFailed() + { + // Arrange + Guid artworkPluginId = Guid.NewGuid(); + IArtworkProvider artworkProvider = Substitute.For(); + artworkProvider.Name.Returns("Artwork Provider"); + artworkProvider.SupportedLibraryTypes.Returns([LibraryType.Book]); + + IBookArtworkService mockBookArtworkService = Substitute.For(); + IFileHashService mockFileHashService = Substitute.For(); + SetupRealServiceProvider(artworkPluginId, artworkProvider, mockBookArtworkService, mockFileHashService); + + _mockArtworkConfigurationRepository.GetByLibraryIdAsync(_libraryId.Value, Arg.Any()) + .Returns(Result.From>([_artworkConfigurationEntityFixture.Create(_libraryId.Value, artworkPluginId, 1)])); + _mockBookRepository.GetBooksNeedingArtworkCountAsync(_libraryId.Value, Arg.Any()) + .Returns(Error.Failure("Database.Error", "Failed to count the books that need artwork")); + _mockUnitOfWork.SaveChangesAsync(Arg.Any()).Returns(Task.CompletedTask); + + // Act + await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None); + + // Assert + Assert.Equal(LibraryScanJobStatus.Failed, _sut.Status); + } + + [Fact] + public async Task ExecuteAsync_WhenGettingTheBooksNeedingArtworkFails_ShouldMarkJobAsFailed() + { + // Arrange + Guid artworkPluginId = Guid.NewGuid(); + IArtworkProvider artworkProvider = Substitute.For(); + artworkProvider.Name.Returns("Artwork Provider"); + artworkProvider.SupportedLibraryTypes.Returns([LibraryType.Book]); + + IBookArtworkService mockBookArtworkService = Substitute.For(); + IFileHashService mockFileHashService = Substitute.For(); + SetupRealServiceProvider(artworkPluginId, artworkProvider, mockBookArtworkService, mockFileHashService); + + _mockArtworkConfigurationRepository.GetByLibraryIdAsync(_libraryId.Value, Arg.Any()) + .Returns(Result.From>([_artworkConfigurationEntityFixture.Create(_libraryId.Value, artworkPluginId, 1)])); + _mockBookRepository.GetBooksNeedingArtworkCountAsync(_libraryId.Value, Arg.Any()) + .Returns(Result.From(1)); + _mockBookRepository.GetBooksNeedingArtworkAsync(_libraryId.Value, Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(Error.Failure("Database.Error", "Failed to get the books that need artwork")); + _mockUnitOfWork.SaveChangesAsync(Arg.Any()).Returns(Task.CompletedTask); + + // Act + await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None); + + // Assert + Assert.Equal(LibraryScanJobStatus.Failed, _sut.Status); + } + + [Fact] + public async Task ExecuteAsync_WhenGettingTheAuthorDisplayNamesFails_ShouldMarkJobAsFailed() + { + // Arrange + Guid artworkPluginId = Guid.NewGuid(); + IArtworkProvider artworkProvider = Substitute.For(); + artworkProvider.Name.Returns("Artwork Provider"); + artworkProvider.SupportedLibraryTypes.Returns([LibraryType.Book]); + + IBookArtworkService mockBookArtworkService = Substitute.For(); + IFileHashService mockFileHashService = Substitute.For(); + SetupRealServiceProvider(artworkPluginId, artworkProvider, mockBookArtworkService, mockFileHashService); + + BookEntity book = _bookEntityFixture.Create(libraryId: _libraryId.Value, path: "/books/test.epub"); + ILibraryRepository mockLibraryRepository = Substitute.For(); + mockLibraryRepository.GetByIdAsync(_libraryId.Value, Arg.Any()) + .Returns(Result.From(_libraryEntityFixture.Create(id: _libraryId.Value, title: "My Library", canDownloadMetadataFromWeb: true))); + _mockUnitOfWork.LibraryRepository.Returns(mockLibraryRepository); + _mockArtworkConfigurationRepository.GetByLibraryIdAsync(_libraryId.Value, Arg.Any()) + .Returns(Result.From>([_artworkConfigurationEntityFixture.Create(_libraryId.Value, artworkPluginId, 1)])); + _mockBookRepository.GetBooksNeedingArtworkCountAsync(_libraryId.Value, Arg.Any()) + .Returns(Result.From(1)); + _mockBookRepository.GetBooksNeedingArtworkAsync(_libraryId.Value, Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(Result.From>([book]), Result.From>([])); + _mockBookRepository.GetAuthorsDisplayNamesByBookIdsAsync(Arg.Any>(), Arg.Any()) + .Returns(Error.Failure("Database.Error", "Failed to get the author display names")); + _mockUnitOfWork.SaveChangesAsync(Arg.Any()).Returns(Task.CompletedTask); + + // Act + await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None); + + // Assert + Assert.Equal(LibraryScanJobStatus.Failed, _sut.Status); + } + + [Fact] + public async Task ExecuteAsync_WhenNoProviderReturnsArtworkAndTheBookHasAnExistingCover_ShouldMarkTheExistingCoverAsFailed() + { + // Arrange + Guid artworkPluginId = Guid.NewGuid(); + IArtworkProvider artworkProvider = Substitute.For(); + artworkProvider.Name.Returns("Artwork Provider"); + artworkProvider.SupportedLibraryTypes.Returns([LibraryType.Book]); + artworkProvider.GetArtworkAsync(Arg.Any(), Arg.Any()) + .Returns((ArtworkDto?)null); + + IBookArtworkService mockBookArtworkService = Substitute.For(); + IFileHashService mockFileHashService = Substitute.For(); + + SetupRealServiceProvider(artworkPluginId, artworkProvider, mockBookArtworkService, mockFileHashService); + BookEntity book = _bookEntityFixture.Create(libraryId: _libraryId.Value, path: "/books/test.epub"); + book.BookArtwork = [_bookArtworkEntityFixture.Create(bookId: book.Id, artworkType: ArtworkType.Cover, ordinal: 0, fileName: "existing\\cover.jpeg", contentHash: 123ul, status: ArtworkStatus.Pending, provider: "Old Provider", lastUpdateUtc: DateTime.UtcNow.AddDays(-1))]; + SetupSingleBookPage(book, artworkPluginId); + _mockBookRepository.GetAuthorsDisplayNamesByBookIdsAsync(Arg.Any>(), Arg.Any()) + .Returns(Result.From>(new Dictionary { [book.Id] = "Frank Herbert" })); + + // Act + await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None); + + // Assert + BookArtworkEntity coverArtwork = Assert.Single(book.BookArtwork); + Assert.Equal(ArtworkStatus.Failed, coverArtwork.Status); + Assert.Equal("existing\\cover.jpeg", coverArtwork.FileName); + Assert.Equal(LibraryScanJobStatus.Completed, _sut.Status); + } + + [Fact] + public async Task ExecuteAsync_WhenStoringTheArtworkFailsAndTheBookHasNoExistingCover_ShouldTrackTheCoverAsFailed() + { + // Arrange + Guid artworkPluginId = Guid.NewGuid(); + IArtworkProvider artworkProvider = Substitute.For(); + artworkProvider.Name.Returns("Artwork Provider"); + artworkProvider.SupportedLibraryTypes.Returns([LibraryType.Book]); + artworkProvider.GetArtworkAsync(Arg.Any(), Arg.Any()) + .Returns(_artworkDtoFixture.Create(localPath: "/some/cover.jpg")); + + IBookArtworkService mockBookArtworkService = Substitute.For(); + mockBookArtworkService.SaveBookArtworkAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(Error.Failure("Storage.Error", "Failed to store the artwork")); + IFileHashService mockFileHashService = Substitute.For(); + mockFileHashService.ComputeFileHash("/some/cover.jpg").Returns(111UL); + + SetupRealServiceProvider(artworkPluginId, artworkProvider, mockBookArtworkService, mockFileHashService); + BookEntity book = _bookEntityFixture.Create(libraryId: _libraryId.Value, path: "/books/test.epub"); + SetupSingleBookPage(book, artworkPluginId); + _mockBookRepository.GetAuthorsDisplayNamesByBookIdsAsync(Arg.Any>(), Arg.Any()) + .Returns(Result.From>(new Dictionary { [book.Id] = "Frank Herbert" })); + + // Act + await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None); + + // Assert + BookArtworkEntity coverArtwork = Assert.Single(book.BookArtwork); + Assert.Equal(ArtworkStatus.Failed, coverArtwork.Status); + Assert.Null(coverArtwork.FileName); + Assert.Equal(LibraryScanJobStatus.Completed, _sut.Status); + } + + [Fact] + public async Task ExecuteAsync_WhenStoringTheArtworkFailsAndTheBookHasAnExistingCover_ShouldMarkTheExistingCoverAsFailed() + { + // Arrange + Guid artworkPluginId = Guid.NewGuid(); + IArtworkProvider artworkProvider = Substitute.For(); + artworkProvider.Name.Returns("Artwork Provider"); + artworkProvider.SupportedLibraryTypes.Returns([LibraryType.Book]); + artworkProvider.GetArtworkAsync(Arg.Any(), Arg.Any()) + .Returns(_artworkDtoFixture.Create(localPath: "/some/cover.jpg")); + + IBookArtworkService mockBookArtworkService = Substitute.For(); + mockBookArtworkService.SaveBookArtworkAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(Error.Failure("Storage.Error", "Failed to store the artwork")); + IFileHashService mockFileHashService = Substitute.For(); + mockFileHashService.ComputeFileHash("/some/cover.jpg").Returns(222UL); + + SetupRealServiceProvider(artworkPluginId, artworkProvider, mockBookArtworkService, mockFileHashService); + BookEntity book = _bookEntityFixture.Create(libraryId: _libraryId.Value, path: "/books/test.epub"); + book.BookArtwork = [_bookArtworkEntityFixture.Create(bookId: book.Id, artworkType: ArtworkType.Cover, ordinal: 0, fileName: "existing\\cover.jpeg", contentHash: 111ul, status: ArtworkStatus.Pending, provider: "Old Provider", lastUpdateUtc: DateTime.UtcNow.AddDays(-1))]; + SetupSingleBookPage(book, artworkPluginId); + _mockBookRepository.GetAuthorsDisplayNamesByBookIdsAsync(Arg.Any>(), Arg.Any()) + .Returns(Result.From>(new Dictionary { [book.Id] = "Frank Herbert" })); + + // Act + await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None); + + // Assert + BookArtworkEntity coverArtwork = Assert.Single(book.BookArtwork); + Assert.Equal(ArtworkStatus.Failed, coverArtwork.Status); + Assert.Equal("existing\\cover.jpeg", coverArtwork.FileName); + Assert.Equal(LibraryScanJobStatus.Completed, _sut.Status); + } + + [Fact] + public async Task ExecuteAsync_WhenTheResolvedArtworkIsRemote_ShouldComputeTheContentHashOfTheStoredArtwork() + { + // Arrange + Guid artworkPluginId = Guid.NewGuid(); + IArtworkProvider artworkProvider = Substitute.For(); + artworkProvider.Name.Returns("Artwork Provider"); + artworkProvider.SupportedLibraryTypes.Returns([LibraryType.Book]); + artworkProvider.RequiresWebAccess.Returns(true); + artworkProvider.GetArtworkAsync(Arg.Any(), Arg.Any()) + .Returns(_artworkDtoFixture.Create(localPath: null, remoteUrl: "https://example.com/cover.jpg")); + + IBookArtworkService mockBookArtworkService = Substitute.For(); + mockBookArtworkService.SaveBookArtworkAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(Result.From("\\media\\books\\Library\\Author\\Title\\cover.jpeg")); + IFileHashService mockFileHashService = Substitute.For(); + mockFileHashService.ComputeFileHash(Arg.Any()).Returns(999UL); + + SetupRealServiceProvider(artworkPluginId, artworkProvider, mockBookArtworkService, mockFileHashService); + BookEntity book = _bookEntityFixture.Create(libraryId: _libraryId.Value, path: "/books/test.epub"); + SetupSingleBookPage(book, artworkPluginId); + _mockBookRepository.GetAuthorsDisplayNamesByBookIdsAsync(Arg.Any>(), Arg.Any()) + .Returns(Result.From>(new Dictionary { [book.Id] = "Frank Herbert" })); + + // Act + await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None); + + // Assert + // for remote artwork, the content hash is computed on the stored copy, so it is only known after the artwork is stored + await mockBookArtworkService.Received(1).SaveBookArtworkAsync(_libraryId.Value, book.Id, "My Library", "Frank Herbert", Arg.Any(), Arg.Any(), Arg.Any()); + BookArtworkEntity coverArtwork = Assert.Single(book.BookArtwork); + Assert.Equal(ArtworkStatus.Enriched, coverArtwork.Status); + Assert.Equal("\\media\\books\\Library\\Author\\Title\\cover.jpeg", coverArtwork.FileName); + Assert.Equal(999ul, coverArtwork.ContentHash); + Assert.Equal("Artwork Provider", coverArtwork.Provider); + Assert.Equal(LibraryScanJobStatus.Completed, _sut.Status); + } + + [Fact] + public async Task ExecuteAsync_WhenTheBookHasAnExistingCoverAndTheArtworkDiffersFromIt_ShouldStoreItAndUpdateTheExistingCover() + { + // Arrange + Guid artworkPluginId = Guid.NewGuid(); + IArtworkProvider artworkProvider = Substitute.For(); + artworkProvider.Name.Returns("Artwork Provider"); + artworkProvider.SupportedLibraryTypes.Returns([LibraryType.Book]); + artworkProvider.GetArtworkAsync(Arg.Any(), Arg.Any()) + .Returns(_artworkDtoFixture.Create(localPath: "/some/cover.jpg")); + + IBookArtworkService mockBookArtworkService = Substitute.For(); + mockBookArtworkService.SaveBookArtworkAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(Result.From("\\media\\books\\Library\\Author\\Title\\cover.jpeg")); + IFileHashService mockFileHashService = Substitute.For(); + mockFileHashService.ComputeFileHash("/some/cover.jpg").Returns(222UL); + + SetupRealServiceProvider(artworkPluginId, artworkProvider, mockBookArtworkService, mockFileHashService); + // the book has no known ISBNs of its own, so the artwork lookup is built without an ISBN + BookEntity book = _bookEntityFixture.Create(libraryId: _libraryId.Value, path: "/books/test.epub", title: "Test Title", includeMetadata: false); + book.BookArtwork = [_bookArtworkEntityFixture.Create(bookId: book.Id, artworkType: ArtworkType.Cover, ordinal: 0, fileName: "existing\\cover.jpeg", contentHash: 111ul, status: ArtworkStatus.Pending, provider: "Old Provider", lastUpdateUtc: DateTime.UtcNow.AddDays(-1))]; + SetupSingleBookPage(book, artworkPluginId); + // the author of the book is not known, so its artwork directory falls back to an empty author name + _mockBookRepository.GetAuthorsDisplayNamesByBookIdsAsync(Arg.Any>(), Arg.Any()) + .Returns(Result.From>(new Dictionary())); + + // Act + await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None); + + // Assert + await mockBookArtworkService.Received(1).SaveBookArtworkAsync( + _libraryId.Value, + book.Id, + "My Library", + string.Empty, + "Test Title", + Arg.Any(), + Arg.Any()); + BookArtworkEntity coverArtwork = Assert.Single(book.BookArtwork); + Assert.Equal(ArtworkStatus.Enriched, coverArtwork.Status); + Assert.Equal("\\media\\books\\Library\\Author\\Title\\cover.jpeg", coverArtwork.FileName); + Assert.Equal(222ul, coverArtwork.ContentHash); + Assert.Equal("Artwork Provider", coverArtwork.Provider); + Assert.NotNull(coverArtwork.LastUpdateUtc); + Assert.Equal(LibraryScanJobStatus.Completed, _sut.Status); + } + + [Fact] + public async Task ExecuteAsync_WhenAnArtworkProviderThrows_ShouldTryTheNextProvider() + { + // Arrange + Guid firstPluginId = Guid.NewGuid(); + Guid secondPluginId = Guid.NewGuid(); + IArtworkProvider firstProvider = Substitute.For(); + firstProvider.Name.Returns("First Provider"); + firstProvider.SupportedLibraryTypes.Returns([LibraryType.Book]); + firstProvider.GetArtworkAsync(Arg.Any(), Arg.Any()) + .Returns(Task.FromException(new InvalidOperationException("The artwork provider failed"))); + IArtworkProvider secondProvider = Substitute.For(); + secondProvider.Name.Returns("Second Provider"); + secondProvider.SupportedLibraryTypes.Returns([LibraryType.Book]); + secondProvider.GetArtworkAsync(Arg.Any(), Arg.Any()) + .Returns(_artworkDtoFixture.Create(localPath: "/some/second-cover.jpg")); + + IBookArtworkService mockBookArtworkService = Substitute.For(); + mockBookArtworkService.SaveBookArtworkAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(Result.From("\\media\\books\\Library\\Author\\Title\\cover.jpeg")); + IFileHashService mockFileHashService = Substitute.For(); + mockFileHashService.ComputeFileHash("/some/second-cover.jpg").Returns(333UL); + + ServiceCollection services = new(); + services.AddKeyedSingleton(firstPluginId, firstProvider); + services.AddKeyedSingleton(secondPluginId, secondProvider); + services.AddSingleton(_mockUnitOfWork); + services.AddSingleton(_mockDomainEventPublisher); + services.AddSingleton(mockBookArtworkService); + services.AddSingleton(mockFileHashService); + // the provider is intentionally not disposed here, so that the async service scope used by the job stays alive for the whole test + ServiceProvider realServiceProvider = services.BuildServiceProvider(); + AsyncServiceScope asyncServiceScope = realServiceProvider.CreateAsyncScope(); + _mockServiceScopeFactory.CreateAsyncScope().Returns(asyncServiceScope); + + BookEntity book = _bookEntityFixture.Create(libraryId: _libraryId.Value, path: "/books/test.epub"); + ILibraryRepository mockLibraryRepository = Substitute.For(); + mockLibraryRepository.GetByIdAsync(_libraryId.Value, Arg.Any()) + .Returns(Result.From(_libraryEntityFixture.Create(id: _libraryId.Value, title: "My Library", canDownloadMetadataFromWeb: true))); + _mockUnitOfWork.LibraryRepository.Returns(mockLibraryRepository); + + _mockArtworkConfigurationRepository.GetByLibraryIdAsync(_libraryId.Value, Arg.Any()) + .Returns(Result.From>([ + _artworkConfigurationEntityFixture.Create(_libraryId.Value, firstPluginId, 1), + _artworkConfigurationEntityFixture.Create(_libraryId.Value, secondPluginId, 2) + ])); + _mockBookRepository.GetBooksNeedingArtworkCountAsync(_libraryId.Value, Arg.Any()) + .Returns(Result.From(1)); + _mockBookRepository.GetBooksNeedingArtworkAsync(_libraryId.Value, Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(Result.From>([book]), Result.From>([])); + _mockUnitOfWork.SaveChangesAsync(Arg.Any()).Returns(Task.CompletedTask); + _mockBookRepository.GetAuthorsDisplayNamesByBookIdsAsync(Arg.Any>(), Arg.Any()) + .Returns(Result.From>(new Dictionary { [book.Id] = "Frank Herbert" })); + + // Act + await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None); + + // Assert + // a failing artwork provider must not prevent the artwork of the other provider from being used + BookArtworkEntity coverArtwork = Assert.Single(book.BookArtwork); + Assert.Equal(ArtworkStatus.Enriched, coverArtwork.Status); + Assert.Equal("Second Provider", coverArtwork.Provider); + Assert.Equal(LibraryScanJobStatus.Completed, _sut.Status); + } + + [Fact] + public async Task ExecuteAsync_WhenAProviderReturnsRemoteArtworkWithoutRequiringWebAccess_ShouldSkipItAndUseTheNextProvider() + { + // Arrange + Guid firstPluginId = Guid.NewGuid(); + Guid secondPluginId = Guid.NewGuid(); + IArtworkProvider firstProvider = Substitute.For(); + firstProvider.Name.Returns("First Provider"); + firstProvider.SupportedLibraryTypes.Returns([LibraryType.Book]); + firstProvider.RequiresWebAccess.Returns(false); + firstProvider.GetArtworkAsync(Arg.Any(), Arg.Any()) + .Returns(_artworkDtoFixture.Create(localPath: null, remoteUrl: "https://example.com/cover.jpg")); + IArtworkProvider secondProvider = Substitute.For(); + secondProvider.Name.Returns("Second Provider"); + secondProvider.SupportedLibraryTypes.Returns([LibraryType.Book]); + secondProvider.GetArtworkAsync(Arg.Any(), Arg.Any()) + .Returns(_artworkDtoFixture.Create(localPath: "/some/second-cover.jpg")); + + IBookArtworkService mockBookArtworkService = Substitute.For(); + mockBookArtworkService.SaveBookArtworkAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(Result.From("\\media\\books\\Library\\Author\\Title\\cover.jpeg")); + IFileHashService mockFileHashService = Substitute.For(); + mockFileHashService.ComputeFileHash("/some/second-cover.jpg").Returns(444UL); + + ServiceCollection services = new(); + services.AddKeyedSingleton(firstPluginId, firstProvider); + services.AddKeyedSingleton(secondPluginId, secondProvider); + services.AddSingleton(_mockUnitOfWork); + services.AddSingleton(_mockDomainEventPublisher); + services.AddSingleton(mockBookArtworkService); + services.AddSingleton(mockFileHashService); + // the provider is intentionally not disposed here, so that the async service scope used by the job stays alive for the whole test + ServiceProvider realServiceProvider = services.BuildServiceProvider(); + AsyncServiceScope asyncServiceScope = realServiceProvider.CreateAsyncScope(); + _mockServiceScopeFactory.CreateAsyncScope().Returns(asyncServiceScope); + + BookEntity book = _bookEntityFixture.Create(libraryId: _libraryId.Value, path: "/books/test.epub"); + ILibraryRepository mockLibraryRepository = Substitute.For(); + mockLibraryRepository.GetByIdAsync(_libraryId.Value, Arg.Any()) + .Returns(Result.From(_libraryEntityFixture.Create(id: _libraryId.Value, title: "My Library", canDownloadMetadataFromWeb: true))); + _mockUnitOfWork.LibraryRepository.Returns(mockLibraryRepository); + + _mockArtworkConfigurationRepository.GetByLibraryIdAsync(_libraryId.Value, Arg.Any()) + .Returns(Result.From>([ + _artworkConfigurationEntityFixture.Create(_libraryId.Value, firstPluginId, 1), + _artworkConfigurationEntityFixture.Create(_libraryId.Value, secondPluginId, 2) + ])); + _mockBookRepository.GetBooksNeedingArtworkCountAsync(_libraryId.Value, Arg.Any()) + .Returns(Result.From(1)); + _mockBookRepository.GetBooksNeedingArtworkAsync(_libraryId.Value, Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(Result.From>([book]), Result.From>([])); + _mockUnitOfWork.SaveChangesAsync(Arg.Any()).Returns(Task.CompletedTask); + _mockBookRepository.GetAuthorsDisplayNamesByBookIdsAsync(Arg.Any>(), Arg.Any()) + .Returns(Result.From>(new Dictionary { [book.Id] = "Frank Herbert" })); + + // Act + await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None); + + // Assert + // a provider that returns remote artwork must require web access, so its artwork is skipped and the next provider is used + BookArtworkEntity coverArtwork = Assert.Single(book.BookArtwork); + Assert.Equal(ArtworkStatus.Enriched, coverArtwork.Status); + Assert.Equal("Second Provider", coverArtwork.Provider); + Assert.Equal(LibraryScanJobStatus.Completed, _sut.Status); + } + + [Fact] + public async Task ExecuteAsync_WhenTheJobHasChildJobs_ShouldExecuteThemAfterCompletingItsPayload() + { + // Arrange + _mockArtworkConfigurationRepository.GetByLibraryIdAsync(_libraryId.Value, Arg.Any()) + .Returns(Result.From>([])); + _mockUnitOfWork.SaveChangesAsync(Arg.Any()).Returns(Task.CompletedTask); + + IMediaLibraryScanJob mockChildJob = Substitute.For(); + mockChildJob.ExecuteAsync(Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(Task.CompletedTask); + _sut.AddChild(mockChildJob); + Guid id = Guid.NewGuid(); + object input = new(); + + // Act + await _sut.ExecuteAsync(id, input, CancellationToken.None); + + // Assert + await mockChildJob.Received(1).ExecuteAsync(id, input, Arg.Any()); + Assert.Equal(LibraryScanJobStatus.Completed, _sut.Status); + } + /// /// Wires a real service provider with the given artwork provider and services, so that the job resolves them from the dependency injection container. /// 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 index 7d107d7b..8b60619f 100644 --- 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 @@ -5,6 +5,7 @@ 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.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; @@ -122,4 +123,23 @@ public class MediaLibraryScanDiffJobTests await Assert.ThrowsAnyAsync(() => operation); Assert.Equal(LibraryScanJobStatus.Canceled, _sut.Status); } + + [Fact] + public async Task ExecuteAsync_WhenMarkingChangesSucceeds_ShouldExecuteTheChildJobs() + { + // Arrange + _mockStagingResultsRepository.MarkChangesAgainstSnapshotAsync(_scanId.Value, _libraryId.Value, Arg.Any()) + .Returns(Result.From(Result.Updated)); + IMediaLibraryScanJob mockChild = Substitute.For(); + _sut.AddChild(mockChild); + Guid id = Guid.NewGuid(); + object input = new(); + + // Act + await _sut.ExecuteAsync(id, input, CancellationToken.None); + + // Assert + Assert.Equal(LibraryScanJobStatus.Completed, _sut.Status); + await mockChild.Received(1).ExecuteAsync(id, input, Arg.Any()); + } } 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 index cc07e71a..8fb60013 100644 --- 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 @@ -7,6 +7,7 @@ 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.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; @@ -170,4 +171,144 @@ public class MediaLibraryScanHashJobTests await Assert.ThrowsAnyAsync(() => operation); Assert.Equal(LibraryScanJobStatus.Canceled, _sut.Status); } + + [Fact] + public async Task ExecuteAsync_WhenGettingTheFilesToHashPageFails_ShouldMarkJobAsFailedAndPublishFailureEvent() + { + // Arrange + _mockStagingResultsRepository.GetFilesToHashCountAsync(_scanId.Value, Arg.Any()) + .Returns(Result.From(1)); + _mockStagingResultsRepository.GetFilesToHashPageAsync(_scanId.Value, Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(Error.Failure("Database.Error", "Failed to get 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_WhenUpdatingTheFileHashesFails_ShouldMarkJobAsFailedAndPublishFailureEvent() + { + // 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(Error.Failure("Database.Error", "Failed to update the file hashes")); + + // Act + await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None); + + // Assert + Assert.Equal(LibraryScanJobStatus.Failed, _sut.Status); + await _mockFileHashService.Received(1).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_WhenTheHashingCallbackRunsBeforeTheProgressInterval_ShouldNotPublishJobProgressFromTheCallback() + { + // Arrange + List filesToHash = [_hashedFileSystemFileDtoFixture.Create(path: "/books/book1.pdf")]; + _mockStagingResultsRepository.GetFilesToHashCountAsync(_scanId.Value, Arg.Any()) + .Returns(Result.From(1)); + _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(async callInfo => + { + await callInfo.Arg>()(); + return 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 _mockStagingResultsRepository.Received(1).UpdateFileHashesAsync( + _scanId.Value, + Arg.Is>(files => files.All(file => file.CurrentHash == 42UL)), + Arg.Any()); + } + + [Fact] + public async Task ExecuteAsync_WhenTheHashingCallbackRunsAfterTheProgressInterval_ShouldPublishJobProgressFromTheCallback() + { + // Arrange + List filesToHash = [_hashedFileSystemFileDtoFixture.Create(path: "/books/book1.pdf")]; + _mockStagingResultsRepository.GetFilesToHashCountAsync(_scanId.Value, Arg.Any()) + .Returns(Result.From(1)); + _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(async callInfo => + { + await Task.Delay(150); + await callInfo.Arg>()(); + return 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); + // the initial progress and the progress published from the hashing callback are both reported + await _mockDomainEventPublisher.Received(2).PublishAsync(Arg.Is(domainEvent => domainEvent.LibraryId == _libraryId), Arg.Any()); + } + + [Fact] + public async Task ExecuteAsync_WhenTheJobHasChildJobs_ShouldExecuteThemAfterCompletingItsPayload() + { + // Arrange + _mockStagingResultsRepository.GetFilesToHashCountAsync(_scanId.Value, Arg.Any()) + .Returns(Result.From(0)); + _mockStagingResultsRepository.GetFilesToHashPageAsync(_scanId.Value, Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(Result.From>([])); + + IMediaLibraryScanJob mockChildJob = Substitute.For(); + mockChildJob.ExecuteAsync(Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(Task.CompletedTask); + _sut.AddChild(mockChildJob); + Guid id = Guid.NewGuid(); + object input = new(); + + // Act + await _sut.ExecuteAsync(id, input, CancellationToken.None); + + // Assert + await mockChildJob.Received(1).ExecuteAsync(id, input, Arg.Any()); + Assert.Equal(LibraryScanJobStatus.Completed, _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 index 343f32c5..01776927 100644 --- a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/MediaLibrary/Management/Scanning/Jobs/Common/MediaLibraryScanMetadataEnrichmentJobTests.cs +++ b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/MediaLibrary/Management/Scanning/Jobs/Common/MediaLibraryScanMetadataEnrichmentJobTests.cs @@ -25,6 +25,7 @@ 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.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; @@ -488,6 +489,223 @@ public class MediaLibraryScanMetadataEnrichmentJobTests Assert.Equal(LibraryScanJobStatus.Completed, _sut.Status); } + [Fact] + public async Task ExecuteAsync_WhenCountingTheBooksNeedingMetadataFails_ShouldMarkJobAsFailed() + { + // Arrange + Guid firstPluginId = Guid.NewGuid(); + IMetadataProvider firstProvider = Substitute.For(); + firstProvider.Name.Returns("First Provider"); + firstProvider.SupportedLibraryTypes.Returns([LibraryType.Book]); + + SetupRealServiceProviderForProviders(firstPluginId, firstProvider, shouldAggregateMetadataWhenMissing: false); + _mockConfigurationRepository.GetByLibraryIdAsync(_libraryId.Value, Arg.Any()) + .Returns(Result.From>([_configurationEntityFixture.Create(_libraryId.Value, firstPluginId, 1)])); + _mockBookRepository.GetBooksNeedingMetadataCountAsync(_libraryId.Value, Arg.Any()) + .Returns(Error.Failure("Database.Error", "Failed to count the books to enrich")); + _mockUnitOfWork.SaveChangesAsync(Arg.Any()).Returns(Task.CompletedTask); + + // Act + await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None); + + // Assert + Assert.Equal(LibraryScanJobStatus.Failed, _sut.Status); + } + + [Fact] + public async Task ExecuteAsync_WhenGettingTheBooksPageNeedingMetadataFails_ShouldMarkJobAsFailed() + { + // Arrange + Guid firstPluginId = Guid.NewGuid(); + IMetadataProvider firstProvider = Substitute.For(); + firstProvider.Name.Returns("First Provider"); + firstProvider.SupportedLibraryTypes.Returns([LibraryType.Book]); + + SetupRealServiceProviderForProviders(firstPluginId, firstProvider, shouldAggregateMetadataWhenMissing: false); + _mockConfigurationRepository.GetByLibraryIdAsync(_libraryId.Value, Arg.Any()) + .Returns(Result.From>([_configurationEntityFixture.Create(_libraryId.Value, firstPluginId, 1)])); + _mockBookRepository.GetBooksNeedingMetadataCountAsync(_libraryId.Value, Arg.Any()) + .Returns(Result.From(1)); + _mockBookRepository.GetBooksNeedingMetadataAsync(_libraryId.Value, Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(Error.Failure("Database.Error", "Failed to get the books to enrich")); + _mockUnitOfWork.SaveChangesAsync(Arg.Any()).Returns(Task.CompletedTask); + + // Act + await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None); + + // Assert + Assert.Equal(LibraryScanJobStatus.Failed, _sut.Status); + } + + [Fact] + public async Task ExecuteAsync_WhenAMetadataProviderThrowsWhileTryingTheProvidersInOrder_ShouldTryTheNextProvider() + { + // Arrange + Guid firstPluginId = Guid.NewGuid(); + Guid secondPluginId = Guid.NewGuid(); + IMetadataProvider firstProvider = Substitute.For(); + firstProvider.Name.Returns("First Provider"); + firstProvider.SupportedLibraryTypes.Returns([LibraryType.Book]); + firstProvider.GetMetadataAsync(Arg.Any(), Arg.Any()) + .Returns(Task.FromException(new InvalidOperationException("The metadata provider failed"))); + IMetadataProvider secondProvider = Substitute.For(); + secondProvider.Name.Returns("Second Provider"); + secondProvider.SupportedLibraryTypes.Returns([LibraryType.Book]); + secondProvider.GetMetadataAsync(Arg.Any(), Arg.Any()) + .Returns(_bookMetadataDtoFixture.Create(title: "Second Title", publisher: "Second Publisher")); + + SetupRealServiceProviderForProviders(firstPluginId, firstProvider, secondPluginId, secondProvider, shouldAggregateMetadataWhenMissing: false); + BookEntity book = _bookEntityFixture.Create(libraryId: _libraryId.Value, path: "/books/test.epub"); + SetupSingleBookPage(book, firstPluginId, secondPluginId); + + // Act + await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None); + + // Assert + // a failing metadata provider must not prevent the metadata of the next provider from being used + Assert.Equal(MetadataStatus.Enriched, book.MetadataStatus); + Assert.Equal("Second Provider", book.MetadataProvider); + Assert.Equal(LibraryScanJobStatus.Completed, _sut.Status); + } + + [Fact] + public async Task ExecuteAsync_WhenAMetadataProviderThrowsWhileAggregatingMetadata_ShouldUseTheFindingsOfTheOtherProviders() + { + // Arrange + Guid firstPluginId = Guid.NewGuid(); + Guid secondPluginId = Guid.NewGuid(); + IMetadataProvider firstProvider = Substitute.For(); + firstProvider.Name.Returns("First Provider"); + firstProvider.SupportedLibraryTypes.Returns([LibraryType.Book]); + firstProvider.GetMetadataAsync(Arg.Any(), Arg.Any()) + .Returns(Task.FromException(new InvalidOperationException("The metadata provider failed"))); + IMetadataProvider secondProvider = Substitute.For(); + secondProvider.Name.Returns("Second Provider"); + secondProvider.SupportedLibraryTypes.Returns([LibraryType.Book]); + secondProvider.GetMetadataAsync(Arg.Any(), Arg.Any()) + .Returns(_bookMetadataDtoFixture.Create(title: "Second Title", publisher: "Second Publisher")); + + SetupRealServiceProviderForProviders(firstPluginId, firstProvider, secondPluginId, secondProvider, shouldAggregateMetadataWhenMissing: true); + BookEntity book = _bookEntityFixture.Create(libraryId: _libraryId.Value, path: "/books/test.epub"); + SetupSingleBookPage(book, firstPluginId, secondPluginId); + + // Act + await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None); + + // Assert + Assert.Equal(MetadataStatus.Enriched, book.MetadataStatus); + Assert.Equal("Second Provider", book.MetadataProvider); + Assert.Equal("Second Title", book.Title); + Assert.Equal(LibraryScanJobStatus.Completed, _sut.Status); + } + + [Fact] + public async Task ExecuteAsync_WhenAContributorHasNoDisplayName_ShouldSkipLinkingIt() + { + // Arrange + Guid firstPluginId = Guid.NewGuid(); + IMetadataProvider firstProvider = Substitute.For(); + firstProvider.Name.Returns("First Provider"); + firstProvider.SupportedLibraryTypes.Returns([LibraryType.Book]); + MediaContributorDto namelessContributor = _mediaContributorDtoFixture.Create(roleName: "Author", roleCategory: MediaContributorRoleCategory.Author) with { Name = null }; + firstProvider.GetMetadataAsync(Arg.Any(), Arg.Any()) + .Returns(_bookMetadataDtoFixture.Create(title: "First Title", contributors: [namelessContributor])); + + SetupRealServiceProviderForProviders(firstPluginId, firstProvider, shouldAggregateMetadataWhenMissing: false); + BookEntity book = _bookEntityFixture.Create(libraryId: _libraryId.Value, path: "/books/test.epub"); + SetupSingleBookPage(book, firstPluginId); + + // Act + await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None); + + // Assert + // a contributor without a display name cannot be linked to the book, so no contributor is queried or created + await _mockMediaContributorRepository.DidNotReceive().FindOrCreateByDisplayNameAsync(Arg.Any(), Arg.Any(), Arg.Any()); + Assert.Empty(book.BookContributors); + Assert.Equal(MetadataStatus.Enriched, book.MetadataStatus); + Assert.Equal(LibraryScanJobStatus.Completed, _sut.Status); + } + + [Fact] + public async Task ExecuteAsync_WhenAContributorHasNoRole_ShouldLinkItWithTheDefaultRole() + { + // Arrange + Guid firstPluginId = Guid.NewGuid(); + IMetadataProvider firstProvider = Substitute.For(); + firstProvider.Name.Returns("First Provider"); + firstProvider.SupportedLibraryTypes.Returns([LibraryType.Book]); + MediaContributorDto contributorWithoutRole = _mediaContributorDtoFixture.Create(displayName: "Frank Herbert") with { Role = null }; + firstProvider.GetMetadataAsync(Arg.Any(), Arg.Any()) + .Returns(_bookMetadataDtoFixture.Create(title: "First Title", contributors: [contributorWithoutRole])); + + SetupRealServiceProviderForProviders(firstPluginId, firstProvider, shouldAggregateMetadataWhenMissing: false); + BookEntity book = _bookEntityFixture.Create(libraryId: _libraryId.Value, path: "/books/test.epub", includeMetadata: false); + SetupSingleBookPage(book, firstPluginId); + + MediaContributorEntity authorEntity = _mediaContributorEntityFixture.Create(displayName: "Frank Herbert"); + _mockMediaContributorRepository.FindOrCreateByDisplayNameAsync("Frank Herbert", Arg.Any(), Arg.Any()) + .Returns(Result.From(authorEntity)); + + // Act + await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None); + + // Assert + BookContributorEntity linkedContributor = Assert.Single(book.BookContributors); + Assert.Equal("Contributor", linkedContributor.RoleName); + Assert.Equal(MediaContributorRoleCategory.Other, linkedContributor.RoleCategory); + Assert.Equal(MetadataStatus.Enriched, book.MetadataStatus); + Assert.Equal(LibraryScanJobStatus.Completed, _sut.Status); + } + + [Fact] + public async Task ExecuteAsync_WhenFindingOrCreatingAContributorFails_ShouldMarkJobAsFailed() + { + // Arrange + Guid firstPluginId = Guid.NewGuid(); + IMetadataProvider firstProvider = Substitute.For(); + firstProvider.Name.Returns("First Provider"); + firstProvider.SupportedLibraryTypes.Returns([LibraryType.Book]); + MediaContributorDto author = _mediaContributorDtoFixture.Create(displayName: "Frank Herbert", roleName: "Author", roleCategory: MediaContributorRoleCategory.Author); + firstProvider.GetMetadataAsync(Arg.Any(), Arg.Any()) + .Returns(_bookMetadataDtoFixture.Create(title: "First Title", contributors: [author])); + + SetupRealServiceProviderForProviders(firstPluginId, firstProvider, shouldAggregateMetadataWhenMissing: false); + BookEntity book = _bookEntityFixture.Create(libraryId: _libraryId.Value, path: "/books/test.epub"); + SetupSingleBookPage(book, firstPluginId); + + _mockMediaContributorRepository.FindOrCreateByDisplayNameAsync("Frank Herbert", Arg.Any(), Arg.Any()) + .Returns(Error.Failure("Database.Error", "Failed to find or create the contributor")); + + // Act + await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None); + + // Assert + Assert.Equal(LibraryScanJobStatus.Failed, _sut.Status); + } + + [Fact] + public async Task ExecuteAsync_WhenTheJobHasChildJobs_ShouldExecuteThemAfterCompletingItsPayload() + { + // Arrange + _mockConfigurationRepository.GetByLibraryIdAsync(_libraryId.Value, Arg.Any()) + .Returns(Result.From>([])); + _mockUnitOfWork.SaveChangesAsync(Arg.Any()).Returns(Task.CompletedTask); + + IMediaLibraryScanJob mockChildJob = Substitute.For(); + mockChildJob.ExecuteAsync(Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(Task.CompletedTask); + _sut.AddChild(mockChildJob); + Guid id = Guid.NewGuid(); + object input = new(); + + // Act + await _sut.ExecuteAsync(id, input, CancellationToken.None); + + // Assert + await mockChildJob.Received(1).ExecuteAsync(id, input, Arg.Any()); + Assert.Equal(LibraryScanJobStatus.Completed, _sut.Status); + } + /// /// Wires a real service provider with the given metadata providers, so that the job resolves them from the dependency injection container. /// diff --git a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/MediaLibrary/Management/Scanning/Jobs/Common/MediaLibraryScanProviderConfigurationInvalidationJobTests.cs b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/MediaLibrary/Management/Scanning/Jobs/Common/MediaLibraryScanProviderConfigurationInvalidationJobTests.cs index 2ec4efc1..ff984873 100644 --- a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/MediaLibrary/Management/Scanning/Jobs/Common/MediaLibraryScanProviderConfigurationInvalidationJobTests.cs +++ b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/MediaLibrary/Management/Scanning/Jobs/Common/MediaLibraryScanProviderConfigurationInvalidationJobTests.cs @@ -14,6 +14,7 @@ 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.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; @@ -249,6 +250,161 @@ public class MediaLibraryScanProviderConfigurationInvalidationJobTests Assert.Equal(LibraryScanJobStatus.Canceled, _sut.Status); } + [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 _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); + await _mockDomainEventPublisher.Received(1).PublishAsync(Arg.Is(domainEvent => + domainEvent.LibraryId == _libraryId), Arg.Any()); + } + + [Fact] + public async Task ExecuteAsync_WhenGettingMetadataConfigurationsFails_ShouldMarkJobAsFailedAndPublishFailureEvent() + { + // Arrange + LibraryEntity library = _libraryEntityFixture.Create(id: _libraryId.Value, title: "My Library"); + SetupLibraryAndConfigurations(library); + _mockMetadataConfigurationRepository.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 _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); + await _mockDomainEventPublisher.Received(1).PublishAsync(Arg.Is(domainEvent => + domainEvent.LibraryId == _libraryId), Arg.Any()); + } + + [Fact] + public async Task ExecuteAsync_WhenGettingArtworkConfigurationsFails_ShouldMarkJobAsFailedAndPublishFailureEvent() + { + // Arrange + LibraryEntity library = _libraryEntityFixture.Create(id: _libraryId.Value, title: "My Library"); + SetupLibraryAndConfigurations(library); + _mockArtworkConfigurationRepository.GetByLibraryIdAsync(_libraryId.Value, Arg.Any()) + .Returns(Error.Failure("Database.Error", "Failed to get the artwork provider configurations")); + + // Act + await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None); + + // Assert + Assert.Equal(LibraryScanJobStatus.Failed, _sut.Status); + await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); + await _mockDomainEventPublisher.Received(1).PublishAsync(Arg.Is(domainEvent => + domainEvent.LibraryId == _libraryId), Arg.Any()); + } + + [Fact] + public async Task ExecuteAsync_WhenResettingMetadataStatusFails_ShouldMarkJobAsFailedAndPublishFailureEvent() + { + // Arrange + LibraryEntity library = _libraryEntityFixture.Create(id: _libraryId.Value, title: "My Library", metadataProvidersConfigurationFingerprint: "STALE_METADATA", artworkProvidersConfigurationFingerprint: null); + SetupLibraryAndConfigurations(library); + _mockBookRepository.ResetMetadataStatusForLibraryAsync(_libraryId.Value, Arg.Any()) + .Returns(Error.Failure("Database.Error", "Failed to reset the metadata status")); + + // Act + await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None); + + // Assert + Assert.Equal(LibraryScanJobStatus.Failed, _sut.Status); + await _mockBookRepository.DidNotReceive().ResetArtworkStatusForLibraryAsync(Arg.Any(), Arg.Any()); + await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); + await _mockDomainEventPublisher.Received(1).PublishAsync(Arg.Is(domainEvent => + domainEvent.LibraryId == _libraryId), Arg.Any()); + } + + [Fact] + public async Task ExecuteAsync_WhenResettingArtworkStatusFails_ShouldMarkJobAsFailedAndPublishFailureEvent() + { + // Arrange + LibraryEntity library = _libraryEntityFixture.Create(id: _libraryId.Value, title: "My Library", metadataProvidersConfigurationFingerprint: null, artworkProvidersConfigurationFingerprint: "STALE_ARTWORK"); + SetupLibraryAndConfigurations(library); + _mockBookRepository.ResetArtworkStatusForLibraryAsync(_libraryId.Value, Arg.Any()) + .Returns(Error.Failure("Database.Error", "Failed to reset the artwork status")); + + // Act + await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None); + + // Assert + Assert.Equal(LibraryScanJobStatus.Failed, _sut.Status); + await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); + await _mockDomainEventPublisher.Received(1).PublishAsync(Arg.Is(domainEvent => + domainEvent.LibraryId == _libraryId), Arg.Any()); + } + + [Fact] + public async Task ExecuteAsync_WhenReadingUserSettingsFails_ShouldStillSeedTheFingerprintsAndComplete() + { + // Arrange + LibraryEntity library = _libraryEntityFixture.Create(id: _libraryId.Value, title: "My Library"); + SetupLibraryAndConfigurations(library); + IUserSettingsRepository mockUserSettingsRepository = Substitute.For(); + mockUserSettingsRepository.GetByUserIdAsync(Arg.Any(), Arg.Any()) + .Returns(Error.Failure("Database.Error", "Failed to read the user settings")); + _mockUnitOfWork.UserSettingsRepository.Returns(mockUserSettingsRepository); + + // Act + await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None); + + // Assert + // reading the user settings is best effort, a failure must not prevent the fingerprints from being persisted + Assert.NotNull(library.MetadataProvidersConfigurationFingerprint); + await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any()); + Assert.Equal(LibraryScanJobStatus.Completed, _sut.Status); + } + + [Fact] + public async Task ExecuteAsync_WhenUserSettingsRepositoryIsNotRegistered_ShouldSeedTheFingerprintsAndComplete() + { + // Arrange + LibraryEntity library = _libraryEntityFixture.Create(id: _libraryId.Value, title: "My Library"); + SetupLibraryAndConfigurations(library); + _mockUnitOfWork.UserSettingsRepository.Returns((IUserSettingsRepository)null!); + + // Act + await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None); + + // Assert + // the user settings repository is optional, its absence must not prevent the fingerprints from being persisted + Assert.NotNull(library.MetadataProvidersConfigurationFingerprint); + await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any()); + Assert.Equal(LibraryScanJobStatus.Completed, _sut.Status); + } + + [Fact] + public async Task ExecuteAsync_WhenJobHasLinkedChildren_ShouldExecuteEachChildAndComplete() + { + // Arrange + LibraryEntity library = _libraryEntityFixture.Create(id: _libraryId.Value, title: "My Library"); + SetupLibraryAndConfigurations(library); + + IMediaLibraryScanJob mockChild = Substitute.For(); + mockChild.ExecuteAsync(Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(Task.CompletedTask); + _sut.AddChild(mockChild); + object input = new(); + + // Act + await _sut.ExecuteAsync(Guid.NewGuid(), input, CancellationToken.None); + + // Assert + Assert.Equal(LibraryScanJobStatus.Completed, _sut.Status); + await mockChild.Received(1).ExecuteAsync(Arg.Any(), Arg.Is(executedInput => executedInput == input), Arg.Any()); + await _mockDomainEventPublisher.DidNotReceive().PublishAsync(Arg.Any(), Arg.Any()); + } + /// /// Stubs the repositories so that the job reads the provided library and its provider configurations. /// 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 index e1f9c3a9..7704dc1a 100644 --- 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 @@ -7,6 +7,7 @@ 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.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; @@ -200,4 +201,202 @@ public class MediaLibraryScanResultsSaveJobTests await Assert.ThrowsAnyAsync(() => operation); Assert.Equal(LibraryScanJobStatus.Canceled, _sut.Status); } + + [Fact] + public async Task ExecuteAsync_WhenGettingChangedPathsFails_ShouldMarkJobAsFailedAndPublishFailureEvent() + { + // Arrange + _mockSnapshotRepository.GetDeletedPathsAsync(_libraryId.Value, _scanId.Value, Arg.Any()) + .Returns(Result.From>([])); + _mockStagingResultsRepository.GetChangedPathsAsync(_scanId.Value, Arg.Any()) + .Returns(Error.Failure("Database.Error", "Failed to get the changed paths")); + + // Act + await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None); + + // Assert + Assert.Equal(LibraryScanJobStatus.Failed, _sut.Status); + await _mockSnapshotRepository.DidNotReceive().ApplySnapshotSwapAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()); + await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); + await _mockDomainEventPublisher.Received(1).PublishAsync(Arg.Is(domainEvent => + domainEvent.LibraryId == _libraryId), Arg.Any()); + } + + [Fact] + public async Task ExecuteAsync_WhenApplyingSnapshotSwapFails_ShouldMarkJobAsFailedAndPublishFailureEvent() + { + // Arrange + _mockSnapshotRepository.GetDeletedPathsAsync(_libraryId.Value, _scanId.Value, Arg.Any()) + .Returns(Result.From>([])); + _mockStagingResultsRepository.GetChangedPathsAsync(_scanId.Value, Arg.Any()) + .Returns(Result.From>([])); + _mockSnapshotRepository.ApplySnapshotSwapAsync(_libraryId.Value, _scanId.Value, _userId.Value, Arg.Any()) + .Returns(Error.Failure("Database.Error", "Failed to apply the snapshot swap")); + + // Act + await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None); + + // Assert + Assert.Equal(LibraryScanJobStatus.Failed, _sut.Status); + await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); + await _mockDomainEventPublisher.Received(1).PublishAsync(Arg.Is(domainEvent => + domainEvent.LibraryId == _libraryId), Arg.Any()); + } + + [Fact] + public async Task ExecuteAsync_WhenResettingEnrichmentStateFails_ShouldMarkJobAsFailedAndPublishFailureEvent() + { + // Arrange + _mockSnapshotRepository.GetDeletedPathsAsync(_libraryId.Value, _scanId.Value, Arg.Any()) + .Returns(Result.From>([])); + _mockStagingResultsRepository.GetChangedPathsAsync(_scanId.Value, Arg.Any()) + .Returns(Result.From>(["changed.pdf"])); + _mockSnapshotRepository.ApplySnapshotSwapAsync(_libraryId.Value, _scanId.Value, _userId.Value, Arg.Any()) + .Returns(Result.From(Result.Updated)); + _mockBookRepository.ResetEnrichmentStateForPathsAsync(_libraryId.Value, Arg.Any>(), Arg.Any()) + .Returns(Error.Failure("Database.Error", "Failed to reset the enrichment state")); + + // Act + await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None); + + // Assert + Assert.Equal(LibraryScanJobStatus.Failed, _sut.Status); + await _mockBookRepository.DidNotReceive().InsertAsync(Arg.Any(), Arg.Any()); + await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); + await _mockDomainEventPublisher.Received(1).PublishAsync(Arg.Is(domainEvent => + domainEvent.LibraryId == _libraryId), Arg.Any()); + } + + [Fact] + public async Task ExecuteAsync_WhenGettingPathsFails_ShouldMarkJobAsFailedAndPublishFailureEvent() + { + // Arrange + _mockSnapshotRepository.GetDeletedPathsAsync(_libraryId.Value, _scanId.Value, Arg.Any()) + .Returns(Result.From>([])); + _mockStagingResultsRepository.GetChangedPathsAsync(_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(Error.Failure("Database.Error", "Failed to get the paths")); + + // Act + await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None); + + // Assert + Assert.Equal(LibraryScanJobStatus.Failed, _sut.Status); + await _mockBookRepository.DidNotReceive().InsertAsync(Arg.Any(), Arg.Any()); + await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); + await _mockDomainEventPublisher.Received(1).PublishAsync(Arg.Is(domainEvent => + domainEvent.LibraryId == _libraryId), Arg.Any()); + } + + [Fact] + public async Task ExecuteAsync_WhenGettingExistingBookFails_ShouldMarkJobAsFailedAndPublishFailureEvent() + { + // Arrange + _mockSnapshotRepository.GetDeletedPathsAsync(_libraryId.Value, _scanId.Value, Arg.Any()) + .Returns(Result.From>([])); + _mockStagingResultsRepository.GetChangedPathsAsync(_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>(["book1.pdf"])); + _mockBookRepository.GetByPathAsync(_libraryId.Value, Arg.Any(), Arg.Any()) + .Returns(Error.Failure("Database.Error", "Failed to get the existing book")); + + // Act + await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None); + + // Assert + Assert.Equal(LibraryScanJobStatus.Failed, _sut.Status); + await _mockBookRepository.DidNotReceive().InsertAsync(Arg.Any(), Arg.Any()); + await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); + await _mockDomainEventPublisher.Received(1).PublishAsync(Arg.Is(domainEvent => + domainEvent.LibraryId == _libraryId), Arg.Any()); + } + + [Fact] + public async Task ExecuteAsync_WhenInsertingShellBookFails_ShouldMarkJobAsFailedAndPublishFailureEvent() + { + // Arrange + _mockSnapshotRepository.GetDeletedPathsAsync(_libraryId.Value, _scanId.Value, Arg.Any()) + .Returns(Result.From>([])); + _mockStagingResultsRepository.GetChangedPathsAsync(_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>(["book1.pdf"])); + _mockBookRepository.GetByPathAsync(_libraryId.Value, Arg.Any(), Arg.Any()) + .Returns(Result.From(null)); + _mockBookRepository.InsertAsync(Arg.Any(), Arg.Any()) + .Returns(Error.Failure("Database.Error", "Failed to insert the shell book")); + + // Act + await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None); + + // Assert + Assert.Equal(LibraryScanJobStatus.Failed, _sut.Status); + await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); + await _mockDomainEventPublisher.Received(1).PublishAsync(Arg.Is(domainEvent => + domainEvent.LibraryId == _libraryId), Arg.Any()); + } + + [Fact] + public async Task ExecuteAsync_WhenJobHasLinkedChildren_ShouldExecuteEachChildWithoutPublishingFinishedEvent() + { + // Arrange + _mockSnapshotRepository.GetDeletedPathsAsync(_libraryId.Value, _scanId.Value, Arg.Any()) + .Returns(Result.From>([])); + _mockStagingResultsRepository.GetChangedPathsAsync(_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>([])); + _mockUnitOfWork.SaveChangesAsync(Arg.Any()).Returns(Task.CompletedTask); + + IMediaLibraryScanJob mockChild = Substitute.For(); + mockChild.ExecuteAsync(Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(Task.CompletedTask); + _sut.AddChild(mockChild); + object input = new(); + + // Act + await _sut.ExecuteAsync(Guid.NewGuid(), input, CancellationToken.None); + + // Assert + Assert.Equal(LibraryScanJobStatus.Completed, _sut.Status); + await mockChild.Received(1).ExecuteAsync(Arg.Any(), Arg.Is(executedInput => executedInput == input), Arg.Any()); + await _mockDomainEventPublisher.DidNotReceive().PublishAsync(Arg.Any(), Arg.Any()); + } + + [Fact] + public async Task ExecuteAsync_WhenBookPathYieldsEmptyDerivedTitle_ShouldFallBackToTheFileNameAsTitle() + { + // Arrange + _mockSnapshotRepository.GetDeletedPathsAsync(_libraryId.Value, _scanId.Value, Arg.Any()) + .Returns(Result.From>([])); + _mockStagingResultsRepository.GetChangedPathsAsync(_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>(["_.pdf"])); + _mockBookRepository.GetByPathAsync(_libraryId.Value, "_.pdf", 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 + // the file name is made only of separators, so the derived title is empty and the raw file name is used as a fallback + await _mockBookRepository.Received(1).InsertAsync(Arg.Is(book => book.Path == "_.pdf" && book.Title == "_"), Arg.Any()); + Assert.Equal(LibraryScanJobStatus.Completed, _sut.Status); + } } 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 index 04b5f70f..fae7f289 100644 --- 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 @@ -2,6 +2,7 @@ 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.Errors; using Lumina.Domain.Common.Events; using Lumina.Domain.Common.Primitives; using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects; @@ -11,7 +12,6 @@ using Lumina.Domain.Core.BoundedContexts.UserManagementBoundedContext.UserAggreg using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects; using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects; using Lumina.Domain.Fixtures.Core.BoundedContexts.UserManagementBoundedContext.UserAggregate.ValueObjects; -using Lumina.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; @@ -19,8 +19,6 @@ 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 @@ -39,13 +37,11 @@ public class BooksFileSystemDiscoveryJobTests 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; @@ -64,10 +60,8 @@ public class BooksFileSystemDiscoveryJobTests _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(); @@ -86,47 +80,6 @@ public class BooksFileSystemDiscoveryJobTests }; } - [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() { @@ -176,48 +129,4 @@ public class BooksFileSystemDiscoveryJobTests 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 index 1a5ff63f..09778c31 100644 --- 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 @@ -168,4 +168,65 @@ public class DebouncedMediaLibraryScanProgressNotifierTests && ((MediaLibraryScanProgressResponse)args[0]!).Status == LibraryScanJobStatus.Failed.ToString()), Arg.Any()); } + + [Fact] + public async Task SendLibraryScanFinishedEventAsync_WhenTokenIsCancelled_ShouldNotRemoveProgressOrSendEvent() + { + // Arrange + MediaLibraryScanCompositeId compositeId = _mediaLibraryScanCompositeIdFixture.Create(); + using CancellationTokenSource cancellationTokenSource = new(); + cancellationTokenSource.Cancel(); + + // Act + await _sut.SendLibraryScanFinishedEventAsync(compositeId, cancellationTokenSource.Token); + + // Assert + _mockProgressTracker.DidNotReceive().RemoveScanProgress(Arg.Any()); + _mockHubClients.DidNotReceive().Group(Arg.Any()); + } + + [Fact] + public async Task SendLibraryScanFailedEventAsync_WhenTokenIsCancelled_ShouldNotRemoveProgressOrSendEvent() + { + // Arrange + MediaLibraryScanCompositeId compositeId = _mediaLibraryScanCompositeIdFixture.Create(); + using CancellationTokenSource cancellationTokenSource = new(); + cancellationTokenSource.Cancel(); + + // Act + await _sut.SendLibraryScanFailedEventAsync(compositeId, cancellationTokenSource.Token); + + // Assert + _mockProgressTracker.DidNotReceive().RemoveScanProgress(Arg.Any()); + _mockHubClients.DidNotReceive().Group(Arg.Any()); + } + + [Fact] + public async Task SendLibraryScanFinishedEventAsync_WhenADebouncedUpdateWasScheduledForTheScan_ShouldRemoveTheDebouncer() + { + // Arrange + MediaLibraryScanCompositeId compositeId = _mediaLibraryScanCompositeIdFixture.Create(); + // The scheduled update is registered by the progress update even when the progress is missing, which also avoids sending an update event. + _mockProgressTracker.GetScanProgress(compositeId) + .Returns(Error.Failure("Tracking.Error", "The scan progress is missing")); + 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.SendLibraryProgressUpdateEventAsync(compositeId, CancellationToken.None); + 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()); + } } diff --git a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Artwork/BookArtworkServiceTests.cs b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Artwork/BookArtworkServiceTests.cs index 6f8cb8d8..28a526c2 100644 --- a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Artwork/BookArtworkServiceTests.cs +++ b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Artwork/BookArtworkServiceTests.cs @@ -8,16 +8,13 @@ using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.File using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Strategies.Environment; using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.ValueObjects; using Lumina.Domain.Fixtures.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.ValueObjects; -using Lumina.Domain.SharedKernel.Common.Enums.PhotoLibrary; using Lumina.Infrastructure.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Artwork; -using Lumina.Infrastructure.Fixtures.Common.Setup; using Microsoft.Extensions.Options; using NSubstitute; using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.IO; -using System.Net; using System.Net.Http; using System.Threading; using System.Threading.Tasks; @@ -31,8 +28,6 @@ namespace Lumina.Infrastructure.UnitTests.Core.MediaLibrary.WrittenContentLibrar [ExcludeFromCodeCoverage] public class BookArtworkServiceTests { - private const long MAX_ARTWORK_SIZE_BYTES = 10 * 1024 * 1024; - private readonly IEnvironmentContext _mockEnvironmentContext; private readonly IFileTypeService _mockFileTypeService; private readonly IFileProviderService _mockFileProviderService; @@ -45,7 +40,6 @@ public class BookArtworkServiceTests private readonly PathSegmentFixture _pathSegmentFixture = new(); private readonly ArtworkDtoFixture _artworkDtoFixture = new(); private readonly MediaSettingsDtoFixture _mediaSettingsDtoFixture = new(); - private readonly StubHttpMessageHandler _stubHttpMessageHandler = new(); /// /// Initializes a new instance of the class. @@ -64,7 +58,6 @@ public class BookArtworkServiceTests _mockPathService.PathSeparator.Returns('\\'); _mockHttpClientFactory = Substitute.For(); - _mockHttpClientFactory.CreateClient().Returns(new HttpClient(_stubHttpMessageHandler)); MediaSettingsDto mediaSettings = _mediaSettingsDtoFixture.Create(rootDirectory: "media", librariesDirectory: "libraries", booksDirectory: "books"); _mockMediaSettingsOptions = Substitute.For>(); @@ -73,91 +66,6 @@ public class BookArtworkServiceTests _sut = new BookArtworkService(_mockEnvironmentContext, _mockPathService, _mockHttpClientFactory, _mockMediaSettingsOptions); } - [Fact] - public async Task SaveBookArtworkAsync_WhenLocalArtworkExists_ShouldCopyItAndReturnARelativePath() - { - // Arrange - Guid libraryId = Guid.NewGuid(); - Guid bookId = Guid.NewGuid(); - string libraryName = "Test Library"; - string authorName = "Test Author"; - string bookTitle = "Test Book"; - - string sourcePath = CreateTempImageFile(smallImageBytes: 1024); - try - { - _mockFileProviderService.FileExists(Arg.Any()).Returns(Result.From(true)); - _mockFileTypeService.GetImageTypeAsync(Arg.Any(), Arg.Any()) - .Returns(Result.From(ImageType.JPEG)); - - string artworkDirectoryPath = BuildArtworkDirectoryPath(libraryId, bookId, libraryName, authorName, bookTitle); - MockArtworkDirectoryStubs(artworkDirectoryPath); - - FileSystemPathId copiedFileId = _fileSystemPathIdFixture.Create(Path.Combine(artworkDirectoryPath, "cover.jpg")); - _mockFileProviderService.CopyFile(Arg.Any(), Arg.Any(), true) - .Returns(Result.From(copiedFileId)); - - string renamedFilePath = Path.Combine(artworkDirectoryPath, "cover.jpeg"); - FileSystemPathId renamedFileId = _fileSystemPathIdFixture.Create(renamedFilePath); - _mockFileProviderService.RenameFile(Arg.Any(), "cover.jpeg") - .Returns(Result.From(renamedFileId)); - - // Act - Result result = await _sut.SaveBookArtworkAsync(libraryId, bookId, libraryName, authorName, bookTitle, _artworkDtoFixture.Create(localPath: sourcePath), CancellationToken.None); - - // Assert - Assert.False(result.IsFailure); - Assert.Equal(renamedFilePath[AppContext.BaseDirectory.Length..].Insert(0, "\\"), result.Value); - _mockFileProviderService.Received(1).CopyFile( - Arg.Is(pathId => pathId.Path == sourcePath), - Arg.Any(), - true); - _mockFileProviderService.Received(1).RenameFile(Arg.Any(), "cover.jpeg"); - } - finally - { - File.Delete(sourcePath); - } - } - - [Fact] - public async Task SaveBookArtworkAsync_WhenAuthorNameIsMissing_ShouldUseUnknownForTheDirectorySegment() - { - // Arrange - Guid libraryId = Guid.NewGuid(); - Guid bookId = Guid.NewGuid(); - string libraryName = "Test Library"; - string bookTitle = "Test Book"; - - string sourcePath = CreateTempImageFile(smallImageBytes: 1024); - try - { - _mockFileProviderService.FileExists(Arg.Any()).Returns(Result.From(true)); - _mockFileTypeService.GetImageTypeAsync(Arg.Any(), Arg.Any()) - .Returns(Result.From(ImageType.JPEG)); - - string artworkDirectoryPath = BuildArtworkDirectoryPath(libraryId, bookId, libraryName, authorName: "Unknown", bookTitle); - MockArtworkDirectoryStubs(artworkDirectoryPath); - - FileSystemPathId renamedFileId = _fileSystemPathIdFixture.Create(Path.Combine(artworkDirectoryPath, "cover.jpeg")); - _mockFileProviderService.CopyFile(Arg.Any(), Arg.Any(), true) - .Returns(Result.From(_fileSystemPathIdFixture.Create(Path.Combine(artworkDirectoryPath, "cover.jpg")))); - _mockFileProviderService.RenameFile(Arg.Any(), "cover.jpeg") - .Returns(Result.From(renamedFileId)); - - // Act - Result result = await _sut.SaveBookArtworkAsync(libraryId, bookId, libraryName, authorName: " ", bookTitle, _artworkDtoFixture.Create(localPath: sourcePath), CancellationToken.None); - - // Assert - Assert.False(result.IsFailure); - _mockPathService.Received(1).SanitizeSegment("Unknown"); - } - finally - { - File.Delete(sourcePath); - } - } - [Fact] public async Task SaveBookArtworkAsync_WhenLocalArtworkDoesNotExist_ShouldReturnFileNotFound() { @@ -174,90 +82,6 @@ public class BookArtworkServiceTests await _mockFileTypeService.DidNotReceive().GetImageTypeAsync(Arg.Any(), Arg.Any()); } - [Fact] - public async Task SaveBookArtworkAsync_WhenLocalArtworkIsALink_ShouldReturnInvalidPath() - { - // Arrange - string targetDirectory = Path.Combine(Path.GetTempPath(), $"lumina-junction-target-{Guid.NewGuid():N}"); - Directory.CreateDirectory(targetDirectory); - string linkPath = Path.Combine(Path.GetTempPath(), $"lumina-junction-link-{Guid.NewGuid():N}"); - if (!TryCreateJunction(linkPath, targetDirectory)) - { - Directory.Delete(targetDirectory, true); - return; // the environment does not support creating reparse points - } - - try - { - _mockFileProviderService.FileExists(Arg.Any()).Returns(Result.From(true)); - - // Act - Result result = await _sut.SaveBookArtworkAsync(Guid.NewGuid(), Guid.NewGuid(), "Library", "Author", "Title", _artworkDtoFixture.Create(localPath: linkPath), CancellationToken.None); - - // Assert - Assert.True(result.IsFailure); - Assert.Equal(Errors.FileSystemManagement.InvalidPath, result.FirstError); - _mockFileProviderService.DidNotReceive().CopyFile(Arg.Any(), Arg.Any(), true); - } - finally - { - // Windows removes a junction with Directory.Delete, while Unix-like platforms unlink the symbolic link with File.Delete - if (OperatingSystem.IsWindows()) - Directory.Delete(linkPath, true); - else - File.Delete(linkPath); - Directory.Delete(targetDirectory, true); - } - } - - [Fact] - public async Task SaveBookArtworkAsync_WhenLocalArtworkExceedsMaxSize_ShouldReturnFileTooLarge() - { - // Arrange - string sourcePath = CreateTempImageFile(smallImageBytes: (int)MAX_ARTWORK_SIZE_BYTES + 1); - try - { - _mockFileProviderService.FileExists(Arg.Any()).Returns(Result.From(true)); - - // Act - Result result = await _sut.SaveBookArtworkAsync(Guid.NewGuid(), Guid.NewGuid(), "Library", "Author", "Title", _artworkDtoFixture.Create(localPath: sourcePath), CancellationToken.None); - - // Assert - Assert.True(result.IsFailure); - Assert.Equal(Errors.FileSystemManagement.FileTooLarge, result.FirstError); - await _mockFileTypeService.DidNotReceive().GetImageTypeAsync(Arg.Any(), Arg.Any()); - } - finally - { - File.Delete(sourcePath); - } - } - - [Fact] - public async Task SaveBookArtworkAsync_WhenLocalArtworkIsNotAnImage_ShouldReturnCoverFileMustBeAnImage() - { - // Arrange - string sourcePath = CreateTempImageFile(smallImageBytes: 1024); - try - { - _mockFileProviderService.FileExists(Arg.Any()).Returns(Result.From(true)); - _mockFileTypeService.GetImageTypeAsync(Arg.Any(), Arg.Any()) - .Returns(Result.From(ImageType.None)); - - // Act - Result result = await _sut.SaveBookArtworkAsync(Guid.NewGuid(), Guid.NewGuid(), "Library", "Author", "Title", _artworkDtoFixture.Create(localPath: sourcePath), CancellationToken.None); - - // Assert - Assert.True(result.IsFailure); - Assert.Equal(Errors.Library.CoverFileMustBeAnImage, result.FirstError); - _mockFileProviderService.DidNotReceive().CopyFile(Arg.Any(), Arg.Any(), true); - } - finally - { - File.Delete(sourcePath); - } - } - [Fact] public async Task SaveBookArtworkAsync_WhenArtworkHasNeitherLocalPathNorRemoteUrl_ShouldReturnFileNotFound() { @@ -270,127 +94,42 @@ public class BookArtworkServiceTests } [Fact] - public async Task SaveBookArtworkAsync_WhenRemoteUrlIsProvided_ShouldDownloadAndStoreTheArtwork() + public async Task SaveBookArtworkAsync_WhenFileExistenceCheckFails_ShouldReturnTheError() + { + // Arrange + string sourcePath = Path.Combine(Path.GetTempPath(), $"missing-artwork-{Guid.NewGuid():N}.jpg"); + _mockFileProviderService.FileExists(Arg.Any()) + .Returns(Error.Failure("FileSystem.Error", "Failed to check the artwork file")); + + // Act + Result result = await _sut.SaveBookArtworkAsync(Guid.NewGuid(), Guid.NewGuid(), "Library", "Author", "Title", _artworkDtoFixture.Create(localPath: sourcePath), CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal("FileSystem.Error", result.FirstError.Code); + } + + [Fact] + public void DeleteBookArtwork_WhenListingTheCoverFilesFails_ShouldReturnSuccessAndDeleteNothing() { // Arrange - byte[] imageBytes = new byte[1024]; - _stubHttpMessageHandler.SetResponse(HttpStatusCode.OK, imageBytes); Guid libraryId = Guid.NewGuid(); Guid bookId = Guid.NewGuid(); string libraryName = "Test Library"; string authorName = "Test Author"; string bookTitle = "Test Book"; - _mockFileProviderService.FileExists(Arg.Any()).Returns(Result.From(true)); - _mockFileTypeService.GetImageTypeAsync(Arg.Any(), Arg.Any()) - .Returns(Result.From(ImageType.JPEG)); - string artworkDirectoryPath = BuildArtworkDirectoryPath(libraryId, bookId, libraryName, authorName, bookTitle); MockArtworkDirectoryStubs(artworkDirectoryPath); - - _mockFileProviderService.CopyFile(Arg.Any(), Arg.Any(), true) - .Returns(Result.From(_fileSystemPathIdFixture.Create(Path.Combine(artworkDirectoryPath, "cover.jpg")))); - FileSystemPathId renamedFileId = _fileSystemPathIdFixture.Create(Path.Combine(artworkDirectoryPath, "cover.jpeg")); - _mockFileProviderService.RenameFile(Arg.Any(), "cover.jpeg") - .Returns(Result.From(renamedFileId)); + _mockFileProviderService.GetFilePaths(Arg.Any(), true) + .Returns(Error.Failure("FileSystem.Error", "Failed to list the artwork files")); // Act - Result result = await _sut.SaveBookArtworkAsync(libraryId, bookId, libraryName, authorName, bookTitle, _artworkDtoFixture.Create(remoteUrl: "http://artwork.example/cover.jpg"), CancellationToken.None); + Result result = _sut.DeleteBookArtwork(libraryId, bookId, libraryName, authorName, bookTitle); // Assert Assert.False(result.IsFailure); - _mockFileProviderService.Received(1).CopyFile( - Arg.Is(pathId => pathId.Path.StartsWith(Path.GetTempPath())), - Arg.Any(), - true); - } - - [Fact] - public async Task SaveBookArtworkAsync_WhenRemoteDownloadReturnsAnErrorStatus_ShouldReturnFileNotFound() - { - // Arrange - _stubHttpMessageHandler.SetResponse(HttpStatusCode.NotFound, []); - - // Act - Result result = await _sut.SaveBookArtworkAsync(Guid.NewGuid(), Guid.NewGuid(), "Library", "Author", "Title", _artworkDtoFixture.Create(remoteUrl: "http://artwork.example/cover.jpg"), CancellationToken.None); - - // Assert - Assert.True(result.IsFailure); - Assert.Equal(Errors.FileSystemManagement.FileNotFound, result.FirstError); - } - - [Fact] - public async Task SaveBookArtworkAsync_WhenRemoteDownloadExceedsMaxSize_ShouldReturnFileTooLarge() - { - // Arrange - _stubHttpMessageHandler.SetResponse(HttpStatusCode.OK, new byte[MAX_ARTWORK_SIZE_BYTES + 1]); - - // Act - Result result = await _sut.SaveBookArtworkAsync(Guid.NewGuid(), Guid.NewGuid(), "Library", "Author", "Title", _artworkDtoFixture.Create(remoteUrl: "http://artwork.example/cover.jpg"), CancellationToken.None); - - // Assert - Assert.True(result.IsFailure); - Assert.Equal(Errors.FileSystemManagement.FileTooLarge, result.FirstError); - } - - [Fact] - public async Task SaveBookArtworkAsync_WhenArtworkHasBothLocalPathAndRemoteUrl_ShouldUseTheLocalFileWithoutDeletingIt() - { - // Arrange - Guid libraryId = Guid.NewGuid(); - Guid bookId = Guid.NewGuid(); - string libraryName = "Test Library"; - string authorName = "Test Author"; - string bookTitle = "Test Book"; - - string sourcePath = CreateTempImageFile(smallImageBytes: 1024); - try - { - _mockFileProviderService.FileExists(Arg.Any()).Returns(Result.From(true)); - _mockFileTypeService.GetImageTypeAsync(Arg.Any(), Arg.Any()) - .Returns(Result.From(ImageType.JPEG)); - - string artworkDirectoryPath = BuildArtworkDirectoryPath(libraryId, bookId, libraryName, authorName, bookTitle); - MockArtworkDirectoryStubs(artworkDirectoryPath); - - FileSystemPathId renamedFileId = _fileSystemPathIdFixture.Create(Path.Combine(artworkDirectoryPath, "cover.jpeg")); - _mockFileProviderService.CopyFile(Arg.Any(), Arg.Any(), true) - .Returns(Result.From(_fileSystemPathIdFixture.Create(Path.Combine(artworkDirectoryPath, "cover.jpg")))); - _mockFileProviderService.RenameFile(Arg.Any(), "cover.jpeg") - .Returns(Result.From(renamedFileId)); - - // Act - Result result = await _sut.SaveBookArtworkAsync(libraryId, bookId, libraryName, authorName, bookTitle, _artworkDtoFixture.Create(localPath: sourcePath, remoteUrl: "http://artwork.example/cover.jpg"), CancellationToken.None); - - // Assert - Assert.False(result.IsFailure); - Assert.True(File.Exists(sourcePath)); - _mockFileProviderService.Received(1).CopyFile( - Arg.Is(pathId => pathId.Path == sourcePath), - Arg.Any(), - true); - } - finally - { - File.Delete(sourcePath); - } - } - - [Fact] - public async Task SaveBookArtworkAsync_WhenRemoteDownloadIsCancelled_ShouldRethrowCancellation() - { - // Arrange - CancellationTokenSource cancellationTokenSource = new(); - cancellationTokenSource.Cancel(); - - // Act - async Task Act() - { - await _sut.SaveBookArtworkAsync(Guid.NewGuid(), Guid.NewGuid(), "Library", "Author", "Title", _artworkDtoFixture.Create(remoteUrl: "http://artwork.example/cover.jpg"), cancellationTokenSource.Token); - } - - // Assert - await Assert.ThrowsAnyAsync(Act); + _mockFileProviderService.DidNotReceive().DeleteFile(Arg.Any()); } [Fact] @@ -456,7 +195,7 @@ public class BookArtworkServiceTests _mockPathService.CombinePath(Arg.Any(), Arg.Any()) .Returns(callInfo => Result.From(Path.Combine(callInfo.ArgAt(0), callInfo.ArgAt(1)))); - // every directory except the artwork directory itself already exists, so that only the final directory is created + // Every directory except the artwork directory itself already exists, so that only the final directory is created. _mockDirectoryProviderService.DirectoryExists(Arg.Any()) .Returns(callInfo => Result.From(!string.Equals(callInfo.Arg().Path, artworkDirectoryPath, StringComparison.OrdinalIgnoreCase))); _mockDirectoryProviderService.CreateDirectory(Arg.Any(), Arg.Any()) @@ -485,57 +224,4 @@ public class BookArtworkServiceTests authorName, $"{bookTitle}-{bookId}"); } - - /// - /// Creates a temporary image file with the given size and returns its path. - /// - /// The size of the temporary image file, in bytes. - /// The file system path of the created temporary image file. - private static string CreateTempImageFile(int smallImageBytes) - { - string sourcePath = Path.Combine(Path.GetTempPath(), $"lumina-artwork-source-{Guid.NewGuid():N}.jpg"); - File.WriteAllBytes(sourcePath, new byte[smallImageBytes]); - return sourcePath; - } - - /// - /// Creates a file system link that points to the target directory: a junction on Windows, and a symbolic link on Unix-like platforms. - /// - /// The file system path of the link to create. - /// The file system path of the directory the link points to. - /// when the link was created, otherwise. - private static bool TryCreateJunction(string linkPath, string targetDirectory) - { - try - { - System.Diagnostics.ProcessStartInfo startInfo = OperatingSystem.IsWindows() - ? new() - { - FileName = "cmd.exe", - Arguments = $"/c mklink /J \"{linkPath}\" \"{targetDirectory}\"", - CreateNoWindow = true, - UseShellExecute = false - } - : new() - { - FileName = "ln", - CreateNoWindow = true, - UseShellExecute = false - }; - if (!OperatingSystem.IsWindows()) - { - startInfo.ArgumentList.Add("-s"); - startInfo.ArgumentList.Add(targetDirectory); - startInfo.ArgumentList.Add(linkPath); - } - - System.Diagnostics.Process process = System.Diagnostics.Process.Start(startInfo)!; - process.WaitForExit(5000); - return process.ExitCode == 0; - } - catch (Exception) - { - return false; - } - } } diff --git a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Reading/BookReadingServiceTests.cs b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Reading/BookReadingServiceTests.cs index 3c06b4b0..29bcf855 100644 --- a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Reading/BookReadingServiceTests.cs +++ b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Reading/BookReadingServiceTests.cs @@ -3,11 +3,8 @@ using Lumina.Application.Common.DataAccess.Entities.Plugins; using Lumina.Application.Common.DataAccess.Repositories.Plugins; using Lumina.Application.Common.DataAccess.UoW; using Lumina.Application.Common.Infrastructure.Plugins; -using Lumina.Application.Common.Infrastructure.Reading; -using Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Reading; using Lumina.Application.Fixtures.Common.DataAccess.Entities.Plugins; using Lumina.Contracts.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary.Reading; -using Lumina.Contracts.Fixtures.Core.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary.Reading; using Lumina.Contracts.Responses.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Reading; using Lumina.Domain.Common.Errors; using Lumina.Domain.Common.Primitives; @@ -19,10 +16,7 @@ using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; 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 @@ -33,7 +27,7 @@ namespace Lumina.Infrastructure.UnitTests.Core.MediaLibrary.WrittenContentLibrar /// Contains unit tests for the class. /// [ExcludeFromCodeCoverage] -public class BookReadingServiceTests : IDisposable +public class BookReadingServiceTests { private readonly IPluginManager _mockPluginManager; private readonly IPlugin _mockPlugin; @@ -42,14 +36,11 @@ public class BookReadingServiceTests : IDisposable private readonly ILibraryBookReaderConfigurationRepository _mockConfigurationRepository; private readonly IServiceProvider _serviceProvider; private readonly BookReadingService _sut; - private readonly TestBookReaderEnablementCache _enablementCache = new(); + private readonly BookReaderEnablementCache _enablementCache = new(); private readonly Guid _pluginId = Guid.NewGuid(); private readonly Guid _bookId = Guid.NewGuid(); private readonly Guid _libraryId = Guid.NewGuid(); private readonly string _bookPath; - private readonly ReadingDocumentDtoFixture _readingDocumentDtoFixture = new(); - private readonly ReadingSpineItemDtoFixture _readingSpineItemDtoFixture = new(); - private readonly ReadingResourceInfoDtoFixture _readingResourceInfoDtoFixture = new(); private readonly LibraryBookReaderConfigurationEntityFixture _configurationEntityFixture = new(); /// @@ -79,136 +70,12 @@ public class BookReadingServiceTests : IDisposable _serviceProvider = services.BuildServiceProvider(); IServiceScopeFactory serviceScopeFactory = _serviceProvider.GetRequiredService(); - _bookPath = Path.Combine(Path.GetTempPath(), $"lumina-test-book-{Guid.NewGuid():N}.epub"); - File.WriteAllText(_bookPath, "test epub content"); + // The resolution and enablement guards under test stop before the book file is probed, so no real file is needed. + _bookPath = $"lumina-test-book-{Guid.NewGuid():N}.epub"; _sut = new BookReadingService(_serviceProvider, _mockPluginManager, _enablementCache, serviceScopeFactory, Substitute.For>()); } - [Fact] - public async Task GetManifestAsync_WhenBookIsNotCached_ShouldExtractAndReturnTheManifest() - { - // Arrange - ReadingDocumentDto document = CreateExtractableDocument(); - StubOpenAsyncToExtract(document); - CancellationToken cancellationToken = CancellationToken.None; - - // Act - Result result = await _sut.GetManifestAsync(_bookId, _libraryId, _bookPath, LibraryType.EBook, shouldRenderPdfAsImages: false, cancellationToken); - - // Assert - Assert.False(result.IsFailure); - Assert.Equal(document.Title, result.Value.Title); - Assert.Equal(document.Author, result.Value.Author); - await _mockReader.Received(1).OpenAsync(_bookPath, Arg.Any(), Arg.Any(), cancellationToken); - } - - [Fact] - public async Task GetManifestAsync_WhenFileIsUnchanged_ShouldReuseTheCachedDocument() - { - // Arrange - ReadingDocumentDto document = CreateExtractableDocument(); - StubOpenAsyncToExtract(document); - CancellationToken cancellationToken = CancellationToken.None; - - // Act - await _sut.GetManifestAsync(_bookId, _libraryId, _bookPath, LibraryType.EBook, shouldRenderPdfAsImages: false, cancellationToken); - Result secondResult = await _sut.GetManifestAsync(_bookId, _libraryId, _bookPath, LibraryType.EBook, shouldRenderPdfAsImages: false, cancellationToken); - - // Assert - Assert.False(secondResult.IsFailure); - await _mockReader.Received(1).OpenAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()); - } - - [Fact] - public async Task GetManifestAsync_WhenFileChanged_ShouldReExtractTheBook() - { - // Arrange - ReadingDocumentDto document = CreateExtractableDocument(); - StubOpenAsyncToExtract(document); - CancellationToken cancellationToken = CancellationToken.None; - - // Act - await _sut.GetManifestAsync(_bookId, _libraryId, _bookPath, LibraryType.EBook, shouldRenderPdfAsImages: false, cancellationToken); - File.WriteAllText(_bookPath, "modified epub content, longer than before"); - Result secondResult = await _sut.GetManifestAsync(_bookId, _libraryId, _bookPath, LibraryType.EBook, shouldRenderPdfAsImages: false, cancellationToken); - - // Assert - Assert.False(secondResult.IsFailure); - await _mockReader.Received(2).OpenAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()); - } - - [Fact] - public async Task GetManifestAsync_WhenRenderingPreferenceDiffers_ShouldExtractTheBookTwice() - { - // Arrange - ReadingDocumentDto document = CreateExtractableDocument(); - StubOpenAsyncToExtract(document); - CancellationToken cancellationToken = CancellationToken.None; - - // Act - await _sut.GetManifestAsync(_bookId, _libraryId, _bookPath, LibraryType.EBook, shouldRenderPdfAsImages: false, cancellationToken); - Result secondResult = await _sut.GetManifestAsync(_bookId, _libraryId, _bookPath, LibraryType.EBook, shouldRenderPdfAsImages: true, cancellationToken); - - // Assert - Assert.False(secondResult.IsFailure); - await _mockReader.Received(2).OpenAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()); - await _mockReader.Received(1).OpenAsync(Arg.Any(), Arg.Any(), false, Arg.Any()); - await _mockReader.Received(1).OpenAsync(Arg.Any(), Arg.Any(), true, Arg.Any()); - } - - [Fact] - public async Task GetManifestAsync_WhenBothRenderingPreferencesAreExtracted_ShouldKeepTheirWorkingDirectoriesSeparate() - { - // Arrange - ReadingDocumentDto document = CreateExtractableDocument(); - StubOpenAsyncToExtract(document); - CancellationToken cancellationToken = CancellationToken.None; - - // Act - await _sut.GetManifestAsync(_bookId, _libraryId, _bookPath, LibraryType.EBook, shouldRenderPdfAsImages: false, cancellationToken); - await _sut.GetManifestAsync(_bookId, _libraryId, _bookPath, LibraryType.EBook, shouldRenderPdfAsImages: true, cancellationToken); - // The text extraction must survive the image extraction of the same book, and still be served from the cache. - Result thirdResult = await _sut.GetManifestAsync(_bookId, _libraryId, _bookPath, LibraryType.EBook, shouldRenderPdfAsImages: false, cancellationToken); - - // Assert - Assert.False(thirdResult.IsFailure); - string textWorkingDirectory = Path.Combine(ReadingCachePaths.GetRootDirectory(), _bookId.ToString("N"), "text"); - string imageWorkingDirectory = Path.Combine(ReadingCachePaths.GetRootDirectory(), _bookId.ToString("N"), "images"); - Assert.True(File.Exists(Path.Combine(textWorkingDirectory, "sections", "0.html"))); - Assert.True(File.Exists(Path.Combine(imageWorkingDirectory, "sections", "0.html"))); - await _mockReader.Received(2).OpenAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()); - } - - [Fact] - public async Task GetManifestAsync_WhenConcurrentRequests_ShouldShareASingleExtraction() - { - // Arrange - ReadingDocumentDto document = CreateExtractableDocument(); - TaskCompletionSource extractionStarted = new(); - TaskCompletionSource allowExtractionToFinish = new(); - _mockReader.OpenAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()) - .Returns(callInfo => Task.Run(async () => - { - extractionStarted.SetResult(true); - await allowExtractionToFinish.Task; - return document; - })); - - // Act - Task> firstTask = _sut.GetManifestAsync(_bookId, _libraryId, _bookPath, LibraryType.EBook, shouldRenderPdfAsImages: false, CancellationToken.None); - await extractionStarted.Task; - Task> secondTask = _sut.GetManifestAsync(_bookId, _libraryId, _bookPath, LibraryType.EBook, shouldRenderPdfAsImages: false, CancellationToken.None); - allowExtractionToFinish.SetResult(true); - Result firstResult = await firstTask; - Result secondResult = await secondTask; - - // Assert - Assert.False(firstResult.IsFailure); - Assert.False(secondResult.IsFailure); - await _mockReader.Received(1).OpenAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()); - } - [Fact] public async Task GetManifestAsync_WhenNoReaderSupportsTheFormat_ShouldReturnNoReaderAvailableError() { @@ -241,284 +108,34 @@ public class BookReadingServiceTests : IDisposable } [Fact] - public async Task GetSectionAsync_WhenSectionExists_ShouldReturnSanitizedContent() + public async Task GetManifestAsync_WhenConfigurationsReadFails_ShouldReturnError() { // Arrange - ReadingDocumentDto document = CreateExtractableDocument(); - StubOpenAsyncToExtract(document); - CancellationToken cancellationToken = CancellationToken.None; - - // Act - Result result = await _sut.GetSectionAsync(_bookId, _libraryId, _bookPath, LibraryType.EBook, "section-1", shouldRenderPdfAsImages: false, shouldPreserveStyles: false, cancellationToken); - - // Assert - Assert.False(result.IsFailure); - Assert.Equal("section-1", result.Value.LocationRef); - Assert.Contains("Chapter 1", result.Value.ContentHtml, StringComparison.Ordinal); - } - - [Fact] - public async Task GetSectionAsync_WhenSectionDoesNotExist_ShouldReturnSectionNotFoundError() - { - // Arrange - ReadingDocumentDto document = CreateExtractableDocument(); - StubOpenAsyncToExtract(document); - - // Act - Result result = await _sut.GetSectionAsync(_bookId, _libraryId, _bookPath, LibraryType.EBook, "missing-section", shouldRenderPdfAsImages: false, shouldPreserveStyles: false, CancellationToken.None); - - // Assert - Assert.True(result.IsFailure); - Assert.Equal(Errors.Reading.SectionNotFound, result.FirstError); - } - - [Fact] - public async Task GetSectionAsync_WhenSectionFileDoesNotExist_ShouldReturnSectionNotFoundError() - { - // Arrange - ReadingDocumentDto document = _readingDocumentDtoFixture.Create( - title: "Test Book", - tableOfContents: [], - spine: - [ - _readingSpineItemDtoFixture.Create(locationRef: "section-1", title: "Chapter 1", relativeSectionFilePath: "sections/missing.html") - ], - resources: new Dictionary() - ); - StubOpenAsyncToExtract(document); - - // Act - Result result = await _sut.GetSectionAsync(_bookId, _libraryId, _bookPath, LibraryType.EBook, "section-1", shouldRenderPdfAsImages: false, shouldPreserveStyles: false, CancellationToken.None); - - // Assert - Assert.True(result.IsFailure); - Assert.Equal(Errors.Reading.SectionNotFound, result.FirstError); - } - - [Fact] - public async Task GetSectionAsync_WhenSectionPathEscapesTheWorkingDirectory_ShouldReturnSectionNotFoundError() - { - // Arrange - ReadingDocumentDto document = _readingDocumentDtoFixture.Create( - title: "Test Book", - tableOfContents: [], - spine: - [ - _readingSpineItemDtoFixture.Create(locationRef: "section-1", title: "Chapter 1", relativeSectionFilePath: "../../escape.html") - ], - resources: new Dictionary() - ); - StubOpenAsyncToExtract(document); - - // Act - Result result = await _sut.GetSectionAsync(_bookId, _libraryId, _bookPath, LibraryType.EBook, "section-1", shouldRenderPdfAsImages: false, shouldPreserveStyles: false, CancellationToken.None); - - // Assert - Assert.True(result.IsFailure); - Assert.Equal(Errors.Reading.SectionNotFound, result.FirstError); - } - - [Fact] - public async Task GetResourceAsync_WhenResourceDoesNotExistInTheDocument_ShouldReturnResourceNotFoundError() - { - // Arrange - ReadingDocumentDto document = CreateExtractableDocument(); - StubOpenAsyncToExtract(document); - - // Act - Result result = await _sut.GetResourceAsync(_bookId, _libraryId, _bookPath, LibraryType.EBook, "missing-key", shouldRenderPdfAsImages: false, CancellationToken.None); - - // Assert - Assert.True(result.IsFailure); - Assert.Equal(Errors.Reading.ResourceNotFound, result.FirstError); - await _mockReader.DidNotReceive().GetResourceAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()); - } - - [Fact] - public async Task GetResourceAsync_WhenResourcePathEscapesTheWorkingDirectory_ShouldReturnResourceNotFoundError() - { - // Arrange - ReadingDocumentDto document = _readingDocumentDtoFixture.Create( - title: "Test Book", - tableOfContents: [], - spine: [], - resources: new Dictionary - { - ["escaping"] = _readingResourceInfoDtoFixture.Create(relativeFilePath: "../../escape.png", mimeType: "image/png") - } - ); - StubOpenAsyncToExtract(document); - - // Act - Result result = await _sut.GetResourceAsync(_bookId, _libraryId, _bookPath, LibraryType.EBook, "escaping", shouldRenderPdfAsImages: false, CancellationToken.None); - - // Assert - Assert.True(result.IsFailure); - Assert.Equal(Errors.Reading.ResourceNotFound, result.FirstError); - await _mockReader.DidNotReceive().GetResourceAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()); - } - - [Fact] - public async Task GetResourceAsync_WhenResourceFileAlreadyExists_ShouldServeItFromDiskWithoutCallingTheReader() - { - // Arrange - ReadingDocumentDto document = CreateExtractableDocument(); - StubOpenAsyncToExtract(document); - await _sut.GetManifestAsync(_bookId, _libraryId, _bookPath, LibraryType.EBook, shouldRenderPdfAsImages: false, CancellationToken.None); - string workingDirectory = Path.Combine(ReadingCachePaths.GetRootDirectory(), _bookId.ToString("N"), "text"); - string resourceFilePath = Path.Combine(workingDirectory, "resources", "cover.png"); - Directory.CreateDirectory(Path.GetDirectoryName(resourceFilePath)!); - File.WriteAllBytes(resourceFilePath, [1, 2, 3]); - - // Act - Result result = await _sut.GetResourceAsync(_bookId, _libraryId, _bookPath, LibraryType.EBook, "cover", shouldRenderPdfAsImages: false, CancellationToken.None); - - // Assert - Assert.False(result.IsFailure); - Assert.Equal(new byte[] { 1, 2, 3 }, result.Value.Data); - Assert.Equal("image/png", result.Value.MimeType); - await _mockReader.DidNotReceive().GetResourceAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()); - } - - [Fact] - public async Task GetResourceAsync_WhenResourceFileDoesNotExist_ShouldProduceItAndCacheItToDisk() - { - // Arrange - ReadingDocumentDto document = CreateExtractableDocument(); - StubOpenAsyncToExtract(document); - byte[] producedResource = [4, 5, 6]; - _mockReader.GetResourceAsync(Arg.Any(), Arg.Any(), "cover", Arg.Any()).Returns(producedResource); - - // Act - Result firstResult = await _sut.GetResourceAsync(_bookId, _libraryId, _bookPath, LibraryType.EBook, "cover", shouldRenderPdfAsImages: false, CancellationToken.None); - Result secondResult = await _sut.GetResourceAsync(_bookId, _libraryId, _bookPath, LibraryType.EBook, "cover", shouldRenderPdfAsImages: false, CancellationToken.None); - - // Assert - Assert.False(firstResult.IsFailure); - Assert.Equal(new byte[] { 4, 5, 6 }, firstResult.Value.Data); - Assert.Equal("image/png", firstResult.Value.MimeType); - Assert.False(secondResult.IsFailure); - Assert.Equal(new byte[] { 4, 5, 6 }, secondResult.Value.Data); - Assert.Equal("image/png", secondResult.Value.MimeType); - await _mockReader.Received(1).GetResourceAsync(_bookPath, Arg.Any(), "cover", Arg.Any()); - string cachedFilePath = Path.Combine(ReadingCachePaths.GetRootDirectory(), _bookId.ToString("N"), "text", "resources", "cover.png"); - Assert.True(File.Exists(cachedFilePath)); - Assert.Equal(new byte[] { 4, 5, 6 }, File.ReadAllBytes(cachedFilePath)); - } - - [Fact] - public async Task GetResourceAsync_WhenReaderIsDisabledForTheLibrary_ShouldReturnReaderDisabledError() - { - // Arrange - ReadingDocumentDto document = CreateExtractableDocument(); - StubOpenAsyncToExtract(document); _mockConfigurationRepository.GetByLibraryAndPluginIdAsync(_libraryId, _pluginId, Arg.Any()) - .Returns(Result.From(null)); - // The resource already exists on disk, from an earlier extraction, but the enablement is read on every request, so it must not be served. - string workingDirectory = Path.Combine(ReadingCachePaths.GetRootDirectory(), _bookId.ToString("N"), "text"); - string resourceFilePath = Path.Combine(workingDirectory, "resources", "cover.png"); - Directory.CreateDirectory(Path.GetDirectoryName(resourceFilePath)!); - File.WriteAllBytes(resourceFilePath, [1, 2, 3]); + .Returns(Error.Failure("Reading.Error", "Failed to read the configuration")); // Act - Result result = await _sut.GetResourceAsync(_bookId, _libraryId, _bookPath, LibraryType.EBook, "cover", shouldRenderPdfAsImages: false, CancellationToken.None); + Result result = await _sut.GetManifestAsync(_bookId, _libraryId, _bookPath, LibraryType.EBook, shouldRenderPdfAsImages: false, CancellationToken.None); // Assert Assert.True(result.IsFailure); - Assert.Equal(Errors.Reading.ReaderDisabled, result.FirstError); - await _mockReader.DidNotReceive().GetResourceAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()); + Assert.Equal("Reading.Error", result.FirstError.Code); + await _mockReader.DidNotReceive().OpenAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()); } [Fact] - public async Task GetResourceAsync_WhenEnablementCacheSaysDisabledAndResourceFileAlreadyExists_ShouldNotServeTheResource() + public async Task GetSectionAsync_WhenNoReaderSupportsTheFormat_ShouldReturnNoReaderAvailableError() { // Arrange - ReadingDocumentDto document = CreateExtractableDocument(); - StubOpenAsyncToExtract(document); - // The reader was disabled after the book was extracted, so the enablement cache already knows it; the request must be cut - // off before the already extracted resource on disk is considered, and without consulting the database again. - _enablementCache.Set(_libraryId, _pluginId, isEnabled: false); - string workingDirectory = Path.Combine(ReadingCachePaths.GetRootDirectory(), _bookId.ToString("N"), "text"); - string resourceFilePath = Path.Combine(workingDirectory, "resources", "cover.png"); - Directory.CreateDirectory(Path.GetDirectoryName(resourceFilePath)!); - File.WriteAllBytes(resourceFilePath, [1, 2, 3]); + _mockPluginManager.GetPlugins().Returns([]); // Act - Result result = await _sut.GetResourceAsync(_bookId, _libraryId, _bookPath, LibraryType.EBook, "cover", shouldRenderPdfAsImages: false, CancellationToken.None); + Result result = await _sut.GetSectionAsync(_bookId, _libraryId, _bookPath, LibraryType.EBook, "section-1", shouldRenderPdfAsImages: false, shouldPreserveStyles: false, CancellationToken.None); // Assert Assert.True(result.IsFailure); - Assert.Equal(Errors.Reading.ReaderDisabled, result.FirstError); - await _mockReader.DidNotReceive().GetResourceAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()); - await _mockConfigurationRepository.DidNotReceive().GetByLibraryAndPluginIdAsync(Arg.Any(), Arg.Any(), Arg.Any()); - } - - [Fact] - public async Task GetResourceAsync_WhenReaderThrowsWhileProducingTheResource_ShouldReturnResourceProductionFailedError() - { - // Arrange - ReadingDocumentDto document = CreateExtractableDocument(); - StubOpenAsyncToExtract(document); - _mockReader.GetResourceAsync(Arg.Any(), Arg.Any(), "cover", Arg.Any()) - .Returns(Task.FromException(new InvalidOperationException("The page renderer failed"))); - - // Act - Result result = await _sut.GetResourceAsync(_bookId, _libraryId, _bookPath, LibraryType.EBook, "cover", shouldRenderPdfAsImages: false, CancellationToken.None); - - // Assert - Assert.True(result.IsFailure); - Assert.Equal("Reading.ResourceProductionFailed", result.FirstError.Code); - await _mockReader.Received(1).GetResourceAsync(Arg.Any(), Arg.Any(), "cover", Arg.Any()); - } - - [Fact] - public async Task GetResourceAsync_WhenReaderProductionIsCancelled_ShouldPropagateTheCancellation() - { - // Arrange - ReadingDocumentDto document = CreateExtractableDocument(); - StubOpenAsyncToExtract(document); - _mockReader.GetResourceAsync(Arg.Any(), Arg.Any(), "cover", Arg.Any()) - .Returns(Task.FromException(new OperationCanceledException())); - - // Act - Task> operationTask = _sut.GetResourceAsync(_bookId, _libraryId, _bookPath, LibraryType.EBook, "cover", shouldRenderPdfAsImages: false, CancellationToken.None); - - // Assert - await Assert.ThrowsAnyAsync(() => operationTask); - } - - [Fact] - public async Task GetSectionAsync_WhenStylesArePreserved_ShouldKeepTheStyleAttributeInTheContent() - { - // Arrange - ReadingDocumentDto document = CreateExtractableDocument(); - StubOpenAsyncToExtractStyledContent(document); - CancellationToken cancellationToken = CancellationToken.None; - - // Act - Result result = await _sut.GetSectionAsync(_bookId, _libraryId, _bookPath, LibraryType.EBook, "section-1", shouldRenderPdfAsImages: false, shouldPreserveStyles: true, cancellationToken); - - // Assert - Assert.False(result.IsFailure); - Assert.Contains("style", result.Value.ContentHtml, StringComparison.OrdinalIgnoreCase); - } - - [Fact] - public async Task GetSectionAsync_WhenStylesAreNotPreserved_ShouldStripTheStyleAttributeFromTheContent() - { - // Arrange - ReadingDocumentDto document = CreateExtractableDocument(); - StubOpenAsyncToExtractStyledContent(document); - CancellationToken cancellationToken = CancellationToken.None; - - // Act - Result result = await _sut.GetSectionAsync(_bookId, _libraryId, _bookPath, LibraryType.EBook, "section-1", shouldRenderPdfAsImages: false, shouldPreserveStyles: false, cancellationToken); - - // Assert - Assert.False(result.IsFailure); - Assert.DoesNotContain("style", result.Value.ContentHtml, StringComparison.OrdinalIgnoreCase); - Assert.DoesNotContain("color:red", result.Value.ContentHtml, StringComparison.OrdinalIgnoreCase); - Assert.Contains("Chapter 1", result.Value.ContentHtml, StringComparison.Ordinal); + Assert.Equal(Errors.Reading.NoReaderAvailable, result.FirstError); + await _mockReader.DidNotReceive().OpenAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()); } [Fact] @@ -567,250 +184,4 @@ public class BookReadingServiceTests : IDisposable Assert.False(result.Value.IsAvailable); Assert.Equal(nameof(Errors.Reading.ReaderDisabled), result.Value.ErrorCode); } - - [Fact] - public async Task GetManifestAsync_WhenReaderOpenThrowsFileNotFoundException_ShouldReturnBookFileNotFoundError() - { - // Arrange - _mockReader.OpenAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()) - .Returns(Task.FromException(new FileNotFoundException("book missing"))); - - // Act - Result result = await _sut.GetManifestAsync(_bookId, _libraryId, _bookPath, LibraryType.EBook, shouldRenderPdfAsImages: false, CancellationToken.None); - - // Assert - Assert.True(result.IsFailure); - Assert.Equal(Errors.Reading.BookFileNotFound, result.FirstError); - } - - [Fact] - public async Task GetManifestAsync_WhenReaderOpenThrowsDirectoryNotFoundException_ShouldReturnBookFileNotFoundError() - { - // Arrange - _mockReader.OpenAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()) - .Returns(Task.FromException(new DirectoryNotFoundException("directory missing"))); - - // Act - Result result = await _sut.GetManifestAsync(_bookId, _libraryId, _bookPath, LibraryType.EBook, shouldRenderPdfAsImages: false, CancellationToken.None); - - // Assert - Assert.True(result.IsFailure); - Assert.Equal(Errors.Reading.BookFileNotFound, result.FirstError); - } - - [Fact] - public async Task GetManifestAsync_WhenReaderOpenThrowsOtherException_ShouldReturnExtractionFailedError() - { - // Arrange - _mockReader.OpenAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()) - .Returns(Task.FromException(new InvalidDataException("broken book"))); - - // Act - Result result = await _sut.GetManifestAsync(_bookId, _libraryId, _bookPath, LibraryType.EBook, shouldRenderPdfAsImages: false, CancellationToken.None); - - // Assert - Assert.True(result.IsFailure); - Assert.Equal("Reading.ExtractionFailed", result.FirstError.Code); - } - - [Fact] - public async Task GetManifestAsync_WhenReaderOpenIsCancelled_ShouldPropagateTheCancellation() - { - // Arrange - _mockReader.OpenAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()) - .Returns(Task.FromException(new OperationCanceledException())); - - // Act - Task> operationTask = _sut.GetManifestAsync(_bookId, _libraryId, _bookPath, LibraryType.EBook, shouldRenderPdfAsImages: false, CancellationToken.None); - - // Assert - await Assert.ThrowsAnyAsync(() => operationTask); - } - - [Fact] - public async Task GetManifestAsync_WhenBookFileIsDeletedAfterExtraction_ShouldReExtractAndFail() - { - // Arrange - ReadingDocumentDto document = CreateExtractableDocument(); - StubOpenAsyncToExtract(document); - await _sut.GetManifestAsync(_bookId, _libraryId, _bookPath, LibraryType.EBook, shouldRenderPdfAsImages: false, CancellationToken.None); - _mockReader.OpenAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()) - .Returns(Task.FromException(new FileNotFoundException("book missing"))); - File.Delete(_bookPath); - - // Act - Result result = await _sut.GetManifestAsync(_bookId, _libraryId, _bookPath, LibraryType.EBook, shouldRenderPdfAsImages: false, CancellationToken.None); - - // Assert - Assert.True(result.IsFailure); - Assert.Equal(Errors.Reading.BookFileNotFound, result.FirstError); - await _mockReader.Received(2).OpenAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()); - } - - [Fact] - public async Task GetManifestAsync_WhenConfigurationsReadFails_ShouldReturnError() - { - // Arrange - _mockConfigurationRepository.GetByLibraryAndPluginIdAsync(_libraryId, _pluginId, Arg.Any()) - .Returns(Error.Failure("Reading.Error", "Failed to read the configuration")); - - // Act - Result result = await _sut.GetManifestAsync(_bookId, _libraryId, _bookPath, LibraryType.EBook, shouldRenderPdfAsImages: false, CancellationToken.None); - - // Assert - Assert.True(result.IsFailure); - Assert.Equal("Reading.Error", result.FirstError.Code); - await _mockReader.DidNotReceive().OpenAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()); - } - - [Fact] - public async Task GetManifestAsync_WhenReaderMatchesExtensionCaseInsensitively_ShouldResolveIt() - { - // Arrange - string uppercaseExtensionPath = Path.Combine(Path.GetTempPath(), $"lumina-test-book-{Guid.NewGuid():N}.EPUB"); - File.WriteAllText(uppercaseExtensionPath, "test epub content"); - try - { - ReadingDocumentDto document = CreateExtractableDocument(); - StubOpenAsyncToExtract(document); - - // Act - Result result = await _sut.GetManifestAsync(_bookId, _libraryId, uppercaseExtensionPath, LibraryType.EBook, shouldRenderPdfAsImages: false, CancellationToken.None); - - // Assert - Assert.False(result.IsFailure); - } - finally - { - File.Delete(uppercaseExtensionPath); - } - } - - [Fact] - public async Task GetManifestAsync_WhenReaderSupportsTheLibraryTypeButNotTheExtension_ShouldReturnNoReaderAvailableError() - { - // Arrange - string unsupportedExtensionPath = Path.Combine(Path.GetTempPath(), $"lumina-test-book-{Guid.NewGuid():N}.txt"); - File.WriteAllText(unsupportedExtensionPath, "test content"); - try - { - // Act - Result result = await _sut.GetManifestAsync(_bookId, _libraryId, unsupportedExtensionPath, LibraryType.EBook, shouldRenderPdfAsImages: false, CancellationToken.None); - - // Assert - Assert.True(result.IsFailure); - Assert.Equal(Errors.Reading.NoReaderAvailable, result.FirstError); - await _mockReader.DidNotReceive().OpenAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()); - } - finally - { - File.Delete(unsupportedExtensionPath); - } - } - - /// - /// Creates a reading document whose spine and resources are extractable into the working directory. - /// - /// The created reading document. - private ReadingDocumentDto CreateExtractableDocument() - { - return _readingDocumentDtoFixture.Create( - title: "Test Book", - author: "Test Author", - tableOfContents: [], - spine: - [ - _readingSpineItemDtoFixture.Create(locationRef: "section-1", title: "Chapter 1", relativeSectionFilePath: "sections/0.html") - ], - resources: new Dictionary - { - ["cover"] = _readingResourceInfoDtoFixture.Create(relativeFilePath: "resources/cover.png", mimeType: "image/png") - }, - hasTextContent: true - ); - } - - /// - /// Stubs the reader's OpenAsync to create the extractable files of the document into the working directory. - /// - /// The document returned by the extraction. - private void StubOpenAsyncToExtract(ReadingDocumentDto document) - { - _mockReader.OpenAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()) - .Returns(callInfo => - { - string workingDirectory = callInfo.ArgAt(1); - Directory.CreateDirectory(Path.Combine(workingDirectory, "sections")); - File.WriteAllText(Path.Combine(workingDirectory, "sections", "0.html"), "

Chapter 1

Some text.

"); - return Task.FromResult(document); - }); - } - - /// - /// Stubs the reader's OpenAsync to create a section whose content carries a style attribute, so that the sanitization - /// preference of the service is observable. - /// - /// The document returned by the extraction. - private void StubOpenAsyncToExtractStyledContent(ReadingDocumentDto document) - { - _mockReader.OpenAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()) - .Returns(callInfo => - { - string workingDirectory = callInfo.ArgAt(1); - Directory.CreateDirectory(Path.Combine(workingDirectory, "sections")); - File.WriteAllText(Path.Combine(workingDirectory, "sections", "0.html"), "

Chapter 1

Some text.

"); - return Task.FromResult(document); - }); - } - - /// - public void Dispose() - { - if (Directory.Exists(ReadingCachePaths.GetRootDirectory())) - Directory.Delete(ReadingCachePaths.GetRootDirectory(), recursive: true); - if (File.Exists(_bookPath)) - File.Delete(_bookPath); - (_serviceProvider as IDisposable)?.Dispose(); - } - - /// - /// In-memory test double for the used by the service under test. - /// - [ExcludeFromCodeCoverage] - private sealed class TestBookReaderEnablementCache : IBookReaderEnablementCache - { - private readonly Dictionary<(Guid LibraryId, Guid PluginId), bool> _enablements = []; - - /// - public bool? Get(Guid libraryId, Guid pluginId) - { - return _enablements.TryGetValue((libraryId, pluginId), out bool isEnabled) ? isEnabled : null; - } - - /// - public void Set(Guid libraryId, Guid pluginId, bool isEnabled) - { - _enablements[(libraryId, pluginId)] = isEnabled; - } - - /// - public void Invalidate(Guid libraryId, Guid pluginId) - { - _enablements.Remove((libraryId, pluginId)); - } - - /// - public void InvalidateLibrary(Guid libraryId) - { - foreach (Guid cachedPluginId in _enablements.Keys.Where(cachedPair => cachedPair.LibraryId == libraryId).Select(cachedPair => cachedPair.PluginId).ToList()) - _enablements.Remove((libraryId, cachedPluginId)); - } - - /// - public void InvalidatePlugin(Guid pluginId) - { - foreach (Guid cachedLibraryId in _enablements.Keys.Where(cachedPair => cachedPair.PluginId == pluginId).Select(cachedPair => cachedPair.LibraryId).ToList()) - _enablements.Remove((cachedLibraryId, pluginId)); - } - } } diff --git a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Plugins/MediaLibraryProviderConfigurationStoreTests.cs b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Plugins/MediaLibraryProviderConfigurationStoreTests.cs index 9d3f049e..d44a916c 100644 --- a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Plugins/MediaLibraryProviderConfigurationStoreTests.cs +++ b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Plugins/MediaLibraryProviderConfigurationStoreTests.cs @@ -736,6 +736,279 @@ public class MediaLibraryProviderConfigurationStoreTests Assert.True(result.IsFailure); } + [Fact] + public async Task RemoveProviderConfigurationsForLibraryAsync_WhenDeletingBookReadersFails_ShouldReturnError() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + _mockMetadataConfigurationRepository.DeleteByLibraryIdAsync(libraryId, Arg.Any()) + .Returns(Result.Deleted); + _mockArtworkConfigurationRepository.DeleteByLibraryIdAsync(libraryId, Arg.Any()) + .Returns(Result.Deleted); + _mockBookReaderConfigurationRepository.DeleteByLibraryIdAsync(libraryId, Arg.Any()) + .Returns(Error.Failure(description: "Failed to delete the configurations")); + MediaLibraryProviderConfigurationStore sut = CreateSut(); + + // Act + Result result = await sut.RemoveProviderConfigurationsForLibraryAsync(libraryId, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + _mockEnablementCache.DidNotReceive().InvalidateLibrary(Arg.Any()); + } + + [Fact] + public async Task RemoveProviderConfigurationsAsync_WhenDeletingBookReadersFails_ShouldReturnError() + { + // Arrange + Guid pluginId = Guid.NewGuid(); + _mockMetadataConfigurationRepository.DeleteByPluginIdAsync(pluginId, Arg.Any()) + .Returns(Result.Deleted); + _mockArtworkConfigurationRepository.DeleteByPluginIdAsync(pluginId, Arg.Any()) + .Returns(Result.Deleted); + _mockBookReaderConfigurationRepository.DeleteByPluginIdAsync(pluginId, Arg.Any()) + .Returns(Error.Failure(description: "Failed to delete the configurations")); + MediaLibraryProviderConfigurationStore sut = CreateSut(); + + // Act + Result result = await sut.RemoveProviderConfigurationsAsync(pluginId, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + _mockEnablementCache.DidNotReceive().InvalidatePlugin(Arg.Any()); + } + + [Fact] + public async Task ReconcileProviderConfigurationsAsync_WhenMetadataProviderIsAlreadyConfigured_ShouldKeepItWithoutUpserting() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + Guid pluginId = Guid.NewGuid(); + IPlugin plugin = CreatePlugin(pluginId, "Plugin"); + _mockPluginManager.GetPlugins().Returns([plugin]); + MediaLibraryProviderConfigurationStore sut = CreateSut((pluginId, CreateMetadataProvider(LibraryType.EBook), null, null)); + LibraryMetadataProviderConfigurationEntity existingConfiguration = _metadataConfigurationFixture.Create(libraryId, pluginId, 1); + _mockMetadataConfigurationRepository.GetByLibraryIdAsync(libraryId, Arg.Any()) + .Returns(Result.From>([existingConfiguration])); + _mockArtworkConfigurationRepository.GetByLibraryIdAsync(libraryId, Arg.Any()) + .Returns(Result.From>([])); + _mockBookReaderConfigurationRepository.GetByLibraryIdAsync(libraryId, Arg.Any()) + .Returns(Result.From>([])); + + // Act + Result result = await sut.ReconcileProviderConfigurationsAsync(libraryId, LibraryType.EBook, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + await _mockMetadataConfigurationRepository.DidNotReceive().UpsertAsync(Arg.Any(), Arg.Any()); + await _mockMetadataConfigurationRepository.DidNotReceive().DeleteByLibraryIdAndPluginIdsAsync(Arg.Any(), Arg.Any>(), Arg.Any()); + } + + [Fact] + public async Task ReconcileProviderConfigurationsAsync_WhenArtworkProviderIsAlreadyConfigured_ShouldKeepItWithoutUpserting() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + Guid pluginId = Guid.NewGuid(); + IPlugin plugin = CreatePlugin(pluginId, "Plugin"); + _mockPluginManager.GetPlugins().Returns([plugin]); + MediaLibraryProviderConfigurationStore sut = CreateSut((pluginId, null, CreateArtworkProvider(LibraryType.EBook), null)); + LibraryArtworkProviderConfigurationEntity existingConfiguration = _artworkConfigurationFixture.Create(libraryId, pluginId, 1); + _mockMetadataConfigurationRepository.GetByLibraryIdAsync(libraryId, Arg.Any()) + .Returns(Result.From>([])); + _mockArtworkConfigurationRepository.GetByLibraryIdAsync(libraryId, Arg.Any()) + .Returns(Result.From>([existingConfiguration])); + _mockBookReaderConfigurationRepository.GetByLibraryIdAsync(libraryId, Arg.Any()) + .Returns(Result.From>([])); + + // Act + Result result = await sut.ReconcileProviderConfigurationsAsync(libraryId, LibraryType.EBook, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + await _mockArtworkConfigurationRepository.DidNotReceive().UpsertAsync(Arg.Any(), Arg.Any()); + await _mockArtworkConfigurationRepository.DidNotReceive().DeleteByLibraryIdAndPluginIdsAsync(Arg.Any(), Arg.Any>(), Arg.Any()); + } + + [Fact] + public async Task ReconcileProviderConfigurationsAsync_WhenReadingMetadataConfigurationsFails_ShouldReturnError() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + Guid pluginId = Guid.NewGuid(); + IPlugin plugin = CreatePlugin(pluginId, "Plugin"); + _mockPluginManager.GetPlugins().Returns([plugin]); + MediaLibraryProviderConfigurationStore sut = CreateSut((pluginId, CreateMetadataProvider(LibraryType.EBook), null, null)); + _mockMetadataConfigurationRepository.GetByLibraryIdAsync(libraryId, Arg.Any()) + .Returns(Error.Failure(description: "Failed to read configurations")); + + // Act + Result result = await sut.ReconcileProviderConfigurationsAsync(libraryId, LibraryType.EBook, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + await _mockArtworkConfigurationRepository.DidNotReceive().GetByLibraryIdAsync(Arg.Any(), Arg.Any()); + await _mockBookReaderConfigurationRepository.DidNotReceive().GetByLibraryIdAsync(Arg.Any(), Arg.Any()); + } + + [Fact] + public async Task ReconcileProviderConfigurationsAsync_WhenDeletingStaleMetadataConfigurationsFails_ShouldReturnError() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + Guid pluginId = Guid.NewGuid(); + IPlugin plugin = CreatePlugin(pluginId, "Plugin"); + _mockPluginManager.GetPlugins().Returns([plugin]); + MediaLibraryProviderConfigurationStore sut = CreateSut((pluginId, CreateMetadataProvider(LibraryType.Book), null, null)); + LibraryMetadataProviderConfigurationEntity staleConfiguration = _metadataConfigurationFixture.Create(libraryId, pluginId, 1); + _mockMetadataConfigurationRepository.GetByLibraryIdAsync(libraryId, Arg.Any()) + .Returns(Result.From>([staleConfiguration])); + _mockMetadataConfigurationRepository.DeleteByLibraryIdAndPluginIdsAsync(libraryId, Arg.Any>(), Arg.Any()) + .Returns(Error.Failure(description: "Failed to delete the configurations")); + + // Act + Result result = await sut.ReconcileProviderConfigurationsAsync(libraryId, LibraryType.EBook, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + } + + [Fact] + public async Task ReconcileProviderConfigurationsAsync_WhenUpsertingMetadataConfigurationFails_ShouldReturnError() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + Guid pluginId = Guid.NewGuid(); + IPlugin plugin = CreatePlugin(pluginId, "Plugin"); + _mockPluginManager.GetPlugins().Returns([plugin]); + MediaLibraryProviderConfigurationStore sut = CreateSut((pluginId, CreateMetadataProvider(LibraryType.EBook), null, null)); + _mockMetadataConfigurationRepository.GetByLibraryIdAsync(libraryId, Arg.Any()) + .Returns(Result.From>([])); + _mockMetadataConfigurationRepository.UpsertAsync(Arg.Any(), Arg.Any()) + .Returns(Error.Failure(description: "Failed to persist the configuration")); + + // Act + Result result = await sut.ReconcileProviderConfigurationsAsync(libraryId, LibraryType.EBook, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + await _mockArtworkConfigurationRepository.DidNotReceive().GetByLibraryIdAsync(Arg.Any(), Arg.Any()); + } + + [Fact] + public async Task ReconcileProviderConfigurationsAsync_WhenReadingArtworkConfigurationsFails_ShouldReturnError() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + Guid pluginId = Guid.NewGuid(); + IPlugin plugin = CreatePlugin(pluginId, "Plugin"); + _mockPluginManager.GetPlugins().Returns([plugin]); + MediaLibraryProviderConfigurationStore sut = CreateSut((pluginId, null, CreateArtworkProvider(LibraryType.EBook), null)); + _mockMetadataConfigurationRepository.GetByLibraryIdAsync(libraryId, Arg.Any()) + .Returns(Result.From>([])); + _mockArtworkConfigurationRepository.GetByLibraryIdAsync(libraryId, Arg.Any()) + .Returns(Error.Failure(description: "Failed to read configurations")); + + // Act + Result result = await sut.ReconcileProviderConfigurationsAsync(libraryId, LibraryType.EBook, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + await _mockBookReaderConfigurationRepository.DidNotReceive().GetByLibraryIdAsync(Arg.Any(), Arg.Any()); + } + + [Fact] + public async Task ReconcileProviderConfigurationsAsync_WhenUpsertingArtworkConfigurationFails_ShouldReturnError() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + Guid pluginId = Guid.NewGuid(); + IPlugin plugin = CreatePlugin(pluginId, "Plugin"); + _mockPluginManager.GetPlugins().Returns([plugin]); + MediaLibraryProviderConfigurationStore sut = CreateSut((pluginId, null, CreateArtworkProvider(LibraryType.EBook), null)); + _mockMetadataConfigurationRepository.GetByLibraryIdAsync(libraryId, Arg.Any()) + .Returns(Result.From>([])); + _mockArtworkConfigurationRepository.GetByLibraryIdAsync(libraryId, Arg.Any()) + .Returns(Result.From>([])); + _mockArtworkConfigurationRepository.UpsertAsync(Arg.Any(), Arg.Any()) + .Returns(Error.Failure(description: "Failed to persist the configuration")); + + // Act + Result result = await sut.ReconcileProviderConfigurationsAsync(libraryId, LibraryType.EBook, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + await _mockBookReaderConfigurationRepository.DidNotReceive().GetByLibraryIdAsync(Arg.Any(), Arg.Any()); + } + + [Fact] + public async Task ReconcileBookReaderConfigurationsAsync_WhenConfigurationAlreadyExists_ShouldKeepItWithoutUpserting() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + Guid pluginId = Guid.NewGuid(); + IPlugin plugin = CreatePlugin(pluginId, "Reader Plugin"); + _mockPluginManager.GetPlugins().Returns([plugin]); + MediaLibraryProviderConfigurationStore sut = CreateSut((pluginId, null, null, CreateBookReader(LibraryType.EBook, ".epub"))); + LibraryBookReaderConfigurationEntity existingConfiguration = _bookReaderConfigurationFixture.Create(libraryId: libraryId, pluginId: pluginId); + _mockMetadataConfigurationRepository.GetByLibraryIdAsync(libraryId, Arg.Any()) + .Returns(Result.From>([])); + _mockArtworkConfigurationRepository.GetByLibraryIdAsync(libraryId, Arg.Any()) + .Returns(Result.From>([])); + _mockBookReaderConfigurationRepository.GetByLibraryIdAsync(libraryId, Arg.Any()) + .Returns(Result.From>([existingConfiguration])); + + // Act + Result result = await sut.ReconcileProviderConfigurationsAsync(libraryId, LibraryType.EBook, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + await _mockBookReaderConfigurationRepository.DidNotReceive().UpsertAsync(Arg.Any(), Arg.Any()); + await _mockBookReaderConfigurationRepository.DidNotReceive().DeleteByLibraryIdAndPluginIdsAsync(Arg.Any(), Arg.Any>(), Arg.Any()); + } + + [Fact] + public async Task EnsureProviderConfigurationsAsync_WhenUpsertingMetadataConfigurationFails_ShouldReturnError() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + Guid pluginId = Guid.NewGuid(); + IPlugin plugin = CreatePlugin(pluginId, "Plugin"); + _mockPluginManager.GetPlugins().Returns([plugin]); + MediaLibraryProviderConfigurationStore sut = CreateSut((pluginId, CreateMetadataProvider(LibraryType.Book), null, null)); + _mockMetadataConfigurationRepository.GetByLibraryIdAsync(libraryId, Arg.Any()) + .Returns(Result.From>([])); + _mockMetadataConfigurationRepository.UpsertAsync(Arg.Any(), Arg.Any()) + .Returns(Error.Failure(description: "Failed to persist the configuration")); + + // Act + Result result = await sut.EnsureProviderConfigurationsAsync(libraryId, LibraryType.Book, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + await _mockArtworkConfigurationRepository.DidNotReceive().GetByLibraryIdAsync(Arg.Any(), Arg.Any()); + } + + [Fact] + public async Task EnsureProviderConfigurationsAsync_WhenReadingArtworkConfigurationsFails_ShouldReturnError() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + Guid pluginId = Guid.NewGuid(); + IPlugin plugin = CreatePlugin(pluginId, "Plugin"); + _mockPluginManager.GetPlugins().Returns([plugin]); + MediaLibraryProviderConfigurationStore sut = CreateSut((pluginId, null, CreateArtworkProvider(LibraryType.Book), null)); + _mockArtworkConfigurationRepository.GetByLibraryIdAsync(libraryId, Arg.Any()) + .Returns(Error.Failure(description: "Failed to read configurations")); + + // Act + Result result = await sut.EnsureProviderConfigurationsAsync(libraryId, LibraryType.Book, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + await _mockMetadataConfigurationRepository.DidNotReceive().GetByLibraryIdAsync(Arg.Any(), Arg.Any()); + } + /// /// Creates the store under test wired to the mocked dependencies, optionally registering the providers and book readers of the loaded plugins. /// diff --git a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Plugins/PluginInstallerTests.cs b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Plugins/PluginInstallerTests.cs index cb97b6e9..26fc868a 100644 --- a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Plugins/PluginInstallerTests.cs +++ b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Plugins/PluginInstallerTests.cs @@ -8,11 +8,8 @@ using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; using NSubstitute; using System; -using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.IO; -using System.IO.Compression; -using System.Text; using System.Threading; using System.Threading.Tasks; #endregion @@ -23,9 +20,8 @@ namespace Lumina.Infrastructure.UnitTests.Core.Plugins; /// Contains unit tests for the class. ///
[ExcludeFromCodeCoverage] -public class PluginInstallerTests : IDisposable +public class PluginInstallerTests { - private readonly string _pluginsDirectory; private readonly PluginInstaller _sut; private readonly PluginsSettingsDtoFixture _pluginsSettingsDtoFixture = new(); @@ -34,79 +30,12 @@ public class PluginInstallerTests : IDisposable /// public PluginInstallerTests() { - _pluginsDirectory = Path.Combine(AppContext.BaseDirectory, $".test-plugins-{Guid.NewGuid():N}"); ILogger mockLogger = Substitute.For>(); IOptions mockOptions = Substitute.For>(); - mockOptions.Value.Returns(_pluginsSettingsDtoFixture.Create(directory: Path.GetFileName(_pluginsDirectory))); + mockOptions.Value.Returns(_pluginsSettingsDtoFixture.Create(directory: $".test-plugins-{Guid.NewGuid():N}")); _sut = new PluginInstaller(mockOptions, mockLogger); } - [Fact] - public async Task InstallAsync_WhenUploadingSingleAssembly_ShouldCopyAssemblyToPluginsDirectory() - { - // Arrange - string assemblyName = "Lumina.TestPlugin.dll"; - await using FileStream stream = File.OpenRead(Path.Combine(AppContext.BaseDirectory, assemblyName)); - - // Act - Result result = await _sut.InstallAsync(stream, assemblyName, CancellationToken.None); - - // Assert - Assert.False(result.IsFailure); - Assert.True(File.Exists(Path.Combine(_pluginsDirectory, assemblyName))); - } - - [Fact] - public async Task InstallAsync_WhenUploadingZipWithAssemblies_ShouldExtractAssembliesFlattenedToPluginsDirectory() - { - // Arrange - await using MemoryStream zipStream = new(); - CreateZipArchive(zipStream, [("nested/plugin/Lumina.TestPlugin.dll", ReadTestAssembly()), ("readme.txt", Encoding.UTF8.GetBytes("not an assembly"))]); - zipStream.Position = 0; - - // Act - Result result = await _sut.InstallAsync(zipStream, "plugin.zip", CancellationToken.None); - - // Assert - Assert.False(result.IsFailure); - Assert.True(File.Exists(Path.Combine(_pluginsDirectory, "Lumina.TestPlugin.dll"))); - Assert.False(File.Exists(Path.Combine(_pluginsDirectory, "readme.txt"))); - } - - [Fact] - public async Task InstallAsync_WhenUploadingZipWithBackslashTraversalEntry_ShouldFlattenItInsidePluginsDirectory() - { - // Arrange - await using MemoryStream zipStream = new(); - // a backslash is not a directory separator on non-Windows platforms, so it must be neutralized explicitly - CreateZipArchive(zipStream, [(@"..\evil.dll", ReadTestAssembly())]); - zipStream.Position = 0; - - // Act - Result result = await _sut.InstallAsync(zipStream, "plugin.zip", CancellationToken.None); - - // Assert - Assert.False(result.IsFailure); - Assert.True(File.Exists(Path.Combine(_pluginsDirectory, "evil.dll"))); - Assert.False(File.Exists(Path.Combine(AppContext.BaseDirectory, "evil.dll"))); - } - - [Fact] - public async Task InstallAsync_WhenUploadingSingleAssemblyWithTraversalFileName_ShouldFlattenItInsidePluginsDirectory() - { - // Arrange - const string TRAVERSAL_FILE_NAME = "traversal-test-plugin.dll"; - await using FileStream stream = File.OpenRead(Path.Combine(AppContext.BaseDirectory, "Lumina.TestPlugin.dll")); - - // Act - Result result = await _sut.InstallAsync(stream, $@"..\{TRAVERSAL_FILE_NAME}", CancellationToken.None); - - // Assert - Assert.False(result.IsFailure); - Assert.True(File.Exists(Path.Combine(_pluginsDirectory, TRAVERSAL_FILE_NAME))); - Assert.False(File.Exists(Path.Combine(AppContext.BaseDirectory, TRAVERSAL_FILE_NAME))); - } - [Fact] public async Task InstallAsync_WhenUploadingUnsupportedFileType_ShouldReturnError() { @@ -119,23 +48,6 @@ public class PluginInstallerTests : IDisposable // Assert Assert.True(result.IsFailure); Assert.Equal(Errors.Plugins.UnsupportedPluginFileType, result.FirstError); - Assert.False(Directory.Exists(_pluginsDirectory)); - } - - [Fact] - public async Task InstallAsync_WhenUploadingZipWithoutAssemblies_ShouldReturnError() - { - // Arrange - await using MemoryStream zipStream = new(); - CreateZipArchive(zipStream, [("readme.txt", Encoding.UTF8.GetBytes("not an assembly"))]); - zipStream.Position = 0; - - // Act - Result result = await _sut.InstallAsync(zipStream, "plugin.zip", CancellationToken.None); - - // Assert - Assert.True(result.IsFailure); - Assert.Equal(Errors.Plugins.PluginArchiveContainsNoAssemblies, result.FirstError); } [Fact] @@ -151,38 +63,4 @@ public class PluginInstallerTests : IDisposable Assert.True(result.IsFailure); Assert.Equal(Errors.Plugins.PluginArchiveNotReadable, result.FirstError); } - - /// - /// Deletes the temporary plugins directory created by the tests. - /// - public void Dispose() - { - if (Directory.Exists(_pluginsDirectory)) - Directory.Delete(_pluginsDirectory, recursive: true); - } - - /// - /// Creates an in-memory ZIP archive containing the provided entries. - /// - /// The stream to write the archive into. - /// The entries to add, as pairs of entry name and content. - private static void CreateZipArchive(MemoryStream zipStream, IEnumerable<(string Name, byte[] Content)> entries) - { - using ZipArchive zipArchive = new(zipStream, ZipArchiveMode.Create, leaveOpen: true); - foreach ((string name, byte[] content) in entries) - { - ZipArchiveEntry entry = zipArchive.CreateEntry(name); - using Stream entryStream = entry.Open(); - entryStream.Write(content); - } - } - - /// - /// Reads the bytes of the Lumina.TestPlugin.dll assembly from the test output directory. - /// - /// The assembly bytes. - private static byte[] ReadTestAssembly() - { - return File.ReadAllBytes(Path.Combine(AppContext.BaseDirectory, "Lumina.TestPlugin.dll")); - } } diff --git a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Themes/ThemeDetectionSyncJobTests.cs b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Themes/ThemeDetectionSyncJobTests.cs index 2892bf8f..9c12665e 100644 --- a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Themes/ThemeDetectionSyncJobTests.cs +++ b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Themes/ThemeDetectionSyncJobTests.cs @@ -436,6 +436,84 @@ public class ThemeDetectionSyncJobTests : IDisposable await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any()); } + [Fact] + public async Task StartAsync_WhenBundledThemeArchiveFileCannotBeOpened_ShouldLogWarningAndContinue() + { + // Arrange + _mockThemeRepository.GetAllAsync(Arg.Any()).Returns(Result.From>([])); + string missingArchivePath = Path.Combine(_testRootPath, "bundled", "missing.zip"); + _mockThemeService.GetBundledThemeArchivePaths().Returns([missingArchivePath]); + _mockThemeService.ReadManifestFromArchiveAsync(missingArchivePath, Arg.Any()).Returns(_themeManifestDtoFixture.Create(id: "bundled-theme")); + + // Act + await StartAndWaitForExecutionAsync(CreateSut()); + + // Assert + await _mockThemeService.DidNotReceive().InstallAsync(Arg.Any(), Arg.Any()); + await _mockThemeRepository.DidNotReceiveWithAnyArgs().InsertAsync(default!, Arg.Any()); + await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task StartAsync_WhenBundledThemeArchivePathIsADirectory_ShouldLogWarningAndContinue() + { + // Arrange + _mockThemeRepository.GetAllAsync(Arg.Any()).Returns(Result.From>([])); + string directoryPath = Path.Combine(_testRootPath, "not-an-archive"); + Directory.CreateDirectory(directoryPath); + _mockThemeService.GetBundledThemeArchivePaths().Returns([directoryPath]); + _mockThemeService.ReadManifestFromArchiveAsync(directoryPath, Arg.Any()).Returns(_themeManifestDtoFixture.Create(id: "bundled-theme")); + + // Act + await StartAndWaitForExecutionAsync(CreateSut()); + + // Assert + await _mockThemeService.DidNotReceive().InstallAsync(Arg.Any(), Arg.Any()); + await _mockThemeRepository.DidNotReceiveWithAnyArgs().InsertAsync(default!, Arg.Any()); + await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task StartAsync_WhenSoftDeletingUnrestorableBundledThemeFails_ShouldLogWarningAndContinue() + { + // Arrange + ThemeEntity brokenTheme = _themeEntityFixture.Create(themeId: "broken-theme", installSource: ThemeInstallSource.Bundled, isDeleted: false); + ThemeEntity healthyTheme = _themeEntityFixture.Create(themeId: "healthy-theme", isCurrent: true, includeIsCurrent: true, installSource: ThemeInstallSource.Bundled, isDeleted: false); + _mockThemeRepository.GetAllAsync(Arg.Any()).Returns(Result.From>([brokenTheme, healthyTheme])); + _mockThemeService.HasThemePack("broken-theme").Returns(false); + _mockThemeService.GetBundledThemeArchivePaths().Returns([]); + _mockThemeService.RestoreBundledThemeAsync("broken-theme", Arg.Any()).Returns(Error.Failure("Theme.Files", "restore failed")); + _mockThemeRepository.UpdateAsync(Arg.Any(), Arg.Any()).Returns(Error.Failure("Database.Error", "update failed")); + + // Act + await StartAndWaitForExecutionAsync(CreateSut()); + + // Assert + await _mockThemeRepository.Received(1).UpdateAsync( + Arg.Is(theme => theme.ThemeId == "broken-theme" && theme.IsDeleted && theme.IsCurrent == null), + Arg.Any()); + await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task StartAsync_WhenCancellationIsRequestedWhileCleaningUp_ShouldLetTheCancellationPropagate() + { + // Arrange + ThemeEntity brokenTheme = _themeEntityFixture.Create(themeId: "user-theme", installSource: ThemeInstallSource.Uploaded, isDeleted: false); + _mockThemeRepository.GetAllAsync(Arg.Any()).Returns(Result.From>([brokenTheme])); + _mockThemeService.HasThemePack("user-theme").Returns(false); + _mockThemeService.GetBundledThemeArchivePaths().Returns([]); + _mockThemeRepository.DeleteByIdAsync(brokenTheme.Id, Arg.Any()) + .Returns(Task.FromException>(new OperationCanceledException())); + + // Act + Task executionTask = StartAndWaitForExecutionAsync(CreateSut()); + + // Assert + await Assert.ThrowsAnyAsync(() => executionTask); + await _mockUnitOfWork.DidNotReceiveWithAnyArgs().SaveChangesAsync(Arg.Any()); + } + /// /// Invokes the protected of the job and awaits its completion. /// diff --git a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Themes/ThemeServiceTests.cs b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Themes/ThemeServiceTests.cs index 89114f94..abd7e1ba 100644 --- a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Themes/ThemeServiceTests.cs +++ b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Themes/ThemeServiceTests.cs @@ -1,23 +1,17 @@ #region ========================================================================= USING ===================================================================================== using Lumina.Application.Common.Infrastructure.Models.DTO.Themes; -using Lumina.Domain.Common.Errors; using Lumina.Domain.Common.Primitives; using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Services; using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.ValueObjects; using Lumina.Infrastructure.Common.Models.DTO.Configuration; using Lumina.Infrastructure.Core.Themes; using Lumina.Infrastructure.Fixtures.Common.Models.DTO.Configuration; -using Lumina.Infrastructure.Fixtures.Core.Themes; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; using NSubstitute; using System; -using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.IO; -using System.IO.Compression; -using System.Linq; -using System.Text; using System.Threading; using System.Threading.Tasks; #endregion @@ -28,16 +22,10 @@ namespace Lumina.Infrastructure.UnitTests.Core.Themes; /// Contains unit tests for the class. /// [ExcludeFromCodeCoverage] -public class ThemeServiceTests : IDisposable +public class ThemeServiceTests { - private const string DEFAULT_TEMPLATE = "default template"; - private const string HOME_TEMPLATE = "home template"; - private const string LIBRARY_TEMPLATE = "library template"; - - private readonly string _testRootPath; + private readonly string _storageRootPath; private readonly ThemeEngineOptionsDto _options; - private readonly ThemeService _sut; - private readonly ThemePackFixture _themePackFixture = new(); private readonly ThemeEngineOptionsDtoFixture _themeEngineOptionsDtoFixture = new(); /// @@ -45,17 +33,15 @@ public class ThemeServiceTests : IDisposable /// public ThemeServiceTests() { - _testRootPath = Path.Combine(Path.GetTempPath(), $"lumina-themes-{Guid.NewGuid():N}"); - Directory.CreateDirectory(_testRootPath); + _storageRootPath = Path.Combine(Path.GetTempPath(), $"lumina-themes-{Guid.NewGuid():N}"); _options = _themeEngineOptionsDtoFixture.Create( - storagePath: Path.Combine(_testRootPath, "themes"), - bundledThemesPath: Path.Combine(_testRootPath, "bundled"), + storagePath: Path.Combine(_storageRootPath, "themes"), + bundledThemesPath: Path.Combine(_storageRootPath, "bundled"), defaultThemeId: "lumina-default", maxArchiveBytes: 8 * 1024 * 1024, maxExpandedBytes: 24 * 1024 * 1024, maxSingleFileBytes: 6 * 1024 * 1024, maxEntries: 250); - _sut = CreateSut(_options); } [Fact] @@ -63,8 +49,8 @@ public class ThemeServiceTests : IDisposable { // Arrange ThemeEngineOptionsDto options = _themeEngineOptionsDtoFixture.Create( - storagePath: Path.Combine(_testRootPath, "themes"), - bundledThemesPath: Path.Combine(_testRootPath, "bundled"), + storagePath: Path.Combine(_storageRootPath, "themes"), + bundledThemesPath: Path.Combine(_storageRootPath, "bundled"), defaultThemeId: "lumina-default", maxArchiveBytes: 8 * 1024 * 1024, maxExpandedBytes: 24 * 1024 * 1024, @@ -85,8 +71,8 @@ public class ThemeServiceTests : IDisposable { // Arrange ThemeEngineOptionsDto options = _themeEngineOptionsDtoFixture.Create( - storagePath: Path.Combine(_testRootPath, "themes"), - bundledThemesPath: Path.Combine(_testRootPath, "bundled"), + storagePath: Path.Combine(_storageRootPath, "themes"), + bundledThemesPath: Path.Combine(_storageRootPath, "bundled"), defaultThemeId: "lumina-default", maxArchiveBytes: 8 * 1024 * 1024, maxExpandedBytes: 24 * 1024 * 1024, @@ -103,1169 +89,25 @@ public class ThemeServiceTests : IDisposable } [Fact] - public void GetBundledThemeArchivePaths_WhenBundledDirectoryDoesNotExist_ShouldReturnEmptyList() + public async Task GetAssetAsync_WhenPathSegmentIsRenamedByPathService_ShouldReturnPackageInvalidError() { // Arrange - // the bundled directory of the default options never exists - - // Act - IReadOnlyList result = _sut.GetBundledThemeArchivePaths(); - - // Assert - Assert.Empty(result); - } - - [Fact] - public void GetBundledThemeArchivePaths_WhenBundledDirectoryContainsZips_ShouldReturnSortedZipPaths() - { - // Arrange - string bundledPath = Path.Combine(_testRootPath, "bundled"); - Directory.CreateDirectory(bundledPath); - File.WriteAllBytes(Path.Combine(bundledPath, "zeta.zip"), _themePackFixture.Create()); - File.WriteAllBytes(Path.Combine(bundledPath, "alpha.zip"), _themePackFixture.Create()); - File.WriteAllBytes(Path.Combine(bundledPath, "notes.txt"), Encoding.UTF8.GetBytes("not a theme archive")); - - // Act - IReadOnlyList result = _sut.GetBundledThemeArchivePaths(); - - // Assert - Assert.Equal(2, result.Count); - Assert.Equal(Path.Combine(bundledPath, "alpha.zip"), result[0]); - Assert.Equal(Path.Combine(bundledPath, "zeta.zip"), result[1]); - } - - [Fact] - public async Task HasThemePack_WhenThemeIsInstalled_ShouldReturnTrue() - { - // Arrange - await InstallValidThemeAsync(_themePackFixture.Create()); - - // Act - bool result = _sut.HasThemePack("test-theme"); - - // Assert - Assert.True(result); - } - - [Fact] - public void HasThemePack_WhenThemeIsNotInstalled_ShouldReturnFalse() - { - // Arrange - // nothing is installed - - // Act - bool result = _sut.HasThemePack("test-theme"); - - // Assert - Assert.False(result); - } - - [Fact] - public void HasThemePack_WhenThemeDirectoryExistsButManifestIsMissing_ShouldReturnFalse() - { - // Arrange - Directory.CreateDirectory(Path.Combine(_options.StoragePath, "test-theme")); - - // Act - bool result = _sut.HasThemePack("test-theme"); - - // Assert - Assert.False(result); - } - - [Fact] - public async Task InstallAsync_WhenArchiveIsValid_ShouldExtractThemeAndReturnManifest() - { - // Arrange - byte[] archive = _themePackFixture.Create(defaultTemplateContent: DEFAULT_TEMPLATE); - - // Act - Result result = await _sut.InstallAsync(new MemoryStream(archive), CancellationToken.None); - - // Assert - Assert.True(result.IsSuccess); - Assert.Equal("test-theme", result.Value.Id); - Assert.Equal("Test Theme", result.Value.Name); - Assert.True(File.Exists(Path.Combine(_options.StoragePath, "test-theme", "theme.json"))); - Assert.True(File.Exists(Path.Combine(_options.StoragePath, "test-theme", "templates", "default.html"))); - Assert.True(File.Exists(Path.Combine(_options.StoragePath, "test-theme", "assets", "preview.png"))); - } - - [Fact] - public async Task InstallAsync_WhenThemeIsAlreadyInstalled_ShouldReplaceExistingThemeFiles() - { - // Arrange - byte[] firstArchive = _themePackFixture.Create(defaultTemplateContent: "first version"); - byte[] secondArchive = _themePackFixture.Create(defaultTemplateContent: "second version"); - - // Act - await InstallValidThemeAsync(firstArchive); - await InstallValidThemeAsync(secondArchive); - Result templateResult = await _sut.GetTemplateAsync("test-theme", "default", CancellationToken.None); - - // Assert - Assert.True(templateResult.IsSuccess); - Assert.Equal("second version", templateResult.Value); - string[] themeDirectories = [.. Directory.GetDirectories(_options.StoragePath).Where(path => Path.GetFileName(path) != ".staging")]; - Assert.Single(themeDirectories); - Assert.Equal("test-theme", Path.GetFileName(themeDirectories[0])); - } - - [Fact] - public async Task InstallAsync_WhenThemeDestinationIsBlocked_ShouldReturnThemeFilesUnreadableInsteadOfThrowing() - { - // Arrange - byte[] archive = _themePackFixture.Create(themeId: "test-theme"); - // the destination path is blocked by an existing file, so the extracted pack cannot be moved into place - Directory.CreateDirectory(_options.StoragePath); - File.WriteAllText(Path.Combine(_options.StoragePath, "test-theme"), "blocked"); - - // Act - Result result = await _sut.InstallAsync(new MemoryStream(archive), CancellationToken.None); - - // Assert - Assert.True(result.IsFailure); - Assert.Equal("ThemeFilesUnreadable", result.FirstError.Description); - } - - [Fact] - public async Task InstallAsync_WhenArchiveExceedsMaxArchiveBytes_ShouldReturnArchiveTooLargeError() - { - // Arrange - ThemeEngineOptionsDto options = _themeEngineOptionsDtoFixture.Create( - storagePath: Path.Combine(_testRootPath, "themes"), - bundledThemesPath: Path.Combine(_testRootPath, "bundled"), - defaultThemeId: "lumina-default", - maxArchiveBytes: 8 * 1024 * 1024, - maxExpandedBytes: 24 * 1024 * 1024, - maxSingleFileBytes: 6 * 1024 * 1024, - maxEntries: 250); - options.MaxArchiveBytes = 128; - ThemeService sut = CreateSut(options); - byte[] archive = _themePackFixture.Create(); - - // Act - Result result = await sut.InstallAsync(new MemoryStream(archive), CancellationToken.None); - - // Assert - Assert.True(result.IsFailure); - Assert.Equal("Theme.Archive.TooLarge", result.FirstError.Code); - Assert.False(sut.HasThemePack("test-theme")); - } - - [Fact] - public async Task InstallAsync_WhenArchiveStreamIsEmpty_ShouldReturnPackageInvalidError() - { - // Arrange - using MemoryStream emptyStream = new(); - - // Act - Result result = await _sut.InstallAsync(emptyStream, CancellationToken.None); - - // Assert - Assert.True(result.IsFailure); - Assert.Equal("Theme.Package.Invalid", result.FirstError.Code); - Assert.Contains("empty", result.FirstError.Description); - } - - [Fact] - public async Task InstallAsync_WhenArchiveContainsNoEntries_ShouldReturnPackageInvalidError() - { - // Arrange - byte[] archive = _themePackFixture.CreateArchive(); - - // Act - Result result = await _sut.InstallAsync(new MemoryStream(archive), CancellationToken.None); - - // Assert - Assert.True(result.IsFailure); - Assert.Equal("Theme.Package.Invalid", result.FirstError.Code); - Assert.Contains("no files", result.FirstError.Description); - } - - [Fact] - public async Task InstallAsync_WhenArchiveIsNotAZip_ShouldReturnThemeArchiveNotReadable() - { - // Arrange - byte[] archive = Encoding.UTF8.GetBytes("this is not a valid zip archive"); - - // Act - Result result = await _sut.InstallAsync(new MemoryStream(archive), CancellationToken.None); - - // Assert - Assert.True(result.IsFailure); - Assert.Equal("ThemeArchiveNotReadable", result.FirstError.Description); - Assert.False(_sut.HasThemePack("test-theme")); - } - - [Fact] - public async Task InstallAsync_WhenArchiveContainsPathTraversalEntry_ShouldReturnPackageInvalidError() - { - // Arrange - string manifestJson = _themePackFixture.CreateManifestJson(); - byte[] archive = _themePackFixture.CreateArchive( - new("theme.json", manifestJson), - new("templates/default.html", DEFAULT_TEMPLATE), - new("../evil.txt", "should not escape the package")); - - // Act - Result result = await _sut.InstallAsync(new MemoryStream(archive), CancellationToken.None); - - // Assert - Assert.True(result.IsFailure); - Assert.Equal("Theme.Package.Invalid", result.FirstError.Code); - Assert.False(_sut.HasThemePack("test-theme")); - } - - [Fact] - public async Task InstallAsync_WhenArchiveContainsBackslashPathEntry_ShouldReturnPackageInvalidError() - { - // Arrange - string manifestJson = _themePackFixture.CreateManifestJson(); - byte[] archive = _themePackFixture.CreateArchive( - new("theme.json", manifestJson), - new("templates/default.html", DEFAULT_TEMPLATE), - new("assets\\..\\evil.txt", "should not escape the package")); - - // Act - Result result = await _sut.InstallAsync(new MemoryStream(archive), CancellationToken.None); - - // Assert - Assert.True(result.IsFailure); - Assert.Equal("Theme.Package.Invalid", result.FirstError.Code); - } - - [Fact] - public async Task InstallAsync_WhenArchiveEntryIsOutsideAllowedLocations_ShouldReturnPackageInvalidError() - { - // Arrange - string manifestJson = _themePackFixture.CreateManifestJson(); - byte[] archive = _themePackFixture.CreateArchive( - new("theme.json", manifestJson), - new("templates/default.html", DEFAULT_TEMPLATE), - new("notes/readme.txt", "files must live under templates or assets")); - - // Act - Result result = await _sut.InstallAsync(new MemoryStream(archive), CancellationToken.None); - - // Assert - Assert.True(result.IsFailure); - Assert.Equal("Theme.Package.Invalid", result.FirstError.Code); - Assert.Contains("outside the allowed", result.FirstError.Description); - } - - [Fact] - public async Task InstallAsync_WhenArchiveContainsSymbolicLinkEntry_ShouldReturnPackageInvalidError() - { - // Arrange - string manifestJson = _themePackFixture.CreateManifestJson(); - byte[] archive = _themePackFixture.CreateArchive( - new("theme.json", manifestJson), - new("templates/default.html", DEFAULT_TEMPLATE), - new("assets/link.png", "symlink target", UnixFileType: 0xA000)); - - // Act - Result result = await _sut.InstallAsync(new MemoryStream(archive), CancellationToken.None); - - // Assert - Assert.True(result.IsFailure); - Assert.Equal("Theme.Package.Invalid", result.FirstError.Code); - Assert.Contains("Symbolic links", result.FirstError.Description); - } - - [Fact] - public async Task InstallAsync_WhenArchiveContainsDuplicateEntryPaths_ShouldReturnPackageInvalidError() - { - // Arrange - string manifestJson = _themePackFixture.CreateManifestJson(); - byte[] archive = _themePackFixture.CreateArchive( - new("theme.json", manifestJson), - new("templates/default.html", DEFAULT_TEMPLATE), - new("templates/default.html", "duplicate")); - - // Act - Result result = await _sut.InstallAsync(new MemoryStream(archive), CancellationToken.None); - - // Assert - Assert.True(result.IsFailure); - Assert.Equal("Theme.Package.Invalid", result.FirstError.Code); - Assert.Contains("duplicate path", result.FirstError.Description); - } - - [Fact] - public async Task InstallAsync_WhenArchiveExceedsMaxEntries_ShouldReturnTooManyEntriesError() - { - // Arrange - ThemeEngineOptionsDto options = _themeEngineOptionsDtoFixture.Create( - storagePath: Path.Combine(_testRootPath, "themes"), - bundledThemesPath: Path.Combine(_testRootPath, "bundled"), - defaultThemeId: "lumina-default", - maxArchiveBytes: 8 * 1024 * 1024, - maxExpandedBytes: 24 * 1024 * 1024, - maxSingleFileBytes: 6 * 1024 * 1024, - maxEntries: 250); - options.MaxEntries = 2; - ThemeService sut = CreateSut(options); - byte[] archive = _themePackFixture.Create(); - - // Act - Result result = await sut.InstallAsync(new MemoryStream(archive), CancellationToken.None); - - // Assert - Assert.True(result.IsFailure); - Assert.Equal("Theme.Archive.TooManyEntries", result.FirstError.Code); - } - - [Fact] - public async Task InstallAsync_WhenArchiveFileExceedsMaxSingleFileBytes_ShouldReturnFileTooLargeError() - { - // Arrange - ThemeEngineOptionsDto options = _themeEngineOptionsDtoFixture.Create( - storagePath: Path.Combine(_testRootPath, "themes"), - bundledThemesPath: Path.Combine(_testRootPath, "bundled"), - defaultThemeId: "lumina-default", - maxArchiveBytes: 8 * 1024 * 1024, - maxExpandedBytes: 24 * 1024 * 1024, - maxSingleFileBytes: 6 * 1024 * 1024, - maxEntries: 250); - options.MaxSingleFileBytes = 10; - ThemeService sut = CreateSut(options); - string manifestJson = _themePackFixture.CreateManifestJson(); - byte[] archive = _themePackFixture.CreateArchive( - new("theme.json", manifestJson), - new("templates/default.html", new string('a', 64))); - - // Act - Result result = await sut.InstallAsync(new MemoryStream(archive), CancellationToken.None); - - // Assert - Assert.True(result.IsFailure); - Assert.Equal("Theme.File.TooLarge", result.FirstError.Code); - } - - [Fact] - public async Task InstallAsync_WhenExpandedSizeExceedsMaxExpandedBytes_ShouldReturnExpandedTooLargeError() - { - // Arrange - ThemeEngineOptionsDto options = _themeEngineOptionsDtoFixture.Create( - storagePath: Path.Combine(_testRootPath, "themes"), - bundledThemesPath: Path.Combine(_testRootPath, "bundled"), - defaultThemeId: "lumina-default", - maxArchiveBytes: 8 * 1024 * 1024, - maxExpandedBytes: 24 * 1024 * 1024, - maxSingleFileBytes: 6 * 1024 * 1024, - maxEntries: 250); - options.MaxSingleFileBytes = 400; - options.MaxExpandedBytes = 300; - ThemeService sut = CreateSut(options); - byte[] archive = _themePackFixture.CreateArchive( - new("templates/default.html", new string('a', 200)), - new("templates/other.html", new string('b', 200))); - - // Act - Result result = await sut.InstallAsync(new MemoryStream(archive), CancellationToken.None); - - // Assert - Assert.True(result.IsFailure); - Assert.Equal("Theme.Archive.ExpandedTooLarge", result.FirstError.Code); - } - - [Fact] - public async Task InstallAsync_WhenSchemaVersionIsUnsupported_ShouldReturnPackageInvalidError() - { - // Arrange - byte[] archive = _themePackFixture.Create(schemaVersion: 2); - - // Act - Result result = await _sut.InstallAsync(new MemoryStream(archive), CancellationToken.None); - - // Assert - AssertPackageInvalid(result, "schemaVersion"); - } - - [Fact] - public async Task InstallAsync_WhenThemeIdIsNotKebabCase_ShouldReturnPackageInvalidError() - { - // Arrange - byte[] archive = _themePackFixture.Create(themeId: "Test_Theme"); - - // Act - Result result = await _sut.InstallAsync(new MemoryStream(archive), CancellationToken.None); - - // Assert - AssertPackageInvalid(result, "kebab-case"); - } - - [Fact] - public async Task InstallAsync_WhenThemeIdIsTooLong_ShouldReturnPackageInvalidError() - { - // Arrange - string longThemeId = string.Join('-', Enumerable.Repeat("a", 33)); - byte[] archive = _themePackFixture.Create(themeId: longThemeId); - - // Act - Result result = await _sut.InstallAsync(new MemoryStream(archive), CancellationToken.None); - - // Assert - AssertPackageInvalid(result, "kebab-case"); - } - - [Fact] - public async Task InstallAsync_WhenNameIsMissing_ShouldReturnPackageInvalidError() - { - // Arrange - byte[] archive = _themePackFixture.Create(name: string.Empty); - - // Act - Result result = await _sut.InstallAsync(new MemoryStream(archive), CancellationToken.None); - - // Assert - AssertPackageInvalid(result, "name"); - } - - [Fact] - public async Task InstallAsync_WhenDescriptionIsMissing_ShouldReturnPackageInvalidError() - { - // Arrange - byte[] archive = _themePackFixture.Create(description: string.Empty); - - // Act - Result result = await _sut.InstallAsync(new MemoryStream(archive), CancellationToken.None); - - // Assert - AssertPackageInvalid(result, "description"); - } - - [Fact] - public async Task InstallAsync_WhenAuthorIsMissing_ShouldReturnPackageInvalidError() - { - // Arrange - byte[] archive = _themePackFixture.Create(author: string.Empty); - - // Act - Result result = await _sut.InstallAsync(new MemoryStream(archive), CancellationToken.None); - - // Assert - AssertPackageInvalid(result, "author"); - } - - [Fact] - public async Task InstallAsync_WhenVersionIsMissing_ShouldReturnPackageInvalidError() - { - // Arrange - byte[] archive = _themePackFixture.Create(version: string.Empty); - - // Act - Result result = await _sut.InstallAsync(new MemoryStream(archive), CancellationToken.None); - - // Assert - AssertPackageInvalid(result, "version"); - } - - [Fact] - public async Task InstallAsync_WhenVersionIsNotSemanticVersion_ShouldReturnPackageInvalidError() - { - // Arrange - byte[] archive = _themePackFixture.Create(version: "1.0"); - - // Act - Result result = await _sut.InstallAsync(new MemoryStream(archive), CancellationToken.None); - - // Assert - AssertPackageInvalid(result, "semantic version"); - } - - [Fact] - public async Task InstallAsync_WhenManifestDeclaresNoTemplates_ShouldInstallSuccessfully() - { - // Arrange - byte[] archive = _themePackFixture.Create(templates: new Dictionary(StringComparer.OrdinalIgnoreCase)); - - // Act - Result result = await _sut.InstallAsync(new MemoryStream(archive), CancellationToken.None); - - // Assert - Assert.True(result.IsSuccess); - } - - [Fact] - public async Task InstallAsync_WhenManifestDeclaresTooManyTemplates_ShouldReturnPackageInvalidError() - { - // Arrange - Dictionary manyTemplates = new(StringComparer.OrdinalIgnoreCase); - for (int index = 0; index < 33; index++) - manyTemplates[$"template-{index}"] = $"templates/template-{index}.html"; - byte[] archive = _themePackFixture.Create(templates: manyTemplates); - - // Act - Result result = await _sut.InstallAsync(new MemoryStream(archive), CancellationToken.None); - - // Assert - AssertPackageInvalid(result, "at most 32"); - } - - [Fact] - public async Task InstallAsync_WhenTemplateKeyIsInvalid_ShouldReturnPackageInvalidError() - { - // Arrange - Dictionary templates = new(StringComparer.OrdinalIgnoreCase) - { - ["default"] = "templates/default.html", - ["Bad Key"] = "templates/bad-key.html" - }; - byte[] archive = _themePackFixture.Create(templates: templates); - - // Act - Result result = await _sut.InstallAsync(new MemoryStream(archive), CancellationToken.None); - - // Assert - AssertPackageInvalid(result, "Template key"); - } - - [Fact] - public async Task InstallAsync_WhenTemplatePathIsOutsideTemplatesDirectory_ShouldReturnPackageInvalidError() - { - // Arrange - string manifestJson = _themePackFixture.CreateManifestJson(templates: new Dictionary(StringComparer.OrdinalIgnoreCase) - { - ["default"] = "assets/not-a-template.html" - }); - byte[] archive = _themePackFixture.CreateArchive( - new("theme.json", manifestJson), - new("assets/not-a-template.html", DEFAULT_TEMPLATE)); - - // Act - Result result = await _sut.InstallAsync(new MemoryStream(archive), CancellationToken.None); - - // Assert - AssertPackageInvalid(result, "under templates"); - } - - [Fact] - public async Task InstallAsync_WhenTemplateFileIsMissing_ShouldReturnPackageInvalidError() - { - // Arrange - string manifestJson = _themePackFixture.CreateManifestJson(templates: new Dictionary(StringComparer.OrdinalIgnoreCase) - { - ["default"] = "templates/missing.html" - }); - byte[] archive = _themePackFixture.CreateArchive(new ThemeArchiveEntry("theme.json", manifestJson)); - - // Act - Result result = await _sut.InstallAsync(new MemoryStream(archive), CancellationToken.None); - - // Assert - AssertPackageInvalid(result, "missing file"); - } - - [Fact] - public async Task InstallAsync_WhenManifestLacksDefaultTemplate_ShouldInstallSuccessfully() - { - // Arrange - Dictionary templates = new(StringComparer.OrdinalIgnoreCase) - { - ["home"] = "templates/home.html" - }; - byte[] archive = _themePackFixture.Create(templates: templates); - - // Act - Result result = await _sut.InstallAsync(new MemoryStream(archive), CancellationToken.None); - - // Assert - Assert.True(result.IsSuccess); - } - - [Fact] - public async Task InstallAsync_WhenPreviewIsOutsideAssetsDirectory_ShouldReturnPackageInvalidError() - { - // Arrange - byte[] archive = _themePackFixture.Create(preview: "templates/default.html"); - - // Act - Result result = await _sut.InstallAsync(new MemoryStream(archive), CancellationToken.None); - - // Assert - AssertPackageInvalid(result, "preview"); - } - - [Fact] - public async Task InstallAsync_WhenPreviewFileIsMissing_ShouldReturnPackageInvalidError() - { - // Arrange - byte[] archive = _themePackFixture.Create(preview: "assets/missing.png", includePreviewAsset: false); - - // Act - Result result = await _sut.InstallAsync(new MemoryStream(archive), CancellationToken.None); - - // Assert - AssertPackageInvalid(result, "preview"); - } - - [Fact] - public async Task InstallAsync_WhenManifestIsNotValidJson_ShouldReturnInvalidJsonError() - { - // Arrange - byte[] archive = _themePackFixture.CreateArchive(new ThemeArchiveEntry("theme.json", "this is not json")); - - // Act - Result result = await _sut.InstallAsync(new MemoryStream(archive), CancellationToken.None); - - // Assert - Assert.True(result.IsFailure); - Assert.Equal("Theme.Manifest.InvalidJson", result.FirstError.Code); - } - - [Fact] - public async Task InstallAsync_WhenManifestExceedsMaximumSize_ShouldReturnManifestTooLargeError() - { - // Arrange - byte[] archive = _themePackFixture.Create(description: new string('a', 70 * 1024)); - - // Act - Result result = await _sut.InstallAsync(new MemoryStream(archive), CancellationToken.None); - - // Assert - Assert.True(result.IsFailure); - Assert.Equal("Theme.Manifest.TooLarge", result.FirstError.Code); - } - - [Fact] - public async Task ReadManifestFromArchiveAsync_WhenArchiveIsValid_ShouldReturnManifest() - { - // Arrange - string archivePath = Path.Combine(_testRootPath, "valid-theme.zip"); - File.WriteAllBytes(archivePath, _themePackFixture.Create(themeId: "manifest-theme")); - - // Act - Result result = await _sut.ReadManifestFromArchiveAsync(archivePath, CancellationToken.None); - - // Assert - Assert.True(result.IsSuccess); - Assert.Equal("manifest-theme", result.Value.Id); - } - - [Fact] - public async Task ReadManifestFromArchiveAsync_WhenManifestEntryIsMissing_ShouldReturnPackageInvalidError() - { - // Arrange - string archivePath = Path.Combine(_testRootPath, "no-manifest.zip"); - File.WriteAllBytes(archivePath, _themePackFixture.CreateArchive(new ThemeArchiveEntry("templates/default.html", DEFAULT_TEMPLATE))); - - // Act - Result result = await _sut.ReadManifestFromArchiveAsync(archivePath, CancellationToken.None); - - // Assert - Assert.True(result.IsFailure); - Assert.Equal("Theme.Package.Invalid", result.FirstError.Code); - Assert.Contains("missing theme.json", result.FirstError.Description); - } - - [Fact] - public async Task ReadManifestFromArchiveAsync_WhenManifestIsNotValidJson_ShouldReturnInvalidJsonError() - { - // Arrange - string archivePath = Path.Combine(_testRootPath, "invalid-json.zip"); - File.WriteAllBytes(archivePath, _themePackFixture.CreateArchive(new ThemeArchiveEntry("theme.json", "not json"))); - - // Act - Result result = await _sut.ReadManifestFromArchiveAsync(archivePath, CancellationToken.None); - - // Assert - Assert.True(result.IsFailure); - Assert.Equal("Theme.Manifest.InvalidJson", result.FirstError.Code); - } - - [Fact] - public async Task ReadManifestFromArchiveAsync_WhenArchiveIsNotAZip_ShouldReturnThemeArchiveNotReadable() - { - // Arrange - string archivePath = Path.Combine(_testRootPath, "not-a-zip.zip"); - File.WriteAllBytes(archivePath, Encoding.UTF8.GetBytes("plain text file")); - - // Act - Result result = await _sut.ReadManifestFromArchiveAsync(archivePath, CancellationToken.None); - - // Assert - Assert.True(result.IsFailure); - Assert.Equal("ThemeArchiveNotReadable", result.FirstError.Description); - } - - [Fact] - public async Task ReadManifestFromArchiveAsync_WhenArchiveFileDoesNotExist_ShouldReturnThemeFilesUnreadable() - { - // Arrange - string archivePath = Path.Combine(_testRootPath, "does-not-exist.zip"); - - // Act - Result result = await _sut.ReadManifestFromArchiveAsync(archivePath, CancellationToken.None); - - // Assert - Assert.True(result.IsFailure); - Assert.Equal("ThemeFilesUnreadable", result.FirstError.Description); - } - - [Fact] - public async Task DeleteAsync_WhenThemeIsInstalled_ShouldRemoveThemePack() - { - // Arrange - await InstallValidThemeAsync(_themePackFixture.Create()); - - // Act - Result result = await _sut.DeleteAsync("test-theme", CancellationToken.None); - - // Assert - Assert.True(result.IsSuccess); - Assert.False(_sut.HasThemePack("test-theme")); - Assert.False(Directory.Exists(Path.Combine(_options.StoragePath, "test-theme"))); - } - - [Fact] - public async Task DeleteAsync_WhenThemeIsNotInstalled_ShouldReturnSuccess() - { - // Arrange - // nothing is installed - - // Act - Result result = await _sut.DeleteAsync("test-theme", CancellationToken.None); - - // Assert - Assert.True(result.IsSuccess); - } - - [Fact] - public async Task LoadManifestAsync_WhenThemeIsNotInstalled_ShouldReturnThemeFilesUnreadable() - { - // Arrange - // nothing is installed - - // Act - Result result = await _sut.LoadManifestAsync("test-theme", CancellationToken.None); - - // Assert - Assert.True(result.IsFailure); - Assert.Equal("ThemeFilesUnreadable", result.FirstError.Description); - } - - [Fact] - public async Task LoadManifestAsync_WhenThemeIsInstalled_ShouldReturnManifest() - { - // Arrange - await InstallValidThemeAsync(_themePackFixture.Create(themeId: "loaded-theme")); - - // Act - Result result = await _sut.LoadManifestAsync("loaded-theme", CancellationToken.None); - - // Assert - Assert.True(result.IsSuccess); - Assert.Equal("loaded-theme", result.Value.Id); - Assert.Equal("Test Theme", result.Value.Name); - } - - [Fact] - public async Task GetTemplateAsync_WhenPageKeyHasExplicitManifestTemplate_ShouldReturnExplicitTemplate() - { - // Arrange - byte[] archive = CreateThemeWithTemplates(); - await InstallValidThemeAsync(archive); - - // Act - Result result = await _sut.GetTemplateAsync("test-theme", "home", CancellationToken.None); - - // Assert - Assert.True(result.IsSuccess); - Assert.Equal(HOME_TEMPLATE, result.Value); - } - - [Fact] - public async Task GetTemplateAsync_WhenPageKeyHasNoExplicitTemplate_ShouldUseMirroredTemplate() - { - // Arrange - byte[] archive = CreateThemeWithTemplates(); - await InstallValidThemeAsync(archive); - - // Act - Result result = await _sut.GetTemplateAsync("test-theme", "library", CancellationToken.None); - - // Assert - Assert.True(result.IsSuccess); - Assert.Equal(LIBRARY_TEMPLATE, result.Value); - } - - [Fact] - public async Task GetTemplateAsync_WhenMirroredTemplateIsMissing_ShouldWalkUpToParentScope() - { - // Arrange - byte[] archive = CreateThemeWithTemplates(); - await InstallValidThemeAsync(archive); - - // Act - Result result = await _sut.GetTemplateAsync("test-theme", "library/book", CancellationToken.None); - - // Assert - Assert.True(result.IsSuccess); - Assert.Equal(LIBRARY_TEMPLATE, result.Value); - } - - [Fact] - public async Task GetTemplateAsync_WhenNoTemplateResolves_ShouldReturnThemeTemplateNotFound() - { - // Arrange - byte[] archive = CreateThemeWithTemplates(); - await InstallValidThemeAsync(archive); - - // Act - Result result = await _sut.GetTemplateAsync("test-theme", "unknown-page", CancellationToken.None); - - // Assert - Assert.True(result.IsFailure); - Assert.Equal(Errors.Themes.ThemeTemplateNotFound, result.FirstError); - } - - [Theory] - [InlineData("../secret")] // parent scope traversal attempt - [InlineData("/etc/passwd")] // rooted path attempt - [InlineData("templates//nested")] // empty segment attempt - public async Task GetTemplateAsync_WhenPageKeyAttemptsToEscapeTheThemePack_ShouldReturnThemeTemplateNotFound(string pageKey) - { - // Arrange - byte[] archive = CreateThemeWithTemplates(); - await InstallValidThemeAsync(archive); - - // Act - Result result = await _sut.GetTemplateAsync("test-theme", pageKey, CancellationToken.None); - - // Assert - Assert.True(result.IsFailure); - Assert.Equal(Errors.Themes.ThemeTemplateNotFound, result.FirstError); - } - - [Fact] - public async Task GetTemplateAsync_WhenSharedLayoutTemplateIsMissing_ShouldReturnThemeTemplateNotFound() - { - // Arrange - byte[] archive = CreateThemeWithTemplates(); - await InstallValidThemeAsync(archive); - - // Act - Result result = await _sut.GetTemplateAsync("test-theme", "shared/layout", CancellationToken.None); - - // Assert - Assert.True(result.IsFailure); - Assert.Equal(Errors.Themes.ThemeTemplateNotFound, result.FirstError); - } - - [Fact] - public async Task GetTemplateAsync_WhenSharedNavMenuTemplateIsMissing_ShouldReturnThemeTemplateNotFound() - { - // Arrange - byte[] archive = CreateThemeWithTemplates(); - await InstallValidThemeAsync(archive); - - // Act - Result result = await _sut.GetTemplateAsync("test-theme", "shared/nav-menu", CancellationToken.None); - - // Assert - Assert.True(result.IsFailure); - Assert.Equal(Errors.Themes.ThemeTemplateNotFound, result.FirstError); - } - - [Fact] - public async Task GetTemplateAsync_WhenSharedNavMenuMirrorExists_ShouldReturnTheMirroredTemplate() - { - // Arrange - const string NAV_TEMPLATE = "nav menu"; - byte[] archive = _themePackFixture.Create(additionalFiles: new Dictionary - { - ["templates/shared/nav-menu.html"] = NAV_TEMPLATE - }); - await InstallValidThemeAsync(archive); - - // Act - Result result = await _sut.GetTemplateAsync("test-theme", "shared/nav-menu", CancellationToken.None); - - // Assert - Assert.True(result.IsSuccess); - Assert.Equal(NAV_TEMPLATE, result.Value); - } - - [Fact] - public async Task GetTemplateAsync_WhenThemeIsNotInstalled_ShouldReturnThemeFilesUnreadable() - { - // Arrange - // nothing is installed - - // Act - Result result = await _sut.GetTemplateAsync("test-theme", "home", CancellationToken.None); - - // Assert - Assert.True(result.IsFailure); - Assert.Equal("ThemeFilesUnreadable", result.FirstError.Description); - } - - [Fact] - public async Task GetTemplateAsync_WhenManifestTemplateFileWasRemoved_ShouldReturnPackageInvalidError() - { - // Arrange - byte[] archive = CreateThemeWithTemplates(); - await InstallValidThemeAsync(archive); - File.Delete(Path.Combine(_options.StoragePath, "test-theme", "templates", "default.html")); - - // Act - Result result = await _sut.GetTemplateAsync("test-theme", "unknown-page", CancellationToken.None); - - // Assert - Assert.True(result.IsFailure); - Assert.Equal("Theme.Package.Invalid", result.FirstError.Code); - Assert.Contains("missing file", result.FirstError.Description); - } - - [Fact] - public async Task GetTemplateAsync_WhenMirroredTemplateFileWasRemoved_ShouldReturnThemeTemplateNotFound() - { - // Arrange - byte[] archive = CreateThemeWithTemplates(); - await InstallValidThemeAsync(archive); - File.Delete(Path.Combine(_options.StoragePath, "test-theme", "templates", "library.html")); - - // Act - Result result = await _sut.GetTemplateAsync("test-theme", "library/book", CancellationToken.None); - - // Assert - Assert.True(result.IsFailure); - Assert.Equal(Errors.Themes.ThemeTemplateNotFound, result.FirstError); - } - - [Fact] - public async Task GetAssetAsync_WhenAssetExists_ShouldReturnFileBytesAndContentType() - { - // Arrange - byte[] archive = _themePackFixture.Create(additionalFiles: new Dictionary - { - ["assets/style.css"] = "body { color: red; }" - }); - await InstallValidThemeAsync(archive); - - // Act - Result result = await _sut.GetAssetAsync("test-theme", "assets/style.css", CancellationToken.None); - - // Assert - Assert.True(result.IsSuccess); - Assert.Equal("text/css", result.Value.ContentType); - Assert.Equal("body { color: red; }", Encoding.UTF8.GetString(result.Value.Bytes)); - } - - [Fact] - public async Task GetAssetAsync_WhenAssetPathIsOutsideAssetsDirectory_ShouldReturnPackageInvalidError() - { - // Arrange - byte[] archive = CreateThemeWithTemplates(); - await InstallValidThemeAsync(archive); - - // Act - Result result = await _sut.GetAssetAsync("test-theme", "templates/default.html", CancellationToken.None); - - // Assert - Assert.True(result.IsFailure); - Assert.Equal("Theme.Package.Invalid", result.FirstError.Code); - } - - [Fact] - public async Task GetAssetAsync_WhenAssetPathAttemptsTraversal_ShouldReturnPackageInvalidError() - { - // Arrange - byte[] archive = _themePackFixture.Create(); - await InstallValidThemeAsync(archive); - - // Act - Result result = await _sut.GetAssetAsync("test-theme", "../secret.txt", CancellationToken.None); - - // Assert - Assert.True(result.IsFailure); - Assert.Equal("Theme.Package.Invalid", result.FirstError.Code); - } - - [Fact] - public async Task GetAssetAsync_WhenAssetFileIsMissing_ShouldReturnThemeFilesUnreadable() - { - // Arrange - byte[] archive = _themePackFixture.Create(); - await InstallValidThemeAsync(archive); - - // Act - Result result = await _sut.GetAssetAsync("test-theme", "assets/missing.png", CancellationToken.None); - - // Assert - Assert.True(result.IsFailure); - Assert.Equal("ThemeFilesUnreadable", result.FirstError.Description); - } - - [Fact] - public async Task GetAssetAsync_WhenAssetIsJavaScript_ShouldReturnJavaScriptContentType() - { - // Arrange - byte[] archive = _themePackFixture.Create(additionalFiles: new Dictionary - { - ["assets/app.js"] = "console.log('hello');" - }); - await InstallValidThemeAsync(archive); - - // Act - Result result = await _sut.GetAssetAsync("test-theme", "assets/app.js", CancellationToken.None); - - // Assert - Assert.True(result.IsSuccess); - Assert.Equal("application/javascript", result.Value.ContentType); - } - - [Fact] - public async Task BuildArchiveAsync_WhenThemeIsInstalled_ShouldReturnDownloadableZipArchive() - { - // Arrange - byte[] archive = _themePackFixture.Create(); - await InstallValidThemeAsync(archive); - - // Act - Result result = await _sut.BuildArchiveAsync("test-theme", CancellationToken.None); - - // Assert - Assert.True(result.IsSuccess); - Assert.Equal("test-theme.zip", result.Value.FileName); - Assert.Equal("application/zip", result.Value.ContentType); - using MemoryStream stream = new(result.Value.Bytes); - using ZipArchive rebuiltArchive = new(stream, ZipArchiveMode.Read); - Assert.Contains(rebuiltArchive.Entries, entry => entry.FullName == "theme.json"); - Assert.Contains(rebuiltArchive.Entries, entry => entry.FullName == "templates/default.html"); - } - - [Fact] - public async Task BuildArchiveAsync_WhenThemeIsNotInstalled_ShouldReturnThemeFilesUnreadable() - { - // Arrange - // nothing is installed - - // Act - Result result = await _sut.BuildArchiveAsync("test-theme", CancellationToken.None); - - // Assert - Assert.True(result.IsFailure); - Assert.Equal("ThemeFilesUnreadable", result.FirstError.Description); - } - - [Fact] - public async Task RestoreBundledThemeAsync_WhenBundledArchiveMatchesThemeId_ShouldInstallTheme() - { - // Arrange - string bundledPath = Path.Combine(_testRootPath, "bundled"); - Directory.CreateDirectory(bundledPath); - File.WriteAllBytes(Path.Combine(bundledPath, "bundled-theme.zip"), _themePackFixture.Create(themeId: "bundled-theme")); - - // Act - Result result = await _sut.RestoreBundledThemeAsync("bundled-theme", CancellationToken.None); - - // Assert - Assert.True(result.IsSuccess); - Assert.True(_sut.HasThemePack("bundled-theme")); - } - - [Fact] - public async Task RestoreBundledThemeAsync_WhenNoBundledArchiveMatches_ShouldReturnThemeFilesUnreadable() - { - // Arrange - string bundledPath = Path.Combine(_testRootPath, "bundled"); - Directory.CreateDirectory(bundledPath); - File.WriteAllBytes(Path.Combine(bundledPath, "other-theme.zip"), _themePackFixture.Create(themeId: "other-theme")); - - // Act - Result result = await _sut.RestoreBundledThemeAsync("bundled-theme", CancellationToken.None); - - // Assert - Assert.True(result.IsFailure); - Assert.Equal("ThemeFilesUnreadable", result.FirstError.Description); - } - - [Fact] - public async Task RestoreBundledThemeAsync_WhenBundledArchiveManifestIsInvalid_ShouldSkipArchiveAndReturnThemeFilesUnreadable() - { - // Arrange - string bundledPath = Path.Combine(_testRootPath, "bundled"); - Directory.CreateDirectory(bundledPath); - File.WriteAllBytes(Path.Combine(bundledPath, "broken.zip"), _themePackFixture.CreateArchive(new ThemeArchiveEntry("templates/default.html", DEFAULT_TEMPLATE))); - - // Act - Result result = await _sut.RestoreBundledThemeAsync("bundled-theme", CancellationToken.None); - - // Assert - Assert.True(result.IsFailure); - Assert.Equal("ThemeFilesUnreadable", result.FirstError.Description); - Assert.False(_sut.HasThemePack("bundled-theme")); - } - - /// - /// Cleans up the temporary storage used by the tests. - /// - public void Dispose() - { - try - { - if (Directory.Exists(_testRootPath)) - Directory.Delete(_testRootPath, recursive: true); - } - catch (IOException) - { - // best effort cleanup of the per-test temp directory - } - catch (UnauthorizedAccessException) - { - // best effort cleanup of the per-test temp directory - } - } - - /// - /// Creates a valid theme pack that declares the default, home and library templates and their files. - /// - /// The created theme pack ZIP archive. - private byte[] CreateThemeWithTemplates() - { - Dictionary templates = new(StringComparer.OrdinalIgnoreCase) - { - ["default"] = "templates/default.html", - ["home"] = "templates/home.html" - }; - - return _themePackFixture.Create( - templates: templates, - additionalFiles: new Dictionary + IPathService pathService = Substitute.For(); + pathService.SanitizeSegment(Arg.Any()) + .Returns(callInfo => { - ["templates/library.html"] = LIBRARY_TEMPLATE + string segment = callInfo.Arg(); + string sanitized = segment == "assets" ? "renamed-assets" : segment; + return PathSegment.Create(sanitized, isDirectory: true, isDrive: false); }); - } + ThemeService sut = new(Options.Create(_options), Substitute.For>(), pathService); - /// - /// Installs the provided theme archive using the provided service and asserts that the install succeeds. - /// - /// The theme pack ZIP archive to install. - /// The service to install with, defaults to the shared system under test. - /// The task representing the asynchronous operation. - private async Task InstallValidThemeAsync(byte[] archive, ThemeService? service = null) - { - ThemeService themeService = service ?? _sut; - using MemoryStream stream = new(archive); - Result result = await themeService.InstallAsync(stream, CancellationToken.None); - Assert.True(result.IsSuccess, result.Match( - success => string.Empty, - errors => $"Expected a successful install but got: {errors.First().Code}: {errors.First().Description}")); - } + // Act + Result result = await sut.GetAssetAsync("test-theme", "assets/logo.png", CancellationToken.None); - /// - /// Asserts that the result is a package invalid failure whose description contains the provided fragment. - /// - /// The result to assert on. - /// The fragment the error description must contain. - private static void AssertPackageInvalid(Result result, string expectedDescriptionFragment) - { + // Assert Assert.True(result.IsFailure); Assert.Equal("Theme.Package.Invalid", result.FirstError.Code); - Assert.Contains(expectedDescriptionFragment, result.FirstError.Description); } /// diff --git a/tests/UnitTests/Lumina.Plugins.Calibre.UnitTests/Core/CalibreArtworkProviderTests.cs b/tests/UnitTests/Lumina.Plugins.Calibre.UnitTests/Core/CalibreArtworkProviderTests.cs index e82c8dac..f86d2c0d 100644 --- a/tests/UnitTests/Lumina.Plugins.Calibre.UnitTests/Core/CalibreArtworkProviderTests.cs +++ b/tests/UnitTests/Lumina.Plugins.Calibre.UnitTests/Core/CalibreArtworkProviderTests.cs @@ -6,10 +6,8 @@ using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; using Lumina.Plugins.Calibre.Core; using Lumina.Plugins.Calibre.Fixtures.Core.Metadata; using Lumina.Plugins.Contracts.Core.Metadata; -using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; -using System.IO; using System.Threading; using System.Threading.Tasks; #endregion @@ -58,149 +56,6 @@ public class CalibreArtworkProviderTests Assert.False(result); } - [Fact] - public async Task GetArtworkAsync_WhenCoverHrefIsABareFileName_ShouldReturnTheLocalCoverPath() - { - // Arrange - string bookDirectory = CreateTempDirectory(); - try - { - string bookPath = Path.Combine(bookDirectory, "book.epub"); - WriteOpf(bookDirectory, coverHref: "cover.jpg"); - File.WriteAllText(Path.Combine(bookDirectory, "cover.jpg"), "image-bytes"); - BookMetadataLookupDto lookup = _bookMetadataLookupDtoFixture.Create(path: bookPath); - - // Act - ArtworkDto? result = await _sut.GetArtworkAsync(lookup, CancellationToken.None); - - // Assert - Assert.NotNull(result); - Assert.Equal(Path.Combine(bookDirectory, "cover.jpg"), result!.LocalPath); - Assert.Null(result.RemoteUrl); - } - finally - { - Directory.Delete(bookDirectory, true); - } - } - - [Fact] - public async Task GetArtworkAsync_WhenCoverHrefIsAnAbsolutePath_ShouldReturnNull() - { - // Arrange - string bookDirectory = CreateTempDirectory(); - try - { - string bookPath = Path.Combine(bookDirectory, "book.epub"); - WriteOpf(bookDirectory, coverHref: @"C:\Windows\System32\drivers\etc\hosts"); - BookMetadataLookupDto lookup = _bookMetadataLookupDtoFixture.Create(path: bookPath); - - // Act - ArtworkDto? result = await _sut.GetArtworkAsync(lookup, CancellationToken.None); - - // Assert - Assert.Null(result); - } - finally - { - Directory.Delete(bookDirectory, true); - } - } - - [Theory] - [InlineData("../cover.jpg")] // parent directory escape - [InlineData("sub/cover.jpg")] // path with a separator - [InlineData("sub\\cover.jpg")] // path with a backslash separator - public async Task GetArtworkAsync_WhenCoverHrefContainsPathTraversalOrSeparators_ShouldReturnNull(string coverHref) - { - // Arrange - string bookDirectory = CreateTempDirectory(); - try - { - string bookPath = Path.Combine(bookDirectory, "book.epub"); - WriteOpf(bookDirectory, coverHref); - BookMetadataLookupDto lookup = _bookMetadataLookupDtoFixture.Create(path: bookPath); - - // Act - ArtworkDto? result = await _sut.GetArtworkAsync(lookup, CancellationToken.None); - - // Assert - Assert.Null(result); - } - finally - { - Directory.Delete(bookDirectory, true); - } - } - - [Fact] - public async Task GetArtworkAsync_WhenCoverFileIsMissing_ShouldReturnNull() - { - // Arrange - string bookDirectory = CreateTempDirectory(); - try - { - string bookPath = Path.Combine(bookDirectory, "book.epub"); - WriteOpf(bookDirectory, coverHref: "cover.jpg"); - BookMetadataLookupDto lookup = _bookMetadataLookupDtoFixture.Create(path: bookPath); - - // Act - ArtworkDto? result = await _sut.GetArtworkAsync(lookup, CancellationToken.None); - - // Assert - Assert.Null(result); - } - finally - { - Directory.Delete(bookDirectory, true); - } - } - - [Fact] - public async Task GetArtworkAsync_WhenOpfFileDoesNotExist_ShouldReturnNull() - { - // Arrange - string bookDirectory = CreateTempDirectory(); - try - { - string bookPath = Path.Combine(bookDirectory, "book.epub"); - BookMetadataLookupDto lookup = _bookMetadataLookupDtoFixture.Create(path: bookPath); - - // Act - ArtworkDto? result = await _sut.GetArtworkAsync(lookup, CancellationToken.None); - - // Assert - Assert.Null(result); - } - finally - { - Directory.Delete(bookDirectory, true); - } - } - - [Fact] - public async Task GetArtworkAsync_WhenOpfHasNoCoverReference_ShouldReturnNull() - { - // Arrange - string bookDirectory = CreateTempDirectory(); - try - { - string bookPath = Path.Combine(bookDirectory, "book.epub"); - File.WriteAllText(Path.Combine(bookDirectory, "metadata.opf"), """Test"""); - BookMetadataLookupDto lookup = _bookMetadataLookupDtoFixture.Create(path: bookPath); - - // Act - ArtworkDto? result = await _sut.GetArtworkAsync(lookup, CancellationToken.None); - - // Assert - Assert.Null(result); - } - finally - { - Directory.Delete(bookDirectory, true); - } - } - [Fact] public async Task GetArtworkAsync_WhenLookupIsNotABookLookup_ShouldReturnNull() { @@ -227,26 +82,4 @@ public class CalibreArtworkProviderTests // Assert Assert.Null(result); } - - /// - /// Writes an OPF file that references the given cover into the book directory. - /// - /// The file system path of the directory the OPF file is written into. - /// The href of the cover the OPF file references. - private static void WriteOpf(string bookDirectory, string coverHref) - { - string opf = $$"""Test"""; - File.WriteAllText(Path.Combine(bookDirectory, "metadata.opf"), opf); - } - - /// - /// Creates a unique temporary directory for the book. - /// - /// The file system path of the created temporary directory. - private static string CreateTempDirectory() - { - string directoryPath = Path.Combine(Path.GetTempPath(), $"lumina-calibre-artwork-{Guid.NewGuid():N}"); - Directory.CreateDirectory(directoryPath); - return directoryPath; - } } diff --git a/tests/UnitTests/Lumina.Plugins.Calibre.UnitTests/Core/CalibreBookMetadataProviderTests.cs b/tests/UnitTests/Lumina.Plugins.Calibre.UnitTests/Core/CalibreBookMetadataProviderTests.cs index 39e1ef2a..a9f03495 100644 --- a/tests/UnitTests/Lumina.Plugins.Calibre.UnitTests/Core/CalibreBookMetadataProviderTests.cs +++ b/tests/UnitTests/Lumina.Plugins.Calibre.UnitTests/Core/CalibreBookMetadataProviderTests.cs @@ -3,10 +3,8 @@ using Lumina.Contracts.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary; using Lumina.Contracts.Fixtures.Core.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary; using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; using Lumina.Plugins.Calibre.Core; -using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; -using System.IO; using System.Threading; using System.Threading.Tasks; #endregion @@ -22,8 +20,6 @@ public class CalibreBookMetadataProviderTests private readonly BookMetadataLookupDtoFixture _bookMetadataLookupDtoFixture = new(); private readonly CalibreBookMetadataProvider _sut = new(); - private const string OPF_DOCUMENT = """Test Book TitleTest Author"""; - [Fact] public void Name_WhenCalled_ShouldReturnTheProviderDisplayName() { @@ -56,52 +52,6 @@ public class CalibreBookMetadataProviderTests Assert.False(result); } - [Fact] - public async Task GetMetadataAsync_WhenOpfFileExistsNextToTheBook_ShouldReturnTheMappedMetadata() - { - // Arrange - string bookDirectory = CreateTempDirectory(); - try - { - string bookPath = Path.Combine(bookDirectory, "book.epub"); - File.WriteAllText(Path.Combine(bookDirectory, "metadata.opf"), OPF_DOCUMENT); - BookMetadataLookupDto lookup = _bookMetadataLookupDtoFixture.Create(path: bookPath); - - // Act - BookMetadataDto? result = await _sut.GetMetadataAsync(lookup, CancellationToken.None); - - // Assert - Assert.NotNull(result); - Assert.Equal("Test Book Title", result!.Title); - } - finally - { - Directory.Delete(bookDirectory, true); - } - } - - [Fact] - public async Task GetMetadataAsync_WhenOpfFileDoesNotExist_ShouldReturnNull() - { - // Arrange - string bookDirectory = CreateTempDirectory(); - try - { - string bookPath = Path.Combine(bookDirectory, "book.epub"); - BookMetadataLookupDto lookup = _bookMetadataLookupDtoFixture.Create(path: bookPath); - - // Act - BookMetadataDto? result = await _sut.GetMetadataAsync(lookup, CancellationToken.None); - - // Assert - Assert.Null(result); - } - finally - { - Directory.Delete(bookDirectory, true); - } - } - [Fact] public async Task GetMetadataAsync_WhenLookupPathIsEmpty_ShouldReturnNull() { @@ -114,61 +64,4 @@ public class CalibreBookMetadataProviderTests // Assert Assert.Null(result); } - - [Fact] - public async Task GetSearchResultsAsync_WhenOpfFileExistsNextToTheBook_ShouldReturnASingleMetadataCandidate() - { - // Arrange - string bookDirectory = CreateTempDirectory(); - try - { - string bookPath = Path.Combine(bookDirectory, "book.epub"); - File.WriteAllText(Path.Combine(bookDirectory, "metadata.opf"), OPF_DOCUMENT); - BookMetadataLookupDto lookup = _bookMetadataLookupDtoFixture.Create(path: bookPath); - - // Act - IReadOnlyList result = await _sut.GetSearchResultsAsync(lookup, CancellationToken.None); - - // Assert - BookMetadataDto metadata = Assert.IsType(Assert.Single(result)); - Assert.Equal("Test Book Title", metadata.Title); - } - finally - { - Directory.Delete(bookDirectory, true); - } - } - - [Fact] - public async Task GetSearchResultsAsync_WhenOpfFileDoesNotExist_ShouldReturnAnEmptyList() - { - // Arrange - string bookDirectory = CreateTempDirectory(); - try - { - string bookPath = Path.Combine(bookDirectory, "book.epub"); - BookMetadataLookupDto lookup = _bookMetadataLookupDtoFixture.Create(path: bookPath); - - // Act - IReadOnlyList result = await _sut.GetSearchResultsAsync(lookup, CancellationToken.None); - - // Assert - Assert.Empty(result); - } - finally - { - Directory.Delete(bookDirectory, true); - } - } - - /// - /// Creates a unique temporary directory for the book. - /// - /// The file system path of the created temporary directory. - private static string CreateTempDirectory() - { - string directoryPath = Path.Combine(Path.GetTempPath(), $"lumina-calibre-metadata-{Guid.NewGuid():N}"); - Directory.CreateDirectory(directoryPath); - return directoryPath; - } } diff --git a/tests/UnitTests/Lumina.Plugins.Epub.UnitTests/Core/EpubReaderTests.cs b/tests/UnitTests/Lumina.Plugins.Epub.UnitTests/Core/EpubReaderTests.cs index 36bb5849..d52a7a09 100644 --- a/tests/UnitTests/Lumina.Plugins.Epub.UnitTests/Core/EpubReaderTests.cs +++ b/tests/UnitTests/Lumina.Plugins.Epub.UnitTests/Core/EpubReaderTests.cs @@ -1,15 +1,8 @@ -#region ========================================================================= USING ===================================================================================== -using Lumina.Contracts.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary.Reading; +#region ========================================================================= USING ===================================================================================== using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; using Lumina.Plugins.Epub.Core; -using Lumina.Plugins.Epub.Fixtures.Core.Epub; -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.Plugins.Epub.UnitTests.Core; @@ -18,71 +11,27 @@ namespace Lumina.Plugins.Epub.UnitTests.Core; /// Contains unit tests for the class. /// [ExcludeFromCodeCoverage] -public class EpubReaderTests : IDisposable +public class EpubReaderTests { - private readonly string _temporaryDirectory = Path.Combine(Path.GetTempPath(), $"lumina-epub-reader-{Guid.NewGuid():N}"); - private readonly string _epubPath; private readonly EpubReader _sut = new(); - /// - /// Initializes a new instance of the class. - /// - public EpubReaderTests() - { - Directory.CreateDirectory(_temporaryDirectory); - _epubPath = Path.Combine(_temporaryDirectory, "minimal.epub"); - TestEpubFileFactory.CreateMinimalEpub(_epubPath); - } - [Fact] public void SupportedExtensions_WhenAccessed_ShouldOnlyContainEpub() { + // Act + IReadOnlyList result = _sut.SupportedExtensions; + // Assert - Assert.Equal([".epub"], _sut.SupportedExtensions); + Assert.Equal([".epub"], result); } [Fact] public void SupportedLibraryTypes_WhenAccessed_ShouldContainEBookAndBook() { - // Assert - Assert.Equal([LibraryType.EBook, LibraryType.Book], _sut.SupportedLibraryTypes); - } - - [Fact] - public async Task OpenAsync_WhenCalled_ShouldReturnTheParsedDocument() - { - // Arrange - string workingDirectory = Path.Combine(_temporaryDirectory, "work"); - // Act - ReadingDocumentDto result = await _sut.OpenAsync(_epubPath, workingDirectory, shouldRenderPdfAsImages: false, CancellationToken.None); + IReadOnlyList result = _sut.SupportedLibraryTypes; // Assert - Assert.Equal("Minimal EPUB Book", result.Title); - Assert.Equal(2, result.Spine.Count); - } - - [Fact] - public async Task GetResourceAsync_WhenResourceWasExtracted_ShouldReturnItsBytes() - { - // Arrange - string workingDirectory = Path.Combine(_temporaryDirectory, "work"); - ReadingDocumentDto document = await _sut.OpenAsync(_epubPath, workingDirectory, shouldRenderPdfAsImages: false, CancellationToken.None); - string resourceKey = document.Resources.Keys.Single(); - - // Act - byte[] result = await _sut.GetResourceAsync(_epubPath, workingDirectory, resourceKey, CancellationToken.None); - - // Assert - Assert.NotNull(result); - Assert.NotEmpty(result); - } - - /// - public void Dispose() - { - if (Directory.Exists(_temporaryDirectory)) - Directory.Delete(_temporaryDirectory, recursive: true); + Assert.Equal([LibraryType.EBook, LibraryType.Book], result); } } - diff --git a/tests/UnitTests/Lumina.Plugins.Pdf.UnitTests/Core/Pdf/PdfDocumentParserTests.cs b/tests/UnitTests/Lumina.Plugins.Pdf.UnitTests/Core/Pdf/PdfDocumentParserTests.cs index 849aacfb..28b099d4 100644 --- a/tests/UnitTests/Lumina.Plugins.Pdf.UnitTests/Core/Pdf/PdfDocumentParserTests.cs +++ b/tests/UnitTests/Lumina.Plugins.Pdf.UnitTests/Core/Pdf/PdfDocumentParserTests.cs @@ -1,9 +1,6 @@ -#region ========================================================================= USING ===================================================================================== -using Lumina.Contracts.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary.Reading; +#region ========================================================================= USING ===================================================================================== using Lumina.Plugins.Pdf.Core.Pdf; -using Lumina.Plugins.Pdf.Fixtures.Core.Pdf; using System; -using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.IO; using System.Runtime.Versioning; @@ -16,81 +13,18 @@ namespace Lumina.Plugins.Pdf.UnitTests.Core.Pdf; /// Contains unit tests for the class. /// [ExcludeFromCodeCoverage] -public class PdfDocumentParserTests : IDisposable +public class PdfDocumentParserTests { - private readonly string _temporaryDirectory = Path.Combine(Path.GetTempPath(), $"lumina-pdf-tests-{Guid.NewGuid():N}"); - private readonly string _pdfPath; - - /// - /// Initializes a new instance of the class. - /// - public PdfDocumentParserTests() - { - Directory.CreateDirectory(_temporaryDirectory); - _pdfPath = Path.Combine(_temporaryDirectory, "minimal.pdf"); - TestPdfFileFactory.CreateMinimalPdf(_pdfPath); - } - - [Fact] - public void Parse_WhenCalledOnPdfWithTextLayer_ShouldReturnDocumentWithTextSections() - { - // Arrange - string workingDirectory = Path.Combine(_temporaryDirectory, "work"); - - // Act - ReadingDocumentDto result = PdfDocumentParser.Parse(_pdfPath, workingDirectory, shouldRenderPdfAsImages: false, CancellationToken.None); - - // Assert - Assert.Equal("minimal", result.Title); - Assert.True(result.HasTextContent); - ReadingSpineItemDto spineItem = Assert.Single(result.Spine); - Assert.Equal("page:1", spineItem.LocationRef); - string sectionContent = File.ReadAllText(Path.Combine(workingDirectory, spineItem.RelativeSectionFilePath)); - Assert.Contains("

Hello PDF Page 1

", sectionContent, StringComparison.Ordinal); - Assert.Empty(result.Resources); - } - - [Fact] - public void Parse_WhenCalledWithRenderAsImages_ShouldReturnDocumentWithImageSectionsAndNoTextContent() - { - // Arrange - string workingDirectory = Path.Combine(_temporaryDirectory, "work"); - - // Act - ReadingDocumentDto result = PdfDocumentParser.Parse(_pdfPath, workingDirectory, shouldRenderPdfAsImages: true, CancellationToken.None); - - // Assert - Assert.Equal("minimal", result.Title); - Assert.False(result.HasTextContent); - ReadingSpineItemDto spineItem = Assert.Single(result.Spine); - Assert.Equal("page:1", spineItem.LocationRef); - KeyValuePair resource = Assert.Single(result.Resources); - Assert.Equal("page:1", resource.Key); - Assert.Equal("image/png", resource.Value.MimeType); - string sectionContent = File.ReadAllText(Path.Combine(workingDirectory, spineItem.RelativeSectionFilePath)); - Assert.Contains("data-lumina-resource=\"page:1\"", sectionContent, StringComparison.Ordinal); - } - - [Fact] - public void Parse_WhenPdfFileDoesNotExist_ShouldThrowFileNotFoundException() - { - // Arrange - string missingPdfPath = Path.Combine(_temporaryDirectory, "missing.pdf"); - string workingDirectory = Path.Combine(_temporaryDirectory, "work"); - - // Act - Action act = () => PdfDocumentParser.Parse(missingPdfPath, workingDirectory, shouldRenderPdfAsImages: false, CancellationToken.None); - - // Assert - Assert.Throws(act); - } - [SupportedOSPlatform("windows")] [Fact] public void RenderResource_WhenResourceKeyDoesNotIdentifyAPage_ShouldThrowInvalidDataException() { + // Arrange + // The resource key is rejected before RenderResource opens the PDF, so the path never needs to exist. + string missingPdfPath = "missing.pdf"; + // Act - Action act = () => PdfDocumentParser.RenderResource(_pdfPath, "not-a-page", CancellationToken.None); + Action act = () => PdfDocumentParser.RenderResource(missingPdfPath, "not-a-page", CancellationToken.None); // Assert Assert.Throws(act); @@ -100,142 +34,14 @@ public class PdfDocumentParserTests : IDisposable [Fact] public void RenderResource_WhenResourceKeyNamesAPageBeyondThePageCap_ShouldThrowInvalidDataException() { + // Arrange + // The page cap is enforced before RenderResource opens the PDF, so the path never needs to exist. + string missingPdfPath = "missing.pdf"; + // Act - // The minimal PDF has a single page, but the key is rejected by the page cap before the document is even opened. - Action act = () => PdfDocumentParser.RenderResource(_pdfPath, "page:10001", CancellationToken.None); + Action act = () => PdfDocumentParser.RenderResource(missingPdfPath, "page:10001", CancellationToken.None); // Assert Assert.Throws(act); } - - [SupportedOSPlatform("windows")] - [Fact] - public void RenderResource_WhenResourceKeyNamesAPageBeyondTheDocument_ShouldThrowInvalidDataException() - { - // Act - // The minimal PDF has a single page, so page 2 is rejected against the page count of the document without rendering it. - Action act = () => PdfDocumentParser.RenderResource(_pdfPath, "page:2", CancellationToken.None); - - // Assert - Assert.Throws(act); - } - - [Fact] - public void Parse_WhenPdfHasBookmarks_ShouldBuildTableOfContentsFromTheOutline() - { - // Arrange - string outlinedPdfPath = Path.Combine(_temporaryDirectory, "outlined.pdf"); - TestPdfFileFactory.CreatePdfWithOutline(outlinedPdfPath); - string workingDirectory = Path.Combine(_temporaryDirectory, "work"); - - // Act - ReadingDocumentDto result = PdfDocumentParser.Parse(outlinedPdfPath, workingDirectory, shouldRenderPdfAsImages: false, CancellationToken.None); - - // Assert - // PdfPig does not surface a bookmark without a title, so only the three titled top-level entries appear. - Assert.Equal(3, result.TableOfContents.Count); - ReadingTocEntryDto chapterOne = result.TableOfContents[0]; - Assert.Equal("Chapter One", chapterOne.Label); - Assert.Equal("page:1", chapterOne.LocationRef); - ReadingTocEntryDto partOne = Assert.Single(chapterOne.Children); - Assert.Equal("Part One", partOne.Label); - Assert.Equal("page:1", partOne.LocationRef); - Assert.Equal("Chapter Two", result.TableOfContents[1].Label); - Assert.Equal("page:2", result.TableOfContents[1].LocationRef); - // A bookmark pointing at a URI instead of a page yields an entry that is not navigable. - Assert.Equal("External Link", result.TableOfContents[2].Label); - Assert.Equal(string.Empty, result.TableOfContents[2].LocationRef); - } - - [Fact] - public void Parse_WhenPdfIsTooLarge_ShouldThrowInvalidDataException() - { - // Arrange - string oversizedPdfPath = Path.Combine(_temporaryDirectory, "oversized.pdf"); - // A sparse file larger than the 500 MB cap, without allocating disk space. - using (FileStream fileStream = new(oversizedPdfPath, FileMode.Create, FileAccess.Write)) - fileStream.SetLength(501L * 1024 * 1024); - string workingDirectory = Path.Combine(_temporaryDirectory, "work"); - - // Act - Action act = () => PdfDocumentParser.Parse(oversizedPdfPath, workingDirectory, shouldRenderPdfAsImages: false, CancellationToken.None); - - // Assert - Assert.Throws(act); - } - - [Fact] - public void Parse_WhenPdfHasABlankTextLine_ShouldSkipTheBlankLineAndKeepTheOthers() - { - // Arrange - string blankLinePdfPath = Path.Combine(_temporaryDirectory, "blankline.pdf"); - TestPdfFileFactory.CreatePdfWithBlankLine(blankLinePdfPath); - string workingDirectory = Path.Combine(_temporaryDirectory, "work"); - - // Act - ReadingDocumentDto result = PdfDocumentParser.Parse(blankLinePdfPath, workingDirectory, shouldRenderPdfAsImages: false, CancellationToken.None); - - // Assert - string sectionContent = File.ReadAllText(Path.Combine(workingDirectory, result.Spine[0].RelativeSectionFilePath)); - Assert.Contains("

First line

", sectionContent, StringComparison.Ordinal); - Assert.Contains("

Third line

", sectionContent, StringComparison.Ordinal); - Assert.DoesNotContain("

", sectionContent, StringComparison.Ordinal); - } - - [Fact] - public void Parse_WhenPdfOutlineIsMalformed_ShouldSkipTheTableOfContentsAndKeepThePages() - { - // Arrange - string malformedOutlinePdfPath = Path.Combine(_temporaryDirectory, "malformed-outline.pdf"); - TestPdfFileFactory.CreatePdfWithMalformedOutline(malformedOutlinePdfPath); - string workingDirectory = Path.Combine(_temporaryDirectory, "work"); - - // Act - ReadingDocumentDto result = PdfDocumentParser.Parse(malformedOutlinePdfPath, workingDirectory, shouldRenderPdfAsImages: false, CancellationToken.None); - - // Assert - // The malformed bookmarks are best effort: the table of contents is skipped, but the pages are still readable. - Assert.Empty(result.TableOfContents); - Assert.Single(result.Spine); - } - - [Fact] - public void Parse_WhenPdfExceedsThePageCap_ShouldStopAtTheCap() - { - // Arrange - string manyPagesPdfPath = Path.Combine(_temporaryDirectory, "many-pages.pdf"); - TestPdfFileFactory.CreatePdfWithMorePagesThanAllowed(manyPagesPdfPath); - string workingDirectory = Path.Combine(_temporaryDirectory, "work"); - - // Act - ReadingDocumentDto result = PdfDocumentParser.Parse(manyPagesPdfPath, workingDirectory, shouldRenderPdfAsImages: false, CancellationToken.None); - - // Assert - // The parser stops enumerating after the page cap instead of reading every page. - Assert.Equal(10_000, result.Spine.Count); - } - - [Fact] - public void ParseAsImages_WhenPdfExceedsThePageCap_ShouldStopAtTheCap() - { - // Arrange - string manyPagesPdfPath = Path.Combine(_temporaryDirectory, "many-pages-images.pdf"); - TestPdfFileFactory.CreatePdfWithMorePagesThanAllowed(manyPagesPdfPath); - string workingDirectory = Path.Combine(_temporaryDirectory, "work"); - - // Act - ReadingDocumentDto result = PdfDocumentParser.Parse(manyPagesPdfPath, workingDirectory, shouldRenderPdfAsImages: true, CancellationToken.None); - - // Assert - Assert.Equal(10_000, result.Spine.Count); - Assert.Equal(10_000, result.Resources.Count); - } - - /// - public void Dispose() - { - if (Directory.Exists(_temporaryDirectory)) - Directory.Delete(_temporaryDirectory, recursive: true); - } } - diff --git a/tests/UnitTests/Lumina.Plugins.Pdf.UnitTests/Core/PdfReaderTests.cs b/tests/UnitTests/Lumina.Plugins.Pdf.UnitTests/Core/PdfReaderTests.cs index 710c45d8..ae290ab2 100644 --- a/tests/UnitTests/Lumina.Plugins.Pdf.UnitTests/Core/PdfReaderTests.cs +++ b/tests/UnitTests/Lumina.Plugins.Pdf.UnitTests/Core/PdfReaderTests.cs @@ -1,14 +1,8 @@ -#region ========================================================================= USING ===================================================================================== -using Lumina.Contracts.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary.Reading; +#region ========================================================================= USING ===================================================================================== using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; using Lumina.Plugins.Pdf.Core; -using Lumina.Plugins.Pdf.Fixtures.Core.Pdf; -using System; +using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; -using System.IO; -using System.Runtime.Versioning; -using System.Threading; -using System.Threading.Tasks; #endregion namespace Lumina.Plugins.Pdf.UnitTests.Core; @@ -17,70 +11,27 @@ namespace Lumina.Plugins.Pdf.UnitTests.Core; /// Contains unit tests for the class. /// [ExcludeFromCodeCoverage] -public class PdfReaderTests : IDisposable +public class PdfReaderTests { - private readonly string _temporaryDirectory = Path.Combine(Path.GetTempPath(), $"lumina-pdf-reader-{Guid.NewGuid():N}"); - private readonly string _pdfPath; private readonly PdfReader _sut = new(); - /// - /// Initializes a new instance of the class. - /// - public PdfReaderTests() - { - Directory.CreateDirectory(_temporaryDirectory); - _pdfPath = Path.Combine(_temporaryDirectory, "minimal.pdf"); - TestPdfFileFactory.CreateMinimalPdf(_pdfPath); - } - [Fact] public void SupportedExtensions_WhenAccessed_ShouldOnlyContainPdf() { + // Act + IReadOnlyList result = _sut.SupportedExtensions; + // Assert - Assert.Equal([".pdf"], _sut.SupportedExtensions); + Assert.Equal([".pdf"], result); } [Fact] public void SupportedLibraryTypes_WhenAccessed_ShouldContainEBookAndBook() { - // Assert - Assert.Equal([LibraryType.EBook, LibraryType.Book], _sut.SupportedLibraryTypes); - } - - [Fact] - public async Task OpenAsync_WhenCalled_ShouldReturnTheParsedDocument() - { - // Arrange - string workingDirectory = Path.Combine(_temporaryDirectory, "work"); - // Act - ReadingDocumentDto result = await _sut.OpenAsync(_pdfPath, workingDirectory, shouldRenderPdfAsImages: false, CancellationToken.None); + IReadOnlyList result = _sut.SupportedLibraryTypes; // Assert - Assert.Equal("minimal", result.Title); - Assert.Single(result.Spine); - } - - [SupportedOSPlatform("windows")] - [Fact] - public async Task GetResourceAsync_WhenCalledForAPage_ShouldRenderThePageImage() - { - // Arrange - string workingDirectory = Path.Combine(_temporaryDirectory, "work"); - - // Act - byte[] result = await _sut.GetResourceAsync(_pdfPath, workingDirectory, "page:1", CancellationToken.None); - - // Assert - Assert.NotNull(result); - Assert.NotEmpty(result); - } - - /// - public void Dispose() - { - if (Directory.Exists(_temporaryDirectory)) - Directory.Delete(_temporaryDirectory, recursive: true); + Assert.Equal([LibraryType.EBook, LibraryType.Book], result); } } - diff --git a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Common/Authentication/HttpContextCurrentUserServiceTests.cs b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Common/Authentication/HttpContextCurrentUserServiceTests.cs index 9b91b3fa..5e4e3341 100644 --- a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Common/Authentication/HttpContextCurrentUserServiceTests.cs +++ b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Common/Authentication/HttpContextCurrentUserServiceTests.cs @@ -44,7 +44,10 @@ public class HttpContextCurrentUserServiceTests public void UserId_WhenUserIsNull_ShouldReturnNull() { // Arrange - HttpContext mockHttpContext = new DefaultHttpContext(); + HttpContext mockHttpContext = new DefaultHttpContext + { + User = null + }; _mockHttpContextAccessor.HttpContext.Returns(mockHttpContext); // Act diff --git a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Common/Middlewares/ExceptionHandlingMiddlewareTests.cs b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Common/Middlewares/ExceptionHandlingMiddlewareTests.cs index 27697a5b..afcbea42 100644 --- a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Common/Middlewares/ExceptionHandlingMiddlewareTests.cs +++ b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Common/Middlewares/ExceptionHandlingMiddlewareTests.cs @@ -6,6 +6,7 @@ using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Logging; using NSubstitute; using System; +using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.IO; using System.Text; @@ -85,6 +86,31 @@ public class ExceptionHandlingMiddlewareTests Arg.Any>()); } + [Fact] + public async Task InvokeAsync_WhenNextThrowsExceptionAndActivityIsCurrent_ShouldUseTheActivityIdAsTraceId() + { + // Arrange + using (Activity activity = new Activity("TestActivity")) + { + activity.Start(); + DefaultHttpContext context = new() + { + Response = { Body = new MemoryStream() } + }; + _nextDelegate = _ => throw new InvalidOperationException("sensitive internal details"); + + // Act + await _sut.InvokeAsync(context); + + // Assert + context.Response.Body.Seek(0, SeekOrigin.Begin); + using StreamReader reader = new(context.Response.Body, Encoding.UTF8); + string responseBody = await reader.ReadToEndAsync(); + ProblemDetails problemDetails = JsonSerializer.Deserialize(responseBody, _jsonOptions)!; + Assert.Equal(activity.Id, problemDetails.Extensions["traceId"]?.ToString()); + } + } + [Fact] public async Task InvokeAsync_WhenNextThrowsOperationCanceledException_ShouldRethrow() { diff --git a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Common/Utilities/MimeTypesTests.cs b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Common/Utilities/MimeTypesTests.cs new file mode 100644 index 00000000..50ad9587 --- /dev/null +++ b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Common/Utilities/MimeTypesTests.cs @@ -0,0 +1,41 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Domain.SharedKernel.Common.Enums.PhotoLibrary; +using Lumina.Presentation.Api.Common.Utilities; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Presentation.Api.UnitTests.Common.Utilities; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class MimeTypesTests +{ + [Theory] + [InlineData(ImageType.BMP, "image/bmp")] // bmp image type + [InlineData(ImageType.JPEG, "image/jpeg")] // jpeg image type + [InlineData(ImageType.JPEG_CANON, "image/jpeg")] // canon jpeg image type + [InlineData(ImageType.SVG, "image/svg+xml")] // svg image type + [InlineData(ImageType.TGA, "image/x-tga")] // tga image type + public void GetMimeType_WhenTypeIsKnown_ShouldReturnTheMappedMimeType(ImageType type, string expectedMimeType) + { + // Act + string result = MimeTypes.GetMimeType(type); + + // Assert + Assert.Equal(expectedMimeType, result); + } + + [Theory] + [InlineData(ImageType.None)] // the none image type has no mime mapping + [InlineData((ImageType)999)] // an unknown image type has no mime mapping + public void GetMimeType_WhenTypeIsUnknown_ShouldReturnOpaqueBinaryMimeType(ImageType type) + { + // Act + string result = MimeTypes.GetMimeType(type); + + // Assert + Assert.Equal("application/octet-stream", result); + } +} diff --git a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Common/BaseEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Common/BaseEndpointTests.cs index 2f382176..2148d262 100644 --- a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Common/BaseEndpointTests.cs +++ b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Common/BaseEndpointTests.cs @@ -6,6 +6,7 @@ using Lumina.Presentation.Api.Fixtures.Core.Endpoints.Common; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Http.HttpResults; using System.Collections.Generic; +using System.Diagnostics; using System.Diagnostics.CodeAnalysis; #endregion @@ -182,4 +183,81 @@ public class BaseEndpointTests Assert.Equal(new[] { "Description1", "Description2" }, validationProblemDetails.Errors["Code1"]); Assert.Equal(new[] { "Description3" }, validationProblemDetails.Errors["Code2"]); } + + [Fact] + public void Problem_WhenCalledWithSingleUnauthorizedError_ShouldReturnForbiddenStatusCode() + { + // Act + IResult result = _sut.TestProblem([Error.Unauthorized("ErrorCode", "ErrorDescription")]); + + // Assert + ProblemHttpResult problemResult = Assert.IsType(result); + Assert.Equal(StatusCodes.Status403Forbidden, problemResult.StatusCode); + } + + [Fact] + public void Problem_WhenCalledWithSingleForbiddenError_ShouldReturnForbiddenStatusCode() + { + // Act + IResult result = _sut.TestProblem([Error.Forbidden("ErrorCode", "ErrorDescription")]); + + // Assert + ProblemHttpResult problemResult = Assert.IsType(result); + Assert.Equal(StatusCodes.Status403Forbidden, problemResult.StatusCode); + } + + [Fact] + public void Problem_WhenCalledWithMixedErrorsStartingWithValidation_ShouldReturnTheValidationStatusCode() + { + // Arrange + List errors = [ + Error.Validation("Code1", "Description1"), + Error.Conflict("Code2", "Description2") + ]; + + // Act + IResult result = _sut.TestProblem(errors); + + // Assert + ProblemHttpResult problemResult = Assert.IsType(result); + Assert.Equal(StatusCodes.Status400BadRequest, problemResult.StatusCode); + Assert.Equal("Code1", problemResult.ProblemDetails.Title); + } + + [Fact] + public void Problem_WhenActivityIsCurrent_ShouldUseTheActivityIdAsTraceId() + { + // Arrange + using (Activity activity = new Activity("TestActivity")) + { + activity.Start(); + List errors = [Error.NotFound("ErrorCode", "ErrorDescription")]; + + // Act + IResult result = _sut.TestProblem(errors); + + // Assert + ProblemHttpResult problemResult = Assert.IsType(result); + Assert.Equal(activity.Id, problemResult.ProblemDetails.Extensions["traceId"]); + } + } + + [Fact] + public void ValidationProblem_WhenActivityIsCurrent_ShouldUseTheActivityIdAsTraceId() + { + // Arrange + using (Activity activity = new Activity("TestActivity")) + { + activity.Start(); + List errors = [Error.Validation("Code1", "Description1")]; + + // Act + IResult result = _sut.TestValidationProblem(errors); + + // Assert + ProblemHttpResult problemResult = Assert.IsType(result); + HttpValidationProblemDetails validationProblemDetails = Assert.IsType(problemResult.ProblemDetails); + Assert.Equal(activity.Id, validationProblemDetails.Extensions["traceId"]); + } + } } diff --git a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/AddBook/AddBookEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/AddBook/AddBookEndpointTests.cs index dc9ca110..614fd2bb 100644 --- a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/AddBook/AddBookEndpointTests.cs +++ b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/AddBook/AddBookEndpointTests.cs @@ -1,10 +1,133 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Application.Common.CQRS; +using Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Commands.AddBook; +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.MediaLibrary.WrittenContentLibrary.BookLibrary.Books; +using Lumina.Domain.Common.Primitives; +using Lumina.Presentation.Api.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.Books.AddBook; +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.WrittenContentLibrary.BookLibrary.Books.AddBook; -internal class AddBookEndpointTests + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class AddBookEndpointTests { + private readonly Lumina.Application.Common.CQRS.ICommandHandler> _mockHandler; + private readonly AddBookEndpoint _sut; + private readonly AddBookRequestFixture _addBookRequestFixture = new(); + private readonly BookResponseFixture _bookResponseFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + public AddBookEndpointTests() + { + _mockHandler = Substitute.For>>(); + _sut = Factory.Create(_mockHandler); + } + + [Fact] + public async Task ExecuteAsync_WhenSuccessful_ShouldReturnCreatedResultWithBookResponse() + { + // Arrange + AddBookRequest request = _addBookRequestFixture.Create(); + CancellationToken cancellationToken = CancellationToken.None; + BookResponse expectedResponse = _bookResponseFixture.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); + Assert.Contains(expectedResponse.Id.ToString(), createdResult.Location); + } + + [Fact] + public async Task ExecuteAsync_WhenHandlerReturnsConflictError_ShouldReturnProblemResult() + { + // Arrange + AddBookRequest request = _addBookRequestFixture.Create(); + CancellationToken cancellationToken = CancellationToken.None; + Error expectedError = Error.Conflict("Book.AlreadyExists", "BookAlreadyExists"); + _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); + Microsoft.AspNetCore.Mvc.ProblemDetails problemDetailsBody = Assert.IsType(problemDetails.ProblemDetails); + Assert.Equal(StatusCodes.Status409Conflict, problemDetailsBody.Status); + Assert.Equal("Book.AlreadyExists", problemDetailsBody.Title); + Assert.Equal("BookAlreadyExists", problemDetailsBody.Detail); + Assert.Equal("https://tools.ietf.org/html/rfc9110#section-15.5.10", problemDetailsBody.Type); + Assert.NotNull(problemDetailsBody.Extensions["traceId"]); + } + + [Fact] + public async Task ExecuteAsync_WhenCalled_ShouldSendAddBookCommandToHandler() + { + // Arrange + AddBookRequest request = _addBookRequestFixture.Create(); + CancellationToken cancellationToken = CancellationToken.None; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From(_bookResponseFixture.Create())); + + // Act + await _sut.ExecuteAsync(request, cancellationToken); + + // Assert + await _mockHandler.Received(1).HandleAsync( + Arg.Is(command => + command.LibraryId == request.LibraryId && + command.Path == request.Path), + Arg.Is(cancellationToken)); + } + + [Fact] + public async Task ExecuteAsync_WhenCancellationRequested_ShouldCancelOperation() + { + // Arrange + AddBookRequest request = _addBookRequestFixture.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(_bookResponseFixture.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/WrittenContentLibrary/BookLibrary/Books/Reading/GetReadingResource/GetReadingResourceEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/Reading/GetReadingResource/GetReadingResourceEndpointTests.cs index ec3878a6..4a1460b9 100644 --- a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/Reading/GetReadingResource/GetReadingResourceEndpointTests.cs +++ b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/Reading/GetReadingResource/GetReadingResourceEndpointTests.cs @@ -79,6 +79,38 @@ public class GetReadingResourceEndpointTests Assert.Equal("ResourceNotFound", problemResult.ProblemDetails.Detail); } + [Theory] + [InlineData("image/png", "image/png")] // a non-svg image is inert content + [InlineData("image/svg+xml", "application/octet-stream")] // an svg can be executed, so it is served as an opaque download + [InlineData("audio/mpeg", "audio/mpeg")] // audio is inert content + [InlineData("video/mp4", "video/mp4")] // video is inert content + [InlineData("font/woff2", "font/woff2")] // fonts are inert content + [InlineData("application/font-woff", "application/font-woff")] // legacy woff font media type + [InlineData("application/font-woff2", "application/font-woff2")] // legacy woff2 font media type + [InlineData("application/vnd.ms-opentype", "application/vnd.ms-opentype")] // opentype font media type + [InlineData("application/x-font-ttf", "application/x-font-ttf")] // ttf font media type + [InlineData("application/x-font-opentype", "application/x-font-opentype")] // otf font media type + [InlineData("text/css", "text/css")] // stylesheets are inert content + [InlineData("text/html", "application/octet-stream")] // an html document can be executed, so it is served as an opaque download + public async Task ExecuteAsync_WhenServingAResource_ShouldUseTheSafeContentType(string mimeType, string expectedContentType) + { + // Arrange + GetReadingResourceRequest request = _getReadingResourceRequestFixture.Create(); + CancellationToken cancellationToken = CancellationToken.None; + ReadingResourceDataDto response = new(Guid.NewGuid().ToByteArray(), mimeType); + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From(response)); + + // Act + IResult result = await _sut.ExecuteAsync(request, cancellationToken); + + // Assert + FileContentHttpResult bytesResult = Assert.IsType(result); + Assert.Equal(response.Data, bytesResult.FileContents); + Assert.Equal(expectedContentType, bytesResult.ContentType); + Assert.Equal("nosniff", _sut.HttpContext.Response.Headers["X-Content-Type-Options"]); + } + [Fact] public async Task ExecuteAsync_WhenCalled_ShouldSendGetReadingResourceQueryToSender() { diff --git a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Plugins/InstallPlugin/InstallPluginEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Plugins/InstallPlugin/InstallPluginEndpointTests.cs index e9871258..22d0c303 100644 --- a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Plugins/InstallPlugin/InstallPluginEndpointTests.cs +++ b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Plugins/InstallPlugin/InstallPluginEndpointTests.cs @@ -147,6 +147,27 @@ public class InstallPluginEndpointTests await Assert.ThrowsAnyAsync(() => operationTask); } + [Fact] + public async Task ExecuteAsync_WhenTheFormIsMalformed_ShouldTreatTheUploadAsMissingAndSendNullArchive() + { + // Arrange + CancellationToken cancellationToken = CancellationToken.None; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From(Result.Success)); + ConfigureMalformedForm(); + + // Act + IResult result = await _sut.ExecuteAsync(EmptyRequest.Instance, cancellationToken); + + // Assert + Assert.IsType(result); + await _mockHandler.Received(1).HandleAsync( + Arg.Is(command => + command.Archive == null && + command.FileName == null), + Arg.Is(cancellationToken)); + } + private void ConfigureFormWithArchive(byte[] content, string fileName) { // the stream stays open for the duration of the test, since the endpoint reads it through the form file during execution @@ -155,8 +176,8 @@ public class InstallPluginEndpointTests FormFileCollection files = [formFile]; IFormCollection form = new FormCollection([], files); _sut.HttpContext.Request.ContentType = "multipart/form-data; boundary=----test"; - // a real FormFeature is used instead of a substitute, because the endpoint execution reads the form through the - // request machinery, which would bypass a mocked feature and parse the (empty) request body + // A real FormFeature is used instead of a substitute, because the endpoint execution reads the form through the + // request machinery, which would bypass a mocked feature and parse the (empty) request body. _sut.HttpContext.Features.Set(new FormFeature(form)); } @@ -166,4 +187,12 @@ public class InstallPluginEndpointTests _sut.HttpContext.Request.ContentType = "multipart/form-data; boundary=----test"; _sut.HttpContext.Features.Set(new FormFeature(form)); } + + private void ConfigureMalformedForm() + { + _sut.HttpContext.Request.ContentType = "multipart/form-data; boundary=----test"; + IFormCollection malformedForm = Substitute.For(); + malformedForm.Files.Returns(_ => throw new InvalidDataException("Malformed multipart body.")); + _sut.HttpContext.Features.Set(new FormFeature(malformedForm)); + } } diff --git a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Themes/Management/InstallTheme/InstallThemeEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Themes/Management/InstallTheme/InstallThemeEndpointTests.cs index 65fe85bb..4a93b17d 100644 --- a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Themes/Management/InstallTheme/InstallThemeEndpointTests.cs +++ b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Themes/Management/InstallTheme/InstallThemeEndpointTests.cs @@ -156,6 +156,29 @@ public class InstallThemeEndpointTests await Assert.ThrowsAnyAsync(() => operationTask); } + [Fact] + public async Task ExecuteAsync_WhenTheFormIsMalformed_ShouldTreatTheUploadAsMissingAndSendNullArchive() + { + // Arrange + CancellationToken cancellationToken = CancellationToken.None; + ThemeResponse expectedResponse = _themeResponseFixture.Create(); + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From(expectedResponse)); + ConfigureMalformedForm(); + + // Act + IResult result = await _sut.ExecuteAsync(EmptyRequest.Instance, cancellationToken); + + // Assert + Ok okResult = Assert.IsType>(result); + Assert.Equal(expectedResponse, okResult.Value); + await _mockHandler.Received(1).HandleAsync( + Arg.Is(command => + command.Archive == null && + command.FileName == null), + Arg.Is(cancellationToken)); + } + private void ConfigureFormWithArchive(byte[] content, string fileName) { // the stream stays open for the duration of the test, since the endpoint reads it through the form file during execution @@ -164,8 +187,8 @@ public class InstallThemeEndpointTests FormFileCollection files = [formFile]; IFormCollection form = new FormCollection([], files); _sut.HttpContext.Request.ContentType = "multipart/form-data; boundary=----test"; - // a real FormFeature is used instead of a substitute, because the endpoint execution reads the form through the - // request machinery, which would bypass a mocked feature and parse the (empty) request body + // A real FormFeature is used instead of a substitute, because the endpoint execution reads the form through the + // request machinery, which would bypass a mocked feature and parse the (empty) request body. _sut.HttpContext.Features.Set(new FormFeature(form)); } @@ -175,4 +198,12 @@ public class InstallThemeEndpointTests _sut.HttpContext.Request.ContentType = "multipart/form-data; boundary=----test"; _sut.HttpContext.Features.Set(new FormFeature(form)); } + + private void ConfigureMalformedForm() + { + _sut.HttpContext.Request.ContentType = "multipart/form-data; boundary=----test"; + IFormCollection malformedForm = Substitute.For(); + malformedForm.Files.Returns(_ => throw new InvalidDataException("Malformed multipart body.")); + _sut.HttpContext.Features.Set(new FormFeature(malformedForm)); + } } diff --git a/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Common/HealthChecks/ApiReachabilityHealthCheckTests.cs b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Common/HealthChecks/ApiReachabilityHealthCheckTests.cs new file mode 100644 index 00000000..d4998a32 --- /dev/null +++ b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Common/HealthChecks/ApiReachabilityHealthCheckTests.cs @@ -0,0 +1,116 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Common.DTO.Configuration; +using Lumina.Presentation.Web.Common.HealthChecks; +using Lumina.Presentation.Web.Fixtures.Common.Api; +using Lumina.Presentation.Web.Fixtures.Common.DTO.Configuration; +using Microsoft.Extensions.Diagnostics.HealthChecks; +using Microsoft.Extensions.Options; +using NSubstitute; +using System; +using System.Diagnostics.CodeAnalysis; +using System.Net; +using System.Net.Http; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.UnitTests.Common.HealthChecks; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class ApiReachabilityHealthCheckTests +{ + private readonly ServerConfigurationDtoFixture _serverConfigurationDtoFixture = new(); + + [Fact] + public async Task CheckHealthAsync_WhenApiReturnsSuccess_ShouldReturnHealthyAndProbeReadyEndpoint() + { + // Arrange + TestApiHttpMessageHandler messageHandler = new(_ => new HttpResponseMessage(HttpStatusCode.OK)); + ApiReachabilityHealthCheck sut = CreateSut(messageHandler); + + // Act + HealthCheckResult result = await sut.CheckHealthAsync(CreateHealthCheckContext(sut), CancellationToken.None); + + // Assert + Assert.Equal(HealthStatus.Healthy, result.Status); + Assert.Single(messageHandler.Requests); + Assert.Equal("http://localhost:5214/health/ready", messageHandler.Requests[0].RequestUri!.ToString()); + } + + [Fact] + public async Task CheckHealthAsync_WhenApiReturnsErrorStatus_ShouldReturnUnhealthyWithStatusCodeDescription() + { + // Arrange + TestApiHttpMessageHandler messageHandler = new(_ => new HttpResponseMessage(HttpStatusCode.ServiceUnavailable)); + ApiReachabilityHealthCheck sut = CreateSut(messageHandler); + + // Act + HealthCheckResult result = await sut.CheckHealthAsync(CreateHealthCheckContext(sut), CancellationToken.None); + + // Assert + Assert.Equal(HealthStatus.Unhealthy, result.Status); + Assert.Equal("The API returned status 503.", result.Description); + } + + [Fact] + public async Task CheckHealthAsync_WhenApiRequestThrowsException_ShouldReturnUnhealthyWithException() + { + // Arrange + TestApiHttpMessageHandler messageHandler = new(_ => throw new HttpRequestException("The API is down.")); + ApiReachabilityHealthCheck sut = CreateSut(messageHandler); + + // Act + HealthCheckResult result = await sut.CheckHealthAsync(CreateHealthCheckContext(sut), CancellationToken.None); + + // Assert + Assert.Equal(HealthStatus.Unhealthy, result.Status); + Assert.Equal("The API is not reachable.", result.Description); + Assert.NotNull(result.Exception); + } + + [Fact] + public async Task CheckHealthAsync_WhenCancellationIsRequestedBeforeProbe_ShouldReturnUnhealthy() + { + // Arrange + TestApiHttpMessageHandler messageHandler = new(_ => new HttpResponseMessage(HttpStatusCode.OK)); + ApiReachabilityHealthCheck sut = CreateSut(messageHandler); + CancellationTokenSource cancellationTokenSource = new(); + cancellationTokenSource.Cancel(); + + // Act + HealthCheckResult result = await sut.CheckHealthAsync(CreateHealthCheckContext(sut), cancellationTokenSource.Token); + + // Assert + Assert.Equal(HealthStatus.Unhealthy, result.Status); + Assert.Equal("The API is not reachable.", result.Description); + } + + /// + /// Creates a whose registration points at the given health check. + /// + /// The health check to register in the context. + /// The created instance. + private static HealthCheckContext CreateHealthCheckContext(IHealthCheck healthCheck) + { + // the ApiReachabilityHealthCheck never reads the registration, so a bare context is sufficient + return new HealthCheckContext(); + } + + /// + /// Creates the system under test configured with the provided message handler and a fixed server configuration. + /// + /// The message handler backing the inner . + /// The created . + private ApiReachabilityHealthCheck CreateSut(TestApiHttpMessageHandler messageHandler) + { + HttpClient httpClient = new(messageHandler); + IHttpClientFactory httpClientFactory = Substitute.For(); + httpClientFactory.CreateClient().Returns(httpClient); + IOptionsSnapshot serverConfigurationOptions = Substitute.For>(); + serverConfigurationOptions.Value.Returns(_serverConfigurationDtoFixture.Create(apiVersion: '1', baseAddress: "http://localhost", port: 5214)); + return new ApiReachabilityHealthCheck(httpClientFactory, serverConfigurationOptions); + } +} diff --git a/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Common/Middlewares/ExceptionHandlingMiddlewareTests.cs b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Common/Middlewares/ExceptionHandlingMiddlewareTests.cs new file mode 100644 index 00000000..cd7baeb9 --- /dev/null +++ b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Common/Middlewares/ExceptionHandlingMiddlewareTests.cs @@ -0,0 +1,397 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Common.DTO.Common; +using Lumina.Presentation.Web.Common.Exceptions; +using Lumina.Presentation.Web.Common.Middlewares; +using Lumina.Presentation.Web.Fixtures.Common.DTO.Common; +using Microsoft.AspNetCore.Authentication; +using Microsoft.AspNetCore.Authentication.Cookies; +using Microsoft.AspNetCore.Http; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Localization; +using Microsoft.Extensions.Logging; +using NSubstitute; +using System; +using System.Diagnostics.CodeAnalysis; +using System.IO; +using System.Net; +using System.Security.Claims; +using System.Text; +using System.Text.Json; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.UnitTests.Common.Middlewares; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class ExceptionHandlingMiddlewareTests +{ + private readonly ILogger _mockLogger; + private readonly IStringLocalizer _mockStringLocalizer; + private readonly IAuthenticationService _mockAuthenticationService; + private readonly ExceptionHandlingMiddleware _sut; + private readonly ProblemDetailsDtoFixture _problemDetailsDtoFixture = new(); + private RequestDelegate _nextDelegate; + + /// + /// Initializes a new instance of the class. + /// + public ExceptionHandlingMiddlewareTests() + { + _mockLogger = Substitute.For>(); + _mockStringLocalizer = Substitute.For>(); + _mockStringLocalizer[Arg.Any()].Returns(callInfo => new LocalizedString(callInfo.Arg(), $"localized:{callInfo.Arg()}")); + _mockAuthenticationService = Substitute.For(); + _mockAuthenticationService.SignOutAsync(Arg.Any(), Arg.Any(), Arg.Any()).Returns(Task.CompletedTask); + _mockAuthenticationService.ForbidAsync(Arg.Any(), Arg.Any(), Arg.Any()).Returns(Task.CompletedTask); + _nextDelegate = context => Task.CompletedTask; + _sut = new ExceptionHandlingMiddleware(context => _nextDelegate(context), _mockLogger, _mockStringLocalizer); + } + + [Fact] + public async Task InvokeAsync_WhenNextCompletesSuccessfully_ShouldNotModifyResponse() + { + // Arrange + DefaultHttpContext httpContext = CreateHttpContext(); + _nextDelegate = context => Task.CompletedTask; + + // Act + await _sut.InvokeAsync(httpContext); + + // Assert + Assert.Equal(StatusCodes.Status200OK, httpContext.Response.StatusCode); + Assert.Equal(0, httpContext.Response.Body.Length); + } + + [Fact] + public async Task InvokeAsync_WhenNextThrowsNonApiException_ShouldLogErrorAndWriteFailureJson() + { + // Arrange + DefaultHttpContext httpContext = CreateHttpContext(); + _nextDelegate = _ => throw new InvalidOperationException("Unexpected failure"); + + // Act + await _sut.InvokeAsync(httpContext); + + // Assert + Assert.Contains("application/json", httpContext.Response.ContentType); + string body = await ReadResponseBodyAsync(httpContext); + using JsonDocument jsonDocument = JsonDocument.Parse(body); + Assert.False(jsonDocument.RootElement.GetProperty("success").GetBoolean()); + Assert.Equal("Unexpected failure", jsonDocument.RootElement.GetProperty("errorMessage").GetString()); + _mockLogger.Received(1).Log( + LogLevel.Error, + Arg.Any(), + Arg.Any(), + Arg.Is(exception => exception is InvalidOperationException && exception.Message == "Unexpected failure"), + Arg.Any>()); + } + + [Fact] + public async Task InvokeAsync_WhenApiExceptionUnauthorizedAndApiRequest_ShouldSignOutAndWriteUnauthorizedJson() + { + // Arrange + DefaultHttpContext httpContext = CreateHttpContext(isApiRequest: true, requestServices: CreateServiceProvider()); + _nextDelegate = _ => throw new ApiException(null, HttpStatusCode.Unauthorized); + + // Act + await _sut.InvokeAsync(httpContext); + + // Assert + Assert.Equal(StatusCodes.Status401Unauthorized, httpContext.Response.StatusCode); + Assert.Equal("Unauthorized", await ReadErrorMessageAsync(httpContext)); + Assert.Contains("Token=", httpContext.Response.Headers["Set-Cookie"].ToString()); + await _mockAuthenticationService.Received(1).SignOutAsync(httpContext, CookieAuthenticationDefaults.AuthenticationScheme, Arg.Any()); + } + + [Fact] + public async Task InvokeAsync_WhenApiExceptionUnauthorizedAndPageRequest_ShouldSignOutAndRedirectToLogin() + { + // Arrange + DefaultHttpContext httpContext = CreateHttpContext(isApiRequest: false, culture: "en-US", requestServices: CreateServiceProvider()); + httpContext.Request.Path = "/library/books"; + httpContext.Request.QueryString = new QueryString("?id=1"); + _nextDelegate = _ => throw new ApiException(null, HttpStatusCode.Unauthorized); + + // Act + await _sut.InvokeAsync(httpContext); + + // Assert + Assert.Equal(StatusCodes.Status302Found, httpContext.Response.StatusCode); + Assert.Equal("/en-us/auth/login?returnUrl=%2Flibrary%2Fbooks%3Fid%3D1", httpContext.Response.Headers.Location.ToString()); + await _mockAuthenticationService.Received(1).SignOutAsync(httpContext, CookieAuthenticationDefaults.AuthenticationScheme, Arg.Any()); + } + + [Fact] + public async Task InvokeAsync_WhenApiExceptionNotFoundAndApiRequest_ShouldWriteNotFoundJson() + { + // Arrange + DefaultHttpContext httpContext = CreateHttpContext(isApiRequest: true); + _nextDelegate = _ => throw new ApiException(_problemDetailsDtoFixture.Create(), HttpStatusCode.NotFound); + + // Act + await _sut.InvokeAsync(httpContext); + + // Assert + Assert.Equal(StatusCodes.Status404NotFound, httpContext.Response.StatusCode); + Assert.Equal("NotFound", await ReadErrorMessageAsync(httpContext)); + } + + [Fact] + public async Task InvokeAsync_WhenApiExceptionNotFoundAndPageRequest_ShouldRedirectToNotFoundPage() + { + // Arrange + DefaultHttpContext httpContext = CreateHttpContext(isApiRequest: false, culture: "de-DE"); + _nextDelegate = _ => throw new ApiException(_problemDetailsDtoFixture.Create(), HttpStatusCode.NotFound); + + // Act + await _sut.InvokeAsync(httpContext); + + // Assert + Assert.Equal(StatusCodes.Status302Found, httpContext.Response.StatusCode); + Assert.Equal("/de-de/not-found", httpContext.Response.Headers.Location.ToString()); + } + + [Fact] + public async Task InvokeAsync_WhenApiExceptionNotFoundForAuthenticatedAuthorizationCheckAndApiRequest_ShouldSignOutAndWriteUnauthorizedJson() + { + // Arrange + DefaultHttpContext httpContext = CreateHttpContext(isApiRequest: true, user: CreateAuthenticatedUser(), requestServices: CreateServiceProvider()); + _nextDelegate = _ => throw new ApiException(_problemDetailsDtoFixture.Create(), HttpStatusCode.NotFound, "/api/v1/auth/get-authorization?userId=1"); + + // Act + await _sut.InvokeAsync(httpContext); + + // Assert + Assert.Equal(StatusCodes.Status401Unauthorized, httpContext.Response.StatusCode); + Assert.Equal("Unauthorized", await ReadErrorMessageAsync(httpContext)); + await _mockAuthenticationService.Received(1).SignOutAsync(httpContext, CookieAuthenticationDefaults.AuthenticationScheme, Arg.Any()); + } + + [Fact] + public async Task InvokeAsync_WhenApiExceptionNotFoundForAuthenticatedAuthorizationCheckAndPageRequest_ShouldSignOutAndRedirectToLogin() + { + // Arrange + DefaultHttpContext httpContext = CreateHttpContext(isApiRequest: false, culture: null, user: CreateAuthenticatedUser(), requestServices: CreateServiceProvider()); + httpContext.Request.Path = "/dashboard"; + _nextDelegate = _ => throw new ApiException(_problemDetailsDtoFixture.Create(), HttpStatusCode.NotFound, "/api/v1/auth/get-authorization?userId=1"); + + // Act + await _sut.InvokeAsync(httpContext); + + // Assert + Assert.Equal(StatusCodes.Status302Found, httpContext.Response.StatusCode); + Assert.Equal("/en-us/auth/login?returnUrl=%2Fdashboard", httpContext.Response.Headers.Location.ToString()); + await _mockAuthenticationService.Received(1).SignOutAsync(httpContext, CookieAuthenticationDefaults.AuthenticationScheme, Arg.Any()); + } + + [Fact] + public async Task InvokeAsync_WhenApiExceptionForbiddenAndApiRequest_ShouldWriteFailureJsonWithProblemDetail() + { + // Arrange + DefaultHttpContext httpContext = CreateHttpContext(isApiRequest: true); + ProblemDetailsDto problemDetails = _problemDetailsDtoFixture.Create(detail: "Access.Denied", title: "General.Forbidden"); + _nextDelegate = _ => throw new ApiException(problemDetails, HttpStatusCode.Forbidden); + + // Act + await _sut.InvokeAsync(httpContext); + + // Assert + string errorMessage = await ReadErrorMessageAsync(httpContext); + Assert.Contains("localized:Access.Denied", errorMessage); + } + + [Fact] + public async Task InvokeAsync_WhenApiExceptionForbiddenAndPageRequest_ShouldForbidTheRequest() + { + // Arrange + DefaultHttpContext httpContext = CreateHttpContext(isApiRequest: false, requestServices: CreateServiceProvider()); + _nextDelegate = _ => throw new ApiException(_problemDetailsDtoFixture.Create(), HttpStatusCode.Forbidden); + + // Act + await _sut.InvokeAsync(httpContext); + + // Assert + await _mockAuthenticationService.Received(1).ForbidAsync(httpContext, Arg.Any(), Arg.Any()); + Assert.Equal(0, httpContext.Response.Body.Length); + } + + [Fact] + public async Task InvokeAsync_WhenApiExceptionForbiddenAndXmlHttpRequestHeader_ShouldWriteFailureJson() + { + // Arrange + DefaultHttpContext httpContext = CreateHttpContext(isApiRequest: false); + httpContext.Request.Headers.XRequestedWith = "XMLHttpRequest"; + ProblemDetailsDto problemDetails = _problemDetailsDtoFixture.Create(detail: "Access.Denied", title: "General.Forbidden"); + _nextDelegate = _ => throw new ApiException(problemDetails, HttpStatusCode.Forbidden); + + // Act + await _sut.InvokeAsync(httpContext); + + // Assert + string errorMessage = await ReadErrorMessageAsync(httpContext); + Assert.Contains("localized:Access.Denied", errorMessage); + } + + [Fact] + public async Task InvokeAsync_WhenApiExceptionHasProblemDetail_ShouldWriteLocalizedDetailMessage() + { + // Arrange + DefaultHttpContext httpContext = CreateHttpContext(isApiRequest: true); + ProblemDetailsDto problemDetails = _problemDetailsDtoFixture.Create(detail: "Validation.Failed", title: "General.Validation", status: 400); + _nextDelegate = _ => throw new ApiException(problemDetails, HttpStatusCode.BadRequest); + + // Act + await _sut.InvokeAsync(httpContext); + + // Assert + string errorMessage = await ReadErrorMessageAsync(httpContext); + Assert.Contains("localized:Validation.Failed", errorMessage); + } + + [Fact] + public async Task InvokeAsync_WhenApiExceptionHasOnlyProblemTitle_ShouldWriteLocalizedTitleMessage() + { + // Arrange + DefaultHttpContext httpContext = CreateHttpContext(isApiRequest: true); + ProblemDetailsDto problemDetails = new() + { + Title = "General.Failure", + Status = 400 + }; + _nextDelegate = _ => throw new ApiException(problemDetails, HttpStatusCode.BadRequest); + + // Act + await _sut.InvokeAsync(httpContext); + + // Assert + string errorMessage = await ReadErrorMessageAsync(httpContext); + Assert.Contains("localized:General.Failure", errorMessage); + } + + [Fact] + public async Task InvokeAsync_WhenApiExceptionProblemDetailsContainValidationErrors_ShouldWriteLocalizedFieldErrors() + { + // Arrange + DefaultHttpContext httpContext = CreateHttpContext(isApiRequest: true); + ProblemDetailsDto problemDetails = DeserializeProblemDetailsWithErrors(); + _nextDelegate = _ => throw new ApiException(problemDetails, HttpStatusCode.BadRequest); + + // Act + await _sut.InvokeAsync(httpContext); + + // Assert + string errorMessage = await ReadErrorMessageAsync(httpContext); + Assert.Contains("localized:General.Validation", errorMessage); + Assert.Contains("localized:EmailIsInvalid", errorMessage); + Assert.Contains("localized:EmailIsTaken", errorMessage); + Assert.Contains("localized:PasswordTooShort", errorMessage); + } + + [Fact] + public async Task InvokeAsync_WhenApiExceptionHasNoProblemDetails_ShouldWriteExceptionMessageAndLocalizedStatus() + { + // Arrange + DefaultHttpContext httpContext = CreateHttpContext(isApiRequest: true); + _nextDelegate = _ => throw new ApiException(null, HttpStatusCode.InternalServerError, "/api/v1/libraries/1"); + + // Act + await _sut.InvokeAsync(httpContext); + + // Assert + string errorMessage = await ReadErrorMessageAsync(httpContext); + Assert.Contains("An error occurred.", errorMessage); + Assert.Contains("localized:InternalServerError", errorMessage); + } + + /// + /// Creates a with a writable response body and optional API/user/culture/service configuration. + /// + /// Whether the request accepts JSON, making it an API request. + /// The culture route value, when no route value is present. + /// The user associated with the context, for anonymous requests. + /// The request services, to leave the default provider in place. + /// The configured instance. + private static DefaultHttpContext CreateHttpContext(bool isApiRequest = false, string? culture = null, ClaimsPrincipal? user = null, IServiceProvider? requestServices = null) + { + DefaultHttpContext httpContext = new() + { + Response = { Body = new MemoryStream() } + }; + if (isApiRequest) + httpContext.Request.Headers.Accept = "application/json"; + if (culture is not null) + httpContext.Request.RouteValues["culture"] = culture; + if (user is not null) + httpContext.User = user; + if (requestServices is not null) + httpContext.RequestServices = requestServices; + return httpContext; + } + + /// + /// Creates a service provider that resolves the mocked . + /// + /// The configured instance. + private IServiceProvider CreateServiceProvider() + { + ServiceCollection services = new(); + services.AddSingleton(_mockAuthenticationService); + return services.BuildServiceProvider(); + } + + /// + /// Creates an authenticated user principal with a name identifier claim. + /// + /// The created instance. + private static ClaimsPrincipal CreateAuthenticatedUser() + { + return new ClaimsPrincipal(new ClaimsIdentity([new Claim(ClaimTypes.NameIdentifier, Guid.NewGuid().ToString())], "TestAuthentication")); + } + + /// + /// Reads the current response body of the provided HTTP context. + /// + /// The HTTP context whose response body is read. + /// The response body content. + private static async Task ReadResponseBodyAsync(HttpContext httpContext) + { + httpContext.Response.Body.Position = 0; + using StreamReader reader = new(httpContext.Response.Body, Encoding.UTF8); + return await reader.ReadToEndAsync(); + } + + /// + /// Reads the errorMessage property from the JSON response body of the provided HTTP context. + /// + /// The HTTP context whose JSON response body is read. + /// The value of the errorMessage property. + private static async Task ReadErrorMessageAsync(HttpContext httpContext) + { + string body = await ReadResponseBodyAsync(httpContext); + using JsonDocument jsonDocument = JsonDocument.Parse(body); + return jsonDocument.RootElement.GetProperty("errorMessage").GetString() ?? string.Empty; + } + + /// + /// Deserializes a problem details payload that contains a validation errors extension object. + /// + /// The deserialized instance. + private static ProblemDetailsDto DeserializeProblemDetailsWithErrors() + { + string problemDetailsJson = """ + { + "type": "https://tools.ietf.org/html/rfc4918#section-11.2", + "title": "General.Validation", + "status": 400, + "errors": { + "Email": ["EmailIsInvalid", "EmailIsTaken"], + "Password": ["PasswordTooShort"] + } + } + """; + return JsonSerializer.Deserialize(problemDetailsJson)!; + } +} diff --git a/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Common/Middlewares/NotFoundRedirectMiddlewareTests.cs b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Common/Middlewares/NotFoundRedirectMiddlewareTests.cs new file mode 100644 index 00000000..c40be59e --- /dev/null +++ b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Common/Middlewares/NotFoundRedirectMiddlewareTests.cs @@ -0,0 +1,224 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Common.Middlewares; +using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Http.Features; +using Microsoft.AspNetCore.Localization; +using Microsoft.Extensions.Logging; +using NSubstitute; +using System; +using System.Diagnostics.CodeAnalysis; +using System.IO; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.UnitTests.Common.Middlewares; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class NotFoundRedirectMiddlewareTests +{ + private readonly ILogger _mockLogger; + private readonly NotFoundRedirectMiddleware _sut; + private RequestDelegate _nextDelegate; + + /// + /// Initializes a new instance of the class. + /// + public NotFoundRedirectMiddlewareTests() + { + _mockLogger = Substitute.For>(); + _nextDelegate = context => Task.CompletedTask; + _sut = new NotFoundRedirectMiddleware(context => _nextDelegate(context), _mockLogger); + } + + [Fact] + public async Task InvokeAsync_WhenResponseIs404AndResponseHasNotStarted_ShouldReexecuteRequestAgainstNotFoundPage() + { + // Arrange + int invocationCount = 0; + string? invokedPath = null; + _nextDelegate = context => + { + invocationCount++; + invokedPath = context.Request.Path.Value; + if (invocationCount == 1) + context.Response.StatusCode = StatusCodes.Status404NotFound; + return Task.CompletedTask; + }; + DefaultHttpContext httpContext = CreateHttpContext(culture: "de-DE"); + httpContext.Request.Path = "/en-us/books/123"; + + // Act + await _sut.InvokeAsync(httpContext); + + // Assert + Assert.Equal(2, invocationCount); + Assert.Equal("/de-de/not-found", invokedPath); + Assert.Equal("/de-de/not-found", httpContext.Request.Path.Value); + Assert.Equal("/en-us/books/123", httpContext.Items["originalPath"] as string); + Assert.Equal(StatusCodes.Status404NotFound, httpContext.Response.StatusCode); + } + + [Fact] + public async Task InvokeAsync_WhenCultureComesFromRequestCultureFeature_ShouldUseTheFeatureCulture() + { + // Arrange + int invocationCount = 0; + string? invokedPath = null; + _nextDelegate = context => + { + invocationCount++; + invokedPath = context.Request.Path.Value; + if (invocationCount == 1) + context.Response.StatusCode = StatusCodes.Status404NotFound; + return Task.CompletedTask; + }; + DefaultHttpContext httpContext = CreateHttpContext(culture: null); + IRequestCultureFeature requestCultureFeature = Substitute.For(); + requestCultureFeature.RequestCulture.Returns(new RequestCulture("fr-FR")); + httpContext.Features.Set(requestCultureFeature); + + // Act + await _sut.InvokeAsync(httpContext); + + // Assert + Assert.Equal(2, invocationCount); + Assert.Equal("/fr-fr/not-found", invokedPath); + } + + [Fact] + public async Task InvokeAsync_WhenNoCultureSourceIsAvailable_ShouldFallBackToDefaultCulture() + { + // Arrange + int invocationCount = 0; + string? invokedPath = null; + _nextDelegate = context => + { + invocationCount++; + invokedPath = context.Request.Path.Value; + if (invocationCount == 1) + context.Response.StatusCode = StatusCodes.Status404NotFound; + return Task.CompletedTask; + }; + DefaultHttpContext httpContext = CreateHttpContext(culture: null); + + // Act + await _sut.InvokeAsync(httpContext); + + // Assert + Assert.Equal(2, invocationCount); + Assert.Equal("/en-us/not-found", invokedPath); + } + + [Fact] + public async Task InvokeAsync_WhenResponseStatusIsNot404_ShouldNotReexecuteRequest() + { + // Arrange + int invocationCount = 0; + _nextDelegate = context => + { + invocationCount++; + context.Response.StatusCode = StatusCodes.Status200OK; + return Task.CompletedTask; + }; + DefaultHttpContext httpContext = CreateHttpContext(culture: "de-DE"); + httpContext.Request.Path = "/en-us/books/123"; + + // Act + await _sut.InvokeAsync(httpContext); + + // Assert + Assert.Equal(1, invocationCount); + Assert.Equal("/en-us/books/123", httpContext.Request.Path.Value); + } + + [Fact] + public async Task InvokeAsync_WhenResponseIs404AndResponseHasStarted_ShouldNotReexecuteRequest() + { + // Arrange + int invocationCount = 0; + _nextDelegate = context => + { + invocationCount++; + context.Response.StatusCode = StatusCodes.Status404NotFound; + return Task.CompletedTask; + }; + DefaultHttpContext httpContext = CreateHttpContext(culture: "de-DE"); + httpContext.Request.Path = "/en-us/books/123"; + httpContext.Features.Set(new StartedHttpResponseFeature()); + + // Act + await _sut.InvokeAsync(httpContext); + + // Assert + Assert.Equal(1, invocationCount); + Assert.Equal("/en-us/books/123", httpContext.Request.Path.Value); + } + + /// + /// Creates a with a writable response body and an optional culture route value. + /// + /// The culture route value, when no route value is present. + /// The configured instance. + private static DefaultHttpContext CreateHttpContext(string? culture) + { + DefaultHttpContext httpContext = new() + { + Response = { Body = new MemoryStream() } + }; + if (culture is not null) + httpContext.Request.RouteValues["culture"] = culture; + return httpContext; + } + + /// + /// Response feature that reports the response as already started, for simulating a response that cannot be replaced. + /// + private sealed class StartedHttpResponseFeature : IHttpResponseFeature + { + /// + /// Gets or sets the HTTP status code of the response. + /// + public int StatusCode { get; set; } = StatusCodes.Status200OK; + + /// + /// Gets or sets the reason phrase of the response. + /// + public string? ReasonPhrase { get; set; } + + /// + /// Gets or sets the response headers. + /// + public IHeaderDictionary Headers { get; set; } = new HeaderDictionary(); + + /// + /// Gets or sets the response body stream. + /// + public Stream Body { get; set; } = Stream.Null; + + /// + /// Gets a value indicating whether the response has already started. + /// + public bool HasStarted => true; + + /// + /// Registers a callback to be invoked when the response is about to start. + /// + /// The callback to invoke. + /// The state passed to the callback. + public void OnStarting(Func callback, object state) + { + } + + /// + /// Registers a callback to be invoked when the response has completed. + /// + /// The callback to invoke. + /// The state passed to the callback. + public void OnCompleted(Func callback, object state) + { + } + } +} diff --git a/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Common/Services/CachedAuthorizationHandlerTests.cs b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Common/Services/CachedAuthorizationHandlerTests.cs new file mode 100644 index 00000000..2e19bbad --- /dev/null +++ b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Common/Services/CachedAuthorizationHandlerTests.cs @@ -0,0 +1,192 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Common.Services; +using Lumina.Presentation.Web.Fixtures.Common.Api; +using Microsoft.AspNetCore.Http; +using Microsoft.Extensions.Caching.Hybrid; +using Microsoft.Extensions.DependencyInjection; +using NSubstitute; +using System; +using System.Diagnostics.CodeAnalysis; +using System.Net; +using System.Net.Http; +using System.Security.Claims; +using System.Text; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.UnitTests.Common.Services; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class CachedAuthorizationHandlerTests +{ + private const string AUTHORIZATION_ENDPOINT = "http://localhost:5214/api/v1/auth/get-authorization"; + private const string LOGIN_ENDPOINT = "http://localhost:5214/api/v1/auth/login"; + private readonly HybridCache _hybridCache; + + /// + /// Initializes a new instance of the class. + /// + public CachedAuthorizationHandlerTests() + { + ServiceCollection services = new(); + services.AddHybridCache(); + _hybridCache = services.BuildServiceProvider().GetRequiredService(); + } + + [Fact] + public async Task SendAsync_WhenAuthorizationRequestIsServedTwice_ShouldCallInnerHandlerOnlyOnce() + { + // Arrange + TestApiHttpMessageHandler messageHandler = new(_ => CreateJsonResponse(HttpStatusCode.OK, """{"role":"Admin","permissions":[]}""")); + HttpClient client = CreateClient(userId: Guid.NewGuid(), messageHandler); + + // Act + HttpResponseMessage firstResponse = await client.GetAsync(AUTHORIZATION_ENDPOINT, CancellationToken.None); + HttpResponseMessage secondResponse = await client.GetAsync(AUTHORIZATION_ENDPOINT, CancellationToken.None); + + // Assert + Assert.Single(messageHandler.Requests); + Assert.Equal(HttpStatusCode.OK, firstResponse.StatusCode); + Assert.Equal(HttpStatusCode.OK, secondResponse.StatusCode); + Assert.Equal(await firstResponse.Content.ReadAsStringAsync(), await secondResponse.Content.ReadAsStringAsync()); + } + + [Fact] + public async Task SendAsync_WhenNonAuthorizationRequestIsServedTwice_ShouldCallInnerHandlerTwice() + { + // Arrange + TestApiHttpMessageHandler messageHandler = new(_ => CreateJsonResponse(HttpStatusCode.OK, """[{"title":"Library One"}]""")); + HttpClient client = CreateClient(userId: Guid.NewGuid(), messageHandler); + + // Act + await client.GetAsync("http://localhost:5214/api/v1/libraries", CancellationToken.None); + await client.GetAsync("http://localhost:5214/api/v1/libraries", CancellationToken.None); + + // Assert + Assert.Equal(2, messageHandler.Requests.Count); + } + + [Fact] + public async Task SendAsync_WhenLoginRequestFollowsCachedAuthorizationRequest_ShouldInvalidateCachedAuthorization() + { + // Arrange + TestApiHttpMessageHandler messageHandler = new(_ => CreateJsonResponse(HttpStatusCode.OK, """{"role":"Admin","permissions":[]}""")); + HttpClient client = CreateClient(userId: Guid.NewGuid(), messageHandler); + + // Act + await client.GetAsync(AUTHORIZATION_ENDPOINT, CancellationToken.None); + await client.PostAsync(LOGIN_ENDPOINT, new StringContent("""{"username":"testuser","password":"TestPass123!"}""", Encoding.UTF8, "application/json"), CancellationToken.None); + await client.GetAsync(AUTHORIZATION_ENDPOINT, CancellationToken.None); + + // Assert + Assert.Equal(3, messageHandler.Requests.Count); + } + + [Fact] + public async Task SendAsync_WhenAuthorizationReturnsUnauthorized_ShouldNotRetainTheCachedResponse() + { + // Arrange + TestApiHttpMessageHandler messageHandler = new(_ => CreateJsonResponse(HttpStatusCode.Unauthorized, """{"title":"Unauthorized"}""")); + HttpClient client = CreateClient(userId: Guid.NewGuid(), messageHandler); + + // Act + HttpResponseMessage firstResponse = await client.GetAsync(AUTHORIZATION_ENDPOINT, CancellationToken.None); + HttpResponseMessage secondResponse = await client.GetAsync(AUTHORIZATION_ENDPOINT, CancellationToken.None); + + // Assert + Assert.Equal(2, messageHandler.Requests.Count); + Assert.Equal(HttpStatusCode.Unauthorized, firstResponse.StatusCode); + Assert.Equal(HttpStatusCode.Unauthorized, secondResponse.StatusCode); + } + + [Fact] + public async Task SendAsync_WhenAuthorizationReturnsNotFound_ShouldNotRetainTheCachedResponse() + { + // Arrange + TestApiHttpMessageHandler messageHandler = new(_ => CreateJsonResponse(HttpStatusCode.NotFound, """{"title":"NotFound"}""")); + HttpClient client = CreateClient(userId: Guid.NewGuid(), messageHandler); + + // Act + await client.GetAsync(AUTHORIZATION_ENDPOINT, CancellationToken.None); + await client.GetAsync(AUTHORIZATION_ENDPOINT, CancellationToken.None); + + // Assert + Assert.Equal(2, messageHandler.Requests.Count); + } + + [Fact] + public async Task SendAsync_WhenAuthorizationRequestIsMadeWithoutAuthenticatedUser_ShouldStillCacheTheResponse() + { + // Arrange + TestApiHttpMessageHandler messageHandler = new(_ => CreateJsonResponse(HttpStatusCode.OK, """{"role":"Admin","permissions":[]}""")); + HttpClient client = CreateClient(userId: null, messageHandler); + + // Act + await client.GetAsync(AUTHORIZATION_ENDPOINT, CancellationToken.None); + await client.GetAsync(AUTHORIZATION_ENDPOINT, CancellationToken.None); + + // Assert + Assert.Single(messageHandler.Requests); + } + + [Fact] + public async Task SendAsync_WhenDifferentUsersRequestAuthorization_ShouldServeSeparateCachedResponses() + { + // Arrange + TestApiHttpMessageHandler messageHandler = new(_ => CreateJsonResponse(HttpStatusCode.OK, """{"role":"Admin","permissions":[]}""")); + HttpClient firstClient = CreateClient(userId: Guid.NewGuid(), messageHandler); + HttpClient secondClient = CreateClient(userId: Guid.NewGuid(), messageHandler); + + // Act + await firstClient.GetAsync(AUTHORIZATION_ENDPOINT, CancellationToken.None); + await firstClient.GetAsync(AUTHORIZATION_ENDPOINT, CancellationToken.None); + + // Assert + Assert.Equal(1, messageHandler.Requests.Count); + + // Act + await secondClient.GetAsync(AUTHORIZATION_ENDPOINT, CancellationToken.None); + await secondClient.GetAsync(AUTHORIZATION_ENDPOINT, CancellationToken.None); + + // Assert + Assert.Equal(2, messageHandler.Requests.Count); + } + + /// + /// Creates an that pipes requests through a backed by the given inner handler. + /// + /// The user id claim placed on the current HTTP context user, for anonymous requests. + /// The message handler backing the inner pipeline. + /// The created . + private HttpClient CreateClient(Guid? userId, TestApiHttpMessageHandler messageHandler) + { + IHttpContextAccessor httpContextAccessor = Substitute.For(); + DefaultHttpContext httpContext = new(); + if (userId is not null) + httpContext.User = new ClaimsPrincipal(new ClaimsIdentity([new Claim(ClaimTypes.NameIdentifier, userId.Value.ToString())], "TestAuthentication")); + httpContextAccessor.HttpContext.Returns(httpContext); + CachedAuthorizationHandler authorizationHandler = new(_hybridCache, httpContextAccessor) + { + InnerHandler = messageHandler + }; + return new HttpClient(authorizationHandler); + } + + /// + /// Creates an with the given status code and JSON body. + /// + /// The HTTP status code of the response. + /// The JSON payload of the response body. + /// The created . + private static HttpResponseMessage CreateJsonResponse(HttpStatusCode statusCode, string json) + { + return new HttpResponseMessage(statusCode) + { + Content = new StringContent(json, Encoding.UTF8, "application/json") + }; + } +} diff --git a/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Common/Validation/ValidationOptionsTests.cs b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Common/Validation/ValidationOptionsTests.cs new file mode 100644 index 00000000..466a7c72 --- /dev/null +++ b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Common/Validation/ValidationOptionsTests.cs @@ -0,0 +1,148 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Common.Primitives; +using Lumina.Presentation.Web.Common.Validation; +using Microsoft.Extensions.Options; +using NSubstitute; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Presentation.Web.UnitTests.Common.Validation; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class ValidationOptionsTests +{ + [Fact] + public void Validate_WhenMatchingName_ShouldValidateOptions() + { + // Arrange + string optionsName = "OptionsName"; + TestOptions options = new(); + IValidator validator = Substitute.For>(); + validator.Validate(options).Returns([]); + ValidationOptions sut = new(optionsName, validator); + + // Act + ValidateOptionsResult result = sut.Validate(optionsName, options); + + // Assert + Assert.IsType(result); + Assert.False(result.Failed); + validator.Received(1).Validate(options); + } + + [Fact] + public void Validate_WhenNonMatchingName_ShouldSkipValidation() + { + // Arrange + string optionsName = "OptionsName"; + string differentOptionsName = "DifferentOptionsName"; + TestOptions options = new(); + IValidator validator = Substitute.For>(); + ValidationOptions sut = new(optionsName, validator); + + // Act + ValidateOptionsResult result = sut.Validate(differentOptionsName, options); + + // Assert + Assert.Equal(ValidateOptionsResult.Skip, result); + validator.DidNotReceive().Validate(options); + } + + [Fact] + public void Validate_WhenNullName_ShouldValidateOptions() + { + // Arrange + TestOptions options = new(); + IValidator validator = Substitute.For>(); + validator.Validate(options).Returns([]); + ValidationOptions sut = new(null, validator); + + // Act + ValidateOptionsResult result = sut.Validate("AnyOptionsName", options); + + // Assert + Assert.IsType(result); + Assert.False(result.Failed); + validator.Received(1).Validate(options); + } + + [Fact] + public void Validate_WhenNullOptions_ShouldThrowArgumentNullException() + { + // Arrange + string optionsName = "OptionsName"; + IValidator validator = Substitute.For>(); + ValidationOptions sut = new(optionsName, validator); + + // Act + Action act = () => sut.Validate(optionsName, null!); + + // Assert + Assert.Throws(act); + validator.DidNotReceive().Validate(Arg.Any()); + } + + [Fact] + public void Validate_WhenInvalidOptions_ShouldReturnFailureResult() + { + // Arrange + string optionsName = "OptionsName"; + TestOptions options = new(); + IValidator validator = Substitute.For>(); + List validationFailures = + [ + Error.Validation("PropertyName", "Error Message") + ]; + validator.Validate(options).Returns(validationFailures); + ValidationOptions sut = new(optionsName, validator); + + // Act + ValidateOptionsResult result = sut.Validate(optionsName, options); + + // Assert + Assert.IsType(result); + Assert.True(result.Failed); + Assert.Single(result.Failures); + Assert.Contains("Options validation failed for 'PropertyName' with error: 'Error Message'", result.Failures); + } + + [Fact] + public void Validate_WhenMultipleValidationErrors_ShouldReturnOneFailureMessagePerError() + { + // Arrange + string optionsName = "OptionsName"; + TestOptions options = new(); + IValidator validator = Substitute.For>(); + List validationFailures = + [ + Error.Validation("PropertyOne", "First Error Message"), + Error.Validation("PropertyTwo", "Second Error Message") + ]; + validator.Validate(options).Returns(validationFailures); + ValidationOptions sut = new(optionsName, validator); + + // Act + ValidateOptionsResult result = sut.Validate(optionsName, options); + + // Assert + Assert.IsType(result); + Assert.True(result.Failed); + Assert.Equal(2, result.Failures.Count()); + Assert.Contains("Options validation failed for 'PropertyOne' with error: 'First Error Message'", result.Failures); + Assert.Contains("Options validation failed for 'PropertyTwo' with error: 'Second Error Message'", result.Failures); + } + + /// + /// Placeholder options type used to exercise the generic class. + /// + [ExcludeFromCodeCoverage] + public sealed class TestOptions + { + } +} diff --git a/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Common/Validation/ValidationRuleForEachTests.cs b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Common/Validation/ValidationRuleForEachTests.cs new file mode 100644 index 00000000..35b4a282 --- /dev/null +++ b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Common/Validation/ValidationRuleForEachTests.cs @@ -0,0 +1,393 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Common.Primitives; +using Lumina.Presentation.Web.Common.Validation; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Presentation.Web.UnitTests.Common.Validation; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class ValidationRuleForEachTests +{ + private readonly ValidationRuleForEach _sut; + + /// + /// Initializes a new instance of the class. + /// + public ValidationRuleForEachTests() + { + _sut = new ValidationRuleForEach(request => request.Items); + } + + [Fact] + public void Validate_WhenNoPredicatesConfigured_ShouldReturnNoErrors() + { + // Arrange + TestRequest request = new() + { + Items = ["value"] + }; + + // Act + List result = [.. _sut.Validate(request)]; + + // Assert + Assert.Empty(result); + } + + [Fact] + public void Validate_WhenCollectionIsNull_ShouldReturnNoErrors() + { + // Arrange + _sut.Must(item => item.Length > 0); + TestRequest request = new() + { + Items = null + }; + + // Act + List result = [.. _sut.Validate(request)]; + + // Assert + Assert.Empty(result); + } + + [Fact] + public void Validate_WhenCollectionIsEmpty_ShouldReturnNoErrors() + { + // Arrange + _sut.Must(item => item.Length > 0); + TestRequest request = new() + { + Items = [] + }; + + // Act + List result = [.. _sut.Validate(request)]; + + // Assert + Assert.Empty(result); + } + + [Fact] + public void Validate_WhenAllItemsSatisfyPredicate_ShouldReturnNoErrors() + { + // Arrange + _sut.Must(item => item.Length > 0); + TestRequest request = new() + { + Items = ["alpha", "beta"] + }; + + // Act + List result = [.. _sut.Validate(request)]; + + // Assert + Assert.Empty(result); + } + + [Fact] + public void Validate_WhenPredicateFailsOnSomeItems_ShouldReturnErrorForEachFailingItem() + { + // Arrange + _sut.Must(item => item.Length > 0); + TestRequest request = new() + { + Items = ["alpha", "", "beta"] + }; + + // Act + List result = [.. _sut.Validate(request)]; + + // Assert + Error error = Assert.Single(result); + Assert.Equal(Error.Validation(), error); + } + + [Fact] + public void Validate_WhenPredicateFailsOnMultipleItems_ShouldReturnOneErrorPerItem() + { + // Arrange + _sut.Must(item => item.Length > 0); + TestRequest request = new() + { + Items = ["", ""] + }; + + // Act + List result = [.. _sut.Validate(request)]; + + // Assert + Assert.Equal(2, result.Count); + Assert.All(result, error => Assert.Equal(Error.Validation(), error)); + } + + [Fact] + public void Validate_WhenMultiplePredicatesFailOnSameItem_ShouldReturnErrorForEachFailingPredicate() + { + // Arrange + _sut.Must(item => item.Length > 3); + _sut.Must(item => item.StartsWith('x')); + TestRequest request = new() + { + Items = ["ab"] + }; + + // Act + List result = [.. _sut.Validate(request)]; + + // Assert + Assert.Equal(2, result.Count); + Assert.All(result, error => Assert.Equal(Error.Validation(), error)); + } + + [Fact] + public void Validate_WhenInstanceAwarePredicateFails_ShouldReturnErrorForEachFailingItem() + { + // Arrange + _sut.Must((request, item) => item != request.ForbiddenItem); + TestRequest request = new() + { + Items = ["forbidden", "allowed"], + ForbiddenItem = "forbidden" + }; + + // Act + List result = [.. _sut.Validate(request)]; + + // Assert + Error error = Assert.Single(result); + Assert.Equal(Error.Validation(), error); + } + + [Fact] + public void Validate_WhenInstanceAwarePredicatePasses_ShouldReturnNoErrors() + { + // Arrange + _sut.Must((request, item) => item != request.ForbiddenItem); + TestRequest request = new() + { + Items = ["allowed", "alsoAllowed"], + ForbiddenItem = "forbidden" + }; + + // Act + List result = [.. _sut.Validate(request)]; + + // Assert + Assert.Empty(result); + } + + [Fact] + public void Validate_WhenConditionEvaluatesToFalse_ShouldSkipValidation() + { + // Arrange + _sut.When(request => request.ShouldValidate) + .Must(item => item.Length > 0); + TestRequest request = new() + { + Items = [""], + ShouldValidate = false + }; + + // Act + List result = [.. _sut.Validate(request)]; + + // Assert + Assert.Empty(result); + } + + [Fact] + public void Validate_WhenConditionEvaluatesToTrue_ShouldRunPredicates() + { + // Arrange + _sut.When(request => request.ShouldValidate) + .Must(item => item.Length > 0); + TestRequest request = new() + { + Items = [""], + ShouldValidate = true + }; + + // Act + List result = [.. _sut.Validate(request)]; + + // Assert + Error error = Assert.Single(result); + Assert.Equal(Error.Validation(), error); + } + + [Fact] + public void Validate_WhenWithErrorConfiguredForPlainPredicate_ShouldReturnConfiguredError() + { + // Arrange + _sut.Must(item => item.Length > 0) + .WithError(Error.Validation(description: "Item must not be empty.")); + TestRequest request = new() + { + Items = [""] + }; + + // Act + List result = [.. _sut.Validate(request)]; + + // Assert + Error error = Assert.Single(result); + Assert.Equal(Error.Validation(description: "Item must not be empty."), error); + } + + [Fact] + public void Validate_WhenWithErrorConfiguredForInstanceAwarePredicate_ShouldReturnConfiguredError() + { + // Arrange + _sut.Must((request, item) => item != request.ForbiddenItem) + .WithError(Error.Validation(description: "Item is forbidden.")); + TestRequest request = new() + { + Items = ["forbidden"], + ForbiddenItem = "forbidden" + }; + + // Act + List result = [.. _sut.Validate(request)]; + + // Assert + Error error = Assert.Single(result); + Assert.Equal(Error.Validation(description: "Item is forbidden."), error); + } + + [Fact] + public void Validate_WhenWithErrorConfiguredBeforeAnyPredicate_ShouldApplyToNextAddedPredicate() + { + // Arrange + _sut.WithError(Error.Validation(description: "Configured before predicate.")) + .Must(item => item.Length > 0); + TestRequest request = new() + { + Items = [""] + }; + + // Act + List result = [.. _sut.Validate(request)]; + + // Assert + Error error = Assert.Single(result); + Assert.Equal(Error.Validation(description: "Configured before predicate."), error); + } + + [Fact] + public void Validate_WhenWithErrorReceivesNonValidationError_ShouldReturnValidationErrorWithSameDescription() + { + // Arrange + _sut.Must(item => item.Length > 0) + .WithError(Error.NotFound(description: "Item is missing.")); + TestRequest request = new() + { + Items = [""] + }; + + // Act + List result = [.. _sut.Validate(request)]; + + // Assert + Error error = Assert.Single(result); + Assert.Equal(Error.Validation(description: "Item is missing."), error); + } + + [Fact] + public void Validate_WhenChildRuleFailsOnItem_ShouldReturnChildValidationError() + { + // Arrange + _sut.ChildRules(childValidator => childValidator.RuleFor(item => item.Length).Must(length => length >= 3)); + TestRequest request = new() + { + Items = ["ab"] + }; + + // Act + List result = [.. _sut.Validate(request)]; + + // Assert + Error error = Assert.Single(result); + Assert.Equal(Error.Validation(), error); + } + + [Fact] + public void Validate_WhenChildRuleFailsOnMultipleItems_ShouldReturnOneErrorPerItem() + { + // Arrange + _sut.ChildRules(childValidator => childValidator.RuleFor(item => item.Length).Must(length => length >= 3)); + TestRequest request = new() + { + Items = ["a", "bb"] + }; + + // Act + List result = [.. _sut.Validate(request)]; + + // Assert + Assert.Equal(2, result.Count); + Assert.All(result, error => Assert.Equal(Error.Validation(), error)); + } + + [Fact] + public void Validate_WhenAllItemsPassChildRule_ShouldReturnNoErrors() + { + // Arrange + _sut.ChildRules(childValidator => childValidator.RuleFor(item => item.Length).Must(length => length >= 3)); + TestRequest request = new() + { + Items = ["abc", "defg"] + }; + + // Act + List result = [.. _sut.Validate(request)]; + + // Assert + Assert.Empty(result); + } + + [Fact] + public void Validate_WhenChildRuleConfiguredAndCollectionContainsNullItem_ShouldSkipNullItem() + { + // Arrange + _sut.ChildRules(childValidator => childValidator.RuleFor(item => item.Length).Must(length => length >= 1)); + TestRequest request = new() + { + Items = ["a", null!] + }; + + // Act + List result = [.. _sut.Validate(request)]; + + // Assert + Assert.Empty(result); + } + + /// + /// Test request type used to exercise the rule. + /// + [ExcludeFromCodeCoverage] + private sealed class TestRequest + { + /// + /// Gets the collection of string items validated by the rule under test. + /// + public List? Items { get; init; } + + /// + /// Gets a value indicating whether the rule condition should allow validation to run. + /// + public bool ShouldValidate { get; init; } = true; + + /// + /// Gets the value used by the instance-aware predicate to identify forbidden items. + /// + public string ForbiddenItem { get; init; } = "forbidden"; + } +}