From 7ad7ad308ea58fe3dab4f3cb16db695b4fcdafad Mon Sep 17 00:00:00 2001 From: Binary Alley Date: Mon, 17 Aug 2026 11:37:31 -0700 Subject: [PATCH] test: adds unit, integration and security test projects for the web project --- src/Lumina.sln | 61 +++++ .../Common/Api/StubApiHttpClient.cs | 255 ++++++++++++++++++ .../Common/Api/TestApiHttpMessageHandler.cs | 51 ++++ .../DTO/Authorization/RoleDtoFixture.cs | 42 +++ .../Common/DTO/Libraries/LibraryDtoFixture.cs | 51 ++++ .../UsersManagement/UserSettingsDtoFixture.cs | 47 ++++ .../Authorization/AddRoleRequestFixture.cs | 42 +++ .../Authorization/DeleteRoleRequestFixture.cs | 39 +++ .../GetDirectoriesRequestFixture.cs | 39 +++ .../Path/ValidatePathRequestFixture.cs | 37 +++ .../Libraries/GetBooksLiteRequestFixture.cs | 63 +++++ .../Management/DeleteLibraryRequestFixture.cs | 39 +++ .../UpdatePluginSettingsRequestFixture.cs | 43 +++ .../Tools/SetLanguageRequestFixture.cs | 40 +++ .../Authentication/LoginViewRequestFixture.cs | 39 +++ .../ChangePasswordRequestFixture.cs | 46 ++++ .../UsersManagement/LoginRequestFixture.cs | 45 ++++ .../RecoverPasswordRequestFixture.cs | 41 +++ .../UsersManagement/RegisterRequestFixture.cs | 48 ++++ .../TestHelpers/JsonResultTestHelper.cs | 29 ++ .../TestHelpers/TestHttpContextFactory.cs | 125 +++++++++ .../Common/TestHelpers/WebTestHelpers.cs | 114 ++++++++ .../Endpoints/Common/BaseEndpointFixture.cs | 73 +++++ .../Lumina.Presentation.Web.Fixtures.csproj | 25 ++ .../Properties/AssemblyInfo.cs | 22 ++ .../Documentation/OpenApiEndpointTests.cs | 52 ++++ .../Common/Setup/LuminaWebFactory.cs | 63 +++++ .../Roles/GetRoles/GetRolesEndpointTests.cs | 70 +++++ .../Endpoints/Home/HomeIndexEndpointTests.cs | 91 +++++++ .../GetLibraries/GetLibrariesEndpointTests.cs | 90 +++++++ .../SaveLibrary/SaveLibraryEndpointTests.cs | 84 ++++++ .../SetLanguage/SetLanguageEndpointTests.cs | 61 +++++ .../Login/LoginEndpointTests.cs | 138 ++++++++++ .../Login/LoginViewEndpointTests.cs | 79 ++++++ ...a.Presentation.Web.IntegrationTests.csproj | 46 ++++ .../Common/Setup/LuminaWebFactory.cs | 63 +++++ .../Roles/GetRoles/GetRolesEndpointTests.cs | 87 ++++++ .../DeleteLibraryEndpointTests.cs | 82 ++++++ .../SaveLibrary/SaveLibraryEndpointTests.cs | 99 +++++++ .../Login/LoginEndpointTests.cs | 127 +++++++++ ...mina.Presentation.Web.SecurityTests.csproj | 46 ++++ .../Common/Api/ApiHttpClientTests.cs | 177 ++++++++++++ .../AuthorizationPoliciesTests.cs | 22 ++ .../AuthorizationServiceTests.cs | 112 ++++++++ .../CoreHtmlLocalizerFactoryTests.cs | 74 +++++ .../Security/CryptographyServiceTests.cs | 88 ++++++ .../Services/ScriptIdentifierHelperTests.cs | 49 ++++ .../Common/Services/UrlServiceTests.cs | 119 ++++++++ .../EncryptionSettingsModelValidatorTests.cs | 60 +++++ .../ServerConfigurationModelValidatorTests.cs | 75 ++++++ .../Roles/AddRole/AddRoleEndpointTests.cs | 63 +++++ .../DeleteRole/DeleteRoleEndpointTests.cs | 54 ++++ .../Roles/GetRoles/GetRolesEndpointTests.cs | 76 ++++++ .../Endpoints/Common/BaseEndpointTests.cs | 109 ++++++++ .../GetDirectoriesEndpointTests.cs | 76 ++++++ .../ValidatePath/ValidatePathEndpointTests.cs | 77 ++++++ .../DeleteLibraryEndpointTests.cs | 54 ++++ .../GetLibraries/GetLibrariesEndpointTests.cs | 71 +++++ .../SaveLibrary/SaveLibraryEndpointTests.cs | 79 ++++++ .../GetLibraryItemsEndpointTests.cs | 124 +++++++++ .../Index/BooksIndexViewEndpointTests.cs | 77 ++++++ .../GetPlugins/GetPluginsEndpointTests.cs | 70 +++++ .../UpdatePluginSettingsEndpointTests.cs | 59 ++++ .../SetLanguage/SetLanguageEndpointTests.cs | 84 ++++++ .../GetUserSettingsEndpointTests.cs | 71 +++++ .../UpdateUserSettingsEndpointTests.cs | 59 ++++ .../Login/LoginViewEndpointTests.cs | 93 +++++++ .../RecoverPasswordEndpointTests.cs | 61 +++++ .../Register/RegisterEndpointTests.cs | 80 ++++++ .../Lumina.Presentation.Web.UnitTests.csproj | 46 ++++ 70 files changed, 4993 insertions(+) create mode 100644 tests/Common/Lumina.Presentation.Web.Fixtures/Common/Api/StubApiHttpClient.cs create mode 100644 tests/Common/Lumina.Presentation.Web.Fixtures/Common/Api/TestApiHttpMessageHandler.cs create mode 100644 tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/Authorization/RoleDtoFixture.cs create mode 100644 tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/Libraries/LibraryDtoFixture.cs create mode 100644 tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/UsersManagement/UserSettingsDtoFixture.cs create mode 100644 tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/Authorization/AddRoleRequestFixture.cs create mode 100644 tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/Authorization/DeleteRoleRequestFixture.cs create mode 100644 tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/FileSystemManagement/Directories/GetDirectoriesRequestFixture.cs create mode 100644 tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/FileSystemManagement/Path/ValidatePathRequestFixture.cs create mode 100644 tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/Libraries/GetBooksLiteRequestFixture.cs create mode 100644 tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/Library/Management/DeleteLibraryRequestFixture.cs create mode 100644 tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/Plugins/UpdatePluginSettingsRequestFixture.cs create mode 100644 tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/Tools/SetLanguageRequestFixture.cs create mode 100644 tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/UsersManagement/Authentication/LoginViewRequestFixture.cs create mode 100644 tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/UsersManagement/ChangePasswordRequestFixture.cs create mode 100644 tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/UsersManagement/LoginRequestFixture.cs create mode 100644 tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/UsersManagement/RecoverPasswordRequestFixture.cs create mode 100644 tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/UsersManagement/RegisterRequestFixture.cs create mode 100644 tests/Common/Lumina.Presentation.Web.Fixtures/Common/TestHelpers/JsonResultTestHelper.cs create mode 100644 tests/Common/Lumina.Presentation.Web.Fixtures/Common/TestHelpers/TestHttpContextFactory.cs create mode 100644 tests/Common/Lumina.Presentation.Web.Fixtures/Common/TestHelpers/WebTestHelpers.cs create mode 100644 tests/Common/Lumina.Presentation.Web.Fixtures/Core/Endpoints/Common/BaseEndpointFixture.cs create mode 100644 tests/Common/Lumina.Presentation.Web.Fixtures/Lumina.Presentation.Web.Fixtures.csproj create mode 100644 tests/Common/Lumina.Presentation.Web.Fixtures/Properties/AssemblyInfo.cs create mode 100644 tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Common/Documentation/OpenApiEndpointTests.cs create mode 100644 tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Common/Setup/LuminaWebFactory.cs create mode 100644 tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Admin/Authorization/Roles/GetRoles/GetRolesEndpointTests.cs create mode 100644 tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Home/HomeIndexEndpointTests.cs create mode 100644 tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/Management/GetLibraries/GetLibrariesEndpointTests.cs create mode 100644 tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/Management/SaveLibrary/SaveLibraryEndpointTests.cs create mode 100644 tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Tools/Language/SetLanguage/SetLanguageEndpointTests.cs create mode 100644 tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/UsersManagement/Authentication/Login/LoginEndpointTests.cs create mode 100644 tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/UsersManagement/Authentication/Login/LoginViewEndpointTests.cs create mode 100644 tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Lumina.Presentation.Web.IntegrationTests.csproj create mode 100644 tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Common/Setup/LuminaWebFactory.cs create mode 100644 tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Admin/Authorization/Roles/GetRoles/GetRolesEndpointTests.cs create mode 100644 tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Library/Management/DeleteLibrary/DeleteLibraryEndpointTests.cs create mode 100644 tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Library/Management/SaveLibrary/SaveLibraryEndpointTests.cs create mode 100644 tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/UsersManagement/Authentication/Login/LoginEndpointTests.cs create mode 100644 tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Lumina.Presentation.Web.SecurityTests.csproj create mode 100644 tests/UnitTests/Lumina.Presentation.Web.UnitTests/Common/Api/ApiHttpClientTests.cs create mode 100644 tests/UnitTests/Lumina.Presentation.Web.UnitTests/Common/Authorization/AuthorizationPoliciesTests.cs create mode 100644 tests/UnitTests/Lumina.Presentation.Web.UnitTests/Common/Authorization/AuthorizationServiceTests.cs create mode 100644 tests/UnitTests/Lumina.Presentation.Web.UnitTests/Common/Localization/CoreHtmlLocalizerFactoryTests.cs create mode 100644 tests/UnitTests/Lumina.Presentation.Web.UnitTests/Common/Security/CryptographyServiceTests.cs create mode 100644 tests/UnitTests/Lumina.Presentation.Web.UnitTests/Common/Services/ScriptIdentifierHelperTests.cs create mode 100644 tests/UnitTests/Lumina.Presentation.Web.UnitTests/Common/Services/UrlServiceTests.cs create mode 100644 tests/UnitTests/Lumina.Presentation.Web.UnitTests/Common/Validators/EncryptionSettingsModelValidatorTests.cs create mode 100644 tests/UnitTests/Lumina.Presentation.Web.UnitTests/Common/Validators/ServerConfigurationModelValidatorTests.cs create mode 100644 tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Admin/Authorization/Roles/AddRole/AddRoleEndpointTests.cs create mode 100644 tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Admin/Authorization/Roles/DeleteRole/DeleteRoleEndpointTests.cs create mode 100644 tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Admin/Authorization/Roles/GetRoles/GetRolesEndpointTests.cs create mode 100644 tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Common/BaseEndpointTests.cs create mode 100644 tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/FileSystemManagement/Directories/GetDirectories/GetDirectoriesEndpointTests.cs create mode 100644 tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/FileSystemManagement/Path/ValidatePath/ValidatePathEndpointTests.cs create mode 100644 tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Library/Management/DeleteLibrary/DeleteLibraryEndpointTests.cs create mode 100644 tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Library/Management/GetLibraries/GetLibrariesEndpointTests.cs create mode 100644 tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Library/Management/SaveLibrary/SaveLibraryEndpointTests.cs create mode 100644 tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/GetLibraryItems/GetLibraryItemsEndpointTests.cs create mode 100644 tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/Index/BooksIndexViewEndpointTests.cs create mode 100644 tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Plugins/GetPlugins/GetPluginsEndpointTests.cs create mode 100644 tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Plugins/UpdatePluginSettings/UpdatePluginSettingsEndpointTests.cs create mode 100644 tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Tools/Language/SetLanguage/SetLanguageEndpointTests.cs create mode 100644 tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Tools/Settings/GetUserSettings/GetUserSettingsEndpointTests.cs create mode 100644 tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Tools/Settings/UpdateUserSettings/UpdateUserSettingsEndpointTests.cs create mode 100644 tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/UsersManagement/Authentication/Login/LoginViewEndpointTests.cs create mode 100644 tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/UsersManagement/Authentication/RecoverPassword/RecoverPasswordEndpointTests.cs create mode 100644 tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/UsersManagement/Authentication/Register/RegisterEndpointTests.cs create mode 100644 tests/UnitTests/Lumina.Presentation.Web.UnitTests/Lumina.Presentation.Web.UnitTests.csproj diff --git a/src/Lumina.sln b/src/Lumina.sln index 2859a645..712b3786 100644 --- a/src/Lumina.sln +++ b/src/Lumina.sln @@ -1,3 +1,4 @@ + Microsoft Visual Studio Solution File, Format Version 12.00 # Visual Studio Version 17 VisualStudioVersion = 17.0.31903.59 @@ -223,6 +224,14 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Lumina.Presentation.Api.Fix EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Lumina.Domain.SharedKernel.Fixtures", "..\tests\Common\Lumina.Domain.SharedKernel.Fixtures\Lumina.Domain.SharedKernel.Fixtures.csproj", "{A6BC3F8B-CAB8-4F3B-BD89-B7428697DE61}" EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Lumina.Presentation.Web.Fixtures", "..\tests\Common\Lumina.Presentation.Web.Fixtures\Lumina.Presentation.Web.Fixtures.csproj", "{52245330-641B-4E14-823A-10B3D9105D58}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Lumina.Presentation.Web.UnitTests", "..\tests\UnitTests\Lumina.Presentation.Web.UnitTests\Lumina.Presentation.Web.UnitTests.csproj", "{697F6057-DBDC-40B9-A7E5-02F295BC18B3}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Lumina.Presentation.Web.IntegrationTests", "..\tests\IntegrationTests\Lumina.Presentation.Web.IntegrationTests\Lumina.Presentation.Web.IntegrationTests.csproj", "{4BE18EDC-02ED-47E2-A23A-3F6650ADAF0A}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Lumina.Presentation.Web.SecurityTests", "..\tests\SecurityTests\Lumina.Presentation.Web.SecurityTests\Lumina.Presentation.Web.SecurityTests.csproj", "{3FE25467-CBC6-438F-BB96-6601AF56E937}" +EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU @@ -517,6 +526,54 @@ Global {A6BC3F8B-CAB8-4F3B-BD89-B7428697DE61}.Release|x64.Build.0 = Release|Any CPU {A6BC3F8B-CAB8-4F3B-BD89-B7428697DE61}.Release|x86.ActiveCfg = Release|Any CPU {A6BC3F8B-CAB8-4F3B-BD89-B7428697DE61}.Release|x86.Build.0 = Release|Any CPU + {52245330-641B-4E14-823A-10B3D9105D58}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {52245330-641B-4E14-823A-10B3D9105D58}.Debug|Any CPU.Build.0 = Debug|Any CPU + {52245330-641B-4E14-823A-10B3D9105D58}.Debug|x64.ActiveCfg = Debug|Any CPU + {52245330-641B-4E14-823A-10B3D9105D58}.Debug|x64.Build.0 = Debug|Any CPU + {52245330-641B-4E14-823A-10B3D9105D58}.Debug|x86.ActiveCfg = Debug|Any CPU + {52245330-641B-4E14-823A-10B3D9105D58}.Debug|x86.Build.0 = Debug|Any CPU + {52245330-641B-4E14-823A-10B3D9105D58}.Release|Any CPU.ActiveCfg = Release|Any CPU + {52245330-641B-4E14-823A-10B3D9105D58}.Release|Any CPU.Build.0 = Release|Any CPU + {52245330-641B-4E14-823A-10B3D9105D58}.Release|x64.ActiveCfg = Release|Any CPU + {52245330-641B-4E14-823A-10B3D9105D58}.Release|x64.Build.0 = Release|Any CPU + {52245330-641B-4E14-823A-10B3D9105D58}.Release|x86.ActiveCfg = Release|Any CPU + {52245330-641B-4E14-823A-10B3D9105D58}.Release|x86.Build.0 = Release|Any CPU + {697F6057-DBDC-40B9-A7E5-02F295BC18B3}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {697F6057-DBDC-40B9-A7E5-02F295BC18B3}.Debug|Any CPU.Build.0 = Debug|Any CPU + {697F6057-DBDC-40B9-A7E5-02F295BC18B3}.Debug|x64.ActiveCfg = Debug|Any CPU + {697F6057-DBDC-40B9-A7E5-02F295BC18B3}.Debug|x64.Build.0 = Debug|Any CPU + {697F6057-DBDC-40B9-A7E5-02F295BC18B3}.Debug|x86.ActiveCfg = Debug|Any CPU + {697F6057-DBDC-40B9-A7E5-02F295BC18B3}.Debug|x86.Build.0 = Debug|Any CPU + {697F6057-DBDC-40B9-A7E5-02F295BC18B3}.Release|Any CPU.ActiveCfg = Release|Any CPU + {697F6057-DBDC-40B9-A7E5-02F295BC18B3}.Release|Any CPU.Build.0 = Release|Any CPU + {697F6057-DBDC-40B9-A7E5-02F295BC18B3}.Release|x64.ActiveCfg = Release|Any CPU + {697F6057-DBDC-40B9-A7E5-02F295BC18B3}.Release|x64.Build.0 = Release|Any CPU + {697F6057-DBDC-40B9-A7E5-02F295BC18B3}.Release|x86.ActiveCfg = Release|Any CPU + {697F6057-DBDC-40B9-A7E5-02F295BC18B3}.Release|x86.Build.0 = Release|Any CPU + {4BE18EDC-02ED-47E2-A23A-3F6650ADAF0A}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {4BE18EDC-02ED-47E2-A23A-3F6650ADAF0A}.Debug|Any CPU.Build.0 = Debug|Any CPU + {4BE18EDC-02ED-47E2-A23A-3F6650ADAF0A}.Debug|x64.ActiveCfg = Debug|Any CPU + {4BE18EDC-02ED-47E2-A23A-3F6650ADAF0A}.Debug|x64.Build.0 = Debug|Any CPU + {4BE18EDC-02ED-47E2-A23A-3F6650ADAF0A}.Debug|x86.ActiveCfg = Debug|Any CPU + {4BE18EDC-02ED-47E2-A23A-3F6650ADAF0A}.Debug|x86.Build.0 = Debug|Any CPU + {4BE18EDC-02ED-47E2-A23A-3F6650ADAF0A}.Release|Any CPU.ActiveCfg = Release|Any CPU + {4BE18EDC-02ED-47E2-A23A-3F6650ADAF0A}.Release|Any CPU.Build.0 = Release|Any CPU + {4BE18EDC-02ED-47E2-A23A-3F6650ADAF0A}.Release|x64.ActiveCfg = Release|Any CPU + {4BE18EDC-02ED-47E2-A23A-3F6650ADAF0A}.Release|x64.Build.0 = Release|Any CPU + {4BE18EDC-02ED-47E2-A23A-3F6650ADAF0A}.Release|x86.ActiveCfg = Release|Any CPU + {4BE18EDC-02ED-47E2-A23A-3F6650ADAF0A}.Release|x86.Build.0 = Release|Any CPU + {3FE25467-CBC6-438F-BB96-6601AF56E937}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {3FE25467-CBC6-438F-BB96-6601AF56E937}.Debug|Any CPU.Build.0 = Debug|Any CPU + {3FE25467-CBC6-438F-BB96-6601AF56E937}.Debug|x64.ActiveCfg = Debug|Any CPU + {3FE25467-CBC6-438F-BB96-6601AF56E937}.Debug|x64.Build.0 = Debug|Any CPU + {3FE25467-CBC6-438F-BB96-6601AF56E937}.Debug|x86.ActiveCfg = Debug|Any CPU + {3FE25467-CBC6-438F-BB96-6601AF56E937}.Debug|x86.Build.0 = Debug|Any CPU + {3FE25467-CBC6-438F-BB96-6601AF56E937}.Release|Any CPU.ActiveCfg = Release|Any CPU + {3FE25467-CBC6-438F-BB96-6601AF56E937}.Release|Any CPU.Build.0 = Release|Any CPU + {3FE25467-CBC6-438F-BB96-6601AF56E937}.Release|x64.ActiveCfg = Release|Any CPU + {3FE25467-CBC6-438F-BB96-6601AF56E937}.Release|x64.Build.0 = Release|Any CPU + {3FE25467-CBC6-438F-BB96-6601AF56E937}.Release|x86.ActiveCfg = Release|Any CPU + {3FE25467-CBC6-438F-BB96-6601AF56E937}.Release|x86.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE @@ -570,6 +627,10 @@ Global {7C2AB7E7-F58B-4F96-BDFB-05E403BD999B} = {7E8A2D6B-3F4C-4E5F-9A6B-1C2D3E4F5A6B} {4E7353D5-5F1C-43A1-B792-6CD1D5DBDB91} = {7E8A2D6B-3F4C-4E5F-9A6B-1C2D3E4F5A6B} {A6BC3F8B-CAB8-4F3B-BD89-B7428697DE61} = {7E8A2D6B-3F4C-4E5F-9A6B-1C2D3E4F5A6B} + {52245330-641B-4E14-823A-10B3D9105D58} = {7E8A2D6B-3F4C-4E5F-9A6B-1C2D3E4F5A6B} + {697F6057-DBDC-40B9-A7E5-02F295BC18B3} = {53B1231B-37F5-44BA-80D5-DBA979775F5C} + {4BE18EDC-02ED-47E2-A23A-3F6650ADAF0A} = {3F057926-562F-4EF4-BFC0-EE62372D4551} + {3FE25467-CBC6-438F-BB96-6601AF56E937} = {8B06B1D2-80B9-490C-9A36-C7748F58B705} EndGlobalSection GlobalSection(ExtensibilityGlobals) = postSolution SolutionGuid = {4A55A28E-C657-4A0B-95EA-2931AE66004E} diff --git a/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Api/StubApiHttpClient.cs b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Api/StubApiHttpClient.cs new file mode 100644 index 00000000..93a80e81 --- /dev/null +++ b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Api/StubApiHttpClient.cs @@ -0,0 +1,255 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Common.Api; +using Lumina.Presentation.Web.Common.DTO.FileSystemManagement; +using Lumina.Presentation.Web.Common.Enums.Authorization; +using Lumina.Presentation.Web.Common.Exceptions; +using Lumina.Presentation.Web.Common.Responses.Authorization; +using Lumina.Presentation.Web.Common.Responses.UsersManagement; +using Lumina.Presentation.Web.Common.Routes; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +using System.Runtime.CompilerServices; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.Fixtures.Common.Api; + +/// +/// Test double for the interface, allowing integration and security tests to stub the +/// remote API responses without hosting a real backend. +/// +[ExcludeFromCodeCoverage] +public class StubApiHttpClient : IApiHttpClient +{ + private readonly Dictionary> _getResponseFactories = []; + private readonly Dictionary> _postResponseFactories = []; + private readonly Dictionary> _putResponseFactories = []; + private readonly HashSet _deleteSuccessEndpoints = []; + + /// + /// Gets the authorization response returned for the auth/get-authorization endpoint. + /// + public GetAuthorizationResponse AuthorizationResponse { get; set; } = new(Guid.NewGuid(), "Admin", Enum.GetValues()); + + /// + /// Gets or sets the initialization response returned for the initialization endpoint. + /// + public InitializationResponse InitializationResponse { get; set; } = new() { IsInitialized = true }; + + /// + /// Gets or sets the login response returned for the auth/login endpoint. + /// + public LoginResponse LoginResponse { get; set; } = new(Guid.NewGuid(), "testuser", "test_jwt_token", false); + + /// + /// Gets the list of GET endpoints that were requested. + /// + public List GetEndpointsCalled { get; } = []; + + /// + /// Gets the list of POST requests that were sent, with their payloads. + /// + public List<(string Endpoint, object? Data)> PostRequests { get; } = []; + + /// + /// Gets the list of PUT requests that were sent, with their payloads. + /// + public List<(string Endpoint, object? Data)> PutRequests { get; } = []; + + /// + /// Gets the list of DELETE endpoints that were requested. + /// + public List DeleteEndpointsCalled { get; } = []; + + /// + /// Registers the response returned when the specified GET endpoint is called. + /// + /// The type of the response. + /// The API endpoint for which to register the response. + /// The response to return. + public void RegisterGetResponse(string endpoint, TResponse response) where TResponse : class + { + _getResponseFactories[endpoint] = () => response; + } + + /// + /// Registers the response factory invoked when the specified GET endpoint is called. + /// + /// The API endpoint for which to register the response factory. + /// The factory that produces the response. + public void RegisterGetResponseFactory(string endpoint, Func responseFactory) + { + _getResponseFactories[endpoint] = responseFactory; + } + + /// + /// Registers the response returned when the specified POST endpoint is called. + /// + /// The type of the response. + /// The API endpoint for which to register the response. + /// The response to return. + public void RegisterPostResponse(string endpoint, TResponse response) where TResponse : class + { + _postResponseFactories[endpoint] = _ => response; + } + + /// + /// Registers the response factory invoked when the specified POST endpoint is called. + /// + /// The API endpoint for which to register the response factory. + /// The factory that produces the response from the request payload. + public void RegisterPostResponseFactory(string endpoint, Func responseFactory) + { + _postResponseFactories[endpoint] = responseFactory; + } + + /// + /// Registers the exception thrown when the specified POST endpoint is called. + /// + /// The API endpoint for which to register the exception. + /// The exception to throw. + public void RegisterPostException(string endpoint, ApiException exception) + { + _postResponseFactories[endpoint] = _ => throw exception; + } + + /// + /// Registers the exception thrown when the specified GET endpoint is called. + /// + /// The API endpoint for which to register the exception. + /// The exception to throw. + public void RegisterGetException(string endpoint, ApiException exception) + { + _getResponseFactories[endpoint] = () => throw exception; + } + + /// + /// Registers the response returned when the specified PUT endpoint is called. + /// + /// The type of the response. + /// The API endpoint for which to register the response. + /// The response to return. + public void RegisterPutResponse(string endpoint, TResponse response) where TResponse : class + { + _putResponseFactories[endpoint] = _ => response; + } + + /// + /// Registers the specified DELETE endpoint as succeeding. + /// + /// The API endpoint for which to register success. + public void RegisterDeleteSuccess(string endpoint) + { + _deleteSuccessEndpoints.Add(endpoint); + } + + /// + /// Resets all registered responses and captured requests, keeping only the default responses. + /// + public void Reset() + { + _getResponseFactories.Clear(); + _postResponseFactories.Clear(); + _putResponseFactories.Clear(); + _deleteSuccessEndpoints.Clear(); + GetEndpointsCalled.Clear(); + PostRequests.Clear(); + PutRequests.Clear(); + DeleteEndpointsCalled.Clear(); + } + + /// + /// Sends a GET request to the specified as an asynchronous operation and returns the result. + /// + /// The expected type of the response content. + /// The API endpoint where the request is being sent. + /// Cancellation token that can be used to stop the execution. + /// The deserialized response containing the result of the GET request. + public Task GetAsync(string endpoint, CancellationToken cancellationToken = default) + { + GetEndpointsCalled.Add(endpoint); + if (_getResponseFactories.TryGetValue(endpoint, out Func? responseFactory)) + return Task.FromResult((TResponse)responseFactory()); + if (endpoint.StartsWith(ApiRoutes.Initialization.CHECK_INITIALIZATION, StringComparison.OrdinalIgnoreCase)) + return Task.FromResult((TResponse)(object)InitializationResponse); + if (endpoint.Contains("auth/get-authorization", StringComparison.OrdinalIgnoreCase)) + return Task.FromResult((TResponse)(object)AuthorizationResponse); + throw new InvalidOperationException($"No GET response is registered for the endpoint '{endpoint}'."); + } + + /// + /// Sends a GET request to the specified as an asynchronous operation and returns the result as a streamable response. + /// + /// The expected type of the response content. + /// The API endpoint where the request is being sent. + /// Cancellation token that can be used to stop the execution. + /// An object, which allows for asynchronous iteration over the deserialized items. + public async IAsyncEnumerable GetAsyncEnumerable(string endpoint, [EnumeratorCancellation] CancellationToken cancellationToken = default) + { + await Task.CompletedTask; + yield break; + } + + /// + /// Sends a GET request to the specified as an asynchronous operation and returns the result. + /// + /// The API endpoint where the request is being sent. + /// Cancellation token that can be used to stop the execution. + /// A model containing the deserialized blob. + public Task GetBlobAsync(string endpoint, CancellationToken cancellationToken = default) + { + throw new NotSupportedException("Blob retrieval is not supported by the test stub."); + } + + /// + /// Sends a DELETE request to the specified as an asynchronous operation. + /// + /// The API endpoint where the request is being sent. + /// Cancellation token that can be used to stop the execution. + public Task DeleteAsync(string endpoint, CancellationToken cancellationToken = default) + { + DeleteEndpointsCalled.Add(endpoint); + if (_deleteSuccessEndpoints.Contains(endpoint)) + return Task.CompletedTask; + throw new ApiException(null, System.Net.HttpStatusCode.InternalServerError, endpoint); + } + + /// + /// Sends a PUT request to the specified as an asynchronous operation and returns the result. + /// + /// The expected type of the response content. + /// The expected type of the payload content. + /// The API endpoint where the request is being sent. + /// The data to be serialized and send to the API. + /// Cancellation token that can be used to stop the execution. + /// The deserialized response containing the result of the PUT request. + public Task PutAsync(string endpoint, TModel data, CancellationToken cancellationToken = default) + { + PutRequests.Add((endpoint, data)); + if (_putResponseFactories.TryGetValue(endpoint, out Func? responseFactory)) + return Task.FromResult((TResponse)responseFactory(data!)); + throw new InvalidOperationException($"No PUT response is registered for the endpoint '{endpoint}'."); + } + + /// + /// Sends a POST request to the specified as an asynchronous operation and returns the result. + /// + /// The expected type of the response content. + /// The expected type of the payload content. + /// The API endpoint where the request is being sent. + /// The data to be serialized and send to the API. + /// Cancellation token that can be used to stop the execution. + /// The deserialized response containing the result of the POST request. + public Task PostAsync(string endpoint, TModel data, CancellationToken cancellationToken = default) + { + PostRequests.Add((endpoint, data)); + if (_postResponseFactories.TryGetValue(endpoint, out Func? responseFactory)) + return Task.FromResult((TResponse)responseFactory(data!)); + if (endpoint == ApiRoutes.Authentication.LOGIN_ACCOUNT) + return Task.FromResult((TResponse)(object)LoginResponse); + throw new InvalidOperationException($"No POST response is registered for the endpoint '{endpoint}'."); + } +} diff --git a/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Api/TestApiHttpMessageHandler.cs b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Api/TestApiHttpMessageHandler.cs new file mode 100644 index 00000000..af327f97 --- /dev/null +++ b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Api/TestApiHttpMessageHandler.cs @@ -0,0 +1,51 @@ +#region ========================================================================= USING ===================================================================================== +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Net.Http; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.Fixtures.Common.Api; + +/// +/// test double that returns a configurable response for every request sent through it. +/// +[ExcludeFromCodeCoverage] +public class TestApiHttpMessageHandler : HttpMessageHandler +{ + private readonly Func _responseFactory; + + /// + /// Gets the list of requests that were sent through this handler. + /// + public List Requests { get; } = []; + + /// + /// Gets the bodies of the requests that were sent through this handler, captured while the request content is still available. + /// + public List RequestBodies { get; } = []; + + /// + /// Initializes a new instance of the class. + /// + /// The factory that produces the response for a given request. + public TestApiHttpMessageHandler(Func responseFactory) + { + _responseFactory = responseFactory; + } + + /// + /// Sends the request to the configured response factory. + /// + /// The HTTP request message to send. + /// Cancellation token that can be used to stop the execution. + /// The configured HTTP response message. + protected override async Task SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) + { + Requests.Add(request); + RequestBodies.Add(request.Content is null ? null : await request.Content.ReadAsStringAsync(cancellationToken)); + return await Task.FromResult(_responseFactory(request)); + } +} diff --git a/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/Authorization/RoleDtoFixture.cs b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/Authorization/RoleDtoFixture.cs new file mode 100644 index 00000000..858f0dc7 --- /dev/null +++ b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/Authorization/RoleDtoFixture.cs @@ -0,0 +1,42 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Presentation.Web.Common.DTO.Authorization; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Presentation.Web.Fixtures.Common.DTO.Authorization; + +/// +/// Fixture class for generating test data. +/// +[ExcludeFromCodeCoverage] +public class RoleDtoFixture +{ + /// + /// Creates a new instance with randomized test data. + /// + /// Optional identifier of the role. + /// Optional name of the role. + /// A configured instance. + public RoleDto Create(Guid? id = null, string? roleName = null) + { + Faker faker = new(); + return new RoleDto( + Id: id ?? Guid.NewGuid(), + RoleName: roleName ?? faker.Commerce.Department() + ); + } + + /// + /// Creates multiple instances with randomized test data. + /// + /// Number of instances to create. + /// List of configured instances. + public List CreateMany(int count = 3) + { + return [.. Enumerable.Range(0, count).Select(_ => Create())]; + } +} diff --git a/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/Libraries/LibraryDtoFixture.cs b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/Libraries/LibraryDtoFixture.cs new file mode 100644 index 00000000..b6a98ac1 --- /dev/null +++ b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/Libraries/LibraryDtoFixture.cs @@ -0,0 +1,51 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Presentation.Web.Common.DTO.Libraries; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Presentation.Web.Fixtures.Common.DTO.Libraries; + +/// +/// Fixture class for generating test data. +/// +[ExcludeFromCodeCoverage] +public class LibraryDtoFixture +{ + /// + /// Creates a new instance with randomized test data. + /// + /// Optional identifier of the media library. + /// Optional title of the library. + /// Optional type of the library. + /// Whether the media library is enabled or not. + /// Optional collection of directories that contain the library files. + /// A configured instance. + public LibraryDto Create(Guid? id = null, string? title = null, string? libraryType = null, bool? isEnabled = null, List? contentLocations = null) + { + Faker faker = new(); + return new LibraryDto + { + Id = id ?? Guid.NewGuid(), + UserId = Guid.NewGuid(), + Title = title ?? faker.Commerce.Department(), + LibraryType = libraryType ?? faker.PickRandom("Book", "Video", "Photo"), + CoverImage = faker.Image.PicsumUrl(), + ContentLocations = contentLocations ?? [faker.System.DirectoryPath()], + IsEnabled = isEnabled ?? faker.Random.Bool() + }; + } + + /// + /// Creates multiple instances with randomized test data. + /// + /// Number of instances to create. + /// List of configured instances. + public List CreateMany(int count = 3) + { + return [.. Enumerable.Range(0, count).Select(_ => Create())]; + } +} diff --git a/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/UsersManagement/UserSettingsDtoFixture.cs b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/UsersManagement/UserSettingsDtoFixture.cs new file mode 100644 index 00000000..74311aa5 --- /dev/null +++ b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/UsersManagement/UserSettingsDtoFixture.cs @@ -0,0 +1,47 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Presentation.Web.Common.DTO.UsersManagement; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Presentation.Web.Fixtures.Common.DTO.UsersManagement; + +/// +/// Fixture class for generating test data. +/// +[ExcludeFromCodeCoverage] +public class UserSettingsDtoFixture +{ + /// + /// Creates a new instance with randomized test data. + /// + /// Optional identifier of the user that owns the settings. + /// Whether pagination is enabled for the user. + /// Number of library items displayed per page. + /// Whether the "The" prefix is ignored by the alpha picker. + /// A configured instance. + public UserSettingsDto Create(Guid? userId = null, bool? isPaginationEnabled = null, int? itemsPerPage = null, bool? ignoreThePrefixForAlphaPicker = null) + { + Faker faker = new(); + return new UserSettingsDto + { + UserId = userId ?? Guid.NewGuid(), + IsPaginationEnabled = isPaginationEnabled ?? faker.Random.Bool(), + ItemsPerPage = itemsPerPage ?? faker.Random.Int(1, 200), + IgnoreThePrefixForAlphaPicker = ignoreThePrefixForAlphaPicker ?? faker.Random.Bool() + }; + } + + /// + /// Creates multiple instances with randomized test data. + /// + /// Number of instances to create. + /// List of configured instances. + public List CreateMany(int count = 3) + { + return [.. Enumerable.Range(0, count).Select(_ => Create())]; + } +} diff --git a/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/Authorization/AddRoleRequestFixture.cs b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/Authorization/AddRoleRequestFixture.cs new file mode 100644 index 00000000..0057f6d2 --- /dev/null +++ b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/Authorization/AddRoleRequestFixture.cs @@ -0,0 +1,42 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Presentation.Web.Common.Requests.Authorization; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Presentation.Web.Fixtures.Common.Requests.Authorization; + +/// +/// Fixture class for generating test data. +/// +[ExcludeFromCodeCoverage] +public class AddRoleRequestFixture +{ + /// + /// Creates a new instance with randomized test data. + /// + /// Optional name of the role. + /// Optional collection of permission identifiers. + /// A configured instance. + public AddRoleRequest Create(string? roleName = null, List? permissions = null) + { + Faker faker = new(); + return new AddRoleRequest( + RoleName: roleName ?? faker.Commerce.Department(), + Permissions: permissions ?? [Guid.NewGuid(), Guid.NewGuid()] + ); + } + + /// + /// Creates multiple instances with randomized test data. + /// + /// Number of instances to create. + /// List of configured instances. + public List CreateMany(int count = 3) + { + return [.. Enumerable.Range(0, count).Select(_ => Create())]; + } +} diff --git a/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/Authorization/DeleteRoleRequestFixture.cs b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/Authorization/DeleteRoleRequestFixture.cs new file mode 100644 index 00000000..73d036cf --- /dev/null +++ b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/Authorization/DeleteRoleRequestFixture.cs @@ -0,0 +1,39 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Presentation.Web.Common.Requests.Authorization; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Presentation.Web.Fixtures.Common.Requests.Authorization; + +/// +/// Fixture class for generating test data. +/// +[ExcludeFromCodeCoverage] +public class DeleteRoleRequestFixture +{ + /// + /// Creates a new instance with randomized test data. + /// + /// Optional identifier of the role. + /// A configured instance. + public DeleteRoleRequest Create(Guid? roleId = null) + { + return new DeleteRoleRequest( + RoleId: roleId ?? Guid.NewGuid() + ); + } + + /// + /// Creates multiple instances with randomized test data. + /// + /// Number of instances to create. + /// List of configured instances. + public List CreateMany(int count = 3) + { + return [.. Enumerable.Range(0, count).Select(_ => Create())]; + } +} diff --git a/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/FileSystemManagement/Directories/GetDirectoriesRequestFixture.cs b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/FileSystemManagement/Directories/GetDirectoriesRequestFixture.cs new file mode 100644 index 00000000..3683b3a4 --- /dev/null +++ b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/FileSystemManagement/Directories/GetDirectoriesRequestFixture.cs @@ -0,0 +1,39 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Common.Requests.FileSystemManagement.Directories; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Presentation.Web.Fixtures.Common.Requests.FileSystemManagement.Directories; + +/// +/// Fixture class for generating test data. +/// +[ExcludeFromCodeCoverage] +public class GetDirectoriesRequestFixture +{ + /// + /// Creates a new instance with randomized test data. + /// + /// Optional file system path whose directories are retrieved. + /// Whether hidden file system elements are included or not. + /// A configured instance. + public GetDirectoriesRequest Create(string? path = null, bool includeHiddenElements = false) + { + return new GetDirectoriesRequest( + Path: path ?? $"/media/{System.Guid.NewGuid():N}", + IncludeHiddenElements: includeHiddenElements + ); + } + + /// + /// Creates multiple instances with randomized test data. + /// + /// Number of instances to create. + /// List of configured instances. + public List CreateMany(int count = 3) + { + return [.. Enumerable.Range(0, count).Select(_ => Create())]; + } +} diff --git a/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/FileSystemManagement/Path/ValidatePathRequestFixture.cs b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/FileSystemManagement/Path/ValidatePathRequestFixture.cs new file mode 100644 index 00000000..4a409d37 --- /dev/null +++ b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/FileSystemManagement/Path/ValidatePathRequestFixture.cs @@ -0,0 +1,37 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Common.Requests.FileSystemManagement.Path; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Presentation.Web.Fixtures.Common.Requests.FileSystemManagement.Path; + +/// +/// Fixture class for generating test data. +/// +[ExcludeFromCodeCoverage] +public class ValidatePathRequestFixture +{ + /// + /// Creates a new instance with randomized test data. + /// + /// Optional file system path to validate. + /// A configured instance. + public ValidatePathRequest Create(string? path = null) + { + return new ValidatePathRequest( + Path: path ?? $"/media/{System.Guid.NewGuid():N}" + ); + } + + /// + /// Creates multiple instances with randomized test data. + /// + /// Number of instances to create. + /// List of configured instances. + public List CreateMany(int count = 3) + { + return [.. Enumerable.Range(0, count).Select(_ => Create())]; + } +} diff --git a/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/Libraries/GetBooksLiteRequestFixture.cs b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/Libraries/GetBooksLiteRequestFixture.cs new file mode 100644 index 00000000..7bf7557f --- /dev/null +++ b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/Libraries/GetBooksLiteRequestFixture.cs @@ -0,0 +1,63 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Presentation.Web.Common.Enums.Common; +using Lumina.Presentation.Web.Common.Requests.Libraries; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Presentation.Web.Fixtures.Common.Requests.Libraries; + +/// +/// Fixture class for generating test data. +/// +[ExcludeFromCodeCoverage] +public class GetBooksLiteRequestFixture +{ + /// + /// Creates a new instance with randomized test data. + /// + /// Optional identifier of the media library. + /// Optional page of results to retrieve. + /// Optional number of books to retrieve per page. + /// Optional search term used to filter results. + /// Optional alpha key used to filter the results. + /// Whether the leading "The " prefix is ignored by the alpha picker. + /// Optional name of the field by which to sort the results. + /// Optional direction in which to sort the results. + /// A configured instance. + public GetBooksLiteRequest Create( + Guid? libraryId = null, + int? currentPage = null, + int? perPage = null, + string? searchTerm = null, + string? filterAlphaKey = null, + bool ignoreThePrefixForAlphaPicker = false, + string? sortBy = null, + SortOrder? sortOrder = null) + { + return new GetBooksLiteRequest + { + LibraryId = libraryId ?? Guid.NewGuid(), + CurrentPage = currentPage, + PerPage = perPage, + SearchTerm = searchTerm, + FilterAlphaKey = filterAlphaKey, + IgnoreThePrefixForAlphaPicker = ignoreThePrefixForAlphaPicker, + SortBy = sortBy, + SortOrder = sortOrder + }; + } + + /// + /// Creates multiple instances with randomized test data. + /// + /// Number of instances to create. + /// List of configured instances. + public List CreateMany(int count = 3) + { + return [.. Enumerable.Range(0, count).Select(_ => Create())]; + } +} diff --git a/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/Library/Management/DeleteLibraryRequestFixture.cs b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/Library/Management/DeleteLibraryRequestFixture.cs new file mode 100644 index 00000000..e2997aa2 --- /dev/null +++ b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/Library/Management/DeleteLibraryRequestFixture.cs @@ -0,0 +1,39 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Presentation.Web.Common.Requests.Library.Management; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Presentation.Web.Fixtures.Common.Requests.Library.Management; + +/// +/// Fixture class for generating test data. +/// +[ExcludeFromCodeCoverage] +public class DeleteLibraryRequestFixture +{ + /// + /// Creates a new instance with randomized test data. + /// + /// Optional identifier of the media library. + /// A configured instance. + public DeleteLibraryRequest Create(Guid? id = null) + { + return new DeleteLibraryRequest( + Id: id ?? Guid.NewGuid() + ); + } + + /// + /// Creates multiple instances with randomized test data. + /// + /// Number of instances to create. + /// List of configured instances. + public List CreateMany(int count = 3) + { + return [.. Enumerable.Range(0, count).Select(_ => Create())]; + } +} diff --git a/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/Plugins/UpdatePluginSettingsRequestFixture.cs b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/Plugins/UpdatePluginSettingsRequestFixture.cs new file mode 100644 index 00000000..725afc87 --- /dev/null +++ b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/Plugins/UpdatePluginSettingsRequestFixture.cs @@ -0,0 +1,43 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Presentation.Web.Common.Requests.Plugins; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Presentation.Web.Fixtures.Common.Requests.Plugins; + +/// +/// Fixture class for generating test data. +/// +[ExcludeFromCodeCoverage] +public class UpdatePluginSettingsRequestFixture +{ + /// + /// Creates a new instance with randomized test data. + /// + /// Optional identifier of the plugin. + /// Optional dictionary of settings. + /// A configured instance. + public UpdatePluginSettingsRequest Create(Guid? pluginId = null, Dictionary? settings = null) + { + Faker faker = new(); + return new UpdatePluginSettingsRequest + { + PluginId = pluginId ?? Guid.NewGuid(), + Settings = settings ?? new Dictionary { [faker.Lorem.Word()] = faker.Lorem.Word() } + }; + } + + /// + /// Creates multiple instances with randomized test data. + /// + /// Number of instances to create. + /// List of configured instances. + public List CreateMany(int count = 3) + { + return [.. Enumerable.Range(0, count).Select(_ => Create())]; + } +} diff --git a/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/Tools/SetLanguageRequestFixture.cs b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/Tools/SetLanguageRequestFixture.cs new file mode 100644 index 00000000..2c3cd82d --- /dev/null +++ b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/Tools/SetLanguageRequestFixture.cs @@ -0,0 +1,40 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Presentation.Web.Common.Requests.Tools; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Presentation.Web.Fixtures.Common.Requests.Tools; + +/// +/// Fixture class for generating test data. +/// +[ExcludeFromCodeCoverage] +public class SetLanguageRequestFixture +{ + /// + /// Creates a new instance with randomized test data. + /// + /// Optional new culture to set. + /// Optional URL to return to, after setting the new culture. + /// A configured instance. + public SetLanguageRequest Create(string? newCulture = "en-US", string? returnUrl = null) + { + return new SetLanguageRequest( + NewCulture: newCulture, + ReturnUrl: returnUrl + ); + } + + /// + /// Creates multiple instances with randomized test data. + /// + /// Number of instances to create. + /// List of configured instances. + public List CreateMany(int count = 3) + { + return [.. Enumerable.Range(0, count).Select(_ => Create())]; + } +} diff --git a/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/UsersManagement/Authentication/LoginViewRequestFixture.cs b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/UsersManagement/Authentication/LoginViewRequestFixture.cs new file mode 100644 index 00000000..fe08c93e --- /dev/null +++ b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/UsersManagement/Authentication/LoginViewRequestFixture.cs @@ -0,0 +1,39 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Presentation.Web.Common.Requests.UsersManagement.Authentication; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Presentation.Web.Fixtures.Common.Requests.UsersManagement.Authentication; + +/// +/// Fixture class for generating test data. +/// +[ExcludeFromCodeCoverage] +public class LoginViewRequestFixture +{ + /// + /// Creates a new instance with randomized test data. + /// + /// Optional URL to return to, after login. + /// A configured instance. + public LoginViewRequest Create(string? returnUrl = null) + { + Faker faker = new(); + return new LoginViewRequest( + ReturnUrl: returnUrl ?? $"/{faker.Random.AlphaNumeric(8)}" + ); + } + + /// + /// Creates multiple instances with randomized test data. + /// + /// Number of instances to create. + /// List of configured instances. + public List CreateMany(int count = 3) + { + return [.. Enumerable.Range(0, count).Select(_ => Create())]; + } +} diff --git a/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/UsersManagement/ChangePasswordRequestFixture.cs b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/UsersManagement/ChangePasswordRequestFixture.cs new file mode 100644 index 00000000..a0e75deb --- /dev/null +++ b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/UsersManagement/ChangePasswordRequestFixture.cs @@ -0,0 +1,46 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Presentation.Web.Common.Requests.UsersManagement; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Presentation.Web.Fixtures.Common.Requests.UsersManagement; + +/// +/// Fixture class for generating test data. +/// +[ExcludeFromCodeCoverage] +public class ChangePasswordRequestFixture +{ + /// + /// Creates a new instance with randomized test data. + /// + /// Optional username. + /// Optional current password. + /// Optional new password. + /// Optional confirmation of the new password. + /// A configured instance. + public ChangePasswordRequest Create(string? username = null, string? currentPassword = null, string? newPassword = null, string? newPasswordConfirm = null) + { + Faker faker = new(); + string generatedNewPassword = newPassword ?? faker.Internet.Password(12); + return new ChangePasswordRequest( + Username: username ?? faker.Internet.UserName(), + CurrentPassword: currentPassword ?? faker.Internet.Password(12), + NewPassword: generatedNewPassword, + NewPasswordConfirm: newPasswordConfirm ?? generatedNewPassword + ); + } + + /// + /// Creates multiple instances with randomized test data. + /// + /// Number of instances to create. + /// List of configured instances. + public List CreateMany(int count = 3) + { + return [.. Enumerable.Range(0, count).Select(_ => Create())]; + } +} diff --git a/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/UsersManagement/LoginRequestFixture.cs b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/UsersManagement/LoginRequestFixture.cs new file mode 100644 index 00000000..9d39afdb --- /dev/null +++ b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/UsersManagement/LoginRequestFixture.cs @@ -0,0 +1,45 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Presentation.Web.Common.Requests.UsersManagement; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Presentation.Web.Fixtures.Common.Requests.UsersManagement; + +/// +/// Fixture class for generating test data. +/// +[ExcludeFromCodeCoverage] +public class LoginRequestFixture +{ + /// + /// Creates a new instance with randomized test data. + /// + /// Optional username. + /// Optional password. + /// Optional TOTP code. + /// Optional URL to return to, after login. + /// A configured instance. + public LoginRequest Create(string? username = null, string? password = null, string? totpCode = null, string? returnUrl = null) + { + Faker faker = new(); + return new LoginRequest( + Username: username ?? faker.Internet.UserName(), + Password: password ?? faker.Internet.Password(12), + TotpCode: totpCode, + ReturnUrl: returnUrl + ); + } + + /// + /// Creates multiple instances with randomized test data. + /// + /// Number of instances to create. + /// List of configured instances. + public List CreateMany(int count = 3) + { + return [.. Enumerable.Range(0, count).Select(_ => Create())]; + } +} diff --git a/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/UsersManagement/RecoverPasswordRequestFixture.cs b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/UsersManagement/RecoverPasswordRequestFixture.cs new file mode 100644 index 00000000..cb8f2ce5 --- /dev/null +++ b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/UsersManagement/RecoverPasswordRequestFixture.cs @@ -0,0 +1,41 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Presentation.Web.Common.Requests.UsersManagement; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Presentation.Web.Fixtures.Common.Requests.UsersManagement; + +/// +/// Fixture class for generating test data. +/// +[ExcludeFromCodeCoverage] +public class RecoverPasswordRequestFixture +{ + /// + /// Creates a new instance with randomized test data. + /// + /// Optional username. + /// Optional TOTP code. + /// A configured instance. + public RecoverPasswordRequest Create(string? username = null, string? totpCode = null) + { + Faker faker = new(); + return new RecoverPasswordRequest( + Username: username ?? faker.Internet.UserName(), + TotpCode: totpCode + ); + } + + /// + /// Creates multiple instances with randomized test data. + /// + /// Number of instances to create. + /// List of configured instances. + public List CreateMany(int count = 3) + { + return [.. Enumerable.Range(0, count).Select(_ => Create())]; + } +} diff --git a/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/UsersManagement/RegisterRequestFixture.cs b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/UsersManagement/RegisterRequestFixture.cs new file mode 100644 index 00000000..a6596a66 --- /dev/null +++ b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/UsersManagement/RegisterRequestFixture.cs @@ -0,0 +1,48 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Presentation.Web.Common.Requests.UsersManagement; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Presentation.Web.Fixtures.Common.Requests.UsersManagement; + +/// +/// Fixture class for generating test data. +/// +[ExcludeFromCodeCoverage] +public class RegisterRequestFixture +{ + /// + /// Creates a new instance with randomized test data. + /// + /// Optional username. + /// Optional password. + /// Optional password confirmation. + /// Optional registration type, e.g. "Admin" or "User". + /// Whether two-factor authentication is enabled for the account. + /// A configured instance. + public RegisterRequest Create(string? username = null, string? password = null, string? passwordConfirm = null, string? registrationType = "User", bool use2fa = true) + { + Faker faker = new(); + string generatedPassword = password ?? faker.Internet.Password(12); + return new RegisterRequest( + Username: username ?? faker.Internet.UserName(), + Password: generatedPassword, + PasswordConfirm: passwordConfirm ?? generatedPassword, + RegistrationType: registrationType, + Use2fa: use2fa + ); + } + + /// + /// Creates multiple instances with randomized test data. + /// + /// Number of instances to create. + /// List of configured instances. + public List CreateMany(int count = 3) + { + return [.. Enumerable.Range(0, count).Select(_ => Create())]; + } +} diff --git a/tests/Common/Lumina.Presentation.Web.Fixtures/Common/TestHelpers/JsonResultTestHelper.cs b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/TestHelpers/JsonResultTestHelper.cs new file mode 100644 index 00000000..f737af84 --- /dev/null +++ b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/TestHelpers/JsonResultTestHelper.cs @@ -0,0 +1,29 @@ +#region ========================================================================= USING ===================================================================================== +using Microsoft.AspNetCore.Http; +using System.Diagnostics.CodeAnalysis; +using System.IO; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.Fixtures.Common.TestHelpers; + +/// +/// Helper for executing instances and reading the JSON response body they produce. +/// +[ExcludeFromCodeCoverage] +public static class JsonResultTestHelper +{ + /// + /// Executes the specified against a fresh HTTP context and reads the response body. + /// + /// The result to execute. + /// Optional HTTP context to execute the result against; a fresh context is created when not provided. + /// The response body produced by the result. + public static async Task GetResponseBodyAsync(IResult result, HttpContext? httpContext = null) + { + DefaultHttpContext context = httpContext as DefaultHttpContext ?? TestHttpContextFactory.Create(); + await result.ExecuteAsync(context); + context.Response.Body.Position = 0; + return await new StreamReader(context.Response.Body).ReadToEndAsync(); + } +} diff --git a/tests/Common/Lumina.Presentation.Web.Fixtures/Common/TestHelpers/TestHttpContextFactory.cs b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/TestHelpers/TestHttpContextFactory.cs new file mode 100644 index 00000000..5727e891 --- /dev/null +++ b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/TestHelpers/TestHttpContextFactory.cs @@ -0,0 +1,125 @@ +#region ========================================================================= USING ===================================================================================== +using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Http.Features; +using Microsoft.AspNetCore.Http.Json; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Logging; +using NSubstitute; +using System; +using System.Diagnostics.CodeAnalysis; +using System.IO; +using System.Security.Claims; +#endregion + +namespace Lumina.Presentation.Web.Fixtures.Common.TestHelpers; + +/// +/// Factory for creating and configuring instances for unit testing Web endpoints. +/// +[ExcludeFromCodeCoverage] +public static class TestHttpContextFactory +{ + /// + /// Creates a with a writable response body, optional culture route value, session and user. + /// + /// The value of the culture route value. + /// The user associated with the context, for anonymous requests. + /// The session associated with the context, when no session is available. + /// A configured instance. + public static DefaultHttpContext Create(string? culture = "en-US", ClaimsPrincipal? user = null, ISession? session = null) + { + DefaultHttpContext httpContext = new(); + // provide a writable response body, so that executed IResult instances can be inspected by the tests + httpContext.Features.Set(new StreamResponseBodyFeature(new MemoryStream())); + // provide the minimal services needed by the result execution machinery (logging, options, JSON options) + httpContext.RequestServices = CreateServiceProvider(); + httpContext.Request.RouteValues["culture"] = culture; + if (user is not null) + httpContext.User = user; + if (session is not null) + httpContext.Features.Set(new TestSessionFeature { Session = session }); + return httpContext; + } + + /// + /// Creates a service provider that provides the minimal services needed by the result execution machinery. + /// + /// A configured instance. + public static IServiceProvider CreateServiceProvider() + { + ServiceCollection services = new(); + services.AddLogging(); + services.AddOptions(); + services.Configure(jsonOptions => jsonOptions.SerializerOptions.MaxDepth = 256); + return services.BuildServiceProvider(); + } + + /// + /// Attaches a session to the provided HTTP context. + /// + /// The HTTP context to configure. + /// The session to attach. + public static void ConfigureSession(HttpContext httpContext, ISession session) + { + httpContext.Features.Set(new TestSessionFeature { Session = session }); + } + + /// + /// Attaches a user to the provided HTTP context. + /// + /// The HTTP context to configure. + /// The user to attach. + public static void ConfigureUser(HttpContext httpContext, ClaimsPrincipal user) + { + httpContext.User = user; + } + + /// + /// Sets the value of the culture route value of the provided HTTP context. + /// + /// The HTTP context to configure. + /// The culture to set. + public static void ConfigureCulture(HttpContext httpContext, string? culture) + { + httpContext.Request.RouteValues["culture"] = culture; + } + + /// + /// Creates a mock that supports the GetString and SetString extension methods. + /// + /// A mock instance. + public static ISession CreateSession() + { + ISession session = Substitute.For(); +#pragma warning disable CS8601 // possible null reference assignment in the NSubstitute out-argument stub + session.TryGetValue(Arg.Any(), out Arg.Any()).Returns(callInfo => + { + callInfo[1] = null; + return false; + }); +#pragma warning restore CS8601 + return session; + } + + /// + /// Creates an authenticated with the specified username. + /// + /// The username of the authenticated user. + /// An authenticated instance. + public static ClaimsPrincipal CreateAuthenticatedUser(string username = "testuser") + { + return new ClaimsPrincipal(new ClaimsIdentity([new Claim(ClaimTypes.Name, username)], "TestAuthentication")); + } + + /// + /// Minimal implementation used to attach a session to test HTTP contexts. + /// + [ExcludeFromCodeCoverage] + private sealed class TestSessionFeature : ISessionFeature + { + /// + /// Gets or sets the session associated with the feature. + /// + public ISession Session { get; set; } = null!; + } +} diff --git a/tests/Common/Lumina.Presentation.Web.Fixtures/Common/TestHelpers/WebTestHelpers.cs b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/TestHelpers/WebTestHelpers.cs new file mode 100644 index 00000000..ba8de2a2 --- /dev/null +++ b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/TestHelpers/WebTestHelpers.cs @@ -0,0 +1,114 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web; +using Lumina.Presentation.Web.Common.Requests.UsersManagement; +using Microsoft.AspNetCore.Mvc.Testing; +using System; +using System.Diagnostics.CodeAnalysis; +using System.Net.Http; +using System.Net.Http.Headers; +using System.Net.Http.Json; +using System.Text.Json; +using System.Text.RegularExpressions; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.Fixtures.Common.TestHelpers; + +/// +/// Represents an HTTP client that has been authenticated through the real login flow of the Web application. +/// +/// The authenticated HTTP client. +/// The antiforgery token captured before the login, valid for subsequent mutating requests. +[ExcludeFromCodeCoverage] +public record AuthenticatedWebClient(HttpClient Client, string AntiforgeryToken); + +/// +/// Helper methods for exercising the authentication and antiforgery flows of the Web application in integration and security tests. +/// +[ExcludeFromCodeCoverage] +public static partial class WebTestHelpers +{ + private const string LOGIN_PAGE_PATH = "/en-us/auth/login"; + private const string LOGIN_ENDPOINT_PATH = "/en-us/auth/api-login"; + + [GeneratedRegex("name=\"__RequestVerificationToken\"[^>]*value=\"([^\"]*)\"")] + private static partial Regex AntiforgeryTokenRegex(); + + /// + /// Creates an anonymous HTTP client that does not follow redirects. + /// + /// The Web application factory. + /// An anonymous HTTP client. + public static HttpClient CreateAnonymousClient(WebApplicationFactory factory) + { + return factory.CreateClient(new WebApplicationFactoryClientOptions { AllowAutoRedirect = false }); + } + + /// + /// Creates an HTTP client that has been authenticated through the real login flow of the application. + /// + /// The Web application factory. + /// The username to authenticate with. + /// The password to authenticate with. + /// An HTTP client authenticated with the application's authentication cookie, together with an antiforgery token. + public static async Task CreateAuthenticatedClientAsync(WebApplicationFactory factory, string? username = "testuser", string? password = "TestPass123!") + { + // the application marks its cookies as secure, so the test client must communicate over HTTPS for the cookies to be sent back + HttpClient client = factory.CreateClient(new WebApplicationFactoryClientOptions + { + BaseAddress = new Uri("https://localhost"), + AllowAutoRedirect = false + }); + string antiforgeryToken = await GetAntiforgeryTokenAsync(client); + await LoginAsync(client, username!, password!, antiforgeryToken); + return new AuthenticatedWebClient(client, antiforgeryToken); + } + + /// + /// Performs the login flow of the application against the provided client. + /// + /// The HTTP client to log in through. + /// The username to authenticate with. + /// The password to authenticate with. + /// The antiforgery token to send with the login request. + public static async Task LoginAsync(HttpClient client, string username, string password, string antiforgeryToken) + { + HttpRequestMessage loginRequest = new(HttpMethod.Post, LOGIN_ENDPOINT_PATH) + { + Content = JsonContent.Create(new LoginRequest(Username: username, Password: password)) + }; + // the antiforgery middleware matches the content type exactly, so the charset suffix must be omitted + loginRequest.Content!.Headers.ContentType = new MediaTypeHeaderValue("application/json"); + loginRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); + loginRequest.Headers.Add("RequestVerificationToken", antiforgeryToken); + HttpResponseMessage response = await client.SendAsync(loginRequest); + response.EnsureSuccessStatusCode(); + } + + /// + /// Retrieves the antiforgery token and cookie by requesting the login page. + /// + /// The HTTP client to retrieve the token through. + /// The antiforgery token value. + public static async Task GetAntiforgeryTokenAsync(HttpClient client) + { + HttpResponseMessage loginPageResponse = await client.GetAsync(LOGIN_PAGE_PATH); + loginPageResponse.EnsureSuccessStatusCode(); + string loginPageHtml = await loginPageResponse.Content.ReadAsStringAsync(); + Match match = AntiforgeryTokenRegex().Match(loginPageHtml); + if (!match.Success) + throw new InvalidOperationException("Could not find the antiforgery token on the login page."); + return System.Net.WebUtility.HtmlDecode(match.Groups[1].Value); + } + + /// + /// Deserializes a JSON response body into a . + /// + /// The HTTP response whose body is deserialized. + /// The parsed . + public static async Task ReadJsonAsync(HttpResponseMessage response) + { + string content = await response.Content.ReadAsStringAsync(); + return JsonDocument.Parse(content); + } +} diff --git a/tests/Common/Lumina.Presentation.Web.Fixtures/Core/Endpoints/Common/BaseEndpointFixture.cs b/tests/Common/Lumina.Presentation.Web.Fixtures/Core/Endpoints/Common/BaseEndpointFixture.cs new file mode 100644 index 00000000..134d8c23 --- /dev/null +++ b/tests/Common/Lumina.Presentation.Web.Fixtures/Core/Endpoints/Common/BaseEndpointFixture.cs @@ -0,0 +1,73 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Presentation.Web.Core.Endpoints.Common; +using Microsoft.AspNetCore.Http; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.Fixtures.Core.Endpoints.Common; + +/// +/// Fixture class for the class. +/// +[ExcludeFromCodeCoverage] +[DontRegister] +public class BaseEndpointFixture : BaseEndpoint +{ + /// + /// Exposes the Culture property of the class. + /// + public string TestCulture => Culture; + + /// + /// Renders a Razor view through the helper. + /// + /// The name or path of the view to render. + /// The model to pass to the view. + /// Optional additional view data entries made available to the view via ViewData. + /// An that renders the view. + public IResult TestView(string viewName, object? model = null, IReadOnlyDictionary? viewData = null) + { + return View(viewName, model, viewData); + } + + /// + /// Creates a JSON response indicating a successful operation through the helper. + /// + /// The payload of the successful response. + /// An containing the success JSON payload. + public IResult TestJsonSuccess(object? data) + { + return JsonSuccess(data); + } + + /// + /// Creates a JSON response indicating a successful operation without a payload through the helper. + /// + /// An containing the success JSON payload. + public IResult TestJsonSuccess() + { + return JsonSuccess(); + } + + /// + /// Configures the endpoint. + /// + public override void Configure() + { + } + + /// + /// Handles the request. + /// + /// The request object. + /// Cancellation token that can be used to stop the execution. + /// An containing the success JSON payload. + public override Task ExecuteAsync(EmptyRequest request, CancellationToken cancellationToken) + { + return Task.FromResult(TestJsonSuccess()); + } +} diff --git a/tests/Common/Lumina.Presentation.Web.Fixtures/Lumina.Presentation.Web.Fixtures.csproj b/tests/Common/Lumina.Presentation.Web.Fixtures/Lumina.Presentation.Web.Fixtures.csproj new file mode 100644 index 00000000..23889ee3 --- /dev/null +++ b/tests/Common/Lumina.Presentation.Web.Fixtures/Lumina.Presentation.Web.Fixtures.csproj @@ -0,0 +1,25 @@ + + + + net10.0 + disable + enable + $(SolutionDir)..\bin\web\ + + false + false + false + + + + + + + + + + + + + + diff --git a/tests/Common/Lumina.Presentation.Web.Fixtures/Properties/AssemblyInfo.cs b/tests/Common/Lumina.Presentation.Web.Fixtures/Properties/AssemblyInfo.cs new file mode 100644 index 00000000..ed54683a --- /dev/null +++ b/tests/Common/Lumina.Presentation.Web.Fixtures/Properties/AssemblyInfo.cs @@ -0,0 +1,22 @@ +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +// General Information about an assembly is controlled through the following +// set of attributes. Change these attribute values to modify the information +// associated with an assembly. +[assembly: AssemblyTitle("Lumina.Presentation.Web.Fixtures")] +[assembly: AssemblyProduct("Lumina.Presentation.Web.Fixtures")] + +// Setting ComVisible to false makes the types in this assembly not visible +// to COM components. If you need to access a type in this assembly from +// COM, set the ComVisible attribute to true on that type. +[assembly: ComVisible(false)] + +// The following GUID is for the ID of the typelib if this project is exposed to COM +[assembly: Guid("B7C8D9E0-0001-4C5D-8E1F-222222222222")] + +[assembly: InternalsVisibleTo("Lumina.Presentation.Web.UnitTests")] +[assembly: InternalsVisibleTo("Lumina.Presentation.Web.IntegrationTests")] +[assembly: InternalsVisibleTo("Lumina.Presentation.Web.SecurityTests")] +[assembly: InternalsVisibleTo("DynamicProxyGenAssembly2")] diff --git a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Common/Documentation/OpenApiEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Common/Documentation/OpenApiEndpointTests.cs new file mode 100644 index 00000000..e2dea7f3 --- /dev/null +++ b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Common/Documentation/OpenApiEndpointTests.cs @@ -0,0 +1,52 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.IntegrationTests.Common.Setup; +using System.Diagnostics.CodeAnalysis; +using System.Net; +using System.Net.Http; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.IntegrationTests.Common.Documentation; + +/// +/// Contains integration tests for the OpenAPI and Scalar documentation endpoints of the Web application. +/// +[ExcludeFromCodeCoverage] +public class OpenApiEndpointTests : IClassFixture +{ + private readonly HttpClient _client; + + /// + /// Initializes a new instance of the class. + /// + /// Injected Web application factory. + public OpenApiEndpointTests(LuminaWebFactory apiFactory) + { + _client = apiFactory.CreateClient(); + } + + [Fact] + public async Task OpenApi_WhenRequested_ShouldServeDocument() + { + // Act + HttpResponseMessage response = await _client.GetAsync("/openapi/v1.json"); + + // Assert + response.EnsureSuccessStatusCode(); + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + string content = await response.Content.ReadAsStringAsync(); + Assert.Contains("openapi", content); + } + + [Fact] + public async Task Scalar_WhenRequested_ShouldServeReferencePage() + { + // Act + HttpResponseMessage response = await _client.GetAsync("/scalar/v1"); + + // Assert + response.EnsureSuccessStatusCode(); + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + Assert.Equal("text/html", response.Content.Headers.ContentType!.MediaType); + } +} diff --git a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Common/Setup/LuminaWebFactory.cs b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Common/Setup/LuminaWebFactory.cs new file mode 100644 index 00000000..0ade61d2 --- /dev/null +++ b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Common/Setup/LuminaWebFactory.cs @@ -0,0 +1,63 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web; +using Lumina.Presentation.Web.Common.Api; +using Lumina.Presentation.Web.Fixtures.Common.Api; +using Microsoft.AspNetCore.Hosting; +using Microsoft.AspNetCore.Mvc.Testing; +using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.DependencyInjection; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Presentation.Web.IntegrationTests.Common.Setup; + +/// +/// Factory for creating the Web application for integration tests, with the remote API client replaced by a configurable stub. +/// +[ExcludeFromCodeCoverage] +public class LuminaWebFactory : WebApplicationFactory, IDisposable +{ + private const string TEST_ENCRYPTION_KEY = "FLYO0QRo6u2VzoFOgNkkEwYNGtqhJ3QGZd7iAHNEJeM="; + + /// + /// Gets the stub used in place of the remote API client. + /// + public StubApiHttpClient ApiClientStub { get; } = new(); + + /// + /// Initializes a new instance of the class. + /// + public LuminaWebFactory() + { + } + + /// + /// Configures the web host for the integration tests. + /// + /// The web host builder to configure. + protected override void ConfigureWebHost(IWebHostBuilder builder) + { + builder.ConfigureAppConfiguration((context, config) => + { + // provide the application configuration values that the Web app validates on startup + config.AddInMemoryCollection(initialData: new Dictionary + { + ["EncryptionSettings:SecretKey"] = TEST_ENCRYPTION_KEY, + ["ServerConfiguration:ApiVersion"] = "1", + ["ServerConfiguration:BaseAddress"] = "http://localhost", + ["ServerConfiguration:Port"] = "5214" + }); + }); + builder.ConfigureServices(services => + { + // remove the typed HTTP client registration, so that the stub can take its place + ServiceDescriptor[] apiClientDescriptors = services.Where(serviceDescriptor => serviceDescriptor.ServiceType == typeof(IApiHttpClient)).ToArray(); + foreach (ServiceDescriptor descriptor in apiClientDescriptors) + services.Remove(descriptor); + services.AddSingleton(ApiClientStub); + }); + } +} diff --git a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Admin/Authorization/Roles/GetRoles/GetRolesEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Admin/Authorization/Roles/GetRoles/GetRolesEndpointTests.cs new file mode 100644 index 00000000..6ed6f97b --- /dev/null +++ b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Admin/Authorization/Roles/GetRoles/GetRolesEndpointTests.cs @@ -0,0 +1,70 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Common.DTO.Authorization; +using Lumina.Presentation.Web.Common.Responses.Authorization; +using Lumina.Presentation.Web.Core.Endpoints.Admin.Authorization.Roles.GetRoles; +using Lumina.Presentation.Web.Fixtures.Common.TestHelpers; +using Lumina.Presentation.Web.IntegrationTests.Common.Setup; +using System; +using System.Diagnostics.CodeAnalysis; +using System.Net; +using System.Net.Http; +using System.Text.Json; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.Admin.Authorization.Roles.GetRoles; + +/// +/// Contains integration tests for the /{culture}/admin/api-get-roles route served by the class. +/// +[ExcludeFromCodeCoverage] +public class GetRolesEndpointTests : IClassFixture +{ + private readonly LuminaWebFactory _apiFactory; + + /// + /// Initializes a new instance of the class. + /// + /// Injected Web application factory. + public GetRolesEndpointTests(LuminaWebFactory apiFactory) + { + _apiFactory = apiFactory; + } + + [Fact] + public async Task GetRoles_WhenCalledByAdminUser_ShouldReturnRolesJson() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + _apiFactory.ApiClientStub.AuthorizationResponse = new GetAuthorizationResponse(Guid.NewGuid(), "Admin", []); + RoleDto[] expectedRoles = [new RoleDto(Guid.NewGuid(), "Admin"), new RoleDto(Guid.NewGuid(), "User")]; + _apiFactory.ApiClientStub.RegisterGetResponse("auth/roles", expectedRoles); + AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); + + // Act + HttpResponseMessage response = await webClient.Client.GetAsync("/en-us/admin/api-get-roles"); + string content = await response.Content.ReadAsStringAsync(); + + // Assert + response.EnsureSuccessStatusCode(); + using JsonDocument json = JsonDocument.Parse(content); + Assert.True(json.RootElement.GetProperty("success").GetBoolean()); + Assert.Equal(2, json.RootElement.GetProperty("data").GetArrayLength()); + } + + [Fact] + public async Task GetRoles_WhenCalledByNonAdminUser_ShouldRedirectToAccessDenied() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + _apiFactory.ApiClientStub.AuthorizationResponse = new GetAuthorizationResponse(Guid.NewGuid(), "User", []); + AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); + + // Act + HttpResponseMessage response = await webClient.Client.GetAsync("/en-us/admin/api-get-roles"); + + // Assert + Assert.Equal(HttpStatusCode.Redirect, response.StatusCode); + Assert.Contains("access-denied", response.Headers.Location!.ToString()); + } +} diff --git a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Home/HomeIndexEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Home/HomeIndexEndpointTests.cs new file mode 100644 index 00000000..25f1c76d --- /dev/null +++ b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Home/HomeIndexEndpointTests.cs @@ -0,0 +1,91 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Core.Endpoints.Home; +using Lumina.Presentation.Web.Fixtures.Common.TestHelpers; +using Lumina.Presentation.Web.IntegrationTests.Common.Setup; +using System.Diagnostics.CodeAnalysis; +using System.Net; +using System.Net.Http; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.Home; + +/// +/// Contains integration tests for the /{culture} and / routes served by the class. +/// +[ExcludeFromCodeCoverage] +public class HomeIndexEndpointTests : IClassFixture +{ + private readonly LuminaWebFactory _apiFactory; + + /// + /// Initializes a new instance of the class. + /// + /// Injected Web application factory. + public HomeIndexEndpointTests(LuminaWebFactory apiFactory) + { + _apiFactory = apiFactory; + } + + [Fact] + public async Task Home_WhenCalledWithoutCulture_ShouldRedirectToDefaultCulture() + { + // Arrange + HttpClient client = WebTestHelpers.CreateAnonymousClient(_apiFactory); + + // Act + HttpResponseMessage response = await client.GetAsync("/"); + + // Assert + Assert.Equal(HttpStatusCode.Redirect, response.StatusCode); + Assert.Equal("/en-us/", response.Headers.Location!.ToString()); + } + + [Fact] + public async Task Home_WhenCalledWithoutAuthentication_ShouldRedirectToLogin() + { + // Arrange + HttpClient client = WebTestHelpers.CreateAnonymousClient(_apiFactory); + + // Act + HttpResponseMessage response = await client.GetAsync("/en-us"); + + // Assert + Assert.Equal(HttpStatusCode.Redirect, response.StatusCode); + Assert.Equal("http://localhost/en-us/auth/login", response.Headers.Location!.ToString()); + } + + [Fact] + public async Task Home_WhenCalledByAuthenticatedUser_ShouldReturnHomePage() + { + // Arrange + AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); + + // Act + HttpResponseMessage response = await webClient.Client.GetAsync("/en-us"); + + // Assert + response.EnsureSuccessStatusCode(); + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + Assert.Equal("text/html", response.Content.Headers.ContentType!.MediaType); + string content = await response.Content.ReadAsStringAsync(); + Assert.Contains("html", content); + } + + [Theory] + [InlineData("/de-de")] // German culture + [InlineData("/fr-fr")] // French culture + [InlineData("/ja-jp")] // Japanese culture + public async Task Home_WhenCalledByAuthenticatedUserWithLocalizedCulture_ShouldReturnHomePage(string culturePath) + { + // Arrange + AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); + + // Act + HttpResponseMessage response = await webClient.Client.GetAsync(culturePath); + + // Assert + response.EnsureSuccessStatusCode(); + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + } +} diff --git a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/Management/GetLibraries/GetLibrariesEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/Management/GetLibraries/GetLibrariesEndpointTests.cs new file mode 100644 index 00000000..5f793a82 --- /dev/null +++ b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/Management/GetLibraries/GetLibrariesEndpointTests.cs @@ -0,0 +1,90 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Common.DTO.Libraries; +using Lumina.Presentation.Web.Core.Endpoints.Library.Management.GetLibraries; +using Lumina.Presentation.Web.Fixtures.Common.TestHelpers; +using Lumina.Presentation.Web.IntegrationTests.Common.Setup; +using System; +using System.Diagnostics.CodeAnalysis; +using System.Net; +using System.Net.Http; +using System.Text.Json; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.Library.Management.GetLibraries; + +/// +/// Contains integration tests for the /{culture}/libraries/manage/api-get-libraries route served by the class. +/// +[ExcludeFromCodeCoverage] +public class GetLibrariesEndpointTests : IClassFixture +{ + private readonly LuminaWebFactory _apiFactory; + + /// + /// Initializes a new instance of the class. + /// + /// Injected Web application factory. + public GetLibrariesEndpointTests(LuminaWebFactory apiFactory) + { + _apiFactory = apiFactory; + } + + [Fact] + public async Task GetLibraries_WhenCalledByAuthenticatedUser_ShouldReturnLibrariesJson() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + LibraryDto[] expectedLibraries = + [ + new LibraryDto { Id = Guid.NewGuid(), Title = "Books", LibraryType = "Book" }, + new LibraryDto { Id = Guid.NewGuid(), Title = "Movies", LibraryType = "Video" } + ]; + _apiFactory.ApiClientStub.RegisterGetResponse("libraries", expectedLibraries); + AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); + + // Act + HttpResponseMessage response = await webClient.Client.GetAsync("/en-us/libraries/manage/api-get-libraries"); + string content = await response.Content.ReadAsStringAsync(); + + // Assert + response.EnsureSuccessStatusCode(); + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + using JsonDocument json = JsonDocument.Parse(content); + Assert.True(json.RootElement.GetProperty("success").GetBoolean()); + JsonElement data = json.RootElement.GetProperty("data"); + Assert.Equal(2, data.GetArrayLength()); + Assert.Equal("Books", data[0].GetProperty("title").GetString()); + } + + [Fact] + public async Task GetLibraries_WhenCalledWithoutAuthentication_ShouldRedirectToLogin() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + HttpClient client = WebTestHelpers.CreateAnonymousClient(_apiFactory); + + // Act + HttpResponseMessage response = await client.GetAsync("/en-us/libraries/manage/api-get-libraries"); + + // Assert + Assert.Equal(HttpStatusCode.Redirect, response.StatusCode); + Assert.Equal("http://localhost/en-us/auth/login", response.Headers.Location!.ToString()); + } + + [Fact] + public async Task GetLibraries_WhenCalled_ShouldRequestLibrariesFromApi() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + _apiFactory.ApiClientStub.RegisterGetResponse("libraries", Array.Empty()); + AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); + + // Act + HttpResponseMessage response = await webClient.Client.GetAsync("/en-us/libraries/manage/api-get-libraries"); + + // Assert + response.EnsureSuccessStatusCode(); + Assert.Contains("libraries", _apiFactory.ApiClientStub.GetEndpointsCalled); + } +} diff --git a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/Management/SaveLibrary/SaveLibraryEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/Management/SaveLibrary/SaveLibraryEndpointTests.cs new file mode 100644 index 00000000..ceea2a3c --- /dev/null +++ b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/Management/SaveLibrary/SaveLibraryEndpointTests.cs @@ -0,0 +1,84 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Common.DTO.Libraries; +using Lumina.Presentation.Web.Core.Endpoints.Library.Management.SaveLibrary; +using Lumina.Presentation.Web.Fixtures.Common.TestHelpers; +using Lumina.Presentation.Web.IntegrationTests.Common.Setup; +using System; +using System.Diagnostics.CodeAnalysis; +using System.Net; +using System.Net.Http; +using System.Net.Http.Headers; +using System.Net.Http.Json; +using System.Text.Json; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.Library.Management.SaveLibrary; + +/// +/// Contains integration tests for the /{culture}/libraries/manage/api-item route served by the class. +/// +[ExcludeFromCodeCoverage] +public class SaveLibraryEndpointTests : IClassFixture +{ + private readonly LuminaWebFactory _apiFactory; + + /// + /// Initializes a new instance of the class. + /// + /// Injected Web application factory. + public SaveLibraryEndpointTests(LuminaWebFactory apiFactory) + { + _apiFactory = apiFactory; + } + + [Fact] + public async Task SaveLibrary_WhenCalledByAuthenticatedUserWithAntiforgeryToken_ShouldSaveLibraryAndReturnSuccess() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + LibraryDto request = new() { Title = "New Books Library", LibraryType = "Book" }; + LibraryDto expectedResponse = new() { Id = Guid.NewGuid(), Title = request.Title, LibraryType = request.LibraryType }; + _apiFactory.ApiClientStub.RegisterPostResponse("libraries", expectedResponse); + AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); + HttpRequestMessage saveRequest = new(HttpMethod.Post, "/en-us/libraries/manage/api-item") + { + Content = JsonContent.Create(request) + }; + saveRequest.Content!.Headers.ContentType = new MediaTypeHeaderValue("application/json"); + saveRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); + saveRequest.Headers.Add("RequestVerificationToken", webClient.AntiforgeryToken); + + // Act + HttpResponseMessage response = await webClient.Client.SendAsync(saveRequest); + string content = await response.Content.ReadAsStringAsync(); + + // Assert + response.EnsureSuccessStatusCode(); + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + using JsonDocument json = JsonDocument.Parse(content); + Assert.True(json.RootElement.GetProperty("success").GetBoolean()); + Assert.Contains(_apiFactory.ApiClientStub.PostRequests, postRequest => postRequest.Endpoint == "libraries"); + } + + [Fact] + public async Task SaveLibrary_WhenCalledWithoutAntiforgeryToken_ShouldReturnBadRequest() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); + HttpRequestMessage saveRequest = new(HttpMethod.Post, "/en-us/libraries/manage/api-item") + { + Content = JsonContent.Create(new LibraryDto { Title = "New Books Library", LibraryType = "Book" }) + }; + saveRequest.Content!.Headers.ContentType = new MediaTypeHeaderValue("application/json"); + saveRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); + + // Act + HttpResponseMessage response = await webClient.Client.SendAsync(saveRequest); + + // Assert + Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode); + Assert.DoesNotContain(_apiFactory.ApiClientStub.PostRequests, postRequest => postRequest.Endpoint == "libraries"); + } +} diff --git a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Tools/Language/SetLanguage/SetLanguageEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Tools/Language/SetLanguage/SetLanguageEndpointTests.cs new file mode 100644 index 00000000..d742300b --- /dev/null +++ b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Tools/Language/SetLanguage/SetLanguageEndpointTests.cs @@ -0,0 +1,61 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Core.Endpoints.Tools.Language.SetLanguage; +using Lumina.Presentation.Web.Fixtures.Common.TestHelpers; +using Lumina.Presentation.Web.IntegrationTests.Common.Setup; +using System; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +using System.Net; +using System.Net.Http; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.Tools.Language.SetLanguage; + +/// +/// Contains integration tests for the /{culture}/tools/language/set-language route served by the class. +/// +[ExcludeFromCodeCoverage] +public class SetLanguageEndpointTests : IClassFixture +{ + private readonly LuminaWebFactory _apiFactory; + + /// + /// Initializes a new instance of the class. + /// + /// Injected Web application factory. + public SetLanguageEndpointTests(LuminaWebFactory apiFactory) + { + _apiFactory = apiFactory; + } + + [Fact] + public async Task SetLanguage_WhenCalledByAuthenticatedUser_ShouldSetCultureCookieAndRedirectWithNewCulture() + { + // Arrange + AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); + string returnUrl = Uri.EscapeDataString("/en-us/tools/settings"); + + // Act + HttpResponseMessage response = await webClient.Client.GetAsync($"/en-us/tools/language/set-language?newCulture=de-DE&returnUrl={returnUrl}"); + + // Assert + Assert.Equal(HttpStatusCode.Redirect, response.StatusCode); + Assert.Equal("/de-de/tools/settings", response.Headers.Location!.ToString()); + Assert.Contains("de-DE", response.Headers.GetValues("Set-Cookie").First()); + } + + [Fact] + public async Task SetLanguage_WhenCalledWithoutAuthentication_ShouldRedirectToLogin() + { + // Arrange + HttpClient client = WebTestHelpers.CreateAnonymousClient(_apiFactory); + + // Act + HttpResponseMessage response = await client.GetAsync("/en-us/tools/language/set-language?newCulture=de-DE"); + + // Assert + Assert.Equal(HttpStatusCode.Redirect, response.StatusCode); + Assert.Equal("http://localhost/en-us/auth/login", response.Headers.Location!.ToString()); + } +} diff --git a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/UsersManagement/Authentication/Login/LoginEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/UsersManagement/Authentication/Login/LoginEndpointTests.cs new file mode 100644 index 00000000..2195b24c --- /dev/null +++ b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/UsersManagement/Authentication/Login/LoginEndpointTests.cs @@ -0,0 +1,138 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Common.DTO.Common; +using Lumina.Presentation.Web.Common.Exceptions; +using Lumina.Presentation.Web.Common.Requests.UsersManagement; +using Lumina.Presentation.Web.Core.Endpoints.UsersManagement.Authentication.Login; +using Lumina.Presentation.Web.Fixtures.Common.TestHelpers; +using Lumina.Presentation.Web.IntegrationTests.Common.Setup; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.IO; +using System.Linq; +using System.Net; +using System.Net.Http; +using System.Net.Http.Headers; +using System.Net.Http.Json; +using System.Text.Json; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.UsersManagement.Authentication.Login; + +/// +/// Contains integration tests for the /{culture}/auth/api-login route served by the class. +/// +[ExcludeFromCodeCoverage] +public class LoginEndpointTests : IClassFixture +{ + private readonly LuminaWebFactory _apiFactory; + + /// + /// Initializes a new instance of the class. + /// + /// Injected Web application factory. + public LoginEndpointTests(LuminaWebFactory apiFactory) + { + _apiFactory = apiFactory; + } + + [Fact] + public async Task Login_WithValidCredentials_ShouldSignInAndReturnRedirectUrl() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + HttpClient client = WebTestHelpers.CreateAnonymousClient(_apiFactory); + string antiforgeryToken = await WebTestHelpers.GetAntiforgeryTokenAsync(client); + HttpRequestMessage loginRequest = CreateLoginRequest(new LoginRequest(Username: "testuser", Password: "TestPass123!"), antiforgeryToken); + + // Act + HttpResponseMessage response = await client.SendAsync(loginRequest); + using JsonDocument json = await WebTestHelpers.ReadJsonAsync(response); + + // Assert + response.EnsureSuccessStatusCode(); + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + Assert.True(json.RootElement.GetProperty("success").GetBoolean()); + Assert.Equal("/en-us/", json.RootElement.GetProperty("data").GetString()); + string allSetCookies = string.Join("; ", response.Headers.GetValues("Set-Cookie")); + Assert.Contains(".Lumina.Auth", allSetCookies); + Assert.Contains("Token=", allSetCookies); + } + + [Fact] + public async Task Login_WhenTotpRequired_ShouldReturnTotpRequiredSignal() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + ProblemDetailsDto problemDetails = new() + { + Title = "General.Validation", + Detail = "OneOrMoreValidationErrorsOccurred", + Extensions = new Dictionary + { + ["errors"] = CreateErrorsElement(["InvalidTotpCode"]) + } + }; + _apiFactory.ApiClientStub.RegisterPostException("auth/login", new ApiException(problemDetails, HttpStatusCode.UnprocessableEntity, "auth/login")); + HttpClient client = WebTestHelpers.CreateAnonymousClient(_apiFactory); + string antiforgeryToken = await WebTestHelpers.GetAntiforgeryTokenAsync(client); + HttpRequestMessage loginRequest = CreateLoginRequest(new LoginRequest(Username: "testuser", Password: "TestPass123!"), antiforgeryToken); + + // Act + HttpResponseMessage response = await client.SendAsync(loginRequest); + using JsonDocument json = await WebTestHelpers.ReadJsonAsync(response); + + // Assert + response.EnsureSuccessStatusCode(); + Assert.True(json.RootElement.GetProperty("success").GetBoolean()); + Assert.True(json.RootElement.GetProperty("data").GetProperty("isTotpRequired").GetBoolean()); + } + + [Fact] + public async Task Login_WhenApiReturnsForbidden_ShouldReturnFailureJson() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + _apiFactory.ApiClientStub.RegisterPostException("auth/login", new ApiException(new ProblemDetailsDto { Title = "General.Failure", Detail = "InvalidUsernameOrPassword" }, HttpStatusCode.Forbidden, "auth/login")); + HttpClient client = WebTestHelpers.CreateAnonymousClient(_apiFactory); + string antiforgeryToken = await WebTestHelpers.GetAntiforgeryTokenAsync(client); + HttpRequestMessage loginRequest = CreateLoginRequest(new LoginRequest(Username: "testuser", Password: "WrongPass123!"), antiforgeryToken); + + // Act + HttpResponseMessage response = await client.SendAsync(loginRequest); + using JsonDocument json = await WebTestHelpers.ReadJsonAsync(response); + + // Assert + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + Assert.False(json.RootElement.GetProperty("success").GetBoolean()); + Assert.Contains("", json.RootElement.GetProperty("errorMessage").GetString()); + } + + private static HttpRequestMessage CreateLoginRequest(LoginRequest request, string antiforgeryToken) + { + HttpRequestMessage loginRequest = new(HttpMethod.Post, "/en-us/auth/api-login") + { + Content = JsonContent.Create(request) + }; + loginRequest.Content!.Headers.ContentType = new MediaTypeHeaderValue("application/json"); + loginRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); + loginRequest.Headers.Add("RequestVerificationToken", antiforgeryToken); + return loginRequest; + } + + private static JsonElement CreateErrorsElement(string[] errorCodes) + { + using MemoryStream stream = new(); + using (Utf8JsonWriter writer = new(stream)) + { + writer.WriteStartObject(); + writer.WriteStartArray("General.Validation"); + foreach (string errorCode in errorCodes) + writer.WriteStringValue(errorCode); + writer.WriteEndArray(); + writer.WriteEndObject(); + } + return JsonDocument.Parse(stream.ToArray()).RootElement.Clone(); + } +} diff --git a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/UsersManagement/Authentication/Login/LoginViewEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/UsersManagement/Authentication/Login/LoginViewEndpointTests.cs new file mode 100644 index 00000000..67cb7f45 --- /dev/null +++ b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/UsersManagement/Authentication/Login/LoginViewEndpointTests.cs @@ -0,0 +1,79 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Core.Endpoints.UsersManagement.Authentication.Login; +using Lumina.Presentation.Web.IntegrationTests.Common.Setup; +using System.Diagnostics.CodeAnalysis; +using System.Net; +using System.Net.Http; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.UsersManagement.Authentication.Login; + +/// +/// Contains integration tests for the /{culture}/auth/login/{returnUrl?} route served by the class. +/// +[ExcludeFromCodeCoverage] +public class LoginViewEndpointTests : IClassFixture +{ + private readonly LuminaWebFactory _apiFactory; + + /// + /// Initializes a new instance of the class. + /// + /// Injected Web application factory. + public LoginViewEndpointTests(LuminaWebFactory apiFactory) + { + _apiFactory = apiFactory; + } + + [Fact] + public async Task LoginView_WhenCalled_ShouldRenderLoginPage() + { + // Arrange + HttpClient client = _apiFactory.CreateClient(); + + // Act + HttpResponseMessage response = await client.GetAsync("/en-us/auth/login"); + + // Assert + response.EnsureSuccessStatusCode(); + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + Assert.Equal("text/html", response.Content.Headers.ContentType!.MediaType); + string content = await response.Content.ReadAsStringAsync(); + Assert.Contains("login-form", content); + } + + [Theory] + [InlineData("/de-de/auth/login")] // German culture + [InlineData("/fr-fr/auth/login")] // French culture + [InlineData("/zh-cn/auth/login")] // Chinese culture + public async Task LoginView_WhenCalledWithLocalizedCulture_ShouldRenderLoginPage(string culturePath) + { + // Arrange + HttpClient client = _apiFactory.CreateClient(); + + // Act + HttpResponseMessage response = await client.GetAsync(culturePath); + + // Assert + response.EnsureSuccessStatusCode(); + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + string content = await response.Content.ReadAsStringAsync(); + Assert.Contains("login-form", content); + } + + [Fact] + public async Task LoginView_WhenCalledWithReturnUrl_ShouldPreserveReturnUrlInView() + { + // Arrange + HttpClient client = _apiFactory.CreateClient(); + + // Act + HttpResponseMessage response = await client.GetAsync("/en-us/auth/login/some-return-url"); + + // Assert + response.EnsureSuccessStatusCode(); + string content = await response.Content.ReadAsStringAsync(); + Assert.Contains("some-return-url", content); + } +} diff --git a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Lumina.Presentation.Web.IntegrationTests.csproj b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Lumina.Presentation.Web.IntegrationTests.csproj new file mode 100644 index 00000000..2ec3ddb4 --- /dev/null +++ b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Lumina.Presentation.Web.IntegrationTests.csproj @@ -0,0 +1,46 @@ + + + + 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/SecurityTests/Lumina.Presentation.Web.SecurityTests/Common/Setup/LuminaWebFactory.cs b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Common/Setup/LuminaWebFactory.cs new file mode 100644 index 00000000..ba24862e --- /dev/null +++ b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Common/Setup/LuminaWebFactory.cs @@ -0,0 +1,63 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web; +using Lumina.Presentation.Web.Common.Api; +using Lumina.Presentation.Web.Fixtures.Common.Api; +using Microsoft.AspNetCore.Hosting; +using Microsoft.AspNetCore.Mvc.Testing; +using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.DependencyInjection; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Presentation.Web.SecurityTests.Common.Setup; + +/// +/// Factory for creating the Web application for security tests, with the remote API client replaced by a configurable stub. +/// +[ExcludeFromCodeCoverage] +public class LuminaWebFactory : WebApplicationFactory, IDisposable +{ + private const string TEST_ENCRYPTION_KEY = "FLYO0QRo6u2VzoFOgNkkEwYNGtqhJ3QGZd7iAHNEJeM="; + + /// + /// Gets the stub used in place of the remote API client. + /// + public StubApiHttpClient ApiClientStub { get; } = new(); + + /// + /// Initializes a new instance of the class. + /// + public LuminaWebFactory() + { + } + + /// + /// Configures the web host for the security tests. + /// + /// The web host builder to configure. + protected override void ConfigureWebHost(IWebHostBuilder builder) + { + builder.ConfigureAppConfiguration((context, config) => + { + // provide the application configuration values that the Web app validates on startup + config.AddInMemoryCollection(initialData: new Dictionary + { + ["EncryptionSettings:SecretKey"] = TEST_ENCRYPTION_KEY, + ["ServerConfiguration:ApiVersion"] = "1", + ["ServerConfiguration:BaseAddress"] = "http://localhost", + ["ServerConfiguration:Port"] = "5214" + }); + }); + builder.ConfigureServices(services => + { + // remove the typed HTTP client registration, so that the stub can take its place + ServiceDescriptor[] apiClientDescriptors = services.Where(serviceDescriptor => serviceDescriptor.ServiceType == typeof(IApiHttpClient)).ToArray(); + foreach (ServiceDescriptor descriptor in apiClientDescriptors) + services.Remove(descriptor); + services.AddSingleton(ApiClientStub); + }); + } +} diff --git a/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Admin/Authorization/Roles/GetRoles/GetRolesEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Admin/Authorization/Roles/GetRoles/GetRolesEndpointTests.cs new file mode 100644 index 00000000..9bcdaa67 --- /dev/null +++ b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Admin/Authorization/Roles/GetRoles/GetRolesEndpointTests.cs @@ -0,0 +1,87 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Common.DTO.Authorization; +using Lumina.Presentation.Web.Common.Responses.Authorization; +using Lumina.Presentation.Web.Core.Endpoints.Admin.Authorization.Roles.GetRoles; +using Lumina.Presentation.Web.Fixtures.Common.TestHelpers; +using Lumina.Presentation.Web.SecurityTests.Common.Setup; +using System; +using System.Diagnostics.CodeAnalysis; +using System.Net; +using System.Net.Http; +using System.Text.Json; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.SecurityTests.Core.Endpoints.Admin.Authorization.Roles.GetRoles; + +/// +/// Contains security tests for the /{culture}/admin/api-get-roles route served by the class. +/// +[ExcludeFromCodeCoverage] +public class GetRolesEndpointTests : IClassFixture +{ + private readonly LuminaWebFactory _apiFactory; + + /// + /// Initializes a new instance of the class. + /// + /// Injected Web application factory. + public GetRolesEndpointTests(LuminaWebFactory apiFactory) + { + _apiFactory = apiFactory; + } + + [Fact] + public async Task GetRoles_WhenCalledWithoutAuthentication_ShouldNotExposeRoleData() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + RoleDto[] unexpectedRoles = [new RoleDto(Guid.NewGuid(), "Admin")]; + _apiFactory.ApiClientStub.RegisterGetResponse("auth/roles", unexpectedRoles); + HttpClient client = WebTestHelpers.CreateAnonymousClient(_apiFactory); + + // Act + HttpResponseMessage response = await client.GetAsync("/en-us/admin/api-get-roles"); + string content = await response.Content.ReadAsStringAsync(); + + // Assert + using JsonDocument json = JsonDocument.Parse(content); + Assert.False(json.RootElement.GetProperty("success").GetBoolean()); + Assert.DoesNotContain("Admin", content); + Assert.DoesNotContain("AdminRole", content); + } + + [Fact] + public async Task GetRoles_WhenCalledByNonAdminUser_ShouldRedirectToAccessDenied() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + _apiFactory.ApiClientStub.AuthorizationResponse = new GetAuthorizationResponse(Guid.NewGuid(), "User", []); + AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); + + // Act + HttpResponseMessage response = await webClient.Client.GetAsync("/en-us/admin/api-get-roles"); + + // Assert + Assert.Equal(HttpStatusCode.Redirect, response.StatusCode); + Assert.Contains("access-denied", response.Headers.Location!.ToString()); + } + + [Fact] + public async Task GetRoles_WhenCalledByAdminUser_ShouldReturnRolesData() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + _apiFactory.ApiClientStub.AuthorizationResponse = new GetAuthorizationResponse(Guid.NewGuid(), "Admin", []); + RoleDto[] expectedRoles = [new RoleDto(Guid.NewGuid(), "Admin")]; + _apiFactory.ApiClientStub.RegisterGetResponse("auth/roles", expectedRoles); + AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); + + // Act + HttpResponseMessage response = await webClient.Client.GetAsync("/en-us/admin/api-get-roles"); + + // Assert + response.EnsureSuccessStatusCode(); + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + } +} diff --git a/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Library/Management/DeleteLibrary/DeleteLibraryEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Library/Management/DeleteLibrary/DeleteLibraryEndpointTests.cs new file mode 100644 index 00000000..ca7a3bf4 --- /dev/null +++ b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Library/Management/DeleteLibrary/DeleteLibraryEndpointTests.cs @@ -0,0 +1,82 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Core.Endpoints.Library.Management.DeleteLibrary; +using Lumina.Presentation.Web.Fixtures.Common.TestHelpers; +using Lumina.Presentation.Web.SecurityTests.Common.Setup; +using System; +using System.Diagnostics.CodeAnalysis; +using System.Net; +using System.Net.Http; +using System.Net.Http.Headers; +using System.Text; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.SecurityTests.Core.Endpoints.Library.Management.DeleteLibrary; + +/// +/// Contains security tests for the /{culture}/libraries/manage/api-item/{{id}} route served by the class. +/// +[ExcludeFromCodeCoverage] +public class DeleteLibraryEndpointTests : IClassFixture +{ + private readonly LuminaWebFactory _apiFactory; + + /// + /// Initializes a new instance of the class. + /// + /// Injected Web application factory. + public DeleteLibraryEndpointTests(LuminaWebFactory apiFactory) + { + _apiFactory = apiFactory; + } + + [Fact] + public async Task DeleteLibrary_WhenCalledWithoutAntiforgeryToken_ShouldRejectRequest() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); + Guid libraryId = Guid.NewGuid(); + HttpRequestMessage deleteRequest = CreateDeleteRequest(libraryId); + + // Act + HttpResponseMessage response = await webClient.Client.SendAsync(deleteRequest); + + // Assert + Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode); + Assert.DoesNotContain(_apiFactory.ApiClientStub.DeleteEndpointsCalled, endpoint => endpoint == $"libraries/{libraryId}"); + } + + [Fact] + public async Task DeleteLibrary_WhenCalledWithoutAuthentication_ShouldNotDeleteLibrary() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + HttpClient client = WebTestHelpers.CreateAnonymousClient(_apiFactory); + string antiforgeryToken = await WebTestHelpers.GetAntiforgeryTokenAsync(client); + Guid libraryId = Guid.NewGuid(); + HttpRequestMessage deleteRequest = CreateDeleteRequest(libraryId); + deleteRequest.Headers.Add("RequestVerificationToken", antiforgeryToken); + + // Act + HttpResponseMessage response = await client.SendAsync(deleteRequest); + + // Assert + Assert.Equal(HttpStatusCode.Redirect, response.StatusCode); + Assert.Equal("http://localhost/en-us/auth/login", response.Headers.Location!.ToString()); + Assert.DoesNotContain(_apiFactory.ApiClientStub.DeleteEndpointsCalled, endpoint => endpoint == $"libraries/{libraryId}"); + } + + private static HttpRequestMessage CreateDeleteRequest(Guid libraryId) + { + HttpRequestMessage deleteRequest = new(HttpMethod.Delete, $"/en-us/libraries/manage/api-item/{libraryId}") + { + // the front-end sends the JSON content type even for DELETE requests, which triggers the antiforgery validation + Content = new StringContent("{}", Encoding.UTF8, "application/json") + }; + // the antiforgery middleware matches the content type exactly, so the charset suffix must be omitted + deleteRequest.Content!.Headers.ContentType = new MediaTypeHeaderValue("application/json"); + deleteRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); + return deleteRequest; + } +} diff --git a/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Library/Management/SaveLibrary/SaveLibraryEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Library/Management/SaveLibrary/SaveLibraryEndpointTests.cs new file mode 100644 index 00000000..16917b88 --- /dev/null +++ b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Library/Management/SaveLibrary/SaveLibraryEndpointTests.cs @@ -0,0 +1,99 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Common.DTO.Libraries; +using Lumina.Presentation.Web.Core.Endpoints.Library.Management.SaveLibrary; +using Lumina.Presentation.Web.Fixtures.Common.TestHelpers; +using Lumina.Presentation.Web.SecurityTests.Common.Setup; +using System; +using System.Diagnostics.CodeAnalysis; +using System.Net; +using System.Net.Http; +using System.Net.Http.Headers; +using System.Net.Http.Json; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.SecurityTests.Core.Endpoints.Library.Management.SaveLibrary; + +/// +/// Contains security tests for the /{culture}/libraries/manage/api-item route served by the class. +/// +[ExcludeFromCodeCoverage] +public class SaveLibraryEndpointTests : IClassFixture +{ + private readonly LuminaWebFactory _apiFactory; + + /// + /// Initializes a new instance of the class. + /// + /// Injected Web application factory. + public SaveLibraryEndpointTests(LuminaWebFactory apiFactory) + { + _apiFactory = apiFactory; + } + + [Fact] + public async Task SaveLibrary_WhenCalledWithoutAntiforgeryToken_ShouldRejectRequest() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); + HttpRequestMessage saveRequest = CreateSaveRequest(new LibraryDto { Title = "New Books Library", LibraryType = "Book" }); + + // Act + HttpResponseMessage response = await webClient.Client.SendAsync(saveRequest); + + // Assert + Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode); + Assert.DoesNotContain(_apiFactory.ApiClientStub.PostRequests, postRequest => postRequest.Endpoint == "libraries"); + } + + [Fact] + public async Task SaveLibrary_WhenCalledWithInvalidAntiforgeryToken_ShouldRejectRequest() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); + HttpRequestMessage saveRequest = CreateSaveRequest(new LibraryDto { Title = "New Books Library", LibraryType = "Book" }); + saveRequest.Headers.Remove("RequestVerificationToken"); + saveRequest.Headers.Add("RequestVerificationToken", "invalid-antiforgery-token"); + + // Act + HttpResponseMessage response = await webClient.Client.SendAsync(saveRequest); + + // Assert + Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode); + Assert.DoesNotContain(_apiFactory.ApiClientStub.PostRequests, postRequest => postRequest.Endpoint == "libraries"); + } + + [Fact] + public async Task SaveLibrary_WhenCalledWithInjectionInLibraryTitle_ShouldRemainSecure() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + LibraryDto request = new() { Title = "'; DROP TABLE Libraries--", LibraryType = "Book" }; + _apiFactory.ApiClientStub.RegisterPostResponse("libraries", new LibraryDto { Id = Guid.NewGuid(), Title = request.Title, LibraryType = request.LibraryType }); + AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); + HttpRequestMessage saveRequest = CreateSaveRequest(request); + saveRequest.Headers.Add("RequestVerificationToken", webClient.AntiforgeryToken); + + // Act + HttpResponseMessage response = await webClient.Client.SendAsync(saveRequest); + string content = await response.Content.ReadAsStringAsync(); + + // Assert + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + Assert.DoesNotContain("SQL", content); + Assert.DoesNotContain("Exception", content); + } + + private static HttpRequestMessage CreateSaveRequest(LibraryDto request) + { + HttpRequestMessage saveRequest = new(HttpMethod.Post, "/en-us/libraries/manage/api-item") + { + Content = JsonContent.Create(request) + }; + saveRequest.Content!.Headers.ContentType = new MediaTypeHeaderValue("application/json"); + saveRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); + return saveRequest; + } +} diff --git a/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/UsersManagement/Authentication/Login/LoginEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/UsersManagement/Authentication/Login/LoginEndpointTests.cs new file mode 100644 index 00000000..4b186aa1 --- /dev/null +++ b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/UsersManagement/Authentication/Login/LoginEndpointTests.cs @@ -0,0 +1,127 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Common.DTO.Common; +using Lumina.Presentation.Web.Common.Exceptions; +using Lumina.Presentation.Web.Common.Requests.UsersManagement; +using Lumina.Presentation.Web.Core.Endpoints.UsersManagement.Authentication.Login; +using Lumina.Presentation.Web.Fixtures.Common.TestHelpers; +using Lumina.Presentation.Web.SecurityTests.Common.Setup; +using System; +using System.Diagnostics.CodeAnalysis; +using System.Net; +using System.Net.Http; +using System.Net.Http.Headers; +using System.Net.Http.Json; +using System.Text.Json; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.SecurityTests.Core.Endpoints.UsersManagement.Authentication.Login; + +/// +/// Contains security tests for the /{culture}/auth/api-login route served by the class. +/// +[ExcludeFromCodeCoverage] +public class LoginEndpointTests : IClassFixture +{ + private readonly LuminaWebFactory _apiFactory; + + /// + /// Initializes a new instance of the class. + /// + /// Injected Web application factory. + public LoginEndpointTests(LuminaWebFactory apiFactory) + { + _apiFactory = apiFactory; + } + + [Theory] + [InlineData("' OR '1'='1")] // basic SQL injection + [InlineData("admin'--")] // comment injection + [InlineData("' UNION SELECT * FROM Users--")] // union injection + [InlineData("'; DROP TABLE Users--")] // destructive injection + [InlineData("{{7*7}}")] // template injection + public async Task Login_WithInjectionAttemptInUsername_ShouldRemainSecure(string maliciousUsername) + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + _apiFactory.ApiClientStub.RegisterPostException("auth/login", new ApiException(new ProblemDetailsDto { Title = "General.Failure", Detail = "InvalidUsernameOrPassword" }, HttpStatusCode.Forbidden, "auth/login")); + HttpClient client = WebTestHelpers.CreateAnonymousClient(_apiFactory); + string antiforgeryToken = await WebTestHelpers.GetAntiforgeryTokenAsync(client); + HttpRequestMessage loginRequest = CreateLoginRequest(new LoginRequest(Username: maliciousUsername, Password: "Abcd123$"), antiforgeryToken); + + // Act + HttpResponseMessage response = await client.SendAsync(loginRequest); + string content = await response.Content.ReadAsStringAsync(); + + // Assert + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + using JsonDocument json = JsonDocument.Parse(content); + Assert.False(json.RootElement.GetProperty("success").GetBoolean()); + Assert.DoesNotContain("SQL", content); + Assert.DoesNotContain("Exception", content); + Assert.DoesNotContain("Abcd123$", content); + Assert.DoesNotContain("hash", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("salt", content, StringComparison.OrdinalIgnoreCase); + } + + [Fact] + public async Task Login_WithValidCredentials_ShouldNotExposeSensitiveData() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + HttpClient client = WebTestHelpers.CreateAnonymousClient(_apiFactory); + string antiforgeryToken = await WebTestHelpers.GetAntiforgeryTokenAsync(client); + HttpRequestMessage loginRequest = CreateLoginRequest(new LoginRequest(Username: "testuser", Password: "TestPass123!"), antiforgeryToken); + + // Act + HttpResponseMessage response = await client.SendAsync(loginRequest); + string content = await response.Content.ReadAsStringAsync(); + + // Assert + response.EnsureSuccessStatusCode(); + Assert.DoesNotContain("TestPass123!", content); + Assert.DoesNotContain("hash", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("salt", content, StringComparison.OrdinalIgnoreCase); + // the JWT token returned by the API must not be exposed in plaintext; it is stored encrypted in the Token cookie + Assert.DoesNotContain("test_jwt_token", content); + string allSetCookies = string.Join("; ", response.Headers.GetValues("Set-Cookie")); + Assert.Contains("Token=", allSetCookies); + Assert.DoesNotContain("test_jwt_token", allSetCookies); + } + + [Fact] + public async Task Login_WhenCalled_ShouldSetAuthenticationCookieWithSecurityAttributes() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + HttpClient client = WebTestHelpers.CreateAnonymousClient(_apiFactory); + string antiforgeryToken = await WebTestHelpers.GetAntiforgeryTokenAsync(client); + HttpRequestMessage loginRequest = CreateLoginRequest(new LoginRequest(Username: "testuser", Password: "TestPass123!"), antiforgeryToken); + + // Act + HttpResponseMessage response = await client.SendAsync(loginRequest); + + // Assert + response.EnsureSuccessStatusCode(); + string authCookie = response.Headers.GetValues("Set-Cookie").First(cookie => cookie.StartsWith(".Lumina.Auth", StringComparison.Ordinal)); + Assert.Contains("httponly", authCookie, StringComparison.OrdinalIgnoreCase); + Assert.Contains("secure", authCookie, StringComparison.OrdinalIgnoreCase); + Assert.Contains("samesite=strict", authCookie, StringComparison.OrdinalIgnoreCase); + string tokenCookie = response.Headers.GetValues("Set-Cookie").First(cookie => cookie.StartsWith("Token=", StringComparison.Ordinal) && !cookie.Contains("1970")); + Assert.Contains("httponly", tokenCookie, StringComparison.OrdinalIgnoreCase); + Assert.Contains("secure", tokenCookie, StringComparison.OrdinalIgnoreCase); + Assert.Contains("samesite=strict", tokenCookie, StringComparison.OrdinalIgnoreCase); + } + + private static HttpRequestMessage CreateLoginRequest(LoginRequest request, string antiforgeryToken) + { + HttpRequestMessage loginRequest = new(HttpMethod.Post, "/en-us/auth/api-login") + { + Content = JsonContent.Create(request) + }; + loginRequest.Content!.Headers.ContentType = new MediaTypeHeaderValue("application/json"); + loginRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); + loginRequest.Headers.Add("RequestVerificationToken", antiforgeryToken); + return loginRequest; + } +} diff --git a/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Lumina.Presentation.Web.SecurityTests.csproj b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Lumina.Presentation.Web.SecurityTests.csproj new file mode 100644 index 00000000..7a0745c3 --- /dev/null +++ b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Lumina.Presentation.Web.SecurityTests.csproj @@ -0,0 +1,46 @@ + + + + net10.0 + enable + enable + + false + true + + + + + <_Parameter1>DisableTestParallelization = true + <_Parameter1_IsLiteral>true + + + + + + + + + all + runtime; build; native; contentfiles; analyzers; buildtransitive + + + + + + + + all + runtime; build; native; contentfiles; analyzers; buildtransitive + + + + + + + + + + + + diff --git a/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Common/Api/ApiHttpClientTests.cs b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Common/Api/ApiHttpClientTests.cs new file mode 100644 index 00000000..b56c9832 --- /dev/null +++ b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Common/Api/ApiHttpClientTests.cs @@ -0,0 +1,177 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Common.Api; +using Lumina.Presentation.Web.Common.DTO.Common; +using Lumina.Presentation.Web.Common.DTO.Configuration; +using Lumina.Presentation.Web.Common.DTO.FileSystemManagement; +using Lumina.Presentation.Web.Common.Exceptions; +using Lumina.Presentation.Web.Fixtures.Common.Api; +using Microsoft.AspNetCore.Http; +using Microsoft.Extensions.Options; +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.Api; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class ApiHttpClientTests +{ + private const string TEST_ENCRYPTION_KEY = "FLYO0QRo6u2VzoFOgNkkEwYNGtqhJ3QGZd7iAHNEJeM="; + + [Fact] + public async Task GetAsync_WhenApiReturnsSuccess_ShouldDeserializeResponseContent() + { + // Arrange + TestApiHttpMessageHandler messageHandler = new(_ => CreateJsonResponse(HttpStatusCode.OK, """[{"title":"Library One"}]""")); + ApiHttpClient sut = CreateSut(messageHandler); + + // Act + Lumina.Presentation.Web.Common.DTO.Libraries.LibraryDto[] result = await sut.GetAsync("libraries", CancellationToken.None); + + // Assert + Assert.Single(result); + Assert.Equal("Library One", result[0].Title); + Assert.Equal(new Uri("http://localhost:5214/api/v1/libraries"), messageHandler.Requests[0].RequestUri); + } + + [Fact] + public async Task GetAsync_WhenApiReturnsError_ShouldThrowApiExceptionWithProblemDetails() + { + // Arrange + string problemDetailsJson = """ + { + "type": "https://tools.ietf.org/html/rfc4918#section-11.2", + "title": "General.Validation", + "status": 422, + "detail": "OneOrMoreValidationErrorsOccurred" + } + """; + TestApiHttpMessageHandler messageHandler = new(_ => CreateJsonResponse(HttpStatusCode.UnprocessableEntity, problemDetailsJson)); + ApiHttpClient sut = CreateSut(messageHandler); + + // Act + ApiException exception = await Assert.ThrowsAsync(() => sut.GetAsync("libraries", CancellationToken.None)); + + // Assert + Assert.Equal(HttpStatusCode.UnprocessableEntity, exception.HttpStatusCode); + Assert.NotNull(exception.ProblemDetails); + Assert.Equal("General.Validation", exception.ProblemDetails!.Title); + Assert.Equal(422, exception.ProblemDetails.Status); + Assert.Equal("OneOrMoreValidationErrorsOccurred", exception.ProblemDetails.Detail); + } + + [Fact] + public async Task GetAsync_WhenApiReturnsEmptyContent_ShouldReturnDefault() + { + // Arrange + TestApiHttpMessageHandler messageHandler = new(_ => new HttpResponseMessage(HttpStatusCode.OK) { Content = new StringContent(string.Empty) }); + ApiHttpClient sut = CreateSut(messageHandler); + + // Act + object? result = await sut.GetAsync("libraries", CancellationToken.None); + + // Assert + Assert.Null(result); + } + + [Fact] + public async Task GetAsync_WhenUserHasTokenClaim_ShouldSendAuthorizationHeader() + { + // Arrange + TestApiHttpMessageHandler messageHandler = new(_ => CreateJsonResponse(HttpStatusCode.OK, "{}")); + ApiHttpClient sut = CreateSut(messageHandler, token: "test-jwt-token"); + + // Act + await sut.GetAsync("libraries", CancellationToken.None); + + // Assert + Assert.Equal("Bearer", messageHandler.Requests[0].Headers.Authorization!.Scheme); + Assert.Equal("test-jwt-token", messageHandler.Requests[0].Headers.Authorization!.Parameter); + } + + [Fact] + public async Task PostAsync_WhenCalled_ShouldSerializePayloadAndDeserializeResponse() + { + // Arrange + TestApiHttpMessageHandler messageHandler = new(_ => CreateJsonResponse(HttpStatusCode.OK, """{"success":true}""")); + ApiHttpClient sut = CreateSut(messageHandler); + + // Act + SuccessResponse result = await sut.PostAsync("auth/login", new { username = "testuser" }, CancellationToken.None); + + // Assert + Assert.True(result.Success); + Assert.Equal(HttpMethod.Post, messageHandler.Requests[0].Method); + Assert.Equal("http://localhost:5214/api/v1/auth/login", messageHandler.Requests[0].RequestUri!.ToString()); + Assert.Contains("testuser", messageHandler.RequestBodies[0]); + } + + [Fact] + public async Task DeleteAsync_WhenApiReturnsError_ShouldThrowApiException() + { + // Arrange + TestApiHttpMessageHandler messageHandler = new(_ => CreateJsonResponse(HttpStatusCode.InternalServerError, """{"title":"General.Failure","status":500}""")); + ApiHttpClient sut = CreateSut(messageHandler); + + // Act + ApiException exception = await Assert.ThrowsAsync(() => sut.DeleteAsync("libraries/1", CancellationToken.None)); + + // Assert + Assert.Equal(HttpStatusCode.InternalServerError, exception.HttpStatusCode); + Assert.Equal("/api/v1/libraries/1", exception.RequestPath); + } + + [Fact] + public async Task GetBlobAsync_WhenApiReturnsSuccess_ShouldReturnBlobData() + { + // Arrange + byte[] imageBytes = Encoding.UTF8.GetBytes("fake-image-bytes"); + TestApiHttpMessageHandler messageHandler = new(_ => + { + HttpResponseMessage response = new(HttpStatusCode.OK) { Content = new ByteArrayContent(imageBytes) }; + response.Content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("image/png"); + return response; + }); + ApiHttpClient sut = CreateSut(messageHandler); + + // Act + BlobDataDto blob = await sut.GetBlobAsync("libraries/1/cover", CancellationToken.None); + + // Assert + Assert.Equal(imageBytes, blob.Data); + Assert.Equal("image/png", blob.ContentType); + } + + private static ApiHttpClient CreateSut(TestApiHttpMessageHandler messageHandler, string? token = null) + { + HttpClient httpClient = new(messageHandler); + IHttpContextAccessor httpContextAccessor = Substitute.For(); + if (token is not null) + { + DefaultHttpContext httpContext = new(); + httpContext.User = new ClaimsPrincipal(new ClaimsIdentity([new Claim("Token", token)], "TestAuthentication")); + httpContextAccessor.HttpContext.Returns(httpContext); + } + IOptionsSnapshot serverConfigurationOptions = Substitute.For>(); + serverConfigurationOptions.Value.Returns(new ServerConfigurationDto { ApiVersion = '1', BaseAddress = "http://localhost", Port = 5214 }); + return new ApiHttpClient(httpClient, httpContextAccessor, serverConfigurationOptions); + } + + 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/Authorization/AuthorizationPoliciesTests.cs b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Common/Authorization/AuthorizationPoliciesTests.cs new file mode 100644 index 00000000..9421e58d --- /dev/null +++ b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Common/Authorization/AuthorizationPoliciesTests.cs @@ -0,0 +1,22 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Common.Authorization; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Presentation.Web.UnitTests.Common.Authorization; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class AuthorizationPoliciesTests +{ + [Fact] + public void PolicyNames_WhenRead_ShouldMatchExpectedPolicyNames() + { + // Act & Assert + Assert.Equal("RequireAdminRole", AuthorizationPolicies.REQUIRE_ADMIN_ROLE); + Assert.Equal("RequireCreateLibrariesPermission", AuthorizationPolicies.REQUIRE_CREATE_LIBRARIES_PERMISSION); + Assert.Equal("RequireInitialization", AuthorizationPolicies.REQUIRE_INITIALIZATION); + } +} diff --git a/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Common/Authorization/AuthorizationServiceTests.cs b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Common/Authorization/AuthorizationServiceTests.cs new file mode 100644 index 00000000..de8002c4 --- /dev/null +++ b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Common/Authorization/AuthorizationServiceTests.cs @@ -0,0 +1,112 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Common.Api; +using Lumina.Presentation.Web.Common.Authorization; +using Lumina.Presentation.Web.Common.Enums.Authorization; +using Lumina.Presentation.Web.Common.Responses.Authorization; +using Microsoft.AspNetCore.Http; +using NSubstitute; +using System; +using System.Diagnostics.CodeAnalysis; +using System.Security.Claims; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.UnitTests.Common.Authorization; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class AuthorizationServiceTests +{ + private readonly IApiHttpClient _mockApiHttpClient; + private readonly AuthorizationService _sut; + private readonly Guid _userId; + + /// + /// Initializes a new instance of the class. + /// + public AuthorizationServiceTests() + { + _userId = Guid.NewGuid(); + _mockApiHttpClient = Substitute.For(); + IHttpContextAccessor httpContextAccessor = Substitute.For(); + DefaultHttpContext httpContext = new(); + httpContext.User = new ClaimsPrincipal(new ClaimsIdentity([new Claim(ClaimTypes.NameIdentifier, _userId.ToString())], "TestAuthentication")); + httpContextAccessor.HttpContext.Returns(httpContext); + _sut = new AuthorizationService(_mockApiHttpClient, httpContextAccessor); + } + + [Fact] + public async Task HasPermissionAsync_WhenUserHasPermission_ShouldReturnTrue() + { + // Arrange + _mockApiHttpClient.GetAsync(Arg.Any(), Arg.Any()) + .Returns(new GetAuthorizationResponse(_userId, "Admin", [AuthorizationPermission.CanCreateLibraries])); + + // Act + bool result = await _sut.HasPermissionAsync(AuthorizationPermission.CanCreateLibraries, CancellationToken.None); + + // Assert + Assert.True(result); + } + + [Fact] + public async Task HasPermissionAsync_WhenUserDoesNotHavePermission_ShouldReturnFalse() + { + // Arrange + _mockApiHttpClient.GetAsync(Arg.Any(), Arg.Any()) + .Returns(new GetAuthorizationResponse(_userId, "Admin", [AuthorizationPermission.CanViewUsers])); + + // Act + bool result = await _sut.HasPermissionAsync(AuthorizationPermission.CanCreateLibraries, CancellationToken.None); + + // Assert + Assert.False(result); + } + + [Fact] + public async Task IsInRoleAsync_WhenRoleMatches_ShouldReturnTrue() + { + // Arrange + _mockApiHttpClient.GetAsync(Arg.Any(), Arg.Any()) + .Returns(new GetAuthorizationResponse(_userId, "Admin", [])); + + // Act + bool result = await _sut.IsInRoleAsync("Admin", CancellationToken.None); + + // Assert + Assert.True(result); + } + + [Fact] + public async Task IsInRoleAsync_WhenRoleDoesNotMatch_ShouldReturnFalse() + { + // Arrange + _mockApiHttpClient.GetAsync(Arg.Any(), Arg.Any()) + .Returns(new GetAuthorizationResponse(_userId, "User", [])); + + // Act + bool result = await _sut.IsInRoleAsync("Admin", CancellationToken.None); + + // Assert + Assert.False(result); + } + + [Fact] + public async Task HasPermissionAsync_WhenCalled_ShouldRequestAuthorizationForCurrentUser() + { + // Arrange + _mockApiHttpClient.GetAsync(Arg.Any(), Arg.Any()) + .Returns(new GetAuthorizationResponse(_userId, "Admin", [])); + + // Act + await _sut.HasPermissionAsync(AuthorizationPermission.CanViewUsers, CancellationToken.None); + + // Assert + await _mockApiHttpClient.Received(1).GetAsync( + Arg.Is(endpoint => endpoint.StartsWith($"auth/get-authorization?userId={_userId}", StringComparison.OrdinalIgnoreCase)), + Arg.Any()); + } +} diff --git a/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Common/Localization/CoreHtmlLocalizerFactoryTests.cs b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Common/Localization/CoreHtmlLocalizerFactoryTests.cs new file mode 100644 index 00000000..017b060e --- /dev/null +++ b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Common/Localization/CoreHtmlLocalizerFactoryTests.cs @@ -0,0 +1,74 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Common.Localization; +using Microsoft.AspNetCore.Mvc.Localization; +using Microsoft.Extensions.Localization; +using NSubstitute; +using System; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Presentation.Web.UnitTests.Common.Localization; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class CoreHtmlLocalizerFactoryTests +{ + private readonly IStringLocalizerFactory _mockStringLocalizerFactory; + private readonly CoreHtmlLocalizerFactory _sut; + + /// + /// Initializes a new instance of the class. + /// + public CoreHtmlLocalizerFactoryTests() + { + _mockStringLocalizerFactory = Substitute.For(); + _mockStringLocalizerFactory.Create(Arg.Any(), Arg.Any()).Returns(Substitute.For()); + _sut = new CoreHtmlLocalizerFactory(_mockStringLocalizerFactory); + } + + [Fact] + public void Create_WhenBaseNameStartsWithLocationCorePrefix_ShouldStripCoreSegment() + { + // Act + IHtmlLocalizer localizer = _sut.Create("Lumina.Presentation.Web.Core.Views.Auth.Login", "Lumina.Presentation.Web"); + + // Assert + Assert.NotNull(localizer); + _mockStringLocalizerFactory.Received(1).Create("Lumina.Presentation.Web.Views.Auth.Login", "Lumina.Presentation.Web"); + } + + [Fact] + public void Create_WhenBaseNameDoesNotStartWithLocationCorePrefix_ShouldKeepBaseNameUnchanged() + { + // Act + IHtmlLocalizer localizer = _sut.Create("Lumina.Presentation.Web.Views.Shared.Layout", "Lumina.Presentation.Web"); + + // Assert + Assert.NotNull(localizer); + _mockStringLocalizerFactory.Received(1).Create("Lumina.Presentation.Web.Views.Shared.Layout", "Lumina.Presentation.Web"); + } + + [Fact] + public void Create_WhenResourceSourceTypeProvided_ShouldCreateLocalizerForType() + { + // Arrange + _mockStringLocalizerFactory.Create(Arg.Any()).Returns(Substitute.For()); + + // Act + IHtmlLocalizer localizer = _sut.Create(typeof(TestLocalizationResource)); + + // Assert + Assert.NotNull(localizer); + _mockStringLocalizerFactory.Received(1).Create(typeof(TestLocalizationResource)); + } + + /// + /// Marker type used for the resource source based localizer creation test. + /// + [ExcludeFromCodeCoverage] + private sealed class TestLocalizationResource + { + } +} diff --git a/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Common/Security/CryptographyServiceTests.cs b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Common/Security/CryptographyServiceTests.cs new file mode 100644 index 00000000..6929a5f3 --- /dev/null +++ b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Common/Security/CryptographyServiceTests.cs @@ -0,0 +1,88 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Common.DTO.Configuration; +using Lumina.Presentation.Web.Common.Security; +using Microsoft.Extensions.Options; +using System; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Presentation.Web.UnitTests.Common.Security; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class CryptographyServiceTests +{ + private const string TEST_ENCRYPTION_KEY = "FLYO0QRo6u2VzoFOgNkkEwYNGtqhJ3QGZd7iAHNEJeM="; + private readonly CryptographyService _sut; + + /// + /// Initializes a new instance of the class. + /// + public CryptographyServiceTests() + { + EncryptionSettingsDto settings = new() { SecretKey = TEST_ENCRYPTION_KEY }; + _sut = new CryptographyService(Options.Create(settings)); + } + + [Fact] + public void Encrypt_WhenCalled_ShouldReturnCiphertextThatDecryptsToPlaintext() + { + // Arrange + const string plaintext = "sensitive-data"; + + // Act + string ciphertext = _sut.Encrypt(plaintext); + + // Assert + Assert.NotEqual(plaintext, ciphertext); + Assert.Equal(plaintext, _sut.Decrypt(ciphertext)); + } + + [Fact] + public void Encrypt_WhenCalledTwice_ShouldReturnDifferentCiphertexts() + { + // Arrange + const string plaintext = "sensitive-data"; + + // Act + string firstCiphertext = _sut.Encrypt(plaintext); + string secondCiphertext = _sut.Encrypt(plaintext); + + // Assert + Assert.NotEqual(firstCiphertext, secondCiphertext); + } + + [Theory] + [InlineData(null)] + [InlineData("")] + public void Encrypt_WhenPlaintextIsNullOrEmpty_ShouldThrowArgumentException(string? plaintext) + { + // Act + ArgumentException exception = Assert.Throws(() => _sut.Encrypt(plaintext!)); + + // Assert + Assert.Equal("plaintext", exception.ParamName); + } + + [Fact] + public void Decrypt_WhenCiphertextIsNotValidBase64_ShouldThrowFormatException() + { + // Act + FormatException exception = Assert.Throws(() => _sut.Decrypt("not-valid-base64!!!")); + + // Assert + Assert.Contains("Base-64", exception.Message); + } + + [Fact] + public void Decrypt_WhenCiphertextIsTooShort_ShouldThrowArgumentException() + { + // Act + ArgumentException exception = Assert.Throws(() => _sut.Decrypt(Convert.ToBase64String([1, 2, 3]))); + + // Assert + Assert.Equal("Invalid ciphertext", exception.Message); + } +} diff --git a/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Common/Services/ScriptIdentifierHelperTests.cs b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Common/Services/ScriptIdentifierHelperTests.cs new file mode 100644 index 00000000..7c2cf6a6 --- /dev/null +++ b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Common/Services/ScriptIdentifierHelperTests.cs @@ -0,0 +1,49 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Common.Services; +using System; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Presentation.Web.UnitTests.Common.Services; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class ScriptIdentifierHelperTests +{ + [Fact] + public void GenerateScriptId_WhenCalled_ShouldReturnScriptPrefixedIdentifier() + { + // Act + string scriptId = ScriptIdentifierHelper.GenerateScriptId(); + + // Assert + Assert.StartsWith("script_", scriptId); + Assert.True(Guid.TryParse(scriptId.AsSpan("script_".Length), out _)); + } + + [Fact] + public void GenerateScriptId_WhenCalledTwice_ShouldReturnDistinctIdentifiers() + { + // Act + string firstScriptId = ScriptIdentifierHelper.GenerateScriptId(); + string secondScriptId = ScriptIdentifierHelper.GenerateScriptId(); + + // Assert + Assert.NotEqual(firstScriptId, secondScriptId); + } + + [Fact] + public void ClearIdentifier_WhenCalledWithGeneratedIdentifier_ShouldNotThrow() + { + // Arrange + string scriptId = ScriptIdentifierHelper.GenerateScriptId(); + + // Act + ScriptIdentifierHelper.ClearIdentifier(scriptId); + + // Assert + Assert.NotNull(scriptId); + } +} diff --git a/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Common/Services/UrlServiceTests.cs b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Common/Services/UrlServiceTests.cs new file mode 100644 index 00000000..868dbfc5 --- /dev/null +++ b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Common/Services/UrlServiceTests.cs @@ -0,0 +1,119 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Common.Routes; +using Lumina.Presentation.Web.Common.Services; +using Microsoft.AspNetCore.Http; +using NSubstitute; +using System; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Presentation.Web.UnitTests.Common.Services; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class UrlServiceTests +{ + private readonly IHttpContextAccessor _mockHttpContextAccessor; + private readonly UrlService _sut; + + /// + /// Initializes a new instance of the class. + /// + public UrlServiceTests() + { + _mockHttpContextAccessor = Substitute.For(); + _sut = new UrlService(_mockHttpContextAccessor); + } + + [Fact] + public void GetAbsoluteUrl_WhenRouteTemplateIsNotDefined_ShouldThrowArgumentException() + { + // Act + ArgumentException exception = Assert.Throws(() => _sut.GetAbsoluteUrl("/not-a-real-route")); + + // Assert + Assert.Contains("not defined in the WebRoutes constants", exception.Message); + } + + [Fact] + public void GetAbsoluteUrl_WhenHttpContextIsNull_ShouldReturnNull() + { + // Arrange + _mockHttpContextAccessor.HttpContext.Returns((HttpContext?)null); + + // Act + string? url = _sut.GetAbsoluteUrl(WebRoutes.Authentication.LOGIN); + + // Assert + Assert.Null(url); + } + + [Fact] + public void GetAbsoluteUrl_WhenCalled_ShouldReplaceCulturePlaceholderAndBuildAbsoluteUrl() + { + // Arrange + DefaultHttpContext httpContext = CreateHttpContext(culture: "en-us", pathBase: "", host: "localhost:5012", scheme: "http"); + _mockHttpContextAccessor.HttpContext.Returns(httpContext); + + // Act + string? url = _sut.GetAbsoluteUrl(WebRoutes.Authentication.LOGIN); + + // Assert + Assert.Equal("http://localhost:5012/en-us/auth/api-login", url); + } + + [Fact] + public void GetAbsoluteUrl_WhenCalledWithAdditionalRouteValues_ShouldReplacePlaceholders() + { + // Arrange + DefaultHttpContext httpContext = CreateHttpContext(culture: "en-us", pathBase: "", host: "localhost:5012", scheme: "http"); + _mockHttpContextAccessor.HttpContext.Returns(httpContext); + Guid id = Guid.NewGuid(); + + // Act + string? url = _sut.GetAbsoluteUrl(WebRoutes.LibraryManagement.DELETE_LIBRARY, new { id }); + + // Assert + Assert.Equal($"http://localhost:5012/en-us/libraries/manage/api-item/{id}", url); + } + + [Fact] + public void GetAbsoluteUrl_WhenPathBaseIsPresent_ShouldIncludePathBase() + { + // Arrange + DefaultHttpContext httpContext = CreateHttpContext(culture: "de-de", pathBase: "/lumina", host: "localhost:5012", scheme: "https"); + _mockHttpContextAccessor.HttpContext.Returns(httpContext); + + // Act + string? url = _sut.GetAbsoluteUrl(WebRoutes.Authentication.REGISTER_VIEW); + + // Assert + Assert.Equal("https://localhost:5012/lumina/de-de/auth/register", url); + } + + [Fact] + public void GetAbsoluteUrl_WhenRouteTemplateDoesNotStartWithSlash_ShouldPrependSlash() + { + // Arrange + DefaultHttpContext httpContext = CreateHttpContext(culture: "en-us", pathBase: "", host: "localhost:5012", scheme: "http"); + _mockHttpContextAccessor.HttpContext.Returns(httpContext); + + // Act + string? url = _sut.GetAbsoluteUrl(WebRoutes.FileSystem.GET_TYPE); + + // Assert + Assert.Equal("http://localhost:5012/file-system/api-get-type", url); + } + + private static DefaultHttpContext CreateHttpContext(string culture, string pathBase, string host, string scheme) + { + DefaultHttpContext httpContext = new(); + httpContext.Request.RouteValues["culture"] = culture; + httpContext.Request.PathBase = pathBase; + httpContext.Request.Host = new HostString(host); + httpContext.Request.Scheme = scheme; + return httpContext; + } +} diff --git a/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Common/Validators/EncryptionSettingsModelValidatorTests.cs b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Common/Validators/EncryptionSettingsModelValidatorTests.cs new file mode 100644 index 00000000..7f4999ac --- /dev/null +++ b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Common/Validators/EncryptionSettingsModelValidatorTests.cs @@ -0,0 +1,60 @@ +#region ========================================================================= USING ===================================================================================== +using FluentValidation; +using FluentValidation.Results; +using Lumina.Presentation.Web.Common.DTO.Configuration; +using Lumina.Presentation.Web.Common.Validators; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Presentation.Web.UnitTests.Common.Validators; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class EncryptionSettingsModelValidatorTests +{ + private const string VALID_BASE64_KEY = "FLYO0QRo6u2VzoFOgNkkEwYNGtqhJ3QGZd7iAHNEJeM="; + private readonly EncryptionSettingsModelValidator _validator = new(); + + [Fact] + public void Validate_WhenSecretKeyIsEmpty_ShouldHaveValidationError() + { + // Arrange + EncryptionSettingsDto settings = new() { SecretKey = string.Empty }; + + // Act + ValidationResult result = _validator.Validate(settings); + + // Assert + Assert.False(result.IsValid); + Assert.Contains(result.Errors, error => error.PropertyName == nameof(EncryptionSettingsDto.SecretKey) && error.ErrorMessage == "Encryption secret key cannot be empty!"); + } + + [Fact] + public void Validate_WhenSecretKeyIsNotBase64_ShouldHaveValidationError() + { + // Arrange + EncryptionSettingsDto settings = new() { SecretKey = "not-base64-key!" }; + + // Act + ValidationResult result = _validator.Validate(settings); + + // Assert + Assert.False(result.IsValid); + Assert.Contains(result.Errors, error => error.PropertyName == nameof(EncryptionSettingsDto.SecretKey) && error.ErrorMessage == "Encryption secret key must be a base64 string!"); + } + + [Fact] + public void Validate_WhenSecretKeyIsValidBase64_ShouldNotHaveValidationError() + { + // Arrange + EncryptionSettingsDto settings = new() { SecretKey = VALID_BASE64_KEY }; + + // Act + ValidationResult result = _validator.Validate(settings); + + // Assert + Assert.True(result.IsValid); + } +} diff --git a/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Common/Validators/ServerConfigurationModelValidatorTests.cs b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Common/Validators/ServerConfigurationModelValidatorTests.cs new file mode 100644 index 00000000..a4509ebf --- /dev/null +++ b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Common/Validators/ServerConfigurationModelValidatorTests.cs @@ -0,0 +1,75 @@ +#region ========================================================================= USING ===================================================================================== +using FluentValidation; +using FluentValidation.Results; +using Lumina.Presentation.Web.Common.DTO.Configuration; +using Lumina.Presentation.Web.Common.Validators; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Presentation.Web.UnitTests.Common.Validators; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class ServerConfigurationModelValidatorTests +{ + private readonly ServerConfigurationModelValidator _validator = new(); + + [Fact] + public void Validate_WhenBaseAddressIsEmpty_ShouldHaveValidationError() + { + // Arrange + ServerConfigurationDto configuration = new() { ApiVersion = '1', BaseAddress = string.Empty, Port = 5214 }; + + // Act + ValidationResult result = _validator.Validate(configuration); + + // Assert + Assert.False(result.IsValid); + Assert.Contains(result.Errors, error => error.PropertyName == nameof(ServerConfigurationDto.BaseAddress) && error.ErrorMessage == "Base address cannot be empty!"); + } + + [Theory] + [InlineData((ushort)0)] // minimum allowed value + [InlineData((ushort)65535)] // maximum allowed value + public void Validate_WhenPortIsAtBoundary_ShouldNotHaveValidationError(ushort port) + { + // Arrange + ServerConfigurationDto configuration = new() { ApiVersion = '1', BaseAddress = "http://localhost", Port = port }; + + // Act + ValidationResult result = _validator.Validate(configuration); + + // Assert + Assert.True(result.IsValid); + } + + [Theory] + [InlineData((char)0)] // minimum allowed API version + [InlineData((char)255)] // maximum allowed API version + public void Validate_WhenApiVersionIsAtBoundary_ShouldNotHaveValidationError(char apiVersion) + { + // Arrange + ServerConfigurationDto configuration = new() { ApiVersion = apiVersion, BaseAddress = "http://localhost", Port = 5214 }; + + // Act + ValidationResult result = _validator.Validate(configuration); + + // Assert + Assert.True(result.IsValid); + } + + [Fact] + public void Validate_WhenConfigurationIsValid_ShouldNotHaveValidationError() + { + // Arrange + ServerConfigurationDto configuration = new() { ApiVersion = '1', BaseAddress = "http://localhost", Port = 5214 }; + + // Act + ValidationResult result = _validator.Validate(configuration); + + // Assert + Assert.True(result.IsValid); + } +} diff --git a/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Admin/Authorization/Roles/AddRole/AddRoleEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Admin/Authorization/Roles/AddRole/AddRoleEndpointTests.cs new file mode 100644 index 00000000..b3ac71bf --- /dev/null +++ b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Admin/Authorization/Roles/AddRole/AddRoleEndpointTests.cs @@ -0,0 +1,63 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Presentation.Web.Common.Api; +using Lumina.Presentation.Web.Common.DTO.Authorization; +using Lumina.Presentation.Web.Common.Enums.Authorization; +using Lumina.Presentation.Web.Common.Requests.Authorization; +using Lumina.Presentation.Web.Common.Routes; +using Lumina.Presentation.Web.Core.Endpoints.Admin.Authorization.Roles.AddRole; +using Lumina.Presentation.Web.Fixtures.Common.Requests.Authorization; +using Lumina.Presentation.Web.Fixtures.Common.TestHelpers; +using Microsoft.AspNetCore.Http; +using NSubstitute; +using System; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +using System.Text.Json; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.UnitTests.Core.Endpoints.Admin.Authorization.Roles.AddRole; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class AddRoleEndpointTests +{ + private readonly IApiHttpClient _mockApiHttpClient; + private readonly AddRoleEndpoint _sut; + private readonly AddRoleRequestFixture _addRoleRequestFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + public AddRoleEndpointTests() + { + _mockApiHttpClient = Substitute.For(); + _sut = Factory.Create(_mockApiHttpClient); + } + + [Fact] + public async Task ExecuteAsync_WhenCalled_ShouldCreateRoleViaApiAndReturnSuccess() + { + // Arrange + AddRoleRequest request = _addRoleRequestFixture.Create(); + RolePermissionsDto expectedResponse = new(new RoleDto(Guid.NewGuid(), request.RoleName!), [new PermissionDto(Guid.NewGuid(), AuthorizationPermission.CanViewUsers)]); + _mockApiHttpClient.PostAsync(Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(expectedResponse); + + // Act + IResult result = await _sut.ExecuteAsync(request, CancellationToken.None); + string body = await JsonResultTestHelper.GetResponseBodyAsync(result); + + // Assert + await _mockApiHttpClient.Received(1).PostAsync( + ApiRoutes.Roles.CREATE_ROLE, + Arg.Is(role => role.RoleName == request.RoleName && role.Permissions!.SequenceEqual(request.Permissions!)), + Arg.Any()); + using JsonDocument jsonDocument = JsonDocument.Parse(body); + Assert.True(jsonDocument.RootElement.GetProperty("success").GetBoolean()); + } +} diff --git a/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Admin/Authorization/Roles/DeleteRole/DeleteRoleEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Admin/Authorization/Roles/DeleteRole/DeleteRoleEndpointTests.cs new file mode 100644 index 00000000..5a9cc33b --- /dev/null +++ b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Admin/Authorization/Roles/DeleteRole/DeleteRoleEndpointTests.cs @@ -0,0 +1,54 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Presentation.Web.Common.Api; +using Lumina.Presentation.Web.Common.Requests.Authorization; +using Lumina.Presentation.Web.Common.Routes; +using Lumina.Presentation.Web.Core.Endpoints.Admin.Authorization.Roles.DeleteRole; +using Lumina.Presentation.Web.Fixtures.Common.Requests.Authorization; +using Lumina.Presentation.Web.Fixtures.Common.TestHelpers; +using Microsoft.AspNetCore.Http; +using NSubstitute; +using System.Diagnostics.CodeAnalysis; +using System.Text.Json; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.UnitTests.Core.Endpoints.Admin.Authorization.Roles.DeleteRole; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class DeleteRoleEndpointTests +{ + private readonly IApiHttpClient _mockApiHttpClient; + private readonly DeleteRoleEndpoint _sut; + private readonly DeleteRoleRequestFixture _deleteRoleRequestFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + public DeleteRoleEndpointTests() + { + _mockApiHttpClient = Substitute.For(); + _sut = Factory.Create(_mockApiHttpClient); + } + + [Fact] + public async Task ExecuteAsync_WhenCalled_ShouldDeleteRoleViaApiAndReturnSuccess() + { + // Arrange + DeleteRoleRequest request = _deleteRoleRequestFixture.Create(); + + // Act + IResult result = await _sut.ExecuteAsync(request, CancellationToken.None); + string body = await JsonResultTestHelper.GetResponseBodyAsync(result); + + // Assert + string expectedEndpoint = ApiRoutes.Roles.DELETE_ROLE.Replace("{roleId}", request.RoleId.ToString()); + await _mockApiHttpClient.Received(1).DeleteAsync(expectedEndpoint, Arg.Any()); + using JsonDocument jsonDocument = JsonDocument.Parse(body); + Assert.True(jsonDocument.RootElement.GetProperty("success").GetBoolean()); + } +} diff --git a/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Admin/Authorization/Roles/GetRoles/GetRolesEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Admin/Authorization/Roles/GetRoles/GetRolesEndpointTests.cs new file mode 100644 index 00000000..dbd0a3ce --- /dev/null +++ b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Admin/Authorization/Roles/GetRoles/GetRolesEndpointTests.cs @@ -0,0 +1,76 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Presentation.Web.Common.Api; +using Lumina.Presentation.Web.Common.DTO.Authorization; +using Lumina.Presentation.Web.Common.Routes; +using Lumina.Presentation.Web.Core.Endpoints.Admin.Authorization.Roles.GetRoles; +using Lumina.Presentation.Web.Fixtures.Common.DTO.Authorization; +using Lumina.Presentation.Web.Fixtures.Common.TestHelpers; +using Microsoft.AspNetCore.Http; +using NSubstitute; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +using System.Text.Json; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.UnitTests.Core.Endpoints.Admin.Authorization.Roles.GetRoles; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class GetRolesEndpointTests +{ + private readonly IApiHttpClient _mockApiHttpClient; + private readonly GetRolesEndpoint _sut; + private readonly RoleDtoFixture _roleDtoFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + public GetRolesEndpointTests() + { + _mockApiHttpClient = Substitute.For(); + _sut = Factory.Create(_mockApiHttpClient); + } + + [Fact] + public async Task ExecuteAsync_WhenApiReturnsRoles_ShouldReturnSuccessJsonWithRoles() + { + // Arrange + RoleDto[] expectedRoles = [.. _roleDtoFixture.CreateMany(2)]; + _mockApiHttpClient.GetAsync(ApiRoutes.Roles.GET_ROLES, Arg.Any()) + .Returns(expectedRoles); + + // Act + IResult result = await _sut.ExecuteAsync(EmptyRequest.Instance, CancellationToken.None); + string body = await JsonResultTestHelper.GetResponseBodyAsync(result); + + // Assert + using JsonDocument jsonDocument = JsonDocument.Parse(body); + Assert.True(jsonDocument.RootElement.GetProperty("success").GetBoolean()); + RoleDto[]? returnedRoles = jsonDocument.RootElement.GetProperty("data").Deserialize(CreateCaseInsensitiveOptions()); + Assert.Equal(expectedRoles.Select(role => role.RoleName), returnedRoles!.Select(role => role.RoleName)); + } + + private static JsonSerializerOptions CreateCaseInsensitiveOptions() + { + return new JsonSerializerOptions { PropertyNameCaseInsensitive = true }; + } + + [Fact] + public async Task ExecuteAsync_WhenCalled_ShouldRequestRolesFromApi() + { + // Arrange + _mockApiHttpClient.GetAsync(ApiRoutes.Roles.GET_ROLES, Arg.Any()) + .Returns([.. _roleDtoFixture.CreateMany(2)]); + + // Act + await _sut.ExecuteAsync(EmptyRequest.Instance, CancellationToken.None); + + // Assert + await _mockApiHttpClient.Received(1).GetAsync(ApiRoutes.Roles.GET_ROLES, Arg.Any()); + } +} diff --git a/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Common/BaseEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Common/BaseEndpointTests.cs new file mode 100644 index 00000000..fda3034e --- /dev/null +++ b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Common/BaseEndpointTests.cs @@ -0,0 +1,109 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Presentation.Web.Common.Http; +using Lumina.Presentation.Web.Fixtures.Common.TestHelpers; +using Lumina.Presentation.Web.Fixtures.Core.Endpoints.Common; +using Microsoft.AspNetCore.Http; +using NSubstitute; +using System.Text.Json; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.UnitTests.Core.Endpoints.Common; + +/// +/// Contains unit tests for the class. +/// +public class BaseEndpointTests +{ + private readonly BaseEndpointFixture _sut; + + /// + /// Initializes a new instance of the class. + /// + public BaseEndpointTests() + { + _sut = Factory.Create(); + } + + [Fact] + public async Task TestJsonSuccess_WhenCalledWithData_ShouldReturnSuccessJsonEnvelopeWithData() + { + // Act + IResult result = _sut.TestJsonSuccess(new { itemId = "test-id" }); + string body = await JsonResultTestHelper.GetResponseBodyAsync(result); + + // Assert + using JsonDocument jsonDocument = JsonDocument.Parse(body); + Assert.True(jsonDocument.RootElement.GetProperty("success").GetBoolean()); + Assert.Equal("test-id", jsonDocument.RootElement.GetProperty("data").GetProperty("itemId").GetString()); + } + + [Fact] + public async Task TestJsonSuccess_WhenCalledWithoutData_ShouldReturnSuccessJsonEnvelope() + { + // Act + IResult result = _sut.TestJsonSuccess(); + string body = await JsonResultTestHelper.GetResponseBodyAsync(result); + + // Assert + using JsonDocument jsonDocument = JsonDocument.Parse(body); + Assert.True(jsonDocument.RootElement.GetProperty("success").GetBoolean()); + Assert.False(jsonDocument.RootElement.TryGetProperty("data", out _)); + } + + [Fact] + public void TestView_WhenCalled_ShouldReturnRazorViewResult() + { + // Arrange + TestHttpContextFactory.ConfigureSession(_sut.HttpContext, TestHttpContextFactory.CreateSession()); + _sut.HttpContext.Request.Path = "/en-us/home"; + + // Act + IResult result = _sut.TestView("/Core/Views/Home/Index.cshtml"); + + // Assert + Assert.IsType(result); + } + + [Fact] + public void TestView_WhenCalled_ShouldStoreLastDisplayedViewInSession() + { + // Arrange + Microsoft.AspNetCore.Http.ISession session = TestHttpContextFactory.CreateSession(); + TestHttpContextFactory.ConfigureSession(_sut.HttpContext, session); + _sut.HttpContext.Request.Path = "/en-us/libraries/manage"; + + // Act + _sut.TestView("/Core/Views/Library/Management/Index.cshtml"); + + // Assert + session.Received(1).Set(HttpContextItemKeys.LAST_DISPLAYED_VIEW, Arg.Any()); + } + + [Fact] + public void TestCulture_WhenCultureRouteValuePresent_ShouldReturnCulture() + { + // Arrange + TestHttpContextFactory.ConfigureCulture(_sut.HttpContext, "de-DE"); + + // Act + string culture = _sut.TestCulture; + + // Assert + Assert.Equal("de-DE", culture); + } + + [Fact] + public void TestCulture_WhenCultureRouteValueMissing_ShouldReturnDefaultCulture() + { + // Arrange + TestHttpContextFactory.ConfigureCulture(_sut.HttpContext, null); + + // Act + string culture = _sut.TestCulture; + + // Assert + Assert.Equal("en-US", culture); + } +} diff --git a/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/FileSystemManagement/Directories/GetDirectories/GetDirectoriesEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/FileSystemManagement/Directories/GetDirectories/GetDirectoriesEndpointTests.cs new file mode 100644 index 00000000..94b232f8 --- /dev/null +++ b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/FileSystemManagement/Directories/GetDirectories/GetDirectoriesEndpointTests.cs @@ -0,0 +1,76 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Presentation.Web.Common.Api; +using Lumina.Presentation.Web.Common.DTO.FileSystemManagement; +using Lumina.Presentation.Web.Common.Requests.FileSystemManagement.Directories; +using Lumina.Presentation.Web.Common.Routes; +using Lumina.Presentation.Web.Core.Endpoints.FileSystemManagement.Directories.GetDirectories; +using Lumina.Presentation.Web.Fixtures.Common.Requests.FileSystemManagement.Directories; +using Lumina.Presentation.Web.Fixtures.Common.TestHelpers; +using Microsoft.AspNetCore.Http; +using NSubstitute; +using System; +using System.Diagnostics.CodeAnalysis; +using System.Text.Json; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.UnitTests.Core.Endpoints.FileSystemManagement.Directories.GetDirectories; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class GetDirectoriesEndpointTests +{ + private readonly IApiHttpClient _mockApiHttpClient; + private readonly GetDirectoriesEndpoint _sut; + private readonly GetDirectoriesRequestFixture _getDirectoriesRequestFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + public GetDirectoriesEndpointTests() + { + _mockApiHttpClient = Substitute.For(); + _sut = Factory.Create(_mockApiHttpClient); + } + + [Fact] + public async Task ExecuteAsync_WhenApiReturnsDirectories_ShouldReturnSuccessJsonWithDirectories() + { + // Arrange + GetDirectoriesRequest request = _getDirectoriesRequestFixture.Create(path: "/media", includeHiddenElements: true); + DirectoryDto[] expectedDirectories = [new DirectoryDto { Path = "/media/books", Name = "books" }]; + _mockApiHttpClient.GetAsync(Arg.Any(), Arg.Any()) + .Returns(expectedDirectories); + + // Act + IResult result = await _sut.ExecuteAsync(request, CancellationToken.None); + string body = await JsonResultTestHelper.GetResponseBodyAsync(result); + + // Assert + string expectedEndpoint = $"{ApiRoutes.Directories.GET_DIRECTORIES}?path={Uri.EscapeDataString(request.Path!)}&includeHiddenElements=True"; + await _mockApiHttpClient.Received(1).GetAsync(expectedEndpoint, Arg.Any()); + using JsonDocument jsonDocument = JsonDocument.Parse(body); + Assert.True(jsonDocument.RootElement.GetProperty("success").GetBoolean()); + Assert.Equal(1, jsonDocument.RootElement.GetProperty("data").GetArrayLength()); + } + + [Fact] + public async Task ExecuteAsync_WhenCalledWithoutHiddenElements_ShouldRequestWithoutHiddenElementsFlag() + { + // Arrange + GetDirectoriesRequest request = _getDirectoriesRequestFixture.Create(path: "/media", includeHiddenElements: false); + _mockApiHttpClient.GetAsync(Arg.Any(), Arg.Any()) + .Returns([]); + + // Act + await _sut.ExecuteAsync(request, CancellationToken.None); + + // Assert + string expectedEndpoint = $"{ApiRoutes.Directories.GET_DIRECTORIES}?path={Uri.EscapeDataString(request.Path!)}&includeHiddenElements=False"; + await _mockApiHttpClient.Received(1).GetAsync(expectedEndpoint, Arg.Any()); + } +} diff --git a/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/FileSystemManagement/Path/ValidatePath/ValidatePathEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/FileSystemManagement/Path/ValidatePath/ValidatePathEndpointTests.cs new file mode 100644 index 00000000..a9da73d8 --- /dev/null +++ b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/FileSystemManagement/Path/ValidatePath/ValidatePathEndpointTests.cs @@ -0,0 +1,77 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Presentation.Web.Common.Api; +using Lumina.Presentation.Web.Common.DTO.FileSystemManagement; +using Lumina.Presentation.Web.Common.Requests.FileSystemManagement.Path; +using Lumina.Presentation.Web.Common.Routes; +using Lumina.Presentation.Web.Core.Endpoints.FileSystemManagement.Path.ValidatePath; +using Lumina.Presentation.Web.Fixtures.Common.Requests.FileSystemManagement.Path; +using Lumina.Presentation.Web.Fixtures.Common.TestHelpers; +using Microsoft.AspNetCore.Http; +using NSubstitute; +using System; +using System.Diagnostics.CodeAnalysis; +using System.Text.Json; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.UnitTests.Core.Endpoints.FileSystemManagement.Path.ValidatePath; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class ValidatePathEndpointTests +{ + private readonly IApiHttpClient _mockApiHttpClient; + private readonly ValidatePathEndpoint _sut; + private readonly ValidatePathRequestFixture _validatePathRequestFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + public ValidatePathEndpointTests() + { + _mockApiHttpClient = Substitute.For(); + _sut = Factory.Create(_mockApiHttpClient); + } + + [Fact] + public async Task ExecuteAsync_WhenApiValidatesPath_ShouldReturnSuccessJsonWithIsValid() + { + // Arrange + ValidatePathRequest request = _validatePathRequestFixture.Create(path: "/media/books"); + _mockApiHttpClient.GetAsync(Arg.Any(), Arg.Any()) + .Returns(new PathValidDto(true)); + + // Act + IResult result = await _sut.ExecuteAsync(request, CancellationToken.None); + string body = await JsonResultTestHelper.GetResponseBodyAsync(result); + + // Assert + string expectedEndpoint = $"{ApiRoutes.Path.VALIDATE}?path={Uri.EscapeDataString(request.Path!)}"; + await _mockApiHttpClient.Received(1).GetAsync(expectedEndpoint, Arg.Any()); + using JsonDocument jsonDocument = JsonDocument.Parse(body); + Assert.True(jsonDocument.RootElement.GetProperty("success").GetBoolean()); + Assert.True(jsonDocument.RootElement.GetProperty("data").GetProperty("isValid").GetBoolean()); + } + + [Fact] + public async Task ExecuteAsync_WhenPathIsInvalid_ShouldReturnSuccessJsonWithIsValidFalse() + { + // Arrange + ValidatePathRequest request = _validatePathRequestFixture.Create(path: "C:/invalid|path"); + _mockApiHttpClient.GetAsync(Arg.Any(), Arg.Any()) + .Returns(new PathValidDto(false)); + + // Act + IResult result = await _sut.ExecuteAsync(request, CancellationToken.None); + string body = await JsonResultTestHelper.GetResponseBodyAsync(result); + + // Assert + using JsonDocument jsonDocument = JsonDocument.Parse(body); + Assert.True(jsonDocument.RootElement.GetProperty("success").GetBoolean()); + Assert.False(jsonDocument.RootElement.GetProperty("data").GetProperty("isValid").GetBoolean()); + } +} diff --git a/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Library/Management/DeleteLibrary/DeleteLibraryEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Library/Management/DeleteLibrary/DeleteLibraryEndpointTests.cs new file mode 100644 index 00000000..76bcefb9 --- /dev/null +++ b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Library/Management/DeleteLibrary/DeleteLibraryEndpointTests.cs @@ -0,0 +1,54 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Presentation.Web.Common.Api; +using Lumina.Presentation.Web.Common.Requests.Library.Management; +using Lumina.Presentation.Web.Common.Routes; +using Lumina.Presentation.Web.Core.Endpoints.Library.Management.DeleteLibrary; +using Lumina.Presentation.Web.Fixtures.Common.Requests.Library.Management; +using Lumina.Presentation.Web.Fixtures.Common.TestHelpers; +using Microsoft.AspNetCore.Http; +using NSubstitute; +using System.Diagnostics.CodeAnalysis; +using System.Text.Json; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.UnitTests.Core.Endpoints.Library.Management.DeleteLibrary; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class DeleteLibraryEndpointTests +{ + private readonly IApiHttpClient _mockApiHttpClient; + private readonly DeleteLibraryEndpoint _sut; + private readonly DeleteLibraryRequestFixture _deleteLibraryRequestFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + public DeleteLibraryEndpointTests() + { + _mockApiHttpClient = Substitute.For(); + _sut = Factory.Create(_mockApiHttpClient); + } + + [Fact] + public async Task ExecuteAsync_WhenCalled_ShouldDeleteLibraryViaApiAndReturnSuccess() + { + // Arrange + DeleteLibraryRequest request = _deleteLibraryRequestFixture.Create(); + + // Act + IResult result = await _sut.ExecuteAsync(request, CancellationToken.None); + string body = await JsonResultTestHelper.GetResponseBodyAsync(result); + + // Assert + string expectedEndpoint = ApiRoutes.Libraries.DELETE_LIBRARY.Replace("{id}", request.Id.ToString()); + await _mockApiHttpClient.Received(1).DeleteAsync(expectedEndpoint, Arg.Any()); + using JsonDocument jsonDocument = JsonDocument.Parse(body); + Assert.True(jsonDocument.RootElement.GetProperty("success").GetBoolean()); + } +} diff --git a/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Library/Management/GetLibraries/GetLibrariesEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Library/Management/GetLibraries/GetLibrariesEndpointTests.cs new file mode 100644 index 00000000..14d32401 --- /dev/null +++ b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Library/Management/GetLibraries/GetLibrariesEndpointTests.cs @@ -0,0 +1,71 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Presentation.Web.Common.Api; +using Lumina.Presentation.Web.Common.DTO.Libraries; +using Lumina.Presentation.Web.Common.Routes; +using Lumina.Presentation.Web.Core.Endpoints.Library.Management.GetLibraries; +using Lumina.Presentation.Web.Fixtures.Common.DTO.Libraries; +using Lumina.Presentation.Web.Fixtures.Common.TestHelpers; +using Microsoft.AspNetCore.Http; +using NSubstitute; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +using System.Text.Json; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.UnitTests.Core.Endpoints.Library.Management.GetLibraries; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class GetLibrariesEndpointTests +{ + private readonly IApiHttpClient _mockApiHttpClient; + private readonly GetLibrariesEndpoint _sut; + private readonly LibraryDtoFixture _libraryDtoFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + public GetLibrariesEndpointTests() + { + _mockApiHttpClient = Substitute.For(); + _sut = Factory.Create(_mockApiHttpClient); + } + + [Fact] + public async Task ExecuteAsync_WhenApiReturnsLibraries_ShouldReturnSuccessJsonWithLibraries() + { + // Arrange + LibraryDto[] expectedLibraries = [.. _libraryDtoFixture.CreateMany(2)]; + _mockApiHttpClient.GetAsync(ApiRoutes.Libraries.GET_LIBRARIES, Arg.Any()) + .Returns(expectedLibraries); + + // Act + IResult result = await _sut.ExecuteAsync(EmptyRequest.Instance, CancellationToken.None); + string body = await JsonResultTestHelper.GetResponseBodyAsync(result); + + // Assert + using JsonDocument jsonDocument = JsonDocument.Parse(body); + Assert.True(jsonDocument.RootElement.GetProperty("success").GetBoolean()); + LibraryDto[]? returnedLibraries = jsonDocument.RootElement.GetProperty("data").Deserialize(new JsonSerializerOptions { PropertyNameCaseInsensitive = true }); + Assert.Equal(expectedLibraries.Select(library => library.Title), returnedLibraries!.Select(library => library.Title)); + } + + [Fact] + public async Task ExecuteAsync_WhenCalled_ShouldRequestLibrariesFromApi() + { + // Arrange + _mockApiHttpClient.GetAsync(ApiRoutes.Libraries.GET_LIBRARIES, Arg.Any()) + .Returns([.. _libraryDtoFixture.CreateMany(2)]); + + // Act + await _sut.ExecuteAsync(EmptyRequest.Instance, CancellationToken.None); + + // Assert + await _mockApiHttpClient.Received(1).GetAsync(ApiRoutes.Libraries.GET_LIBRARIES, Arg.Any()); + } +} diff --git a/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Library/Management/SaveLibrary/SaveLibraryEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Library/Management/SaveLibrary/SaveLibraryEndpointTests.cs new file mode 100644 index 00000000..e3f7b830 --- /dev/null +++ b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Library/Management/SaveLibrary/SaveLibraryEndpointTests.cs @@ -0,0 +1,79 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Presentation.Web.Common.Api; +using Lumina.Presentation.Web.Common.DTO.Libraries; +using Lumina.Presentation.Web.Common.Routes; +using Lumina.Presentation.Web.Core.Endpoints.Library.Management.SaveLibrary; +using Lumina.Presentation.Web.Fixtures.Common.DTO.Libraries; +using Lumina.Presentation.Web.Fixtures.Common.TestHelpers; +using Microsoft.AspNetCore.Http; +using NSubstitute; +using System; +using System.Diagnostics.CodeAnalysis; +using System.Text.Json; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.UnitTests.Core.Endpoints.Library.Management.SaveLibrary; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class SaveLibraryEndpointTests +{ + private readonly IApiHttpClient _mockApiHttpClient; + private readonly SaveLibraryEndpoint _sut; + private readonly LibraryDtoFixture _libraryDtoFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + public SaveLibraryEndpointTests() + { + _mockApiHttpClient = Substitute.For(); + _sut = Factory.Create(_mockApiHttpClient); + } + + [Fact] + public async Task ExecuteAsync_WhenRequestHasId_ShouldUpdateLibraryViaApi() + { + // Arrange + LibraryDto request = _libraryDtoFixture.Create(); + LibraryDto expectedResponse = _libraryDtoFixture.Create(id: request.Id); + _mockApiHttpClient.PutAsync(Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(expectedResponse); + + // Act + IResult result = await _sut.ExecuteAsync(request, CancellationToken.None); + string body = await JsonResultTestHelper.GetResponseBodyAsync(result); + + // Assert + string expectedEndpoint = ApiRoutes.Libraries.UPDATE_LIBRARY.Replace("{id}", request.Id!.Value.ToString()); + await _mockApiHttpClient.Received(1).PutAsync(expectedEndpoint, Arg.Is(library => library.Title == request.Title), Arg.Any()); + using JsonDocument jsonDocument = JsonDocument.Parse(body); + Assert.True(jsonDocument.RootElement.GetProperty("success").GetBoolean()); + } + + [Fact] + public async Task ExecuteAsync_WhenRequestHasNoId_ShouldCreateLibraryViaApi() + { + // Arrange + LibraryDto request = _libraryDtoFixture.Create(); + request.Id = null; + LibraryDto expectedResponse = _libraryDtoFixture.Create(id: request.Id); + _mockApiHttpClient.PostAsync(Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(expectedResponse); + + // Act + IResult result = await _sut.ExecuteAsync(request, CancellationToken.None); + string body = await JsonResultTestHelper.GetResponseBodyAsync(result); + + // Assert + await _mockApiHttpClient.Received(1).PostAsync(ApiRoutes.Libraries.ADD_LIBRARY, Arg.Is(library => library.Title == request.Title), Arg.Any()); + await _mockApiHttpClient.DidNotReceive().PutAsync(Arg.Any(), Arg.Any(), Arg.Any()); + using JsonDocument jsonDocument = JsonDocument.Parse(body); + Assert.True(jsonDocument.RootElement.GetProperty("success").GetBoolean()); + } +} diff --git a/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/GetLibraryItems/GetLibraryItemsEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/GetLibraryItems/GetLibraryItemsEndpointTests.cs new file mode 100644 index 00000000..13a5562f --- /dev/null +++ b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/GetLibraryItems/GetLibraryItemsEndpointTests.cs @@ -0,0 +1,124 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Presentation.Web.Common.Api; +using Lumina.Presentation.Web.Common.DTO.Libraries; +using Lumina.Presentation.Web.Common.Enums.Common; +using Lumina.Presentation.Web.Common.Requests.Libraries; +using Lumina.Presentation.Web.Common.Routes; +using Lumina.Presentation.Web.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.Books.GetLibraryItems; +using Lumina.Presentation.Web.Fixtures.Common.Requests.Libraries; +using Lumina.Presentation.Web.Fixtures.Common.TestHelpers; +using Microsoft.AspNetCore.Http; +using NSubstitute; +using System; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +using System.Text.Json; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.UnitTests.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.Books.GetLibraryItems; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class GetLibraryItemsEndpointTests +{ + private readonly IApiHttpClient _mockApiHttpClient; + private readonly GetLibraryItemsEndpoint _sut; + private readonly GetBooksLiteRequestFixture _getBooksLiteRequestFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + public GetLibraryItemsEndpointTests() + { + _mockApiHttpClient = Substitute.For(); + _sut = Factory.Create(_mockApiHttpClient); + } + + [Fact] + public async Task ExecuteAsync_WhenCalled_ShouldRequestLibraryItemsWithQueryParameters() + { + // Arrange + GetBooksLiteRequest request = _getBooksLiteRequestFixture.Create( + currentPage: 2, + perPage: 48, + searchTerm: "the hobbit", + filterAlphaKey: "H", + ignoreThePrefixForAlphaPicker: true, + sortBy: "title", + sortOrder: SortOrder.Ascending); + _mockApiHttpClient.GetAsync(Arg.Any(), Arg.Any()) + .Returns(new PaginatedBookLiteDto()); + + // Act + await _sut.ExecuteAsync(request, CancellationToken.None); + + // Assert + await _mockApiHttpClient.Received(1).GetAsync( + Arg.Is(endpoint => + endpoint.StartsWith(ApiRoutes.Books.GET_BOOKS_LITE, StringComparison.OrdinalIgnoreCase) && + endpoint.Contains($"libraryId={request.LibraryId}") && + endpoint.Contains("currentPage=2") && + endpoint.Contains("perPage=48") && + endpoint.Contains("searchTerm=the%20hobbit") && + endpoint.Contains("filterAlphaKey=H") && + endpoint.Contains("ignoreThePrefixForAlphaPicker=True") && + endpoint.Contains("sortBy=title") && + endpoint.Contains("sortOrder=Ascending")), + Arg.Any()); + } + + [Fact] + public async Task ExecuteAsync_WhenCalledWithOnlyLibraryId_ShouldRequestWithoutOptionalParameters() + { + // Arrange + GetBooksLiteRequest request = _getBooksLiteRequestFixture.Create(); + _mockApiHttpClient.GetAsync(Arg.Any(), Arg.Any()) + .Returns(new PaginatedBookLiteDto()); + + // Act + await _sut.ExecuteAsync(request, CancellationToken.None); + + // Assert + await _mockApiHttpClient.Received(1).GetAsync( + Arg.Is(endpoint => + endpoint.StartsWith(ApiRoutes.Books.GET_BOOKS_LITE, StringComparison.OrdinalIgnoreCase) && + endpoint.EndsWith($"libraryId={request.LibraryId}&ignoreThePrefixForAlphaPicker=False", StringComparison.OrdinalIgnoreCase) && + !endpoint.Contains("currentPage=") && + !endpoint.Contains("searchTerm=") && + !endpoint.Contains("sortBy=")), + Arg.Any()); + } + + [Fact] + public async Task ExecuteAsync_WhenApiReturnsPaginatedItems_ShouldReturnSuccessJsonWithItems() + { + // Arrange + GetBooksLiteRequest request = _getBooksLiteRequestFixture.Create(); + PaginatedBookLiteDto expectedResponse = new() + { + CurrentPage = 1, + PerPage = 48, + Count = 1, + NumberOfPages = 1, + Data = [new BookLiteDto { Id = Guid.NewGuid(), Title = "Test Book" }] + }; + _mockApiHttpClient.GetAsync(Arg.Any(), Arg.Any()) + .Returns(expectedResponse); + + // Act + IResult result = await _sut.ExecuteAsync(request, CancellationToken.None); + string body = await JsonResultTestHelper.GetResponseBodyAsync(result); + + // Assert + using JsonDocument jsonDocument = JsonDocument.Parse(body); + Assert.True(jsonDocument.RootElement.GetProperty("success").GetBoolean()); + JsonElement data = jsonDocument.RootElement.GetProperty("data"); + Assert.Equal(1, data.GetProperty("currentPage").GetInt32()); + Assert.Equal(1, data.GetProperty("data").GetArrayLength()); + } +} diff --git a/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/Index/BooksIndexViewEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/Index/BooksIndexViewEndpointTests.cs new file mode 100644 index 00000000..bc80d5b6 --- /dev/null +++ b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/Index/BooksIndexViewEndpointTests.cs @@ -0,0 +1,77 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Presentation.Web.Common.Api; +using Lumina.Presentation.Web.Common.DTO.Libraries; +using Lumina.Presentation.Web.Common.Http; +using Lumina.Presentation.Web.Common.Requests.Library.WrittenContentLibrary.BookLibrary.Books; +using Lumina.Presentation.Web.Common.Routes; +using Lumina.Presentation.Web.Common.Services; +using Lumina.Presentation.Web.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.Books.Index; +using Lumina.Presentation.Web.Fixtures.Common.DTO.Libraries; +using Lumina.Presentation.Web.Fixtures.Common.TestHelpers; +using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Http.HttpResults; +using NSubstitute; +using System; +using System.Diagnostics.CodeAnalysis; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.UnitTests.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.Books.Index; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class BooksIndexViewEndpointTests +{ + private readonly IApiHttpClient _mockApiHttpClient; + private readonly IUrlService _mockUrlService; + private readonly BooksIndexViewEndpoint _sut; + private readonly LibraryDtoFixture _libraryDtoFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + public BooksIndexViewEndpointTests() + { + _mockApiHttpClient = Substitute.For(); + _mockUrlService = Substitute.For(); + _sut = Factory.Create(_mockApiHttpClient, _mockUrlService); + TestHttpContextFactory.ConfigureSession(_sut.HttpContext, TestHttpContextFactory.CreateSession()); + _sut.HttpContext.Request.Path = "/en-us/library/written-content-library/books-library/books"; + } + + [Fact] + public async Task ExecuteAsync_WhenLibraryIdIsNull_ShouldRedirectToHome() + { + // Arrange + _mockUrlService.GetAbsoluteUrl(WebRoutes.Home.INDEX_CULTURED).Returns("http://localhost/en-us"); + + // Act + IResult result = await _sut.ExecuteAsync(new GetBooksViewRequest(null), CancellationToken.None); + + // Assert + RedirectHttpResult redirectResult = Assert.IsType(result); + Assert.Equal("http://localhost/en-us", redirectResult.Url); + await _mockApiHttpClient.DidNotReceive().GetAsync(Arg.Any(), Arg.Any()); + } + + [Fact] + public async Task ExecuteAsync_WhenLibraryIdProvided_ShouldReturnRazorViewResultWithLibraryModel() + { + // Arrange + LibraryDto expectedLibrary = _libraryDtoFixture.Create(); + _mockApiHttpClient.GetAsync(Arg.Any(), Arg.Any()) + .Returns(expectedLibrary); + + // Act + IResult result = await _sut.ExecuteAsync(new GetBooksViewRequest(expectedLibrary.Id), CancellationToken.None); + + // Assert + Assert.IsType(result); + string expectedEndpoint = ApiRoutes.Libraries.GET_LIBRARY_BY_ID.Replace("{id}", expectedLibrary.Id!.Value.ToString()); + await _mockApiHttpClient.Received(1).GetAsync(expectedEndpoint, Arg.Any()); + } +} diff --git a/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Plugins/GetPlugins/GetPluginsEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Plugins/GetPlugins/GetPluginsEndpointTests.cs new file mode 100644 index 00000000..bb08ee79 --- /dev/null +++ b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Plugins/GetPlugins/GetPluginsEndpointTests.cs @@ -0,0 +1,70 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Presentation.Web.Common.Api; +using Lumina.Presentation.Web.Common.DTO.Plugins; +using Lumina.Presentation.Web.Common.Routes; +using Lumina.Presentation.Web.Core.Endpoints.Plugins.GetPlugins; +using Lumina.Presentation.Web.Fixtures.Common.TestHelpers; +using Microsoft.AspNetCore.Http; +using NSubstitute; +using System; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +using System.Text.Json; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.UnitTests.Core.Endpoints.Plugins.GetPlugins; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class GetPluginsEndpointTests +{ + private readonly IApiHttpClient _mockApiHttpClient; + private readonly GetPluginsEndpoint _sut; + + /// + /// Initializes a new instance of the class. + /// + public GetPluginsEndpointTests() + { + _mockApiHttpClient = Substitute.For(); + _sut = Factory.Create(_mockApiHttpClient); + } + + [Fact] + public async Task ExecuteAsync_WhenApiReturnsPlugins_ShouldReturnSuccessJsonWithPlugins() + { + // Arrange + PluginDto[] expectedPlugins = [new PluginDto { Id = Guid.NewGuid(), Name = "OpenLibrary", Author = "Test Author", Version = "1.0.0" }]; + _mockApiHttpClient.GetAsync(ApiRoutes.Plugins.GET_PLUGINS, Arg.Any()) + .Returns(expectedPlugins); + + // Act + IResult result = await _sut.ExecuteAsync(EmptyRequest.Instance, CancellationToken.None); + string body = await JsonResultTestHelper.GetResponseBodyAsync(result); + + // Assert + using JsonDocument jsonDocument = JsonDocument.Parse(body); + Assert.True(jsonDocument.RootElement.GetProperty("success").GetBoolean()); + PluginDto[]? returnedPlugins = jsonDocument.RootElement.GetProperty("data").Deserialize(new JsonSerializerOptions { PropertyNameCaseInsensitive = true }); + Assert.Equal(expectedPlugins.Select(plugin => plugin.Name), returnedPlugins!.Select(plugin => plugin.Name)); + } + + [Fact] + public async Task ExecuteAsync_WhenCalled_ShouldRequestPluginsFromApi() + { + // Arrange + _mockApiHttpClient.GetAsync(ApiRoutes.Plugins.GET_PLUGINS, Arg.Any()) + .Returns([new PluginDto { Id = Guid.NewGuid(), Name = "OpenLibrary" }]); + + // Act + await _sut.ExecuteAsync(EmptyRequest.Instance, CancellationToken.None); + + // Assert + await _mockApiHttpClient.Received(1).GetAsync(ApiRoutes.Plugins.GET_PLUGINS, Arg.Any()); + } +} diff --git a/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Plugins/UpdatePluginSettings/UpdatePluginSettingsEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Plugins/UpdatePluginSettings/UpdatePluginSettingsEndpointTests.cs new file mode 100644 index 00000000..a2534b6a --- /dev/null +++ b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Plugins/UpdatePluginSettings/UpdatePluginSettingsEndpointTests.cs @@ -0,0 +1,59 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Presentation.Web.Common.Api; +using Lumina.Presentation.Web.Common.Requests.Plugins; +using Lumina.Presentation.Web.Common.Routes; +using Lumina.Presentation.Web.Core.Endpoints.Plugins.UpdatePluginSettings; +using Lumina.Presentation.Web.Fixtures.Common.Requests.Plugins; +using Lumina.Presentation.Web.Fixtures.Common.TestHelpers; +using Microsoft.AspNetCore.Http; +using NSubstitute; +using System.Diagnostics.CodeAnalysis; +using System.Text.Json; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.UnitTests.Core.Endpoints.Plugins.UpdatePluginSettings; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class UpdatePluginSettingsEndpointTests +{ + private readonly IApiHttpClient _mockApiHttpClient; + private readonly UpdatePluginSettingsEndpoint _sut; + private readonly UpdatePluginSettingsRequestFixture _updatePluginSettingsRequestFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + public UpdatePluginSettingsEndpointTests() + { + _mockApiHttpClient = Substitute.For(); + _sut = Factory.Create(_mockApiHttpClient); + } + + [Fact] + public async Task ExecuteAsync_WhenCalled_ShouldUpdatePluginSettingsViaApiAndReturnSuccess() + { + // Arrange + UpdatePluginSettingsRequest request = _updatePluginSettingsRequestFixture.Create(); + _mockApiHttpClient.PutAsync(Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(new Lumina.Presentation.Web.Common.Requests.Common.EmptyRequest()); + + // Act + IResult result = await _sut.ExecuteAsync(request, CancellationToken.None); + string body = await JsonResultTestHelper.GetResponseBodyAsync(result); + + // Assert + string expectedEndpoint = ApiRoutes.Plugins.UPDATE_PLUGIN_SETTINGS.Replace("{pluginId}", request.PluginId.ToString()); + await _mockApiHttpClient.Received(1).PutAsync( + expectedEndpoint, + Arg.Is(settings => settings.PluginId == request.PluginId), + Arg.Any()); + using JsonDocument jsonDocument = JsonDocument.Parse(body); + Assert.True(jsonDocument.RootElement.GetProperty("success").GetBoolean()); + } +} diff --git a/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Tools/Language/SetLanguage/SetLanguageEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Tools/Language/SetLanguage/SetLanguageEndpointTests.cs new file mode 100644 index 00000000..3e72c209 --- /dev/null +++ b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Tools/Language/SetLanguage/SetLanguageEndpointTests.cs @@ -0,0 +1,84 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Presentation.Web.Common.Requests.Tools; +using Lumina.Presentation.Web.Common.Routes; +using Lumina.Presentation.Web.Common.Services; +using Lumina.Presentation.Web.Core.Endpoints.Tools.Language.SetLanguage; +using Lumina.Presentation.Web.Fixtures.Common.TestHelpers; +using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Http.HttpResults; +using Microsoft.AspNetCore.Localization; +using NSubstitute; +using System.Diagnostics.CodeAnalysis; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.UnitTests.Core.Endpoints.Tools.Language.SetLanguage; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class SetLanguageEndpointTests +{ + private readonly IUrlService _mockUrlService; + private readonly SetLanguageEndpoint _sut; + + /// + /// Initializes a new instance of the class. + /// + public SetLanguageEndpointTests() + { + _mockUrlService = Substitute.For(); + _sut = Factory.Create(_mockUrlService); + } + + [Fact] + public async Task ExecuteAsync_WhenCalledWithoutReturnUrl_ShouldSetCultureCookieAndRedirectWithNewCulture() + { + // Arrange + TestHttpContextFactory.ConfigureCulture(_sut.HttpContext, "en-us"); + _mockUrlService.GetAbsoluteUrl(WebRoutes.Home.INDEX_CULTURED).Returns("http://localhost/en-us/"); + + // Act + IResult result = await _sut.ExecuteAsync(new SetLanguageRequest("de-DE", null), CancellationToken.None); + + // Assert + RedirectHttpResult redirectResult = Assert.IsType(result); + Assert.Equal("http://localhost/de-de/", redirectResult.Url); + Assert.True(redirectResult.AcceptLocalUrlOnly); + string setCookieHeader = _sut.HttpContext.Response.Headers.SetCookie.ToString(); + Assert.Contains(CookieRequestCultureProvider.DefaultCookieName, setCookieHeader); + Assert.Contains("de-DE", setCookieHeader); + } + + [Fact] + public async Task ExecuteAsync_WhenReturnUrlProvided_ShouldReplaceCultureInReturnUrl() + { + // Arrange + TestHttpContextFactory.ConfigureCulture(_sut.HttpContext, "en-us"); + + // Act + IResult result = await _sut.ExecuteAsync(new SetLanguageRequest("de-DE", "/en-us/tools/settings"), CancellationToken.None); + + // Assert + RedirectHttpResult redirectResult = Assert.IsType(result); + Assert.Equal("/de-de/tools/settings", redirectResult.Url); + } + + [Fact] + public async Task ExecuteAsync_WhenPathBasePresent_ShouldKeepPathBaseInRedirectUrl() + { + // Arrange + TestHttpContextFactory.ConfigureCulture(_sut.HttpContext, "en-us"); + _sut.HttpContext.Request.PathBase = "/lumina"; + + // Act + IResult result = await _sut.ExecuteAsync(new SetLanguageRequest("fr-FR", "/en-us/tools/settings"), CancellationToken.None); + + // Assert + RedirectHttpResult redirectResult = Assert.IsType(result); + Assert.Equal("/lumina/fr-fr/tools/settings", redirectResult.Url); + } +} diff --git a/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Tools/Settings/GetUserSettings/GetUserSettingsEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Tools/Settings/GetUserSettings/GetUserSettingsEndpointTests.cs new file mode 100644 index 00000000..b55cfc50 --- /dev/null +++ b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Tools/Settings/GetUserSettings/GetUserSettingsEndpointTests.cs @@ -0,0 +1,71 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Presentation.Web.Common.Api; +using Lumina.Presentation.Web.Common.DTO.UsersManagement; +using Lumina.Presentation.Web.Common.Routes; +using Lumina.Presentation.Web.Core.Endpoints.Tools.Settings.GetUserSettings; +using Lumina.Presentation.Web.Fixtures.Common.DTO.UsersManagement; +using Lumina.Presentation.Web.Fixtures.Common.TestHelpers; +using Microsoft.AspNetCore.Http; +using NSubstitute; +using System.Diagnostics.CodeAnalysis; +using System.Text.Json; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.UnitTests.Core.Endpoints.Tools.Settings.GetUserSettings; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class GetUserSettingsEndpointTests +{ + private readonly IApiHttpClient _mockApiHttpClient; + private readonly GetUserSettingsEndpoint _sut; + private readonly UserSettingsDtoFixture _userSettingsDtoFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + public GetUserSettingsEndpointTests() + { + _mockApiHttpClient = Substitute.For(); + _sut = Factory.Create(_mockApiHttpClient); + } + + [Fact] + public async Task ExecuteAsync_WhenApiReturnsSettings_ShouldReturnSuccessJsonWithSettings() + { + // Arrange + UserSettingsDto expectedSettings = _userSettingsDtoFixture.Create(); + _mockApiHttpClient.GetAsync(ApiRoutes.Users.GET_USER_SETTINGS, Arg.Any()) + .Returns(expectedSettings); + + // Act + IResult result = await _sut.ExecuteAsync(EmptyRequest.Instance, CancellationToken.None); + string body = await JsonResultTestHelper.GetResponseBodyAsync(result); + + // Assert + using JsonDocument jsonDocument = JsonDocument.Parse(body); + Assert.True(jsonDocument.RootElement.GetProperty("success").GetBoolean()); + JsonElement data = jsonDocument.RootElement.GetProperty("data"); + Assert.Equal(expectedSettings.ItemsPerPage, data.GetProperty("itemsPerPage").GetInt32()); + Assert.Equal(expectedSettings.IsPaginationEnabled, data.GetProperty("isPaginationEnabled").GetBoolean()); + } + + [Fact] + public async Task ExecuteAsync_WhenCalled_ShouldRequestUserSettingsFromApi() + { + // Arrange + _mockApiHttpClient.GetAsync(ApiRoutes.Users.GET_USER_SETTINGS, Arg.Any()) + .Returns(_userSettingsDtoFixture.Create()); + + // Act + await _sut.ExecuteAsync(EmptyRequest.Instance, CancellationToken.None); + + // Assert + await _mockApiHttpClient.Received(1).GetAsync(ApiRoutes.Users.GET_USER_SETTINGS, Arg.Any()); + } +} diff --git a/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Tools/Settings/UpdateUserSettings/UpdateUserSettingsEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Tools/Settings/UpdateUserSettings/UpdateUserSettingsEndpointTests.cs new file mode 100644 index 00000000..3691a19a --- /dev/null +++ b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Tools/Settings/UpdateUserSettings/UpdateUserSettingsEndpointTests.cs @@ -0,0 +1,59 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Presentation.Web.Common.Api; +using Lumina.Presentation.Web.Common.DTO.UsersManagement; +using Lumina.Presentation.Web.Common.Routes; +using Lumina.Presentation.Web.Core.Endpoints.Tools.Settings.UpdateUserSettings; +using Lumina.Presentation.Web.Fixtures.Common.DTO.UsersManagement; +using Lumina.Presentation.Web.Fixtures.Common.TestHelpers; +using Microsoft.AspNetCore.Http; +using NSubstitute; +using System.Diagnostics.CodeAnalysis; +using System.Text.Json; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.UnitTests.Core.Endpoints.Tools.Settings.UpdateUserSettings; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class UpdateUserSettingsEndpointTests +{ + private readonly IApiHttpClient _mockApiHttpClient; + private readonly UpdateUserSettingsEndpoint _sut; + private readonly UserSettingsDtoFixture _userSettingsDtoFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + public UpdateUserSettingsEndpointTests() + { + _mockApiHttpClient = Substitute.For(); + _sut = Factory.Create(_mockApiHttpClient); + } + + [Fact] + public async Task ExecuteAsync_WhenCalled_ShouldUpdateSettingsViaApiAndReturnSuccess() + { + // Arrange + UserSettingsDto request = _userSettingsDtoFixture.Create(); + _mockApiHttpClient.PutAsync(Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(new Lumina.Presentation.Web.Common.Requests.Common.EmptyRequest()); + + // Act + IResult result = await _sut.ExecuteAsync(request, CancellationToken.None); + string body = await JsonResultTestHelper.GetResponseBodyAsync(result); + + // Assert + await _mockApiHttpClient.Received(1).PutAsync( + ApiRoutes.Users.UPDATE_USER_SETTINGS, + Arg.Is(settings => settings.ItemsPerPage == request.ItemsPerPage && settings.IsPaginationEnabled == request.IsPaginationEnabled), + Arg.Any()); + using JsonDocument jsonDocument = JsonDocument.Parse(body); + Assert.True(jsonDocument.RootElement.GetProperty("success").GetBoolean()); + Assert.True(jsonDocument.RootElement.GetProperty("data").GetProperty("isUpdated").GetBoolean()); + } +} diff --git a/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/UsersManagement/Authentication/Login/LoginViewEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/UsersManagement/Authentication/Login/LoginViewEndpointTests.cs new file mode 100644 index 00000000..aa221b50 --- /dev/null +++ b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/UsersManagement/Authentication/Login/LoginViewEndpointTests.cs @@ -0,0 +1,93 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Presentation.Web.Common.Http; +using Lumina.Presentation.Web.Common.Requests.UsersManagement.Authentication; +using Lumina.Presentation.Web.Common.Routes; +using Lumina.Presentation.Web.Common.Services; +using Lumina.Presentation.Web.Core.Endpoints.UsersManagement.Authentication.Login; +using Lumina.Presentation.Web.Fixtures.Common.TestHelpers; +using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Http.HttpResults; +using NSubstitute; +using System; +using System.Diagnostics.CodeAnalysis; +using System.Text; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.UnitTests.Core.Endpoints.UsersManagement.Authentication.Login; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class LoginViewEndpointTests +{ + private readonly IUrlService _mockUrlService; + private readonly LoginViewEndpoint _sut; + + /// + /// Initializes a new instance of the class. + /// + public LoginViewEndpointTests() + { + _mockUrlService = Substitute.For(); + _sut = Factory.Create(_mockUrlService); + } + + [Fact] + public async Task ExecuteAsync_WhenUserAlreadyAuthenticated_ShouldRedirectToHome() + { + // Arrange + TestHttpContextFactory.ConfigureUser(_sut.HttpContext, TestHttpContextFactory.CreateAuthenticatedUser()); + TestHttpContextFactory.ConfigureSession(_sut.HttpContext, TestHttpContextFactory.CreateSession()); + _mockUrlService.GetAbsoluteUrl(WebRoutes.Home.INDEX_CULTURED).Returns("http://localhost/en-us"); + + // Act + IResult result = await _sut.ExecuteAsync(new LoginViewRequest(), CancellationToken.None); + + // Assert + RedirectHttpResult redirectResult = Assert.IsType(result); + Assert.Equal("http://localhost/en-us", redirectResult.Url); + _mockUrlService.Received(1).GetAbsoluteUrl(WebRoutes.Home.INDEX_CULTURED); + } + + [Fact] + public async Task ExecuteAsync_WhenSuperAdminSetupPending_ShouldRedirectToRegisterView() + { + // Arrange + Microsoft.AspNetCore.Http.ISession session = Substitute.For(); + byte[] pendingBytes = Encoding.UTF8.GetBytes("true"); +#pragma warning disable CS8601 // possible null reference assignment in the NSubstitute out-argument stub + session.TryGetValue(HttpContextItemKeys.PENDING_SUPER_ADMIN_SETUP, out Arg.Any()).Returns(callInfo => + { + callInfo[1] = pendingBytes; + return true; + }); +#pragma warning restore CS8601 + TestHttpContextFactory.ConfigureSession(_sut.HttpContext, session); + _mockUrlService.GetAbsoluteUrl(WebRoutes.Authentication.REGISTER_VIEW).Returns("http://localhost/en-us/auth/register"); + + // Act + IResult result = await _sut.ExecuteAsync(new LoginViewRequest(), CancellationToken.None); + + // Assert + RedirectHttpResult redirectResult = Assert.IsType(result); + Assert.Equal("http://localhost/en-us/auth/register", redirectResult.Url); + _mockUrlService.Received(1).GetAbsoluteUrl(WebRoutes.Authentication.REGISTER_VIEW); + } + + [Fact] + public async Task ExecuteAsync_WhenNotAuthenticatedAndInitialized_ShouldReturnRazorViewResult() + { + // Arrange + TestHttpContextFactory.ConfigureSession(_sut.HttpContext, TestHttpContextFactory.CreateSession()); + + // Act + IResult result = await _sut.ExecuteAsync(new LoginViewRequest(), CancellationToken.None); + + // Assert + Assert.IsType(result); + } +} diff --git a/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/UsersManagement/Authentication/RecoverPassword/RecoverPasswordEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/UsersManagement/Authentication/RecoverPassword/RecoverPasswordEndpointTests.cs new file mode 100644 index 00000000..fad145e5 --- /dev/null +++ b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/UsersManagement/Authentication/RecoverPassword/RecoverPasswordEndpointTests.cs @@ -0,0 +1,61 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Presentation.Web.Common.Api; +using Lumina.Presentation.Web.Common.Requests.UsersManagement; +using Lumina.Presentation.Web.Common.Responses.UsersManagement; +using Lumina.Presentation.Web.Common.Routes; +using Lumina.Presentation.Web.Core.Endpoints.UsersManagement.Authentication.RecoverPassword; +using Lumina.Presentation.Web.Fixtures.Common.Requests.UsersManagement; +using Lumina.Presentation.Web.Fixtures.Common.TestHelpers; +using Microsoft.AspNetCore.Http; +using NSubstitute; +using System.Diagnostics.CodeAnalysis; +using System.Text.Json; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.UnitTests.Core.Endpoints.UsersManagement.Authentication.RecoverPassword; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class RecoverPasswordEndpointTests +{ + private readonly IApiHttpClient _mockApiHttpClient; + private readonly RecoverPasswordEndpoint _sut; + private readonly RecoverPasswordRequestFixture _recoverPasswordRequestFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + public RecoverPasswordEndpointTests() + { + _mockApiHttpClient = Substitute.For(); + _sut = Factory.Create(_mockApiHttpClient); + } + + [Fact] + public async Task ExecuteAsync_WhenCalled_ShouldRecoverPasswordViaApiAndReturnSuccess() + { + // Arrange + RecoverPasswordRequest request = _recoverPasswordRequestFixture.Create(); + RecoverPasswordResponse expectedResponse = new(true); + _mockApiHttpClient.PostAsync(Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(expectedResponse); + + // Act + IResult result = await _sut.ExecuteAsync(request, CancellationToken.None); + string body = await JsonResultTestHelper.GetResponseBodyAsync(result); + + // Assert + await _mockApiHttpClient.Received(1).PostAsync( + ApiRoutes.Authentication.RECOVER_PASSWORD, + Arg.Is(recovery => recovery.Username == request.Username), + Arg.Any()); + using JsonDocument jsonDocument = JsonDocument.Parse(body); + Assert.True(jsonDocument.RootElement.GetProperty("success").GetBoolean()); + Assert.True(jsonDocument.RootElement.GetProperty("data").GetProperty("isPasswordReset").GetBoolean()); + } +} diff --git a/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/UsersManagement/Authentication/Register/RegisterEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/UsersManagement/Authentication/Register/RegisterEndpointTests.cs new file mode 100644 index 00000000..7db86624 --- /dev/null +++ b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/UsersManagement/Authentication/Register/RegisterEndpointTests.cs @@ -0,0 +1,80 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Presentation.Web.Common.Api; +using Lumina.Presentation.Web.Common.Requests.UsersManagement; +using Lumina.Presentation.Web.Common.Responses.UsersManagement; +using Lumina.Presentation.Web.Common.Routes; +using Lumina.Presentation.Web.Core.Endpoints.UsersManagement.Authentication.Register; +using Lumina.Presentation.Web.Fixtures.Common.Requests.UsersManagement; +using Lumina.Presentation.Web.Fixtures.Common.TestHelpers; +using Microsoft.AspNetCore.Http; +using NSubstitute; +using System.Diagnostics.CodeAnalysis; +using System.Text.Json; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.UnitTests.Core.Endpoints.UsersManagement.Authentication.Register; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class RegisterEndpointTests +{ + private readonly IApiHttpClient _mockApiHttpClient; + private readonly RegisterEndpoint _sut; + private readonly RegisterRequestFixture _registerRequestFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + public RegisterEndpointTests() + { + _mockApiHttpClient = Substitute.For(); + _sut = Factory.Create(_mockApiHttpClient); + } + + [Fact] + public async Task ExecuteAsync_WhenRegistrationTypeIsAdmin_ShouldSetupApplicationViaApi() + { + // Arrange + RegisterRequest request = _registerRequestFixture.Create(registrationType: "Admin"); + _mockApiHttpClient.PostAsync(Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(new RegisterResponse(request.Username, null)); + + // Act + IResult result = await _sut.ExecuteAsync(request, CancellationToken.None); + string body = await JsonResultTestHelper.GetResponseBodyAsync(result); + + // Assert + await _mockApiHttpClient.Received(1).PostAsync( + ApiRoutes.Initialization.SETUP_APPLICATION, + Arg.Is(registration => registration.Username == request.Username), + Arg.Any()); + using JsonDocument jsonDocument = JsonDocument.Parse(body); + Assert.True(jsonDocument.RootElement.GetProperty("success").GetBoolean()); + } + + [Fact] + public async Task ExecuteAsync_WhenRegistrationTypeIsUser_ShouldRegisterAccountViaApi() + { + // Arrange + RegisterRequest request = _registerRequestFixture.Create(registrationType: "User"); + _mockApiHttpClient.PostAsync(Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(new RegisterResponse(request.Username, null)); + + // Act + IResult result = await _sut.ExecuteAsync(request, CancellationToken.None); + string body = await JsonResultTestHelper.GetResponseBodyAsync(result); + + // Assert + await _mockApiHttpClient.Received(1).PostAsync( + ApiRoutes.Authentication.REGISTER_ACCOUNT, + Arg.Is(registration => registration.Username == request.Username), + Arg.Any()); + using JsonDocument jsonDocument = JsonDocument.Parse(body); + Assert.True(jsonDocument.RootElement.GetProperty("success").GetBoolean()); + } +} diff --git a/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Lumina.Presentation.Web.UnitTests.csproj b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Lumina.Presentation.Web.UnitTests.csproj new file mode 100644 index 00000000..cac91d11 --- /dev/null +++ b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Lumina.Presentation.Web.UnitTests.csproj @@ -0,0 +1,46 @@ + + + + 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 + + + + + + + + + + + +