From 64e51632291ade999ca5e77feb95c7582c01385b Mon Sep 17 00:00:00 2001 From: Binary Alley Date: Tue, 3 Nov 2026 10:00:00 +0200 Subject: [PATCH] Updates the provider configuration and ownership tests Covers the provider and reader choices saved with a library, the reconciliation and stale configuration deletion in the provider store, the library type lookups, the ownership and permission checks for update and delete, and the validator behavior for enum names. --- .../LibraryProviderSelectionDtoFixture.cs | 43 ++ .../AddLibrary/AddLibraryCommandFixture.cs | 14 +- .../UpdateLibraryCommandFixture.cs | 18 +- ...erLibraryArtworkProvidersCommandFixture.cs | 46 -- ...rLibraryMetadataProvidersCommandFixture.cs | 44 -- ...aryArtworkProviderEnabledCommandFixture.cs | 50 -- ...tLibraryBookReaderEnabledCommandFixture.cs | 41 -- ...ryMetadataProviderEnabledCommandFixture.cs | 47 -- ...LibraryTypeArtworkProvidersQueryFixture.cs | 35 + .../GetLibraryTypeBookReadersQueryFixture.cs | 35 + ...ibraryTypeMetadataProvidersQueryFixture.cs | 35 + .../Management/AddLibraryRequestFixture.cs | 13 +- .../LibraryProviderSelectionRequestFixture.cs | 43 ++ .../Management/UpdateLibraryRequestFixture.cs | 16 +- ...braryTypeArtworkProvidersRequestFixture.cs | 35 + ...GetLibraryTypeBookReadersRequestFixture.cs | 35 + ...raryTypeMetadataProvidersRequestFixture.cs | 35 + ...erLibraryArtworkProvidersRequestFixture.cs | 45 -- ...rLibraryMetadataProvidersRequestFixture.cs | 45 -- ...aryArtworkProviderEnabledRequestFixture.cs | 48 -- ...tLibraryBookReaderEnabledRequestFixture.cs | 41 -- ...ryMetadataProviderEnabledRequestFixture.cs | 48 -- .../Common/DTO/Libraries/LibraryDtoFixture.cs | 1 - .../LibraryProviderSelectionDtoFixture.cs | 48 ++ ...braryTypeArtworkProvidersRequestFixture.cs | 36 + ...GetLibraryTypeBookReadersRequestFixture.cs | 36 + ...raryTypeMetadataProvidersRequestFixture.cs | 36 + ...erLibraryArtworkProvidersRequestFixture.cs | 45 -- ...rLibraryMetadataProvidersRequestFixture.cs | 45 -- .../SetBookReaderEnabledRequestFixture.cs | 45 -- ...aryArtworkProviderEnabledRequestFixture.cs | 48 -- ...ryMetadataProviderEnabledRequestFixture.cs | 48 -- .../Setup/AuthenticatedLuminaApiFactory.cs | 36 +- .../AddLibrary/AddLibraryEndpointTests.cs | 128 +++- .../DeleteLibraryEndpointTests.cs | 3 +- .../UpdateLibraryEndpointTests.cs | 75 +- ...ibraryTypeArtworkProvidersEndpointTests.cs | 112 +++ .../GetLibraryTypeBookReadersEndpointTests.cs | 112 +++ ...braryTypeMetadataProvidersEndpointTests.cs | 112 +++ ...derLibraryArtworkProvidersEndpointTests.cs | 140 ---- ...erLibraryMetadataProvidersEndpointTests.cs | 140 ---- ...raryArtworkProviderEnabledEndpointTests.cs | 156 ---- ...etLibraryBookReaderEnabledEndpointTests.cs | 199 ------ ...aryMetadataProviderEnabledEndpointTests.cs | 156 ---- ...ibraryTypeArtworkProvidersEndpointTests.cs | 96 +++ .../GetLibraryTypeBookReadersEndpointTests.cs | 96 +++ ...braryTypeMetadataProvidersEndpointTests.cs | 96 +++ .../Index/LibrariesIndexViewEndpointTests.cs | 49 +- .../ReorderArtworkProvidersEndpointTests.cs | 71 -- .../ReorderMetadataProvidersEndpointTests.cs | 71 -- .../SaveLibrary/SaveLibraryEndpointTests.cs | 37 + .../SetArtworkProviderEnabledEndpointTests.cs | 71 -- .../SetBookReaderEnabledEndpointTests.cs | 87 --- ...SetMetadataProviderEnabledEndpointTests.cs | 71 -- .../Common/Setup/LuminaApiFactory.cs | 43 +- .../DeleteLibraryEndpointTests.cs | 76 +- .../UpdateLibraryEndpointTests.cs | 144 +++- ...ibraryTypeArtworkProvidersEndpointTests.cs | 114 +++ .../GetLibraryTypeBookReadersEndpointTests.cs | 114 +++ ...braryTypeMetadataProvidersEndpointTests.cs | 114 +++ ...derLibraryArtworkProvidersEndpointTests.cs | 133 ---- ...erLibraryMetadataProvidersEndpointTests.cs | 133 ---- ...raryArtworkProviderEnabledEndpointTests.cs | 126 ---- ...etLibraryBookReaderEnabledEndpointTests.cs | 77 -- ...aryMetadataProviderEnabledEndpointTests.cs | 126 ---- .../AddLibrary/AddLibraryViewEndpointTests.cs | 18 + .../DeleteLibraryEndpointTests.cs | 43 ++ .../EditLibraryViewEndpointTests.cs | 20 + ...ibraryTypeArtworkProvidersEndpointTests.cs | 67 ++ .../GetLibraryTypeBookReadersEndpointTests.cs | 67 ++ ...braryTypeMetadataProvidersEndpointTests.cs | 67 ++ .../ReorderMetadataProvidersEndpointTests.cs | 89 --- .../SaveLibrary/SaveLibraryEndpointTests.cs | 62 +- .../SetBookReaderEnabledEndpointTests.cs | 81 --- ...SetMetadataProviderEnabledEndpointTests.cs | 93 --- .../AddMediaLibraryRequestMappingTests.cs | 85 +++ .../UpdateLibraryRequestMappingTests.cs | 85 +++ ...TypeArtworkProvidersRequestMappingTests.cs | 32 + ...braryTypeBookReadersRequestMappingTests.cs | 32 + ...ypeMetadataProvidersRequestMappingTests.cs | 32 + ...raryArtworkProvidersRequestMappingTests.cs | 32 - ...aryMetadataProvidersRequestMappingTests.cs | 35 - ...tworkProviderEnabledRequestMappingTests.cs | 33 - ...aryBookReaderEnabledRequestMappingTests.cs | 34 - ...adataProviderEnabledRequestMappingTests.cs | 35 - .../AddLibraryCommandHandlerTests.cs | 43 +- .../AddLibraryCommandValidatorTests.cs | 176 ++++- .../DeleteLibraryCommandHandlerTests.cs | 48 +- .../UpdateLibraryCommandHandlerTests.cs | 273 ++++++- .../UpdateLibraryCommandValidatorTests.cs | 202 ++++-- ...braryPathTemplatePartsQueryHandlerTests.cs | 7 +- ...raryArtworkProvidersCommandHandlerTests.cs | 184 ----- ...ryArtworkProvidersCommandValidatorTests.cs | 104 --- ...aryMetadataProvidersCommandHandlerTests.cs | 144 ---- ...yMetadataProvidersCommandValidatorTests.cs | 104 --- ...tworkProviderEnabledCommandHandlerTests.cs | 243 ------- ...orkProviderEnabledCommandValidatorTests.cs | 89 --- ...aryBookReaderEnabledCommandHandlerTests.cs | 210 ------ ...yBookReaderEnabledCommandValidatorTests.cs | 62 -- ...adataProviderEnabledCommandHandlerTests.cs | 172 ----- ...ataProviderEnabledCommandValidatorTests.cs | 89 --- ...ryTypeArtworkProvidersQueryHandlerTests.cs | 184 +++++ ...TypeArtworkProvidersQueryValidatorTests.cs | 67 ++ ...LibraryTypeBookReadersQueryHandlerTests.cs | 187 +++++ ...braryTypeBookReadersQueryValidatorTests.cs | 67 ++ ...yTypeMetadataProvidersQueryHandlerTests.cs | 184 +++++ ...ypeMetadataProvidersQueryValidatorTests.cs | 67 ++ .../Common/Errors/ErrorsTests.cs | 4 +- .../MediaLibraryScanProcessorJobTests.cs | 5 +- ...aLibraryProviderConfigurationStoreTests.cs | 669 +++++++++++++++--- .../Plugins/PluginDetectionSyncJobTests.cs | 6 +- .../UpdateLibraryEndpointTests.cs | 9 +- ...ibraryTypeArtworkProvidersEndpointTests.cs | 128 ++++ .../GetLibraryTypeBookReadersEndpointTests.cs | 128 ++++ ...braryTypeMetadataProvidersEndpointTests.cs | 128 ++++ ...derLibraryArtworkProvidersEndpointTests.cs | 129 ---- ...erLibraryMetadataProvidersEndpointTests.cs | 129 ---- ...raryArtworkProviderEnabledEndpointTests.cs | 129 ---- ...etLibraryBookReaderEnabledEndpointTests.cs | 124 ---- ...aryMetadataProviderEnabledEndpointTests.cs | 129 ---- .../PermissionAuthorizationHandlerTests.cs | 86 +++ ...ibraryTypeArtworkProvidersEndpointTests.cs | 117 +++ .../GetLibraryTypeBookReadersEndpointTests.cs | 117 +++ ...braryTypeMetadataProvidersEndpointTests.cs | 117 +++ .../Index/LibrariesIndexViewEndpointTests.cs | 115 +++ .../SaveLibrary/SaveLibraryEndpointTests.cs | 26 + .../SetBookReaderEnabledEndpointTests.cs | 80 --- 127 files changed, 5541 insertions(+), 5296 deletions(-) create mode 100644 tests/Common/Lumina.Application.Fixtures/Common/DTO/MediaLibrary/Management/LibraryProviderSelectionDtoFixture.cs delete mode 100644 tests/Common/Lumina.Application.Fixtures/Core/Plugins/Commands/ReorderLibraryArtworkProviders/ReorderLibraryArtworkProvidersCommandFixture.cs delete mode 100644 tests/Common/Lumina.Application.Fixtures/Core/Plugins/Commands/ReorderLibraryMetadataProviders/ReorderLibraryMetadataProvidersCommandFixture.cs delete mode 100644 tests/Common/Lumina.Application.Fixtures/Core/Plugins/Commands/SetLibraryArtworkProviderEnabled/SetLibraryArtworkProviderEnabledCommandFixture.cs delete mode 100644 tests/Common/Lumina.Application.Fixtures/Core/Plugins/Commands/SetLibraryBookReaderEnabled/SetLibraryBookReaderEnabledCommandFixture.cs delete mode 100644 tests/Common/Lumina.Application.Fixtures/Core/Plugins/Commands/SetLibraryMetadataProviderEnabled/SetLibraryMetadataProviderEnabledCommandFixture.cs create mode 100644 tests/Common/Lumina.Application.Fixtures/Core/Plugins/Queries/GetLibraryTypeArtworkProviders/GetLibraryTypeArtworkProvidersQueryFixture.cs create mode 100644 tests/Common/Lumina.Application.Fixtures/Core/Plugins/Queries/GetLibraryTypeBookReaders/GetLibraryTypeBookReadersQueryFixture.cs create mode 100644 tests/Common/Lumina.Application.Fixtures/Core/Plugins/Queries/GetLibraryTypeMetadataProviders/GetLibraryTypeMetadataProvidersQueryFixture.cs create mode 100644 tests/Common/Lumina.Contracts.Fixtures/Core/Requests/MediaLibrary/Management/LibraryProviderSelectionRequestFixture.cs create mode 100644 tests/Common/Lumina.Contracts.Fixtures/Core/Requests/Plugins/GetLibraryTypeArtworkProvidersRequestFixture.cs create mode 100644 tests/Common/Lumina.Contracts.Fixtures/Core/Requests/Plugins/GetLibraryTypeBookReadersRequestFixture.cs create mode 100644 tests/Common/Lumina.Contracts.Fixtures/Core/Requests/Plugins/GetLibraryTypeMetadataProvidersRequestFixture.cs delete mode 100644 tests/Common/Lumina.Contracts.Fixtures/Core/Requests/Plugins/ReorderLibraryArtworkProvidersRequestFixture.cs delete mode 100644 tests/Common/Lumina.Contracts.Fixtures/Core/Requests/Plugins/ReorderLibraryMetadataProvidersRequestFixture.cs delete mode 100644 tests/Common/Lumina.Contracts.Fixtures/Core/Requests/Plugins/SetLibraryArtworkProviderEnabledRequestFixture.cs delete mode 100644 tests/Common/Lumina.Contracts.Fixtures/Core/Requests/Plugins/SetLibraryBookReaderEnabledRequestFixture.cs delete mode 100644 tests/Common/Lumina.Contracts.Fixtures/Core/Requests/Plugins/SetLibraryMetadataProviderEnabledRequestFixture.cs create mode 100644 tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/Libraries/LibraryProviderSelectionDtoFixture.cs create mode 100644 tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/Library/Management/GetLibraryTypeArtworkProvidersRequestFixture.cs create mode 100644 tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/Library/Management/GetLibraryTypeBookReadersRequestFixture.cs create mode 100644 tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/Library/Management/GetLibraryTypeMetadataProvidersRequestFixture.cs delete mode 100644 tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/Plugins/ReorderLibraryArtworkProvidersRequestFixture.cs delete mode 100644 tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/Plugins/ReorderLibraryMetadataProvidersRequestFixture.cs delete mode 100644 tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/Plugins/SetBookReaderEnabledRequestFixture.cs delete mode 100644 tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/Plugins/SetLibraryArtworkProviderEnabledRequestFixture.cs delete mode 100644 tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/Plugins/SetLibraryMetadataProviderEnabledRequestFixture.cs create mode 100644 tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Plugins/GetLibraryTypeArtworkProviders/GetLibraryTypeArtworkProvidersEndpointTests.cs create mode 100644 tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Plugins/GetLibraryTypeBookReaders/GetLibraryTypeBookReadersEndpointTests.cs create mode 100644 tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Plugins/GetLibraryTypeMetadataProviders/GetLibraryTypeMetadataProvidersEndpointTests.cs delete mode 100644 tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Plugins/ReorderLibraryArtworkProviders/ReorderLibraryArtworkProvidersEndpointTests.cs delete mode 100644 tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Plugins/ReorderLibraryMetadataProviders/ReorderLibraryMetadataProvidersEndpointTests.cs delete mode 100644 tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Plugins/SetLibraryArtworkProviderEnabled/SetLibraryArtworkProviderEnabledEndpointTests.cs delete mode 100644 tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Plugins/SetLibraryBookReaderEnabled/SetLibraryBookReaderEnabledEndpointTests.cs delete mode 100644 tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Plugins/SetLibraryMetadataProviderEnabled/SetLibraryMetadataProviderEnabledEndpointTests.cs create mode 100644 tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/Management/GetLibraryTypeArtworkProviders/GetLibraryTypeArtworkProvidersEndpointTests.cs create mode 100644 tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/Management/GetLibraryTypeBookReaders/GetLibraryTypeBookReadersEndpointTests.cs create mode 100644 tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/Management/GetLibraryTypeMetadataProviders/GetLibraryTypeMetadataProvidersEndpointTests.cs delete mode 100644 tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/Management/ReorderArtworkProviders/ReorderArtworkProvidersEndpointTests.cs delete mode 100644 tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/Management/ReorderMetadataProviders/ReorderMetadataProvidersEndpointTests.cs delete mode 100644 tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/Management/SetArtworkProviderEnabled/SetArtworkProviderEnabledEndpointTests.cs delete mode 100644 tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/Management/SetBookReaderEnabled/SetBookReaderEnabledEndpointTests.cs delete mode 100644 tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/Management/SetMetadataProviderEnabled/SetMetadataProviderEnabledEndpointTests.cs create mode 100644 tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Plugins/GetLibraryTypeArtworkProviders/GetLibraryTypeArtworkProvidersEndpointTests.cs create mode 100644 tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Plugins/GetLibraryTypeBookReaders/GetLibraryTypeBookReadersEndpointTests.cs create mode 100644 tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Plugins/GetLibraryTypeMetadataProviders/GetLibraryTypeMetadataProvidersEndpointTests.cs delete mode 100644 tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Plugins/ReorderLibraryArtworkProviders/ReorderLibraryArtworkProvidersEndpointTests.cs delete mode 100644 tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Plugins/ReorderLibraryMetadataProviders/ReorderLibraryMetadataProvidersEndpointTests.cs delete mode 100644 tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Plugins/SetLibraryArtworkProviderEnabled/SetLibraryArtworkProviderEnabledEndpointTests.cs delete mode 100644 tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Plugins/SetLibraryBookReaderEnabled/SetLibraryBookReaderEnabledEndpointTests.cs delete mode 100644 tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Plugins/SetLibraryMetadataProviderEnabled/SetLibraryMetadataProviderEnabledEndpointTests.cs create mode 100644 tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Library/Management/GetLibraryTypeArtworkProviders/GetLibraryTypeArtworkProvidersEndpointTests.cs create mode 100644 tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Library/Management/GetLibraryTypeBookReaders/GetLibraryTypeBookReadersEndpointTests.cs create mode 100644 tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Library/Management/GetLibraryTypeMetadataProviders/GetLibraryTypeMetadataProvidersEndpointTests.cs delete mode 100644 tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Library/Management/ReorderMetadataProviders/ReorderMetadataProvidersEndpointTests.cs delete mode 100644 tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Library/Management/SetBookReaderEnabled/SetBookReaderEnabledEndpointTests.cs delete mode 100644 tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Library/Management/SetMetadataProviderEnabled/SetMetadataProviderEnabledEndpointTests.cs create mode 100644 tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Plugins/GetLibraryTypeArtworkProvidersRequestMappingTests.cs create mode 100644 tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Plugins/GetLibraryTypeBookReadersRequestMappingTests.cs create mode 100644 tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Plugins/GetLibraryTypeMetadataProvidersRequestMappingTests.cs delete mode 100644 tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Plugins/ReorderLibraryArtworkProvidersRequestMappingTests.cs delete mode 100644 tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Plugins/ReorderLibraryMetadataProvidersRequestMappingTests.cs delete mode 100644 tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Plugins/SetLibraryArtworkProviderEnabledRequestMappingTests.cs delete mode 100644 tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Plugins/SetLibraryBookReaderEnabledRequestMappingTests.cs delete mode 100644 tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Plugins/SetLibraryMetadataProviderEnabledRequestMappingTests.cs delete mode 100644 tests/UnitTests/Lumina.Application.UnitTests/Core/Plugins/Commands/ReorderLibraryArtworkProviders/ReorderLibraryArtworkProvidersCommandHandlerTests.cs delete mode 100644 tests/UnitTests/Lumina.Application.UnitTests/Core/Plugins/Commands/ReorderLibraryArtworkProviders/ReorderLibraryArtworkProvidersCommandValidatorTests.cs delete mode 100644 tests/UnitTests/Lumina.Application.UnitTests/Core/Plugins/Commands/ReorderLibraryMetadataProviders/ReorderLibraryMetadataProvidersCommandHandlerTests.cs delete mode 100644 tests/UnitTests/Lumina.Application.UnitTests/Core/Plugins/Commands/ReorderLibraryMetadataProviders/ReorderLibraryMetadataProvidersCommandValidatorTests.cs delete mode 100644 tests/UnitTests/Lumina.Application.UnitTests/Core/Plugins/Commands/SetLibraryArtworkProviderEnabled/SetLibraryArtworkProviderEnabledCommandHandlerTests.cs delete mode 100644 tests/UnitTests/Lumina.Application.UnitTests/Core/Plugins/Commands/SetLibraryArtworkProviderEnabled/SetLibraryArtworkProviderEnabledCommandValidatorTests.cs delete mode 100644 tests/UnitTests/Lumina.Application.UnitTests/Core/Plugins/Commands/SetLibraryBookReaderEnabled/SetLibraryBookReaderEnabledCommandHandlerTests.cs delete mode 100644 tests/UnitTests/Lumina.Application.UnitTests/Core/Plugins/Commands/SetLibraryBookReaderEnabled/SetLibraryBookReaderEnabledCommandValidatorTests.cs delete mode 100644 tests/UnitTests/Lumina.Application.UnitTests/Core/Plugins/Commands/SetLibraryMetadataProviderEnabled/SetLibraryMetadataProviderEnabledCommandHandlerTests.cs delete mode 100644 tests/UnitTests/Lumina.Application.UnitTests/Core/Plugins/Commands/SetLibraryMetadataProviderEnabled/SetLibraryMetadataProviderEnabledCommandValidatorTests.cs create mode 100644 tests/UnitTests/Lumina.Application.UnitTests/Core/Plugins/Queries/GetLibraryTypeArtworkProviders/GetLibraryTypeArtworkProvidersQueryHandlerTests.cs create mode 100644 tests/UnitTests/Lumina.Application.UnitTests/Core/Plugins/Queries/GetLibraryTypeArtworkProviders/GetLibraryTypeArtworkProvidersQueryValidatorTests.cs create mode 100644 tests/UnitTests/Lumina.Application.UnitTests/Core/Plugins/Queries/GetLibraryTypeBookReaders/GetLibraryTypeBookReadersQueryHandlerTests.cs create mode 100644 tests/UnitTests/Lumina.Application.UnitTests/Core/Plugins/Queries/GetLibraryTypeBookReaders/GetLibraryTypeBookReadersQueryValidatorTests.cs create mode 100644 tests/UnitTests/Lumina.Application.UnitTests/Core/Plugins/Queries/GetLibraryTypeMetadataProviders/GetLibraryTypeMetadataProvidersQueryHandlerTests.cs create mode 100644 tests/UnitTests/Lumina.Application.UnitTests/Core/Plugins/Queries/GetLibraryTypeMetadataProviders/GetLibraryTypeMetadataProvidersQueryValidatorTests.cs create mode 100644 tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Plugins/GetLibraryTypeArtworkProviders/GetLibraryTypeArtworkProvidersEndpointTests.cs create mode 100644 tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Plugins/GetLibraryTypeBookReaders/GetLibraryTypeBookReadersEndpointTests.cs create mode 100644 tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Plugins/GetLibraryTypeMetadataProviders/GetLibraryTypeMetadataProvidersEndpointTests.cs delete mode 100644 tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Plugins/ReorderLibraryArtworkProviders/ReorderLibraryArtworkProvidersEndpointTests.cs delete mode 100644 tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Plugins/ReorderLibraryMetadataProviders/ReorderLibraryMetadataProvidersEndpointTests.cs delete mode 100644 tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Plugins/SetLibraryArtworkProviderEnabled/SetLibraryArtworkProviderEnabledEndpointTests.cs delete mode 100644 tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Plugins/SetLibraryBookReaderEnabled/SetLibraryBookReaderEnabledEndpointTests.cs delete mode 100644 tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Plugins/SetLibraryMetadataProviderEnabled/SetLibraryMetadataProviderEnabledEndpointTests.cs create mode 100644 tests/UnitTests/Lumina.Presentation.Web.UnitTests/Common/Authorization/PermissionAuthorizationHandlerTests.cs create mode 100644 tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Library/Management/GetLibraryTypeArtworkProviders/GetLibraryTypeArtworkProvidersEndpointTests.cs create mode 100644 tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Library/Management/GetLibraryTypeBookReaders/GetLibraryTypeBookReadersEndpointTests.cs create mode 100644 tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Library/Management/GetLibraryTypeMetadataProviders/GetLibraryTypeMetadataProvidersEndpointTests.cs create mode 100644 tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Library/Management/Index/LibrariesIndexViewEndpointTests.cs delete mode 100644 tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Library/Management/SetBookReaderEnabled/SetBookReaderEnabledEndpointTests.cs diff --git a/tests/Common/Lumina.Application.Fixtures/Common/DTO/MediaLibrary/Management/LibraryProviderSelectionDtoFixture.cs b/tests/Common/Lumina.Application.Fixtures/Common/DTO/MediaLibrary/Management/LibraryProviderSelectionDtoFixture.cs new file mode 100644 index 00000000..e4181a9c --- /dev/null +++ b/tests/Common/Lumina.Application.Fixtures/Common/DTO/MediaLibrary/Management/LibraryProviderSelectionDtoFixture.cs @@ -0,0 +1,43 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DTO.MediaLibrary.Management; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Application.Fixtures.Common.DTO.MediaLibrary.Management; + +/// +/// Fixture class for the record. +/// +[ExcludeFromCodeCoverage] +public class LibraryProviderSelectionDtoFixture +{ + /// + /// Creates a random valid . + /// + /// Optional. The Id of the plugin providing the provider or reader. + /// Whether the provider or reader is enabled. + /// Whether the choice carries an enabled state. When , the enabled state is . + /// The created . + public LibraryProviderSelectionDto Create( + Guid? pluginId = null, + bool isEnabled = true, + bool includeIsEnabled = true) + { + return new LibraryProviderSelectionDto( + pluginId ?? Guid.NewGuid(), + includeIsEnabled ? isEnabled : null); + } + + /// + /// Creates a list of . + /// + /// The number of elements to create. + /// The created list. + public List CreateMany(int count = 3) + { + return [.. Enumerable.Range(0, count).Select(_ => Create())]; + } +} diff --git a/tests/Common/Lumina.Application.Fixtures/Core/MediaLibrary/Management/Commands/AddLibrary/AddLibraryCommandFixture.cs b/tests/Common/Lumina.Application.Fixtures/Core/MediaLibrary/Management/Commands/AddLibrary/AddLibraryCommandFixture.cs index f773e3b5..239fb080 100644 --- a/tests/Common/Lumina.Application.Fixtures/Core/MediaLibrary/Management/Commands/AddLibrary/AddLibraryCommandFixture.cs +++ b/tests/Common/Lumina.Application.Fixtures/Core/MediaLibrary/Management/Commands/AddLibrary/AddLibraryCommandFixture.cs @@ -32,6 +32,9 @@ public class AddLibraryCommandFixture /// Optional. Whether the consumption progress of the media library items should be tracked, or not. /// Optional. The percentage of a media library item that must be consumed for its session to be considered completed. /// Optional. The ordered parts of the path template of the media library. + /// Optional. The choices made for the metadata providers of the media library. + /// Optional. The choices made for the artwork providers of the media library. + /// Optional. The choices made for the book readers of the media library. /// The created command. public AddLibraryCommand Create( string? title = null, @@ -46,7 +49,10 @@ public class AddLibraryCommandFixture bool isContentOnSsd = false, bool? shouldTrackConsumptionProgress = null, int? completionThresholdPercentage = null, - LibraryPathTemplatePartDto[]? pathTemplateParts = null) + LibraryPathTemplatePartDto[]? pathTemplateParts = null, + LibraryProviderSelectionDto[]? metadataProviders = null, + LibraryProviderSelectionDto[]? artworkProviders = null, + LibraryProviderSelectionDto[]? bookReaders = null) { return new Faker() .CustomInstantiator(f => new AddLibraryCommand( @@ -62,6 +68,9 @@ public class AddLibraryCommandFixture false, shouldTrackConsumptionProgress, completionThresholdPercentage, + null, + null, + null, null )) .RuleFor(x => x.Title, f => title ?? f.Lorem.Word()) @@ -75,6 +84,9 @@ public class AddLibraryCommandFixture .RuleFor(x => x.ShouldSkipUnchangedDirectoriesDuringScan, shouldSkipUnchangedDirectoriesDuringScan) .RuleFor(x => x.IsContentOnSsd, isContentOnSsd) .RuleFor(x => x.PathTemplateParts, pathTemplateParts) + .RuleFor(x => x.MetadataProviders, metadataProviders) + .RuleFor(x => x.ArtworkProviders, artworkProviders) + .RuleFor(x => x.BookReaders, bookReaders) .Generate(); } diff --git a/tests/Common/Lumina.Application.Fixtures/Core/MediaLibrary/Management/Commands/UpdateLibrary/UpdateLibraryCommandFixture.cs b/tests/Common/Lumina.Application.Fixtures/Core/MediaLibrary/Management/Commands/UpdateLibrary/UpdateLibraryCommandFixture.cs index 84bb39e0..510acaea 100644 --- a/tests/Common/Lumina.Application.Fixtures/Core/MediaLibrary/Management/Commands/UpdateLibrary/UpdateLibraryCommandFixture.cs +++ b/tests/Common/Lumina.Application.Fixtures/Core/MediaLibrary/Management/Commands/UpdateLibrary/UpdateLibraryCommandFixture.cs @@ -21,7 +21,6 @@ public class UpdateLibraryCommandFixture /// Creates a random valid command to update a media library. /// /// Optional. The Id of the media library. - /// Optional. The Id of the user owning the media library. /// Optional. The title of the media library. /// Optional. The type of the media library. /// Optional. The content locations of the media library. @@ -35,10 +34,12 @@ public class UpdateLibraryCommandFixture /// Optional. Whether the consumption progress of the media library items should be tracked, or not. /// Optional. The percentage of a media library item that must be consumed for its session to be considered completed. /// Optional. The ordered parts of the path template of the media library. + /// Optional. The choices made for the metadata providers of the media library. + /// Optional. The choices made for the artwork providers of the media library. + /// Optional. The choices made for the book readers of the media library. /// The created command. public UpdateLibraryCommand Create( Guid? id = null, - Guid? ownerId = null, string? title = null, string? libraryType = null, string[]? contentLocations = null, @@ -51,11 +52,13 @@ public class UpdateLibraryCommandFixture bool isContentOnSsd = false, bool? shouldTrackConsumptionProgress = null, int? completionThresholdPercentage = null, - LibraryPathTemplatePartDto[]? pathTemplateParts = null) + LibraryPathTemplatePartDto[]? pathTemplateParts = null, + LibraryProviderSelectionDto[]? metadataProviders = null, + LibraryProviderSelectionDto[]? artworkProviders = null, + LibraryProviderSelectionDto[]? bookReaders = null) { return new Faker() .CustomInstantiator(f => new UpdateLibraryCommand( - default, default, default!, default!, @@ -69,10 +72,12 @@ public class UpdateLibraryCommandFixture false, shouldTrackConsumptionProgress, completionThresholdPercentage, + null, + null, + null, null )) .RuleFor(x => x.Id, id ?? Guid.NewGuid()) - .RuleFor(x => x.OwnerId, ownerId ?? Guid.NewGuid()) .RuleFor(x => x.Title, f => title ?? f.Lorem.Word()) .RuleFor(x => x.LibraryType, f => libraryType ?? f.Random.Enum().ToString()) .RuleFor(x => x.ContentLocations, f => contentLocations ?? [f.System.DirectoryPath(), f.System.DirectoryPath(), f.System.DirectoryPath()]) @@ -84,6 +89,9 @@ public class UpdateLibraryCommandFixture .RuleFor(x => x.ShouldSkipUnchangedDirectoriesDuringScan, shouldSkipUnchangedDirectoriesDuringScan) .RuleFor(x => x.IsContentOnSsd, isContentOnSsd) .RuleFor(x => x.PathTemplateParts, pathTemplateParts) + .RuleFor(x => x.MetadataProviders, metadataProviders) + .RuleFor(x => x.ArtworkProviders, artworkProviders) + .RuleFor(x => x.BookReaders, bookReaders) .Generate(); } diff --git a/tests/Common/Lumina.Application.Fixtures/Core/Plugins/Commands/ReorderLibraryArtworkProviders/ReorderLibraryArtworkProvidersCommandFixture.cs b/tests/Common/Lumina.Application.Fixtures/Core/Plugins/Commands/ReorderLibraryArtworkProviders/ReorderLibraryArtworkProvidersCommandFixture.cs deleted file mode 100644 index 42ecdbc6..00000000 --- a/tests/Common/Lumina.Application.Fixtures/Core/Plugins/Commands/ReorderLibraryArtworkProviders/ReorderLibraryArtworkProvidersCommandFixture.cs +++ /dev/null @@ -1,46 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using Bogus; -using Lumina.Application.Core.Plugins.Commands.ReorderLibraryArtworkProviders; -using System; -using System.Collections.Generic; -using System.Diagnostics.CodeAnalysis; -using System.Linq; -#endregion - -namespace Lumina.Application.Fixtures.Core.Plugins.Commands.ReorderLibraryArtworkProviders; - -/// -/// Fixture class for the class. -/// -[ExcludeFromCodeCoverage] -public class ReorderLibraryArtworkProvidersCommandFixture -{ - /// - /// Creates a random valid command to reorder the artwork providers of a media library. - /// - /// Optional. The Id of the media library whose artwork providers are reordered. - /// Optional. The plugin Ids in the new order. - /// The created command. - public ReorderLibraryArtworkProvidersCommand Create( - Guid? libraryId = null, - IReadOnlyList? pluginIds = null) - { - return new Faker() - .CustomInstantiator(f => new ReorderLibraryArtworkProvidersCommand( - default, - default!)) - .RuleFor(x => x.LibraryId, libraryId ?? Guid.NewGuid()) - .RuleFor(x => x.PluginIds, f => pluginIds ?? [Guid.NewGuid(), Guid.NewGuid(), Guid.NewGuid()]) - .Generate(); - } - - /// - /// Creates a list of . - /// - /// The number of elements to create. - /// The created list. - public List CreateMany(int count = 3) - { - return [.. Enumerable.Range(0, count).Select(_ => Create())]; - } -} diff --git a/tests/Common/Lumina.Application.Fixtures/Core/Plugins/Commands/ReorderLibraryMetadataProviders/ReorderLibraryMetadataProvidersCommandFixture.cs b/tests/Common/Lumina.Application.Fixtures/Core/Plugins/Commands/ReorderLibraryMetadataProviders/ReorderLibraryMetadataProvidersCommandFixture.cs deleted file mode 100644 index 6855acd8..00000000 --- a/tests/Common/Lumina.Application.Fixtures/Core/Plugins/Commands/ReorderLibraryMetadataProviders/ReorderLibraryMetadataProvidersCommandFixture.cs +++ /dev/null @@ -1,44 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using Bogus; -using Lumina.Application.Core.Plugins.Commands.ReorderLibraryMetadataProviders; -using System; -using System.Collections.Generic; -using System.Diagnostics.CodeAnalysis; -using System.Linq; -#endregion - -namespace Lumina.Application.Fixtures.Core.Plugins.Commands.ReorderLibraryMetadataProviders; - -/// -/// Fixture class for the class. -/// -[ExcludeFromCodeCoverage] -public class ReorderLibraryMetadataProvidersCommandFixture -{ - /// - /// Creates a random valid command to reorder the metadata providers of a media library. - /// - /// Optional. The Id of the media library whose metadata providers are reordered. - /// Optional. The plugin Ids in the new order. - /// The created command. - public ReorderLibraryMetadataProvidersCommand Create(Guid? libraryId = null, IReadOnlyList? pluginIds = null) - { - return new Faker() - .CustomInstantiator(f => new ReorderLibraryMetadataProvidersCommand( - default, - default!)) - .RuleFor(x => x.LibraryId, libraryId ?? Guid.NewGuid()) - .RuleFor(x => x.PluginIds, f => pluginIds ?? [Guid.NewGuid(), Guid.NewGuid(), Guid.NewGuid()]) - .Generate(); - } - - /// - /// Creates a list of . - /// - /// The number of elements to create. - /// The created list. - public List CreateMany(int count = 3) - { - return [.. Enumerable.Range(0, count).Select(_ => Create())]; - } -} diff --git a/tests/Common/Lumina.Application.Fixtures/Core/Plugins/Commands/SetLibraryArtworkProviderEnabled/SetLibraryArtworkProviderEnabledCommandFixture.cs b/tests/Common/Lumina.Application.Fixtures/Core/Plugins/Commands/SetLibraryArtworkProviderEnabled/SetLibraryArtworkProviderEnabledCommandFixture.cs deleted file mode 100644 index db917fec..00000000 --- a/tests/Common/Lumina.Application.Fixtures/Core/Plugins/Commands/SetLibraryArtworkProviderEnabled/SetLibraryArtworkProviderEnabledCommandFixture.cs +++ /dev/null @@ -1,50 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using Bogus; -using Lumina.Application.Core.Plugins.Commands.SetLibraryArtworkProviderEnabled; -using System; -using System.Collections.Generic; -using System.Diagnostics.CodeAnalysis; -using System.Linq; -#endregion - -namespace Lumina.Application.Fixtures.Core.Plugins.Commands.SetLibraryArtworkProviderEnabled; - -/// -/// Fixture class for the class. -/// -[ExcludeFromCodeCoverage] -public class SetLibraryArtworkProviderEnabledCommandFixture -{ - /// - /// Creates a random valid command to enable or disable an artwork provider for a media library. - /// - /// Optional. The Id of the media library whose artwork provider is enabled or disabled. - /// Optional. The Id of the plugin providing the artwork. - /// Whether the artwork provider should be enabled for the media library. - /// The created command. - public SetLibraryArtworkProviderEnabledCommand Create( - Guid? libraryId = null, - Guid? pluginId = null, - bool isEnabled = true) - { - return new Faker() - .CustomInstantiator(f => new SetLibraryArtworkProviderEnabledCommand( - default, - default, - true)) - .RuleFor(x => x.LibraryId, libraryId ?? Guid.NewGuid()) - .RuleFor(x => x.PluginId, pluginId ?? Guid.NewGuid()) - .RuleFor(x => x.IsEnabled, isEnabled) - .Generate(); - } - - /// - /// Creates a list of . - /// - /// The number of elements to create. - /// The created list. - public List CreateMany(int count = 3) - { - return [.. Enumerable.Range(0, count).Select(_ => Create())]; - } -} diff --git a/tests/Common/Lumina.Application.Fixtures/Core/Plugins/Commands/SetLibraryBookReaderEnabled/SetLibraryBookReaderEnabledCommandFixture.cs b/tests/Common/Lumina.Application.Fixtures/Core/Plugins/Commands/SetLibraryBookReaderEnabled/SetLibraryBookReaderEnabledCommandFixture.cs deleted file mode 100644 index ef39d0f1..00000000 --- a/tests/Common/Lumina.Application.Fixtures/Core/Plugins/Commands/SetLibraryBookReaderEnabled/SetLibraryBookReaderEnabledCommandFixture.cs +++ /dev/null @@ -1,41 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using Lumina.Application.Core.Plugins.Commands.SetLibraryBookReaderEnabled; -using System; -using System.Collections.Generic; -using System.Diagnostics.CodeAnalysis; -using System.Linq; -#endregion - -namespace Lumina.Application.Fixtures.Core.Plugins.Commands.SetLibraryBookReaderEnabled; - -/// -/// Fixture class for the class. -/// -[ExcludeFromCodeCoverage] -public class SetLibraryBookReaderEnabledCommandFixture -{ - /// - /// Creates a random valid command to enable or disable a book reader for a media library. - /// - /// Optional. The Id of the media library whose book reader is enabled or disabled. - /// Optional. The unique identifier of the plugin providing the book reader. - /// Optional. Whether the book reader should be enabled for the media library. - /// The created . - public SetLibraryBookReaderEnabledCommand Create( - Guid? libraryId = null, - Guid? pluginId = null, - bool? isEnabled = null) - { - return new SetLibraryBookReaderEnabledCommand(libraryId ?? Guid.NewGuid(), pluginId ?? Guid.NewGuid(), isEnabled ?? true); - } - - /// - /// Creates a list of . - /// - /// The number of elements to create. - /// The created list. - public List CreateMany(int count = 3) - { - return [.. Enumerable.Range(0, count).Select(_ => Create())]; - } -} diff --git a/tests/Common/Lumina.Application.Fixtures/Core/Plugins/Commands/SetLibraryMetadataProviderEnabled/SetLibraryMetadataProviderEnabledCommandFixture.cs b/tests/Common/Lumina.Application.Fixtures/Core/Plugins/Commands/SetLibraryMetadataProviderEnabled/SetLibraryMetadataProviderEnabledCommandFixture.cs deleted file mode 100644 index c640fb2c..00000000 --- a/tests/Common/Lumina.Application.Fixtures/Core/Plugins/Commands/SetLibraryMetadataProviderEnabled/SetLibraryMetadataProviderEnabledCommandFixture.cs +++ /dev/null @@ -1,47 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using Bogus; -using Lumina.Application.Core.Plugins.Commands.SetLibraryMetadataProviderEnabled; -using System; -using System.Collections.Generic; -using System.Diagnostics.CodeAnalysis; -using System.Linq; -#endregion - -namespace Lumina.Application.Fixtures.Core.Plugins.Commands.SetLibraryMetadataProviderEnabled; - -/// -/// Fixture class for the class. -/// -[ExcludeFromCodeCoverage] -public class SetLibraryMetadataProviderEnabledCommandFixture -{ - /// - /// Creates a random valid command to enable or disable a metadata provider for a media library. - /// - /// Optional. The Id of the media library whose metadata provider is enabled or disabled. - /// Optional. The Id of the plugin providing the metadata. - /// Whether the metadata provider should be enabled for the media library. - /// The created command. - public SetLibraryMetadataProviderEnabledCommand Create(Guid? libraryId = null, Guid? pluginId = null, bool isEnabled = true) - { - return new Faker() - .CustomInstantiator(f => new SetLibraryMetadataProviderEnabledCommand( - default, - default, - true)) - .RuleFor(x => x.LibraryId, libraryId ?? Guid.NewGuid()) - .RuleFor(x => x.PluginId, pluginId ?? Guid.NewGuid()) - .RuleFor(x => x.IsEnabled, isEnabled) - .Generate(); - } - - /// - /// Creates a list of . - /// - /// The number of elements to create. - /// The created list. - public List CreateMany(int count = 3) - { - return [.. Enumerable.Range(0, count).Select(_ => Create())]; - } -} diff --git a/tests/Common/Lumina.Application.Fixtures/Core/Plugins/Queries/GetLibraryTypeArtworkProviders/GetLibraryTypeArtworkProvidersQueryFixture.cs b/tests/Common/Lumina.Application.Fixtures/Core/Plugins/Queries/GetLibraryTypeArtworkProviders/GetLibraryTypeArtworkProvidersQueryFixture.cs new file mode 100644 index 00000000..85c9fb5d --- /dev/null +++ b/tests/Common/Lumina.Application.Fixtures/Core/Plugins/Queries/GetLibraryTypeArtworkProviders/GetLibraryTypeArtworkProvidersQueryFixture.cs @@ -0,0 +1,35 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Core.Plugins.Queries.GetLibraryTypeArtworkProviders; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Application.Fixtures.Core.Plugins.Queries.GetLibraryTypeArtworkProviders; + +/// +/// Fixture class for the record. +/// +[ExcludeFromCodeCoverage] +public class GetLibraryTypeArtworkProvidersQueryFixture +{ + /// + /// Creates a random valid . + /// + /// Optional. The media library type whose available artwork providers are retrieved. + /// The created . + public GetLibraryTypeArtworkProvidersQuery Create(string? libraryType = null) + { + return new GetLibraryTypeArtworkProvidersQuery(libraryType ?? "Book"); + } + + /// + /// Creates a list of . + /// + /// The number of elements to create. + /// The created list. + public List CreateMany(int count = 3) + { + return [.. Enumerable.Range(0, count).Select(_ => Create())]; + } +} diff --git a/tests/Common/Lumina.Application.Fixtures/Core/Plugins/Queries/GetLibraryTypeBookReaders/GetLibraryTypeBookReadersQueryFixture.cs b/tests/Common/Lumina.Application.Fixtures/Core/Plugins/Queries/GetLibraryTypeBookReaders/GetLibraryTypeBookReadersQueryFixture.cs new file mode 100644 index 00000000..55779a76 --- /dev/null +++ b/tests/Common/Lumina.Application.Fixtures/Core/Plugins/Queries/GetLibraryTypeBookReaders/GetLibraryTypeBookReadersQueryFixture.cs @@ -0,0 +1,35 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Core.Plugins.Queries.GetLibraryTypeBookReaders; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Application.Fixtures.Core.Plugins.Queries.GetLibraryTypeBookReaders; + +/// +/// Fixture class for the record. +/// +[ExcludeFromCodeCoverage] +public class GetLibraryTypeBookReadersQueryFixture +{ + /// + /// Creates a random valid . + /// + /// Optional. The media library type whose available book readers are retrieved. + /// The created . + public GetLibraryTypeBookReadersQuery Create(string? libraryType = null) + { + return new GetLibraryTypeBookReadersQuery(libraryType ?? "Book"); + } + + /// + /// Creates a list of . + /// + /// The number of elements to create. + /// The created list. + public List CreateMany(int count = 3) + { + return [.. Enumerable.Range(0, count).Select(_ => Create())]; + } +} diff --git a/tests/Common/Lumina.Application.Fixtures/Core/Plugins/Queries/GetLibraryTypeMetadataProviders/GetLibraryTypeMetadataProvidersQueryFixture.cs b/tests/Common/Lumina.Application.Fixtures/Core/Plugins/Queries/GetLibraryTypeMetadataProviders/GetLibraryTypeMetadataProvidersQueryFixture.cs new file mode 100644 index 00000000..50624d95 --- /dev/null +++ b/tests/Common/Lumina.Application.Fixtures/Core/Plugins/Queries/GetLibraryTypeMetadataProviders/GetLibraryTypeMetadataProvidersQueryFixture.cs @@ -0,0 +1,35 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Core.Plugins.Queries.GetLibraryTypeMetadataProviders; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Application.Fixtures.Core.Plugins.Queries.GetLibraryTypeMetadataProviders; + +/// +/// Fixture class for the record. +/// +[ExcludeFromCodeCoverage] +public class GetLibraryTypeMetadataProvidersQueryFixture +{ + /// + /// Creates a random valid . + /// + /// Optional. The media library type whose available metadata providers are retrieved. + /// The created . + public GetLibraryTypeMetadataProvidersQuery Create(string? libraryType = null) + { + return new GetLibraryTypeMetadataProvidersQuery(libraryType ?? "Book"); + } + + /// + /// Creates a list of . + /// + /// The number of elements to create. + /// The created list. + public List CreateMany(int count = 3) + { + return [.. Enumerable.Range(0, count).Select(_ => Create())]; + } +} diff --git a/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/MediaLibrary/Management/AddLibraryRequestFixture.cs b/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/MediaLibrary/Management/AddLibraryRequestFixture.cs index c705b5a7..837b1bf3 100644 --- a/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/MediaLibrary/Management/AddLibraryRequestFixture.cs +++ b/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/MediaLibrary/Management/AddLibraryRequestFixture.cs @@ -32,6 +32,9 @@ public class AddLibraryRequestFixture /// Optional. Whether the consumption progress of the media library items should be tracked, or not. /// Optional. The percentage of a media library item that must be consumed for its session to be considered completed. /// Optional. The ordered parts of the path template of the media library. + /// Optional. The choices made for the metadata providers of the media library. + /// Optional. The choices made for the artwork providers of the media library. + /// Optional. The choices made for the book readers of the media library. /// The created . public AddLibraryRequest Create( string? title = null, @@ -46,7 +49,10 @@ public class AddLibraryRequestFixture bool? isContentOnSsd = null, bool? shouldTrackConsumptionProgress = null, int? completionThresholdPercentage = null, - LibraryPathTemplatePartRequest[]? pathTemplateParts = null) + LibraryPathTemplatePartRequest?[]? pathTemplateParts = null, + LibraryProviderSelectionRequest?[]? metadataProviders = null, + LibraryProviderSelectionRequest?[]? artworkProviders = null, + LibraryProviderSelectionRequest?[]? bookReaders = null) { return new AddLibraryRequest( title ?? _faker.Commerce.Department(), @@ -61,7 +67,10 @@ public class AddLibraryRequestFixture isContentOnSsd ?? false, shouldTrackConsumptionProgress, completionThresholdPercentage, - pathTemplateParts + pathTemplateParts, + metadataProviders, + artworkProviders, + bookReaders ); } diff --git a/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/MediaLibrary/Management/LibraryProviderSelectionRequestFixture.cs b/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/MediaLibrary/Management/LibraryProviderSelectionRequestFixture.cs new file mode 100644 index 00000000..c8787577 --- /dev/null +++ b/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/MediaLibrary/Management/LibraryProviderSelectionRequestFixture.cs @@ -0,0 +1,43 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Contracts.Requests.MediaLibrary.Management; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Contracts.Fixtures.Core.Requests.MediaLibrary.Management; + +/// +/// Fixture class for the record. +/// +[ExcludeFromCodeCoverage] +public class LibraryProviderSelectionRequestFixture +{ + /// + /// Creates a random valid . + /// + /// Optional. The Id of the plugin providing the provider or reader. + /// Whether the provider or reader is enabled. + /// Whether the choice carries an enabled state. When , the enabled state is . + /// The created . + public LibraryProviderSelectionRequest Create( + Guid? pluginId = null, + bool isEnabled = true, + bool includeIsEnabled = true) + { + return new LibraryProviderSelectionRequest( + pluginId ?? Guid.NewGuid(), + includeIsEnabled ? isEnabled : null); + } + + /// + /// Creates a list of . + /// + /// The number of elements to create. + /// The created list. + public List CreateMany(int count = 3) + { + return [.. Enumerable.Range(0, count).Select(_ => Create())]; + } +} diff --git a/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/MediaLibrary/Management/UpdateLibraryRequestFixture.cs b/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/MediaLibrary/Management/UpdateLibraryRequestFixture.cs index 44208473..423d02a8 100644 --- a/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/MediaLibrary/Management/UpdateLibraryRequestFixture.cs +++ b/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/MediaLibrary/Management/UpdateLibraryRequestFixture.cs @@ -21,7 +21,6 @@ public class UpdateLibraryRequestFixture /// Creates a random valid . /// /// Optional. The Id of the media library to update. - /// Optional. The Id of the user owning the media library. /// Optional. The title of the media library. /// Optional. The type of the media library. /// Optional. The file system paths of the media library content directories. @@ -35,10 +34,12 @@ public class UpdateLibraryRequestFixture /// Optional. Whether the consumption progress of the media library items should be tracked, or not. /// Optional. The percentage of a media library item that must be consumed for its session to be considered completed. /// Optional. The ordered parts of the path template of the media library. + /// Optional. The choices made for the metadata providers of the media library. + /// Optional. The choices made for the artwork providers of the media library. + /// Optional. The choices made for the book readers of the media library. /// The created . public UpdateLibraryRequest Create( Guid? id = null, - Guid? userId = null, string? title = null, string? libraryType = null, string[]? contentLocations = null, @@ -51,11 +52,13 @@ public class UpdateLibraryRequestFixture bool? isContentOnSsd = null, bool? shouldTrackConsumptionProgress = null, int? completionThresholdPercentage = null, - LibraryPathTemplatePartRequest[]? pathTemplateParts = null) + LibraryPathTemplatePartRequest?[]? pathTemplateParts = null, + LibraryProviderSelectionRequest?[]? metadataProviders = null, + LibraryProviderSelectionRequest?[]? artworkProviders = null, + LibraryProviderSelectionRequest?[]? bookReaders = null) { return new UpdateLibraryRequest( id ?? _faker.Random.Guid(), - userId ?? _faker.Random.Guid(), title ?? _faker.Commerce.Department(), libraryType ?? "EBook", contentLocations ?? [_faker.System.DirectoryPath()], @@ -68,7 +71,10 @@ public class UpdateLibraryRequestFixture isContentOnSsd ?? false, shouldTrackConsumptionProgress, completionThresholdPercentage, - pathTemplateParts + pathTemplateParts, + metadataProviders, + artworkProviders, + bookReaders ); } diff --git a/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/Plugins/GetLibraryTypeArtworkProvidersRequestFixture.cs b/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/Plugins/GetLibraryTypeArtworkProvidersRequestFixture.cs new file mode 100644 index 00000000..d7e7605a --- /dev/null +++ b/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/Plugins/GetLibraryTypeArtworkProvidersRequestFixture.cs @@ -0,0 +1,35 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Contracts.Requests.Plugins; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Contracts.Fixtures.Core.Requests.Plugins; + +/// +/// Fixture class for the record. +/// +[ExcludeFromCodeCoverage] +public class GetLibraryTypeArtworkProvidersRequestFixture +{ + /// + /// Creates a random valid . + /// + /// Optional. The media library type whose available artwork providers are retrieved. + /// The created . + public GetLibraryTypeArtworkProvidersRequest Create(string? libraryType = null) + { + return new GetLibraryTypeArtworkProvidersRequest(libraryType ?? "Book"); + } + + /// + /// Creates a list of . + /// + /// The number of elements to create. + /// The created list. + public List CreateMany(int count = 3) + { + return [.. Enumerable.Range(0, count).Select(_ => Create())]; + } +} diff --git a/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/Plugins/GetLibraryTypeBookReadersRequestFixture.cs b/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/Plugins/GetLibraryTypeBookReadersRequestFixture.cs new file mode 100644 index 00000000..d542f775 --- /dev/null +++ b/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/Plugins/GetLibraryTypeBookReadersRequestFixture.cs @@ -0,0 +1,35 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Contracts.Requests.Plugins; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Contracts.Fixtures.Core.Requests.Plugins; + +/// +/// Fixture class for the record. +/// +[ExcludeFromCodeCoverage] +public class GetLibraryTypeBookReadersRequestFixture +{ + /// + /// Creates a random valid . + /// + /// Optional. The media library type whose available book readers are retrieved. + /// The created . + public GetLibraryTypeBookReadersRequest Create(string? libraryType = null) + { + return new GetLibraryTypeBookReadersRequest(libraryType ?? "Book"); + } + + /// + /// Creates a list of . + /// + /// The number of elements to create. + /// The created list. + public List CreateMany(int count = 3) + { + return [.. Enumerable.Range(0, count).Select(_ => Create())]; + } +} diff --git a/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/Plugins/GetLibraryTypeMetadataProvidersRequestFixture.cs b/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/Plugins/GetLibraryTypeMetadataProvidersRequestFixture.cs new file mode 100644 index 00000000..18ba5f97 --- /dev/null +++ b/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/Plugins/GetLibraryTypeMetadataProvidersRequestFixture.cs @@ -0,0 +1,35 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Contracts.Requests.Plugins; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Contracts.Fixtures.Core.Requests.Plugins; + +/// +/// Fixture class for the record. +/// +[ExcludeFromCodeCoverage] +public class GetLibraryTypeMetadataProvidersRequestFixture +{ + /// + /// Creates a random valid . + /// + /// Optional. The media library type whose available metadata providers are retrieved. + /// The created . + public GetLibraryTypeMetadataProvidersRequest Create(string? libraryType = null) + { + return new GetLibraryTypeMetadataProvidersRequest(libraryType ?? "Book"); + } + + /// + /// Creates a list of . + /// + /// The number of elements to create. + /// The created list. + public List CreateMany(int count = 3) + { + return [.. Enumerable.Range(0, count).Select(_ => Create())]; + } +} diff --git a/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/Plugins/ReorderLibraryArtworkProvidersRequestFixture.cs b/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/Plugins/ReorderLibraryArtworkProvidersRequestFixture.cs deleted file mode 100644 index 8c65fa86..00000000 --- a/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/Plugins/ReorderLibraryArtworkProvidersRequestFixture.cs +++ /dev/null @@ -1,45 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using Bogus; -using Lumina.Contracts.Requests.Plugins; -using System; -using System.Collections.Generic; -using System.Diagnostics.CodeAnalysis; -using System.Linq; -#endregion - -namespace Lumina.Contracts.Fixtures.Core.Requests.Plugins; - -/// -/// Fixture class for the record. -/// -[ExcludeFromCodeCoverage] -public class ReorderLibraryArtworkProvidersRequestFixture -{ - private readonly Faker _faker = new(); - - /// - /// Creates a random valid . - /// - /// Optional. The Id of the media library whose artwork providers are reordered. - /// Optional. The plugin Ids in the new order. - /// The created . - public ReorderLibraryArtworkProvidersRequest Create( - Guid? libraryId = null, - IReadOnlyList? pluginIds = null) - { - return new ReorderLibraryArtworkProvidersRequest( - libraryId ?? _faker.Random.Guid(), - pluginIds ?? [Guid.NewGuid(), Guid.NewGuid(), Guid.NewGuid()] - ); - } - - /// - /// Creates a list of . - /// - /// The number of elements to create. - /// The created list. - public List CreateMany(int count = 3) - { - return [.. Enumerable.Range(0, count).Select(_ => Create())]; - } -} diff --git a/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/Plugins/ReorderLibraryMetadataProvidersRequestFixture.cs b/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/Plugins/ReorderLibraryMetadataProvidersRequestFixture.cs deleted file mode 100644 index a740a144..00000000 --- a/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/Plugins/ReorderLibraryMetadataProvidersRequestFixture.cs +++ /dev/null @@ -1,45 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using Bogus; -using Lumina.Contracts.Requests.Plugins; -using System; -using System.Collections.Generic; -using System.Diagnostics.CodeAnalysis; -using System.Linq; -#endregion - -namespace Lumina.Contracts.Fixtures.Core.Requests.Plugins; - -/// -/// Fixture class for the record. -/// -[ExcludeFromCodeCoverage] -public class ReorderLibraryMetadataProvidersRequestFixture -{ - private readonly Faker _faker = new(); - - /// - /// Creates a random valid . - /// - /// Optional. The Id of the media library whose metadata providers are reordered. - /// Optional. The plugin Ids in the new order. - /// The created . - public ReorderLibraryMetadataProvidersRequest Create( - Guid? libraryId = null, - IReadOnlyList? pluginIds = null) - { - return new ReorderLibraryMetadataProvidersRequest( - libraryId ?? _faker.Random.Guid(), - pluginIds ?? [Guid.NewGuid(), Guid.NewGuid(), Guid.NewGuid()] - ); - } - - /// - /// Creates a list of . - /// - /// The number of elements to create. - /// The created list. - public List CreateMany(int count = 3) - { - return [.. Enumerable.Range(0, count).Select(_ => Create())]; - } -} diff --git a/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/Plugins/SetLibraryArtworkProviderEnabledRequestFixture.cs b/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/Plugins/SetLibraryArtworkProviderEnabledRequestFixture.cs deleted file mode 100644 index cd7f3dbb..00000000 --- a/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/Plugins/SetLibraryArtworkProviderEnabledRequestFixture.cs +++ /dev/null @@ -1,48 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using Bogus; -using Lumina.Contracts.Requests.Plugins; -using System; -using System.Collections.Generic; -using System.Diagnostics.CodeAnalysis; -using System.Linq; -#endregion - -namespace Lumina.Contracts.Fixtures.Core.Requests.Plugins; - -/// -/// Fixture class for the record. -/// -[ExcludeFromCodeCoverage] -public class SetLibraryArtworkProviderEnabledRequestFixture -{ - private readonly Faker _faker = new(); - - /// - /// Creates a random valid . - /// - /// Optional. The Id of the media library whose artwork provider is enabled or disabled. - /// Optional. The Id of the plugin providing the artwork. - /// Optional. Whether the artwork provider should be enabled. - /// The created . - public SetLibraryArtworkProviderEnabledRequest Create( - Guid? libraryId = null, - Guid? pluginId = null, - bool? isEnabled = null) - { - return new SetLibraryArtworkProviderEnabledRequest( - libraryId ?? _faker.Random.Guid(), - pluginId ?? _faker.Random.Guid(), - isEnabled ?? _faker.Random.Bool() - ); - } - - /// - /// Creates a list of . - /// - /// The number of elements to create. - /// The created list. - public List CreateMany(int count = 3) - { - return [.. Enumerable.Range(0, count).Select(_ => Create())]; - } -} diff --git a/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/Plugins/SetLibraryBookReaderEnabledRequestFixture.cs b/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/Plugins/SetLibraryBookReaderEnabledRequestFixture.cs deleted file mode 100644 index 68cdb841..00000000 --- a/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/Plugins/SetLibraryBookReaderEnabledRequestFixture.cs +++ /dev/null @@ -1,41 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using Lumina.Contracts.Requests.Plugins; -using System; -using System.Collections.Generic; -using System.Diagnostics.CodeAnalysis; -using System.Linq; -#endregion - -namespace Lumina.Contracts.Fixtures.Core.Requests.Plugins; - -/// -/// Fixture class for the record. -/// -[ExcludeFromCodeCoverage] -public class SetLibraryBookReaderEnabledRequestFixture -{ - /// - /// Creates a random valid . - /// - /// Optional. The Id of the media library whose book reader is enabled or disabled. - /// Optional. The unique identifier of the plugin providing the book reader. - /// Optional. Whether the book reader should be enabled for the media library. - /// The created . - public SetLibraryBookReaderEnabledRequest Create( - Guid? libraryId = null, - Guid? pluginId = null, - bool? isEnabled = null) - { - return new SetLibraryBookReaderEnabledRequest(libraryId ?? Guid.NewGuid(), pluginId ?? Guid.NewGuid(), isEnabled ?? true); - } - - /// - /// Creates a list of . - /// - /// The number of elements to create. - /// The created list. - public List CreateMany(int count = 3) - { - return [.. Enumerable.Range(0, count).Select(_ => Create())]; - } -} diff --git a/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/Plugins/SetLibraryMetadataProviderEnabledRequestFixture.cs b/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/Plugins/SetLibraryMetadataProviderEnabledRequestFixture.cs deleted file mode 100644 index 2e47ed9c..00000000 --- a/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/Plugins/SetLibraryMetadataProviderEnabledRequestFixture.cs +++ /dev/null @@ -1,48 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using Bogus; -using Lumina.Contracts.Requests.Plugins; -using System; -using System.Collections.Generic; -using System.Diagnostics.CodeAnalysis; -using System.Linq; -#endregion - -namespace Lumina.Contracts.Fixtures.Core.Requests.Plugins; - -/// -/// Fixture class for the record. -/// -[ExcludeFromCodeCoverage] -public class SetLibraryMetadataProviderEnabledRequestFixture -{ - private readonly Faker _faker = new(); - - /// - /// Creates a random valid . - /// - /// Optional. The Id of the media library whose metadata provider is enabled or disabled. - /// Optional. The Id of the plugin providing the metadata. - /// Optional. Whether the metadata provider should be enabled. - /// The created . - public SetLibraryMetadataProviderEnabledRequest Create( - Guid? libraryId = null, - Guid? pluginId = null, - bool? isEnabled = null) - { - return new SetLibraryMetadataProviderEnabledRequest( - libraryId ?? _faker.Random.Guid(), - pluginId ?? _faker.Random.Guid(), - isEnabled ?? _faker.Random.Bool() - ); - } - - /// - /// Creates a list of . - /// - /// The number of elements to create. - /// The created list. - public List CreateMany(int count = 3) - { - return [.. Enumerable.Range(0, count).Select(_ => Create())]; - } -} diff --git a/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/Libraries/LibraryDtoFixture.cs b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/Libraries/LibraryDtoFixture.cs index 4fcd5780..896eda2f 100644 --- a/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/Libraries/LibraryDtoFixture.cs +++ b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/Libraries/LibraryDtoFixture.cs @@ -31,7 +31,6 @@ public class LibraryDtoFixture 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(), diff --git a/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/Libraries/LibraryProviderSelectionDtoFixture.cs b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/Libraries/LibraryProviderSelectionDtoFixture.cs new file mode 100644 index 00000000..6f631a1f --- /dev/null +++ b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/Libraries/LibraryProviderSelectionDtoFixture.cs @@ -0,0 +1,48 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Presentation.Web.Common.DTO.Libraries; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Presentation.Web.Fixtures.Common.DTO.Libraries; + +/// +/// Fixture class for the class. +/// +[ExcludeFromCodeCoverage] +public class LibraryProviderSelectionDtoFixture +{ + private readonly Faker _faker = new(); + + /// + /// Creates a random valid . + /// + /// Optional. The Id of the plugin providing the provider or reader. + /// Optional. Whether the provider or reader is enabled. + /// Whether the choice carries an enabled state. When , the enabled state is . + /// The created . + public LibraryProviderSelectionDto Create( + Guid? pluginId = null, + bool? isEnabled = null, + bool includeIsEnabled = true) + { + return new LibraryProviderSelectionDto + { + PluginId = pluginId ?? Guid.NewGuid(), + IsEnabled = includeIsEnabled ? isEnabled ?? _faker.Random.Bool() : null + }; + } + + /// + /// Creates a list of . + /// + /// The number of elements to create. + /// The created list. + public List CreateMany(int count = 3) + { + return [.. Enumerable.Range(0, count).Select(_ => Create())]; + } +} diff --git a/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/Library/Management/GetLibraryTypeArtworkProvidersRequestFixture.cs b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/Library/Management/GetLibraryTypeArtworkProvidersRequestFixture.cs new file mode 100644 index 00000000..c93cdf6f --- /dev/null +++ b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/Library/Management/GetLibraryTypeArtworkProvidersRequestFixture.cs @@ -0,0 +1,36 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Common.Requests.Library.Management; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Presentation.Web.Fixtures.Common.Requests.Library.Management; + +/// +/// Fixture class for the record. +/// +[ExcludeFromCodeCoverage] +public class GetLibraryTypeArtworkProvidersRequestFixture +{ + /// + /// Creates a random valid . + /// + /// Optional. The media library type whose available artwork providers are retrieved. + /// The created . + public GetLibraryTypeArtworkProvidersRequest Create( + string? libraryType = null) + { + return new GetLibraryTypeArtworkProvidersRequest(libraryType ?? "Book"); + } + + /// + /// Creates a list of . + /// + /// The number of elements to create. + /// The created list. + public List CreateMany(int count = 3) + { + return [.. Enumerable.Range(0, count).Select(_ => Create())]; + } +} diff --git a/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/Library/Management/GetLibraryTypeBookReadersRequestFixture.cs b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/Library/Management/GetLibraryTypeBookReadersRequestFixture.cs new file mode 100644 index 00000000..4acb383a --- /dev/null +++ b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/Library/Management/GetLibraryTypeBookReadersRequestFixture.cs @@ -0,0 +1,36 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Common.Requests.Library.Management; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Presentation.Web.Fixtures.Common.Requests.Library.Management; + +/// +/// Fixture class for the record. +/// +[ExcludeFromCodeCoverage] +public class GetLibraryTypeBookReadersRequestFixture +{ + /// + /// Creates a random valid . + /// + /// Optional. The media library type whose available book readers are retrieved. + /// The created . + public GetLibraryTypeBookReadersRequest Create( + string? libraryType = null) + { + return new GetLibraryTypeBookReadersRequest(libraryType ?? "Book"); + } + + /// + /// Creates a list of . + /// + /// The number of elements to create. + /// The created list. + public List CreateMany(int count = 3) + { + return [.. Enumerable.Range(0, count).Select(_ => Create())]; + } +} diff --git a/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/Library/Management/GetLibraryTypeMetadataProvidersRequestFixture.cs b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/Library/Management/GetLibraryTypeMetadataProvidersRequestFixture.cs new file mode 100644 index 00000000..2634e21f --- /dev/null +++ b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/Library/Management/GetLibraryTypeMetadataProvidersRequestFixture.cs @@ -0,0 +1,36 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Common.Requests.Library.Management; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Presentation.Web.Fixtures.Common.Requests.Library.Management; + +/// +/// Fixture class for the record. +/// +[ExcludeFromCodeCoverage] +public class GetLibraryTypeMetadataProvidersRequestFixture +{ + /// + /// Creates a random valid . + /// + /// Optional. The media library type whose available metadata providers are retrieved. + /// The created . + public GetLibraryTypeMetadataProvidersRequest Create( + string? libraryType = null) + { + return new GetLibraryTypeMetadataProvidersRequest(libraryType ?? "Book"); + } + + /// + /// Creates a list of . + /// + /// The number of elements to create. + /// The created list. + public List CreateMany(int count = 3) + { + return [.. Enumerable.Range(0, count).Select(_ => Create())]; + } +} diff --git a/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/Plugins/ReorderLibraryArtworkProvidersRequestFixture.cs b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/Plugins/ReorderLibraryArtworkProvidersRequestFixture.cs deleted file mode 100644 index d0cb7a97..00000000 --- a/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/Plugins/ReorderLibraryArtworkProvidersRequestFixture.cs +++ /dev/null @@ -1,45 +0,0 @@ -#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 the record. -/// -[ExcludeFromCodeCoverage] -public class ReorderLibraryArtworkProvidersRequestFixture -{ - private readonly Faker _faker = new(); - - /// - /// Creates a new instance with randomized test data. - /// - /// Optional identifier of the media library. - /// Optional plugin Ids in the new order. - /// A configured instance. - public ReorderLibraryArtworkProvidersRequest Create( - Guid? libraryId = null, - List? pluginIds = null) - { - return new ReorderLibraryArtworkProvidersRequest( - LibraryId: libraryId ?? Guid.NewGuid(), - PluginIds: pluginIds ?? [_faker.Random.Guid(), _faker.Random.Guid()] - ); - } - - /// - /// Creates multiple instances with randomized test data. - /// - /// Number of instances to create. - /// List of configured instances. - public List CreateMany(int count = 3) - { - return [.. Enumerable.Range(0, count).Select(_ => Create())]; - } -} diff --git a/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/Plugins/ReorderLibraryMetadataProvidersRequestFixture.cs b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/Plugins/ReorderLibraryMetadataProvidersRequestFixture.cs deleted file mode 100644 index c52dcdfc..00000000 --- a/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/Plugins/ReorderLibraryMetadataProvidersRequestFixture.cs +++ /dev/null @@ -1,45 +0,0 @@ -#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 the record. -/// -[ExcludeFromCodeCoverage] -public class ReorderLibraryMetadataProvidersRequestFixture -{ - private readonly Faker _faker = new(); - - /// - /// Creates a new instance with randomized test data. - /// - /// Optional identifier of the media library. - /// Optional plugin Ids in the new order. - /// A configured instance. - public ReorderLibraryMetadataProvidersRequest Create( - Guid? libraryId = null, - List? pluginIds = null) - { - return new ReorderLibraryMetadataProvidersRequest( - LibraryId: libraryId ?? Guid.NewGuid(), - PluginIds: pluginIds ?? [_faker.Random.Guid(), _faker.Random.Guid()] - ); - } - - /// - /// Creates multiple instances with randomized test data. - /// - /// Number of instances to create. - /// List of configured instances. - public List CreateMany(int count = 3) - { - return [.. Enumerable.Range(0, count).Select(_ => Create())]; - } -} diff --git a/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/Plugins/SetBookReaderEnabledRequestFixture.cs b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/Plugins/SetBookReaderEnabledRequestFixture.cs deleted file mode 100644 index 3e1047c5..00000000 --- a/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/Plugins/SetBookReaderEnabledRequestFixture.cs +++ /dev/null @@ -1,45 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -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 the record. -/// -[ExcludeFromCodeCoverage] -public class SetBookReaderEnabledRequestFixture -{ - /// - /// Creates a random valid . - /// - /// Optional. The Id of the media library whose book reader is enabled or disabled. - /// Optional. The unique identifier of the plugin providing the book reader. - /// Optional. Whether the book reader should be enabled for the media library. - /// The created . - public SetBookReaderEnabledRequest Create( - Guid? libraryId = null, - Guid? pluginId = null, - bool? isEnabled = null) - { - return new SetBookReaderEnabledRequest( - LibraryId: libraryId ?? Guid.NewGuid(), - PluginId: pluginId ?? Guid.NewGuid(), - IsEnabled: isEnabled ?? true - ); - } - - /// - /// Creates a list of . - /// - /// The number of elements to create. - /// The created list. - public List CreateMany(int count = 3) - { - return [.. Enumerable.Range(0, count).Select(_ => Create())]; - } -} diff --git a/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/Plugins/SetLibraryArtworkProviderEnabledRequestFixture.cs b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/Plugins/SetLibraryArtworkProviderEnabledRequestFixture.cs deleted file mode 100644 index db568e49..00000000 --- a/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/Plugins/SetLibraryArtworkProviderEnabledRequestFixture.cs +++ /dev/null @@ -1,48 +0,0 @@ -#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 the record. -/// -[ExcludeFromCodeCoverage] -public class SetLibraryArtworkProviderEnabledRequestFixture -{ - private readonly Faker _faker = new(); - - /// - /// Creates a new instance with randomized test data. - /// - /// Optional identifier of the media library. - /// Optional identifier of the plugin. - /// Optional value indicating whether the artwork provider is enabled. - /// A configured instance. - public SetLibraryArtworkProviderEnabledRequest Create( - Guid? libraryId = null, - Guid? pluginId = null, - bool? isEnabled = null) - { - return new SetLibraryArtworkProviderEnabledRequest( - LibraryId: libraryId ?? Guid.NewGuid(), - PluginId: pluginId ?? Guid.NewGuid(), - IsEnabled: isEnabled ?? _faker.Random.Bool() - ); - } - - /// - /// Creates multiple instances with randomized test data. - /// - /// Number of instances to create. - /// List of configured instances. - public List CreateMany(int count = 3) - { - return [.. Enumerable.Range(0, count).Select(_ => Create())]; - } -} diff --git a/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/Plugins/SetLibraryMetadataProviderEnabledRequestFixture.cs b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/Plugins/SetLibraryMetadataProviderEnabledRequestFixture.cs deleted file mode 100644 index fdf26cb3..00000000 --- a/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/Plugins/SetLibraryMetadataProviderEnabledRequestFixture.cs +++ /dev/null @@ -1,48 +0,0 @@ -#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 the record. -/// -[ExcludeFromCodeCoverage] -public class SetLibraryMetadataProviderEnabledRequestFixture -{ - private readonly Faker _faker = new(); - - /// - /// Creates a new instance with randomized test data. - /// - /// Optional identifier of the media library. - /// Optional identifier of the plugin. - /// Optional value indicating whether the metadata provider is enabled. - /// A configured instance. - public SetLibraryMetadataProviderEnabledRequest Create( - Guid? libraryId = null, - Guid? pluginId = null, - bool? isEnabled = null) - { - return new SetLibraryMetadataProviderEnabledRequest( - LibraryId: libraryId ?? Guid.NewGuid(), - PluginId: pluginId ?? Guid.NewGuid(), - IsEnabled: isEnabled ?? _faker.Random.Bool() - ); - } - - /// - /// Creates multiple instances with randomized test data. - /// - /// Number of instances to create. - /// List of configured instances. - public List CreateMany(int count = 3) - { - return [.. Enumerable.Range(0, count).Select(_ => Create())]; - } -} diff --git a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Common/Setup/AuthenticatedLuminaApiFactory.cs b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Common/Setup/AuthenticatedLuminaApiFactory.cs index da59de5a..c89d7987 100644 --- a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Common/Setup/AuthenticatedLuminaApiFactory.cs +++ b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Common/Setup/AuthenticatedLuminaApiFactory.cs @@ -1,11 +1,13 @@ #region ========================================================================= USING ===================================================================================== using Lumina.Application.Common.DataAccess.Entities.UsersManagement; using Lumina.Application.Common.DataAccess.Seed; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.Authorization; using Lumina.Application.Fixtures.Common.DataAccess.Entities.UsersManagement; using Lumina.Contracts.Fixtures.Core.Requests.Authentication; using Lumina.Contracts.Requests.Authentication; using Lumina.Contracts.Responses.Authentication; using Lumina.DataAccess.Core.UoW; +using Lumina.Domain.SharedKernel.Common.Enums.Authorization; using Lumina.Infrastructure.Core.Security; using Microsoft.Extensions.DependencyInjection; using System; @@ -33,6 +35,8 @@ public class AuthenticatedLuminaApiFactory : LuminaApiFactory, IDisposable PropertyNameCaseInsensitive = true }; private readonly UserEntityFixture _userEntityFixture = new(); + private readonly PermissionEntityFixture _permissionEntityFixture = new(); + private readonly UserPermissionEntityFixture _userPermissionEntityFixture = new(); private readonly LoginRequestFixture _loginRequestFixture = new(); /// @@ -43,17 +47,18 @@ public class AuthenticatedLuminaApiFactory : LuminaApiFactory, IDisposable /// /// Creates an HTTP client with authentication headers and a test user /// + /// The permissions granted directly to the test user, if any. /// An HTTP client configured with auth headers - public async Task CreateAuthenticatedClientAsync() + public async Task CreateAuthenticatedClientAsync(params AuthorizationPermission[] permissions) { HttpClient client = CreateClient(); TestUsername = $"testuser_{Guid.NewGuid()}"; - // add the X-Forwarded-For header + // Add the X-Forwarded-For header. client.DefaultRequestHeaders.Add("X-Forwarded-For", $"192.{Random.Shared.Next(0, 255)}.{Random.Shared.Next(0, 255)}.{Random.Shared.Next(0, 255)}"); - // perform authentication - await CreateAndAuthenticateUser(client); + // Perform authentication. + await CreateAndAuthenticateUser(client, permissions); return client; } @@ -62,20 +67,23 @@ public class AuthenticatedLuminaApiFactory : LuminaApiFactory, IDisposable /// Creates and authenticates a test user. /// /// The HTTP client to configure with auth. + /// The permissions granted directly to the test user. /// The created user entity. - private async Task CreateAndAuthenticateUser(HttpClient client) + private async Task CreateAndAuthenticateUser(HttpClient client, AuthorizationPermission[] permissions) { using IServiceScope scope = Services.CreateScope(); LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); - // create test user + // Create test user, with the permissions granted directly to it. UserEntity user = _userEntityFixture.Create(username: TestUsername!, password: _hashService.HashString("TestPass123!")); user.TotpSecret = null; + foreach (AuthorizationPermission permission in permissions) + user.UserPermissions.Add(_userPermissionEntityFixture.Create(user, _permissionEntityFixture.Create(permissionName: permission, createdBy: user.Id))); dbContext.Users.Add(user); await dbContext.SaveChangesAsync(); - // authenticate user + // Authenticate user. LoginRequest loginRequest = _loginRequestFixture.Create( username: user.Username, password: "TestPass123!", @@ -86,7 +94,7 @@ public class AuthenticatedLuminaApiFactory : LuminaApiFactory, IDisposable string content = await loginResponse.Content.ReadAsStringAsync(); LoginResponse? result = JsonSerializer.Deserialize(content, _jsonOptions); - // set auth header for subsequent requests + // Set auth header for subsequent requests. client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", result!.Token); return user; @@ -101,11 +109,11 @@ public class AuthenticatedLuminaApiFactory : LuminaApiFactory, IDisposable HttpClient client = CreateClient(); TestUsername = $"testuser_{Guid.NewGuid()}"; - // add the X-Forwarded-For header + // Add the X-Forwarded-For header. client.DefaultRequestHeaders.Add("X-Forwarded-For", $"192.{Random.Shared.Next(0, 255)}.{Random.Shared.Next(0, 255)}.{Random.Shared.Next(0, 255)}"); - // create and authenticate admin user + // Create and authenticate admin user. await CreateAndAuthenticateAdminUser(client); return client; @@ -122,20 +130,20 @@ public class AuthenticatedLuminaApiFactory : LuminaApiFactory, IDisposable LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); IDataSeedService dataSeedService = scope.ServiceProvider.GetRequiredService(); - // create test user + // Create test user. UserEntity user = _userEntityFixture.Create(username: TestUsername!, password: _hashService.HashString("TestPass123!")); user.TotpSecret = null; dbContext.Users.Add(user); await dbContext.SaveChangesAsync(); - // set up admin permissions and roles + // Set up admin permissions and roles. await dataSeedService.SetDefaultAuthorizationPermissionsAsync(user.Id, CancellationToken.None); await dataSeedService.SetDefaultAuthorizationRolesAsync(user.Id, CancellationToken.None); await dataSeedService.SetAdminRolePermissionsAsync(user.Id, CancellationToken.None); await dataSeedService.SetAdminRoleToAdministratorAccount(user.Id, CancellationToken.None); - // authenticate user + // Authenticate user. LoginRequest loginRequest = _loginRequestFixture.Create( username: user.Username, password: "TestPass123!", @@ -146,7 +154,7 @@ public class AuthenticatedLuminaApiFactory : LuminaApiFactory, IDisposable string content = await loginResponse.Content.ReadAsStringAsync(); LoginResponse? result = JsonSerializer.Deserialize(content, _jsonOptions); - // set auth header for subsequent requests + // Set auth header for subsequent requests. client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", result!.Token); return user; diff --git a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Library/Management/AddLibrary/AddLibraryEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Library/Management/AddLibrary/AddLibraryEndpointTests.cs index e8f615d3..a4f62d7c 100644 --- a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Library/Management/AddLibrary/AddLibraryEndpointTests.cs +++ b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Library/Management/AddLibrary/AddLibraryEndpointTests.cs @@ -10,6 +10,7 @@ using Lumina.Presentation.Api.IntegrationTests.Common.Setup; using Microsoft.AspNetCore.Http; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.DependencyInjection; +using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Linq; @@ -32,6 +33,7 @@ public class AddLibraryEndpointTests : IClassFixture candidate.Title == title)); } + [Fact] + public async Task AddLibrary_WhenAProviderChoiceNamesAnUnsupportedPlugin_ShouldReturnValidationProblemAndNotPersist() + { + // Arrange + string title = "Unsupported Provider Library"; + AddLibraryRequest request = _addLibraryRequestFixture.Create( + title: title, + libraryType: "Book", + contentLocations: ["C:/Media"], + coverImage: null, + metadataProviders: [_libraryProviderSelectionRequestFixture.Create(isEnabled: true)] + ); + + // Act + HttpResponseMessage response = await _client.PostAsJsonAsync("/api/v1/libraries", request); + + // Assert + await AssertValidationProblemAsync(response, "PluginNotSupportedForLibraryType"); + + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + Assert.False(await dbContext.Libraries.AnyAsync(candidate => candidate.Title == title)); + } + + [Fact] + public async Task AddLibrary_WhenAProviderChoiceIsNull_ShouldReturnValidationProblemAndNotPersist() + { + // Arrange + string title = "Null Provider Choice Library"; + AddLibraryRequest request = _addLibraryRequestFixture.Create( + title: title, + libraryType: "Book", + contentLocations: ["C:/Media"], + coverImage: null, + bookReaders: [null] + ); + + // Act + HttpResponseMessage response = await _client.PostAsJsonAsync("/api/v1/libraries", request); + + // Assert + await AssertValidationProblemAsync(response, "PluginIdCannotBeEmpty"); + + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + Assert.False(await dbContext.Libraries.AnyAsync(candidate => candidate.Title == title)); + } + + [Fact] + public async Task AddLibrary_WhenAPathTemplatePartIsNull_ShouldReturnValidationProblemAndNotPersist() + { + // Arrange + string title = "Null Path Template Part Library"; + AddLibraryRequest request = _addLibraryRequestFixture.Create( + title: title, + libraryType: "Book", + contentLocations: ["C:/Media"], + coverImage: null, + pathTemplateParts: [null] + ); + + // Act + HttpResponseMessage response = await _client.PostAsJsonAsync("/api/v1/libraries", request); + + // Assert + await AssertValidationProblemAsync(response, "PathTemplatePartKindNotSupportedForLibraryType"); + + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + Assert.False(await dbContext.Libraries.AnyAsync(candidate => candidate.Title == title)); + } + + [Fact] + public async Task AddLibrary_WhenProviderPluginIdsAreDuplicated_ShouldReturnValidationProblemAndNotPersist() + { + // Arrange + string title = "Duplicated Provider Library"; + Guid pluginId = Guid.NewGuid(); + AddLibraryRequest request = _addLibraryRequestFixture.Create( + title: title, + libraryType: "Book", + contentLocations: ["C:/Media"], + coverImage: null, + bookReaders: [_libraryProviderSelectionRequestFixture.Create(pluginId: pluginId), _libraryProviderSelectionRequestFixture.Create(pluginId: pluginId, isEnabled: false)] + ); + + // Act + HttpResponseMessage response = await _client.PostAsJsonAsync("/api/v1/libraries", request); + + // Assert + await AssertValidationProblemAsync(response, "PluginIdsMustBeUnique"); + + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + Assert.False(await dbContext.Libraries.AnyAsync(candidate => candidate.Title == title)); + } + + [Fact] + public async Task AddLibrary_WhenProviderChoicesAreEmpty_ShouldCreateLibrary() + { + // Arrange + string title = "Empty Provider Choices Library"; + AddLibraryRequest request = _addLibraryRequestFixture.Create( + title: title, + libraryType: "Book", + contentLocations: ["C:/Media"], + coverImage: null, + metadataProviders: [], + artworkProviders: [], + bookReaders: [] + ); + + // Act + HttpResponseMessage response = await _client.PostAsJsonAsync("/api/v1/libraries", request); + + // Assert + Assert.Equal(HttpStatusCode.Created, response.StatusCode); + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + Assert.True(await dbContext.Libraries.AnyAsync(candidate => candidate.Title == title)); + } + /// /// Asserts that carries the standard validation problem of the add library route. /// @@ -395,12 +519,12 @@ public class AddLibraryEndpointTests : IClassFixture(); - // clear junction tables first + // Clear junction tables first. await dbContext.Set().ExecuteDeleteAsync(); await dbContext.Set().ExecuteDeleteAsync(); await dbContext.Set().ExecuteDeleteAsync(); - // then clear main tables + // Then clear main tables. await dbContext.Set().ExecuteDeleteAsync(); await dbContext.Set().ExecuteDeleteAsync(); await dbContext.Set().ExecuteDeleteAsync(); diff --git a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Library/Management/DeleteLibrary/DeleteLibraryEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Library/Management/DeleteLibrary/DeleteLibraryEndpointTests.cs index c55d61f2..0bf11ce0 100644 --- a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Library/Management/DeleteLibrary/DeleteLibraryEndpointTests.cs +++ b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Library/Management/DeleteLibrary/DeleteLibraryEndpointTests.cs @@ -4,6 +4,7 @@ using Lumina.Application.Common.DataAccess.Entities.UsersManagement; using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management; using Lumina.Application.Fixtures.Common.DataAccess.Entities.UsersManagement; using Lumina.DataAccess.Core.UoW; +using Lumina.Domain.SharedKernel.Common.Enums.Authorization; using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; using Lumina.Presentation.Api.Core.Endpoints.Library.Management.DeleteLibrary; using Lumina.Presentation.Api.IntegrationTests.Common.Setup; @@ -54,7 +55,7 @@ public class DeleteLibraryEndpointTests : IClassFixture public async Task InitializeAsync() { - _client = await _apiFactory.CreateAuthenticatedClientAsync(); + _client = await _apiFactory.CreateAuthenticatedClientAsync(AuthorizationPermission.CanCreateLibraries); } [Fact] diff --git a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Library/Management/UpdateLibrary/UpdateLibraryEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Library/Management/UpdateLibrary/UpdateLibraryEndpointTests.cs index d73469a3..7ce5c05b 100644 --- a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Library/Management/UpdateLibrary/UpdateLibraryEndpointTests.cs +++ b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Library/Management/UpdateLibrary/UpdateLibraryEndpointTests.cs @@ -6,6 +6,7 @@ using Lumina.Contracts.Fixtures.Core.Requests.MediaLibrary.Management; using Lumina.Contracts.Requests.MediaLibrary.Management; using Lumina.Contracts.Responses.MediaLibrary.Management; using Lumina.DataAccess.Core.UoW; +using Lumina.Domain.SharedKernel.Common.Enums.Authorization; using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; using Lumina.Presentation.Api.Core.Endpoints.Library.Management.UpdateLibrary; using Lumina.Presentation.Api.IntegrationTests.Common.Setup; @@ -41,6 +42,7 @@ public class UpdateLibraryEndpointTests : IClassFixture /// Initializes a new instance of the class. @@ -57,7 +59,7 @@ public class UpdateLibraryEndpointTests : IClassFixture public async Task InitializeAsync() { - _client = await _apiFactory.CreateAuthenticatedClientAsync(); + _client = await _apiFactory.CreateAuthenticatedClientAsync(AuthorizationPermission.CanCreateLibraries); } [Fact] @@ -69,7 +71,6 @@ public class UpdateLibraryEndpointTests : IClassFixture(); + LibraryEntity? storedLibrary = await dbContext.Libraries.FirstOrDefaultAsync(candidate => candidate.Id == libraryId); + Assert.NotNull(storedLibrary); + Assert.Equal("Original Title", storedLibrary!.Title); + } + + [Fact] + public async Task UpdateLibrary_WhenProviderChoicesAreEmpty_ShouldUpdateTheLibrary() + { + // Arrange + Guid userId = GetCurrentUserId(); + Guid libraryId = Guid.NewGuid(); + await SeedLibraryAsync(libraryId, userId, "Original Title", shouldTrackConsumptionProgress: true, completionThresholdPercentage: 70); + UpdateLibraryRequest request = _updateLibraryRequestFixture.Create( + id: libraryId, + title: "Updated Title", + libraryType: "EBook", + contentLocations: ["C:/Media"], + coverImage: null, + shouldTrackConsumptionProgress: true, + completionThresholdPercentage: 70, + metadataProviders: [], + artworkProviders: [], + bookReaders: [] + ); + + // Act + HttpResponseMessage response = await _client.PutAsJsonAsync($"/api/v1/libraries/{libraryId}", request); + + // Assert + response.EnsureSuccessStatusCode(); + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + LibraryEntity? storedLibrary = await dbContext.Libraries.FirstOrDefaultAsync(candidate => candidate.Id == libraryId); + Assert.NotNull(storedLibrary); + Assert.Equal("Updated Title", storedLibrary!.Title); + } + /// /// Asserts that carries the standard validation problem of the update library route. /// diff --git a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Plugins/GetLibraryTypeArtworkProviders/GetLibraryTypeArtworkProvidersEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Plugins/GetLibraryTypeArtworkProviders/GetLibraryTypeArtworkProvidersEndpointTests.cs new file mode 100644 index 00000000..f8e83eea --- /dev/null +++ b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Plugins/GetLibraryTypeArtworkProviders/GetLibraryTypeArtworkProvidersEndpointTests.cs @@ -0,0 +1,112 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Contracts.Responses.Plugins; +using Lumina.Presentation.Api.Core.Endpoints.Plugins.GetLibraryTypeArtworkProviders; +using Lumina.Presentation.Api.IntegrationTests.Common.Setup; +using Microsoft.AspNetCore.Http; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Net; +using System.Net.Http; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Api.IntegrationTests.Core.Endpoints.Plugins.GetLibraryTypeArtworkProviders; + +/// +/// Contains integration tests for the class. +/// +[ExcludeFromCodeCoverage] +public class GetLibraryTypeArtworkProvidersEndpointTests : IClassFixture, IAsyncLifetime +{ + private HttpClient _client; + private readonly AuthenticatedLuminaApiFactory _apiFactory; + private readonly JsonSerializerOptions _jsonOptions = new() + { + PropertyNameCaseInsensitive = true, + Converters = { new JsonStringEnumConverter(JsonNamingPolicy.CamelCase) } + }; + + /// + /// Initializes a new instance of the class. + /// + /// Injected in-memory API factory. + public GetLibraryTypeArtworkProvidersEndpointTests(AuthenticatedLuminaApiFactory apiFactory) + { + _client = apiFactory.CreateClient(); + _apiFactory = apiFactory; + } + + /// + /// Initializes authenticated API client. + /// + public async Task InitializeAsync() + { + _client = await _apiFactory.CreateAuthenticatedClientAsync(); + } + + [Theory] + [InlineData("Book")] + [InlineData("music")] // The casing of the type is ignored. + public async Task GetLibraryTypeArtworkProviders_WhenLibraryTypeIsValid_ShouldReturnOkWithTheAvailableProviders(string libraryType) + { + // Act + HttpResponseMessage response = await _client.GetAsync($"/api/v1/libraries/artwork-providers/{libraryType}"); + + // Assert + response.EnsureSuccessStatusCode(); + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + string content = await response.Content.ReadAsStringAsync(); + List? providers = JsonSerializer.Deserialize>(content, _jsonOptions); + Assert.NotNull(providers); + // The test host loads no plugins, so no provider supports the type; every provider that is returned starts disabled. + Assert.All(providers!, provider => Assert.False(provider.IsEnabled)); + } + + [Fact] + public async Task GetLibraryTypeArtworkProviders_WhenLibraryTypeIsUnknown_ShouldReturnProblemResult() + { + // Arrange + string libraryType = "NotARealLibraryType"; + + // Act + HttpResponseMessage response = await _client.GetAsync($"/api/v1/libraries/artwork-providers/{libraryType}"); + + // Assert + Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode); + string content = await response.Content.ReadAsStringAsync(); + Dictionary? problemDetails = JsonSerializer.Deserialize>(content, _jsonOptions); + Assert.NotNull(problemDetails); + Assert.Equal(StatusCodes.Status422UnprocessableEntity, problemDetails!["status"].GetInt32()); + Assert.Equal("https://tools.ietf.org/html/rfc4918#section-11.2", problemDetails["type"].GetString()); + Assert.Equal("General.Validation", problemDetails["title"].GetString()); + Assert.Equal("OneOrMoreValidationErrorsOccurred", problemDetails["detail"].GetString()); + Dictionary? errors = problemDetails["errors"].Deserialize>(_jsonOptions); + Assert.NotNull(errors); + Assert.Contains("UnknownLibraryType", errors!["General.Validation"]); + Assert.Equal($"/api/v1/libraries/artwork-providers/{libraryType}", problemDetails["instance"].GetString()); + Assert.False(string.IsNullOrEmpty(problemDetails["traceId"].GetString())); + } + + [Fact] + public async Task GetLibraryTypeArtworkProviders_WhenUnauthorized_ShouldReturnUnauthorizedResult() + { + // Arrange + HttpClient unauthenticatedClient = _apiFactory.CreateClient(); + + // Act + HttpResponseMessage response = await unauthenticatedClient.GetAsync("/api/v1/libraries/artwork-providers/Book"); + + // Assert + Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode); + } + + /// + /// Disposes API factory resources. + /// + public async Task DisposeAsync() + { + await _apiFactory.RemoveTestUserAsync(); + } +} diff --git a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Plugins/GetLibraryTypeBookReaders/GetLibraryTypeBookReadersEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Plugins/GetLibraryTypeBookReaders/GetLibraryTypeBookReadersEndpointTests.cs new file mode 100644 index 00000000..ea4ab772 --- /dev/null +++ b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Plugins/GetLibraryTypeBookReaders/GetLibraryTypeBookReadersEndpointTests.cs @@ -0,0 +1,112 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Contracts.Responses.Plugins; +using Lumina.Presentation.Api.Core.Endpoints.Plugins.GetLibraryTypeBookReaders; +using Lumina.Presentation.Api.IntegrationTests.Common.Setup; +using Microsoft.AspNetCore.Http; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Net; +using System.Net.Http; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Api.IntegrationTests.Core.Endpoints.Plugins.GetLibraryTypeBookReaders; + +/// +/// Contains integration tests for the class. +/// +[ExcludeFromCodeCoverage] +public class GetLibraryTypeBookReadersEndpointTests : IClassFixture, IAsyncLifetime +{ + private HttpClient _client; + private readonly AuthenticatedLuminaApiFactory _apiFactory; + private readonly JsonSerializerOptions _jsonOptions = new() + { + PropertyNameCaseInsensitive = true, + Converters = { new JsonStringEnumConverter(JsonNamingPolicy.CamelCase) } + }; + + /// + /// Initializes a new instance of the class. + /// + /// Injected in-memory API factory. + public GetLibraryTypeBookReadersEndpointTests(AuthenticatedLuminaApiFactory apiFactory) + { + _client = apiFactory.CreateClient(); + _apiFactory = apiFactory; + } + + /// + /// Initializes authenticated API client. + /// + public async Task InitializeAsync() + { + _client = await _apiFactory.CreateAuthenticatedClientAsync(); + } + + [Theory] + [InlineData("Book")] + [InlineData("music")] // The casing of the type is ignored. + public async Task GetLibraryTypeBookReaders_WhenLibraryTypeIsValid_ShouldReturnOkWithTheAvailableReaders(string libraryType) + { + // Act + HttpResponseMessage response = await _client.GetAsync($"/api/v1/libraries/book-readers/{libraryType}"); + + // Assert + response.EnsureSuccessStatusCode(); + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + string content = await response.Content.ReadAsStringAsync(); + List? readers = JsonSerializer.Deserialize>(content, _jsonOptions); + Assert.NotNull(readers); + // The test host loads no plugins, so no reader supports the type; every reader that is returned starts disabled. + Assert.All(readers!, reader => Assert.False(reader.IsEnabled)); + } + + [Fact] + public async Task GetLibraryTypeBookReaders_WhenLibraryTypeIsUnknown_ShouldReturnProblemResult() + { + // Arrange + string libraryType = "NotARealLibraryType"; + + // Act + HttpResponseMessage response = await _client.GetAsync($"/api/v1/libraries/book-readers/{libraryType}"); + + // Assert + Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode); + string content = await response.Content.ReadAsStringAsync(); + Dictionary? problemDetails = JsonSerializer.Deserialize>(content, _jsonOptions); + Assert.NotNull(problemDetails); + Assert.Equal(StatusCodes.Status422UnprocessableEntity, problemDetails!["status"].GetInt32()); + Assert.Equal("https://tools.ietf.org/html/rfc4918#section-11.2", problemDetails["type"].GetString()); + Assert.Equal("General.Validation", problemDetails["title"].GetString()); + Assert.Equal("OneOrMoreValidationErrorsOccurred", problemDetails["detail"].GetString()); + Dictionary? errors = problemDetails["errors"].Deserialize>(_jsonOptions); + Assert.NotNull(errors); + Assert.Contains("UnknownLibraryType", errors!["General.Validation"]); + Assert.Equal($"/api/v1/libraries/book-readers/{libraryType}", problemDetails["instance"].GetString()); + Assert.False(string.IsNullOrEmpty(problemDetails["traceId"].GetString())); + } + + [Fact] + public async Task GetLibraryTypeBookReaders_WhenUnauthorized_ShouldReturnUnauthorizedResult() + { + // Arrange + HttpClient unauthenticatedClient = _apiFactory.CreateClient(); + + // Act + HttpResponseMessage response = await unauthenticatedClient.GetAsync("/api/v1/libraries/book-readers/Book"); + + // Assert + Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode); + } + + /// + /// Disposes API factory resources. + /// + public async Task DisposeAsync() + { + await _apiFactory.RemoveTestUserAsync(); + } +} diff --git a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Plugins/GetLibraryTypeMetadataProviders/GetLibraryTypeMetadataProvidersEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Plugins/GetLibraryTypeMetadataProviders/GetLibraryTypeMetadataProvidersEndpointTests.cs new file mode 100644 index 00000000..73af45cb --- /dev/null +++ b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Plugins/GetLibraryTypeMetadataProviders/GetLibraryTypeMetadataProvidersEndpointTests.cs @@ -0,0 +1,112 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Contracts.Responses.Plugins; +using Lumina.Presentation.Api.Core.Endpoints.Plugins.GetLibraryTypeMetadataProviders; +using Lumina.Presentation.Api.IntegrationTests.Common.Setup; +using Microsoft.AspNetCore.Http; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Net; +using System.Net.Http; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Api.IntegrationTests.Core.Endpoints.Plugins.GetLibraryTypeMetadataProviders; + +/// +/// Contains integration tests for the class. +/// +[ExcludeFromCodeCoverage] +public class GetLibraryTypeMetadataProvidersEndpointTests : IClassFixture, IAsyncLifetime +{ + private HttpClient _client; + private readonly AuthenticatedLuminaApiFactory _apiFactory; + private readonly JsonSerializerOptions _jsonOptions = new() + { + PropertyNameCaseInsensitive = true, + Converters = { new JsonStringEnumConverter(JsonNamingPolicy.CamelCase) } + }; + + /// + /// Initializes a new instance of the class. + /// + /// Injected in-memory API factory. + public GetLibraryTypeMetadataProvidersEndpointTests(AuthenticatedLuminaApiFactory apiFactory) + { + _client = apiFactory.CreateClient(); + _apiFactory = apiFactory; + } + + /// + /// Initializes authenticated API client. + /// + public async Task InitializeAsync() + { + _client = await _apiFactory.CreateAuthenticatedClientAsync(); + } + + [Theory] + [InlineData("Book")] + [InlineData("music")] // The casing of the type is ignored. + public async Task GetLibraryTypeMetadataProviders_WhenLibraryTypeIsValid_ShouldReturnOkWithTheAvailableProviders(string libraryType) + { + // Act + HttpResponseMessage response = await _client.GetAsync($"/api/v1/libraries/metadata-providers/{libraryType}"); + + // Assert + response.EnsureSuccessStatusCode(); + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + string content = await response.Content.ReadAsStringAsync(); + List? providers = JsonSerializer.Deserialize>(content, _jsonOptions); + Assert.NotNull(providers); + // The test host loads no plugins, so no provider supports the type; every provider that is returned starts disabled. + Assert.All(providers!, provider => Assert.False(provider.IsEnabled)); + } + + [Fact] + public async Task GetLibraryTypeMetadataProviders_WhenLibraryTypeIsUnknown_ShouldReturnProblemResult() + { + // Arrange + string libraryType = "NotARealLibraryType"; + + // Act + HttpResponseMessage response = await _client.GetAsync($"/api/v1/libraries/metadata-providers/{libraryType}"); + + // Assert + Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode); + string content = await response.Content.ReadAsStringAsync(); + Dictionary? problemDetails = JsonSerializer.Deserialize>(content, _jsonOptions); + Assert.NotNull(problemDetails); + Assert.Equal(StatusCodes.Status422UnprocessableEntity, problemDetails!["status"].GetInt32()); + Assert.Equal("https://tools.ietf.org/html/rfc4918#section-11.2", problemDetails["type"].GetString()); + Assert.Equal("General.Validation", problemDetails["title"].GetString()); + Assert.Equal("OneOrMoreValidationErrorsOccurred", problemDetails["detail"].GetString()); + Dictionary? errors = problemDetails["errors"].Deserialize>(_jsonOptions); + Assert.NotNull(errors); + Assert.Contains("UnknownLibraryType", errors!["General.Validation"]); + Assert.Equal($"/api/v1/libraries/metadata-providers/{libraryType}", problemDetails["instance"].GetString()); + Assert.False(string.IsNullOrEmpty(problemDetails["traceId"].GetString())); + } + + [Fact] + public async Task GetLibraryTypeMetadataProviders_WhenUnauthorized_ShouldReturnUnauthorizedResult() + { + // Arrange + HttpClient unauthenticatedClient = _apiFactory.CreateClient(); + + // Act + HttpResponseMessage response = await unauthenticatedClient.GetAsync("/api/v1/libraries/metadata-providers/Book"); + + // Assert + Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode); + } + + /// + /// Disposes API factory resources. + /// + public async Task DisposeAsync() + { + await _apiFactory.RemoveTestUserAsync(); + } +} diff --git a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Plugins/ReorderLibraryArtworkProviders/ReorderLibraryArtworkProvidersEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Plugins/ReorderLibraryArtworkProviders/ReorderLibraryArtworkProvidersEndpointTests.cs deleted file mode 100644 index 6887dc59..00000000 --- a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Plugins/ReorderLibraryArtworkProviders/ReorderLibraryArtworkProvidersEndpointTests.cs +++ /dev/null @@ -1,140 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using Lumina.Application.Common.DataAccess.Entities.Plugins; -using Lumina.Application.Common.DataAccess.Entities.UsersManagement; -using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management; -using Lumina.Application.Fixtures.Common.DataAccess.Entities.Plugins; -using Lumina.Contracts.Fixtures.Core.Requests.Plugins; -using Lumina.Contracts.Requests.Plugins; -using Lumina.DataAccess.Core.UoW; -using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; -using Lumina.Presentation.Api.Core.Endpoints.Plugins.ReorderLibraryArtworkProviders; -using Lumina.Presentation.Api.IntegrationTests.Common.Setup; -using Microsoft.EntityFrameworkCore; -using Microsoft.Extensions.DependencyInjection; -using System; -using System.Collections.Generic; -using System.Diagnostics.CodeAnalysis; -using System.Linq; -using System.Net; -using System.Net.Http; -using System.Net.Http.Json; -using System.Threading.Tasks; -#endregion - -namespace Lumina.Presentation.Api.IntegrationTests.Core.Endpoints.Plugins.ReorderLibraryArtworkProviders; - -/// -/// Contains integration tests for the class. -/// -[ExcludeFromCodeCoverage] -public class ReorderLibraryArtworkProvidersEndpointTests : IClassFixture, IAsyncLifetime -{ - private HttpClient _client; - private readonly AuthenticatedLuminaApiFactory _apiFactory; - private readonly LibraryEntityFixture _libraryEntityFixture = new(); - private readonly LibraryArtworkProviderConfigurationEntityFixture _libraryArtworkProviderConfigurationEntityFixture = new(); - private readonly ReorderLibraryArtworkProvidersRequestFixture _reorderLibraryArtworkProvidersRequestFixture = new(); - - /// - /// Initializes a new instance of the class. - /// - /// Injected in-memory API factory. - public ReorderLibraryArtworkProvidersEndpointTests(AuthenticatedLuminaApiFactory apiFactory) - { - _client = apiFactory.CreateClient(); - _apiFactory = apiFactory; - } - - /// - /// Initializes authenticated API client. - /// - public async Task InitializeAsync() - { - _client = await _apiFactory.CreateAuthenticatedClientAsync(); - } - - [Fact] - public async Task ReorderLibraryArtworkProviders_WhenCalledWithValidData_ShouldReorderTheProviders() - { - // Arrange - Guid userId = GetCurrentUserId(); - Guid libraryId = Guid.NewGuid(); - await SeedLibraryAsync(libraryId, userId); - Guid pluginIdA = Guid.NewGuid(); - Guid pluginIdB = Guid.NewGuid(); - await SeedConfigurationAsync(libraryId, pluginIdA, rank: 1); - await SeedConfigurationAsync(libraryId, pluginIdB, rank: 2); - ReorderLibraryArtworkProvidersRequest request = _reorderLibraryArtworkProvidersRequestFixture.Create( - libraryId: libraryId, - pluginIds: [pluginIdB, pluginIdA] - ); - - // Act - HttpResponseMessage response = await _client.PutAsJsonAsync($"/api/v1/libraries/{libraryId}/artwork-providers/reorder", request); - - // Assert - response.EnsureSuccessStatusCode(); - Assert.Equal(HttpStatusCode.OK, response.StatusCode); - - using IServiceScope scope = _apiFactory.Services.CreateScope(); - LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); - List configurations = await dbContext.LibraryArtworkProviderConfigurations - .Where(config => config.LibraryId == libraryId) - .OrderBy(config => config.Rank) - .ToListAsync(); - Assert.Equal(2, configurations.Count); - Assert.Equal(pluginIdB, configurations[0].PluginId); - Assert.Equal(1, configurations[0].Rank); - Assert.Equal(pluginIdA, configurations[1].PluginId); - Assert.Equal(2, configurations[1].Rank); - } - - /// - /// Seeds a owned by . - /// - /// The Id of the library to seed. - /// The Id of the user that owns the library. - /// A task representing the asynchronous operation. - private async Task SeedLibraryAsync(Guid libraryId, Guid userId) - { - using IServiceScope scope = _apiFactory.Services.CreateScope(); - LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); - dbContext.Libraries.Add(_libraryEntityFixture.Create(id: libraryId, userId: userId, title: "Test Library", libraryType: LibraryType.EBook, contentLocations: [])); - await dbContext.SaveChangesAsync(); - } - - /// - /// Seeds a in the database. - /// - /// The Id of the media library. - /// The Id of the plugin. - /// The rank of the provider. - /// A task representing the asynchronous operation. - private async Task SeedConfigurationAsync(Guid libraryId, Guid pluginId, int rank) - { - using IServiceScope scope = _apiFactory.Services.CreateScope(); - LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); - dbContext.LibraryArtworkProviderConfigurations.Add(_libraryArtworkProviderConfigurationEntityFixture.Create(libraryId: libraryId, pluginId: pluginId, rank: rank)); - await dbContext.SaveChangesAsync(); - } - - /// - /// Gets the Id of the currently authenticated test user. - /// - /// The Id of the authenticated test user. - private Guid GetCurrentUserId() - { - using IServiceScope scope = _apiFactory.Services.CreateScope(); - LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); - UserEntity user = dbContext.Users.First(user => user.Username == _apiFactory.TestUsername); - return user.Id; - } - - /// - /// Disposes API factory resources. - /// - public async Task DisposeAsync() - { - await _apiFactory.RemoveTestUserAsync(); - } -} diff --git a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Plugins/ReorderLibraryMetadataProviders/ReorderLibraryMetadataProvidersEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Plugins/ReorderLibraryMetadataProviders/ReorderLibraryMetadataProvidersEndpointTests.cs deleted file mode 100644 index e71c05ac..00000000 --- a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Plugins/ReorderLibraryMetadataProviders/ReorderLibraryMetadataProvidersEndpointTests.cs +++ /dev/null @@ -1,140 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using Lumina.Application.Common.DataAccess.Entities.Plugins; -using Lumina.Application.Common.DataAccess.Entities.UsersManagement; -using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management; -using Lumina.Application.Fixtures.Common.DataAccess.Entities.Plugins; -using Lumina.Contracts.Fixtures.Core.Requests.Plugins; -using Lumina.Contracts.Requests.Plugins; -using Lumina.DataAccess.Core.UoW; -using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; -using Lumina.Presentation.Api.Core.Endpoints.Plugins.ReorderLibraryMetadataProviders; -using Lumina.Presentation.Api.IntegrationTests.Common.Setup; -using Microsoft.EntityFrameworkCore; -using Microsoft.Extensions.DependencyInjection; -using System; -using System.Collections.Generic; -using System.Diagnostics.CodeAnalysis; -using System.Linq; -using System.Net; -using System.Net.Http; -using System.Net.Http.Json; -using System.Threading.Tasks; -#endregion - -namespace Lumina.Presentation.Api.IntegrationTests.Core.Endpoints.Plugins.ReorderLibraryMetadataProviders; - -/// -/// Contains integration tests for the class. -/// -[ExcludeFromCodeCoverage] -public class ReorderLibraryMetadataProvidersEndpointTests : IClassFixture, IAsyncLifetime -{ - private HttpClient _client; - private readonly AuthenticatedLuminaApiFactory _apiFactory; - private readonly LibraryEntityFixture _libraryEntityFixture = new(); - private readonly LibraryMetadataProviderConfigurationEntityFixture _libraryMetadataProviderConfigurationEntityFixture = new(); - private readonly ReorderLibraryMetadataProvidersRequestFixture _reorderLibraryMetadataProvidersRequestFixture = new(); - - /// - /// Initializes a new instance of the class. - /// - /// Injected in-memory API factory. - public ReorderLibraryMetadataProvidersEndpointTests(AuthenticatedLuminaApiFactory apiFactory) - { - _client = apiFactory.CreateClient(); - _apiFactory = apiFactory; - } - - /// - /// Initializes authenticated API client. - /// - public async Task InitializeAsync() - { - _client = await _apiFactory.CreateAuthenticatedClientAsync(); - } - - [Fact] - public async Task ReorderLibraryMetadataProviders_WhenCalledWithValidData_ShouldReorderTheProviders() - { - // Arrange - Guid userId = GetCurrentUserId(); - Guid libraryId = Guid.NewGuid(); - await SeedLibraryAsync(libraryId, userId); - Guid pluginIdA = Guid.NewGuid(); - Guid pluginIdB = Guid.NewGuid(); - await SeedConfigurationAsync(libraryId, pluginIdA, rank: 1); - await SeedConfigurationAsync(libraryId, pluginIdB, rank: 2); - ReorderLibraryMetadataProvidersRequest request = _reorderLibraryMetadataProvidersRequestFixture.Create( - libraryId: libraryId, - pluginIds: [pluginIdB, pluginIdA] - ); - - // Act - HttpResponseMessage response = await _client.PutAsJsonAsync($"/api/v1/libraries/{libraryId}/metadata-providers/reorder", request); - - // Assert - response.EnsureSuccessStatusCode(); - Assert.Equal(HttpStatusCode.OK, response.StatusCode); - - using IServiceScope scope = _apiFactory.Services.CreateScope(); - LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); - List configurations = await dbContext.LibraryMetadataProviderConfigurations - .Where(config => config.LibraryId == libraryId) - .OrderBy(config => config.Rank) - .ToListAsync(); - Assert.Equal(2, configurations.Count); - Assert.Equal(pluginIdB, configurations[0].PluginId); - Assert.Equal(1, configurations[0].Rank); - Assert.Equal(pluginIdA, configurations[1].PluginId); - Assert.Equal(2, configurations[1].Rank); - } - - /// - /// Seeds a owned by . - /// - /// The Id of the library to seed. - /// The Id of the user that owns the library. - /// A task representing the asynchronous operation. - private async Task SeedLibraryAsync(Guid libraryId, Guid userId) - { - using IServiceScope scope = _apiFactory.Services.CreateScope(); - LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); - dbContext.Libraries.Add(_libraryEntityFixture.Create(id: libraryId, userId: userId, title: "Test Library", libraryType: LibraryType.EBook, contentLocations: [])); - await dbContext.SaveChangesAsync(); - } - - /// - /// Seeds a in the database. - /// - /// The Id of the media library. - /// The Id of the plugin. - /// The rank of the provider. - /// A task representing the asynchronous operation. - private async Task SeedConfigurationAsync(Guid libraryId, Guid pluginId, int rank) - { - using IServiceScope scope = _apiFactory.Services.CreateScope(); - LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); - dbContext.LibraryMetadataProviderConfigurations.Add(_libraryMetadataProviderConfigurationEntityFixture.Create(libraryId: libraryId, pluginId: pluginId, rank: rank)); - await dbContext.SaveChangesAsync(); - } - - /// - /// Gets the Id of the currently authenticated test user. - /// - /// The Id of the authenticated test user. - private Guid GetCurrentUserId() - { - using IServiceScope scope = _apiFactory.Services.CreateScope(); - LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); - UserEntity user = dbContext.Users.First(user => user.Username == _apiFactory.TestUsername); - return user.Id; - } - - /// - /// Disposes API factory resources. - /// - public async Task DisposeAsync() - { - await _apiFactory.RemoveTestUserAsync(); - } -} diff --git a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Plugins/SetLibraryArtworkProviderEnabled/SetLibraryArtworkProviderEnabledEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Plugins/SetLibraryArtworkProviderEnabled/SetLibraryArtworkProviderEnabledEndpointTests.cs deleted file mode 100644 index a8d33410..00000000 --- a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Plugins/SetLibraryArtworkProviderEnabled/SetLibraryArtworkProviderEnabledEndpointTests.cs +++ /dev/null @@ -1,156 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using Lumina.Application.Common.DataAccess.Entities.Plugins; -using Lumina.Application.Common.DataAccess.Entities.UsersManagement; -using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management; -using Lumina.Application.Fixtures.Common.DataAccess.Entities.Plugins; -using Lumina.Contracts.Fixtures.Core.Requests.Plugins; -using Lumina.Contracts.Requests.Plugins; -using Lumina.DataAccess.Core.UoW; -using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; -using Lumina.Presentation.Api.Core.Endpoints.Plugins.SetLibraryArtworkProviderEnabled; -using Lumina.Presentation.Api.IntegrationTests.Common.Setup; -using Microsoft.EntityFrameworkCore; -using Microsoft.Extensions.DependencyInjection; -using System; -using System.Diagnostics.CodeAnalysis; -using System.Linq; -using System.Net; -using System.Net.Http; -using System.Net.Http.Json; -using System.Threading.Tasks; -#endregion - -namespace Lumina.Presentation.Api.IntegrationTests.Core.Endpoints.Plugins.SetLibraryArtworkProviderEnabled; - -/// -/// Contains integration tests for the class. -/// -[ExcludeFromCodeCoverage] -public class SetLibraryArtworkProviderEnabledEndpointTests : IClassFixture, IAsyncLifetime -{ - private HttpClient _client; - private readonly AuthenticatedLuminaApiFactory _apiFactory; - private readonly LibraryEntityFixture _libraryEntityFixture = new(); - private readonly LibraryArtworkProviderConfigurationEntityFixture _libraryArtworkProviderConfigurationEntityFixture = new(); - private readonly SetLibraryArtworkProviderEnabledRequestFixture _setLibraryArtworkProviderEnabledRequestFixture = new(); - - /// - /// Initializes a new instance of the class. - /// - /// Injected in-memory API factory. - public SetLibraryArtworkProviderEnabledEndpointTests(AuthenticatedLuminaApiFactory apiFactory) - { - _client = apiFactory.CreateClient(); - _apiFactory = apiFactory; - } - - /// - /// Initializes authenticated API client. - /// - public async Task InitializeAsync() - { - _client = await _apiFactory.CreateAuthenticatedClientAsync(); - } - - [Fact] - public async Task SetLibraryArtworkProviderEnabled_WhenNoConfigurationExists_ShouldCreateIt() - { - // Arrange - Guid userId = GetCurrentUserId(); - Guid libraryId = Guid.NewGuid(); - await SeedLibraryAsync(libraryId, userId); - Guid pluginId = Guid.NewGuid(); - SetLibraryArtworkProviderEnabledRequest request = _setLibraryArtworkProviderEnabledRequestFixture.Create(libraryId: libraryId, pluginId: pluginId, isEnabled: true); - - // Act - HttpResponseMessage response = await _client.PutAsJsonAsync($"/api/v1/libraries/{libraryId}/artwork-providers/{pluginId}/enabled", request); - - // Assert - response.EnsureSuccessStatusCode(); - Assert.Equal(HttpStatusCode.OK, response.StatusCode); - - using IServiceScope scope = _apiFactory.Services.CreateScope(); - LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); - LibraryArtworkProviderConfigurationEntity? configuration = await dbContext.LibraryArtworkProviderConfigurations - .FirstOrDefaultAsync(config => config.LibraryId == libraryId && config.PluginId == pluginId); - Assert.NotNull(configuration); - Assert.True(configuration!.IsEnabled); - Assert.Equal(1, configuration.Rank); - } - - [Fact] - public async Task SetLibraryArtworkProviderEnabled_WhenConfigurationExists_ShouldUpdateItsEnabledState() - { - // Arrange - Guid userId = GetCurrentUserId(); - Guid libraryId = Guid.NewGuid(); - await SeedLibraryAsync(libraryId, userId); - Guid pluginId = Guid.NewGuid(); - await SeedConfigurationAsync(libraryId, pluginId, isEnabled: false, rank: 1); - SetLibraryArtworkProviderEnabledRequest request = _setLibraryArtworkProviderEnabledRequestFixture.Create(libraryId: libraryId, pluginId: pluginId, isEnabled: true); - - // Act - HttpResponseMessage response = await _client.PutAsJsonAsync($"/api/v1/libraries/{libraryId}/artwork-providers/{pluginId}/enabled", request); - - // Assert - response.EnsureSuccessStatusCode(); - Assert.Equal(HttpStatusCode.OK, response.StatusCode); - - using IServiceScope scope = _apiFactory.Services.CreateScope(); - LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); - LibraryArtworkProviderConfigurationEntity? configuration = await dbContext.LibraryArtworkProviderConfigurations - .FirstOrDefaultAsync(config => config.LibraryId == libraryId && config.PluginId == pluginId); - Assert.NotNull(configuration); - Assert.True(configuration!.IsEnabled); - } - - /// - /// Seeds a owned by . - /// - /// The Id of the library to seed. - /// The Id of the user that owns the library. - /// A task representing the asynchronous operation. - private async Task SeedLibraryAsync(Guid libraryId, Guid userId) - { - using IServiceScope scope = _apiFactory.Services.CreateScope(); - LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); - dbContext.Libraries.Add(_libraryEntityFixture.Create(id: libraryId, userId: userId, title: "Test Library", libraryType: LibraryType.EBook, contentLocations: [])); - await dbContext.SaveChangesAsync(); - } - - /// - /// Seeds a in the database. - /// - /// The Id of the media library. - /// The Id of the plugin. - /// Whether the provider is enabled. - /// The rank of the provider. - /// A task representing the asynchronous operation. - private async Task SeedConfigurationAsync(Guid libraryId, Guid pluginId, bool isEnabled, int rank) - { - using IServiceScope scope = _apiFactory.Services.CreateScope(); - LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); - dbContext.LibraryArtworkProviderConfigurations.Add(_libraryArtworkProviderConfigurationEntityFixture.Create(libraryId: libraryId, pluginId: pluginId, rank: rank, isEnabled: isEnabled)); - await dbContext.SaveChangesAsync(); - } - - /// - /// Gets the Id of the currently authenticated test user. - /// - /// The Id of the authenticated test user. - private Guid GetCurrentUserId() - { - using IServiceScope scope = _apiFactory.Services.CreateScope(); - LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); - UserEntity user = dbContext.Users.First(user => user.Username == _apiFactory.TestUsername); - return user.Id; - } - - /// - /// Disposes API factory resources. - /// - public async Task DisposeAsync() - { - await _apiFactory.RemoveTestUserAsync(); - } -} diff --git a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Plugins/SetLibraryBookReaderEnabled/SetLibraryBookReaderEnabledEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Plugins/SetLibraryBookReaderEnabled/SetLibraryBookReaderEnabledEndpointTests.cs deleted file mode 100644 index 5d6bfd50..00000000 --- a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Plugins/SetLibraryBookReaderEnabled/SetLibraryBookReaderEnabledEndpointTests.cs +++ /dev/null @@ -1,199 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management; -using Lumina.Application.Common.DataAccess.Entities.Plugins; -using Lumina.Application.Common.DataAccess.Entities.UsersManagement; -using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management; -using Lumina.Application.Fixtures.Common.DataAccess.Entities.Plugins; -using Lumina.Application.Fixtures.Common.DataAccess.Entities.UsersManagement; -using Lumina.Contracts.Fixtures.Core.Requests.Plugins; -using Lumina.Contracts.Requests.Plugins; -using Lumina.DataAccess.Core.UoW; -using Lumina.Presentation.Api.IntegrationTests.Common.Setup; -using Microsoft.EntityFrameworkCore; -using Microsoft.Extensions.DependencyInjection; -using System; -using System.Diagnostics.CodeAnalysis; -using System.Linq; -using System.Net; -using System.Net.Http; -using System.Net.Http.Json; -using System.Threading.Tasks; -#endregion - -namespace Lumina.Presentation.Api.IntegrationTests.Core.Endpoints.Plugins.SetLibraryBookReaderEnabled; - -/// -/// Contains integration tests for the class. -/// -[ExcludeFromCodeCoverage] -public class SetLibraryBookReaderEnabledEndpointTests : IClassFixture, IAsyncLifetime -{ - private HttpClient _client; - private readonly AuthenticatedLuminaApiFactory _apiFactory; - private readonly LibraryEntityFixture _libraryEntityFixture = new(); - private readonly LibraryBookReaderConfigurationEntityFixture _libraryBookReaderConfigurationEntityFixture = new(); - private readonly SetLibraryBookReaderEnabledRequestFixture _setLibraryBookReaderEnabledRequestFixture = new(); - private readonly UserEntityFixture _userEntityFixture = new(); - - /// - /// Initializes a new instance of the class. - /// - /// Injected in-memory API factory. - public SetLibraryBookReaderEnabledEndpointTests(AuthenticatedLuminaApiFactory apiFactory) - { - _client = apiFactory.CreateClient(); - _apiFactory = apiFactory; - } - - /// - /// Initializes authenticated API client. - /// - public async Task InitializeAsync() - { - _client = await _apiFactory.CreateAuthenticatedClientAsync(); - } - - [Fact] - public async Task SetLibraryBookReaderEnabled_WhenNoConfigurationExists_ShouldCreateIt() - { - // Arrange - Guid userId = GetCurrentUserId(); - Guid libraryId = Guid.NewGuid(); - await SeedLibraryAsync(libraryId, userId); - Guid pluginId = Guid.NewGuid(); - SetLibraryBookReaderEnabledRequest request = _setLibraryBookReaderEnabledRequestFixture.Create(libraryId: libraryId, pluginId: pluginId, isEnabled: true); - - // Act - HttpResponseMessage response = await _client.PutAsJsonAsync($"/api/v1/libraries/{libraryId}/book-readers/{pluginId}/enabled", request); - - // Assert - response.EnsureSuccessStatusCode(); - Assert.Equal(HttpStatusCode.OK, response.StatusCode); - - using IServiceScope scope = _apiFactory.Services.CreateScope(); - LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); - LibraryBookReaderConfigurationEntity? configuration = await dbContext.LibraryBookReaderConfigurations - .FirstOrDefaultAsync(config => config.LibraryId == libraryId && config.PluginId == pluginId); - Assert.NotNull(configuration); - Assert.True(configuration!.IsEnabled); - } - - [Fact] - public async Task SetLibraryBookReaderEnabled_WhenConfigurationExists_ShouldUpdateItsEnabledState() - { - // Arrange - Guid userId = GetCurrentUserId(); - Guid libraryId = Guid.NewGuid(); - await SeedLibraryAsync(libraryId, userId); - Guid pluginId = Guid.NewGuid(); - await SeedConfigurationAsync(libraryId, pluginId, isEnabled: false); - SetLibraryBookReaderEnabledRequest request = _setLibraryBookReaderEnabledRequestFixture.Create(libraryId: libraryId, pluginId: pluginId, isEnabled: true); - - // Act - HttpResponseMessage response = await _client.PutAsJsonAsync($"/api/v1/libraries/{libraryId}/book-readers/{pluginId}/enabled", request); - - // Assert - response.EnsureSuccessStatusCode(); - Assert.Equal(HttpStatusCode.OK, response.StatusCode); - - using IServiceScope scope = _apiFactory.Services.CreateScope(); - LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); - LibraryBookReaderConfigurationEntity configuration = await dbContext.LibraryBookReaderConfigurations - .SingleAsync(config => config.LibraryId == libraryId && config.PluginId == pluginId); - Assert.True(configuration.IsEnabled); - } - - [Fact] - public async Task SetLibraryBookReaderEnabled_WhenLibraryIsNotOwned_ShouldReturnForbidden() - { - // Arrange - Guid otherUserId = await SeedOtherUserAsync(); - Guid libraryId = Guid.NewGuid(); - await SeedLibraryAsync(libraryId, otherUserId); - Guid pluginId = Guid.NewGuid(); - SetLibraryBookReaderEnabledRequest request = _setLibraryBookReaderEnabledRequestFixture.Create(libraryId: libraryId, pluginId: pluginId, isEnabled: true); - - // Act - HttpResponseMessage response = await _client.PutAsJsonAsync($"/api/v1/libraries/{libraryId}/book-readers/{pluginId}/enabled", request); - - // Assert - Assert.Equal(HttpStatusCode.Forbidden, response.StatusCode); - } - - [Fact] - public async Task SetLibraryBookReaderEnabled_WhenUnauthorized_ShouldReturnUnauthorizedResult() - { - // Arrange - HttpClient unauthenticatedClient = _apiFactory.CreateClient(); - Guid libraryId = Guid.NewGuid(); - Guid pluginId = Guid.NewGuid(); - SetLibraryBookReaderEnabledRequest request = _setLibraryBookReaderEnabledRequestFixture.Create(libraryId: libraryId, pluginId: pluginId, isEnabled: true); - - // Act - HttpResponseMessage response = await unauthenticatedClient.PutAsJsonAsync($"/api/v1/libraries/{libraryId}/book-readers/{pluginId}/enabled", request); - - // Assert - Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode); - } - - /// - /// Seeds a library owned by . - /// - /// The Id of the library to seed. - /// The Id of the user that owns the library. - private async Task SeedLibraryAsync(Guid libraryId, Guid userId) - { - using IServiceScope scope = _apiFactory.Services.CreateScope(); - LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); - dbContext.Libraries.Add(_libraryEntityFixture.Create(id: libraryId, userId: userId, title: "Test Library", libraryType: Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary.LibraryType.EBook, contentLocations: [])); - await dbContext.SaveChangesAsync(); - } - - /// - /// Seeds a book reader configuration for the library and plugin. - /// - /// The Id of the library. - /// The Id of the plugin. - /// Whether the book reader is enabled. - private async Task SeedConfigurationAsync(Guid libraryId, Guid pluginId, bool isEnabled) - { - using IServiceScope scope = _apiFactory.Services.CreateScope(); - LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); - dbContext.LibraryBookReaderConfigurations.Add(_libraryBookReaderConfigurationEntityFixture.Create(libraryId: libraryId, pluginId: pluginId, isEnabled: isEnabled)); - await dbContext.SaveChangesAsync(); - } - - /// - /// Seeds a user that is not the authenticated one and returns its Id. - /// - /// The Id of the seeded user. - private async Task SeedOtherUserAsync() - { - using IServiceScope scope = _apiFactory.Services.CreateScope(); - LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); - Guid userId = Guid.NewGuid(); - dbContext.Users.Add(_userEntityFixture.Create(id: userId, username: $"otheruser_{Guid.NewGuid()}", password: "TestPass123!")); - await dbContext.SaveChangesAsync(); - return userId; - } - - /// - /// Gets the Id of the currently authenticated test user. - /// - /// The Id of the authenticated test user. - private Guid GetCurrentUserId() - { - using IServiceScope scope = _apiFactory.Services.CreateScope(); - LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); - UserEntity user = dbContext.Users.First(user => user.Username == _apiFactory.TestUsername); - return user.Id; - } - - /// - /// Disposes API factory resources. - /// - public async Task DisposeAsync() - { - await _apiFactory.RemoveTestUserAsync(); - } -} diff --git a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Plugins/SetLibraryMetadataProviderEnabled/SetLibraryMetadataProviderEnabledEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Plugins/SetLibraryMetadataProviderEnabled/SetLibraryMetadataProviderEnabledEndpointTests.cs deleted file mode 100644 index 0eb07d2a..00000000 --- a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Plugins/SetLibraryMetadataProviderEnabled/SetLibraryMetadataProviderEnabledEndpointTests.cs +++ /dev/null @@ -1,156 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using Lumina.Application.Common.DataAccess.Entities.Plugins; -using Lumina.Application.Common.DataAccess.Entities.UsersManagement; -using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management; -using Lumina.Application.Fixtures.Common.DataAccess.Entities.Plugins; -using Lumina.Contracts.Fixtures.Core.Requests.Plugins; -using Lumina.Contracts.Requests.Plugins; -using Lumina.DataAccess.Core.UoW; -using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; -using Lumina.Presentation.Api.Core.Endpoints.Plugins.SetLibraryMetadataProviderEnabled; -using Lumina.Presentation.Api.IntegrationTests.Common.Setup; -using Microsoft.EntityFrameworkCore; -using Microsoft.Extensions.DependencyInjection; -using System; -using System.Diagnostics.CodeAnalysis; -using System.Linq; -using System.Net; -using System.Net.Http; -using System.Net.Http.Json; -using System.Threading.Tasks; -#endregion - -namespace Lumina.Presentation.Api.IntegrationTests.Core.Endpoints.Plugins.SetLibraryMetadataProviderEnabled; - -/// -/// Contains integration tests for the class. -/// -[ExcludeFromCodeCoverage] -public class SetLibraryMetadataProviderEnabledEndpointTests : IClassFixture, IAsyncLifetime -{ - private HttpClient _client; - private readonly AuthenticatedLuminaApiFactory _apiFactory; - private readonly LibraryEntityFixture _libraryEntityFixture = new(); - private readonly LibraryMetadataProviderConfigurationEntityFixture _libraryMetadataProviderConfigurationEntityFixture = new(); - private readonly SetLibraryMetadataProviderEnabledRequestFixture _setLibraryMetadataProviderEnabledRequestFixture = new(); - - /// - /// Initializes a new instance of the class. - /// - /// Injected in-memory API factory. - public SetLibraryMetadataProviderEnabledEndpointTests(AuthenticatedLuminaApiFactory apiFactory) - { - _client = apiFactory.CreateClient(); - _apiFactory = apiFactory; - } - - /// - /// Initializes authenticated API client. - /// - public async Task InitializeAsync() - { - _client = await _apiFactory.CreateAuthenticatedClientAsync(); - } - - [Fact] - public async Task SetLibraryMetadataProviderEnabled_WhenNoConfigurationExists_ShouldCreateIt() - { - // Arrange - Guid userId = GetCurrentUserId(); - Guid libraryId = Guid.NewGuid(); - await SeedLibraryAsync(libraryId, userId); - Guid pluginId = Guid.NewGuid(); - SetLibraryMetadataProviderEnabledRequest request = _setLibraryMetadataProviderEnabledRequestFixture.Create(libraryId: libraryId, pluginId: pluginId, isEnabled: true); - - // Act - HttpResponseMessage response = await _client.PutAsJsonAsync($"/api/v1/libraries/{libraryId}/metadata-providers/{pluginId}/enabled", request); - - // Assert - response.EnsureSuccessStatusCode(); - Assert.Equal(HttpStatusCode.OK, response.StatusCode); - - using IServiceScope scope = _apiFactory.Services.CreateScope(); - LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); - LibraryMetadataProviderConfigurationEntity? configuration = await dbContext.LibraryMetadataProviderConfigurations - .FirstOrDefaultAsync(config => config.LibraryId == libraryId && config.PluginId == pluginId); - Assert.NotNull(configuration); - Assert.True(configuration!.IsEnabled); - Assert.Equal(1, configuration.Rank); - } - - [Fact] - public async Task SetLibraryMetadataProviderEnabled_WhenConfigurationExists_ShouldUpdateItsEnabledState() - { - // Arrange - Guid userId = GetCurrentUserId(); - Guid libraryId = Guid.NewGuid(); - await SeedLibraryAsync(libraryId, userId); - Guid pluginId = Guid.NewGuid(); - await SeedConfigurationAsync(libraryId, pluginId, isEnabled: false, rank: 1); - SetLibraryMetadataProviderEnabledRequest request = _setLibraryMetadataProviderEnabledRequestFixture.Create(libraryId: libraryId, pluginId: pluginId, isEnabled: true); - - // Act - HttpResponseMessage response = await _client.PutAsJsonAsync($"/api/v1/libraries/{libraryId}/metadata-providers/{pluginId}/enabled", request); - - // Assert - response.EnsureSuccessStatusCode(); - Assert.Equal(HttpStatusCode.OK, response.StatusCode); - - using IServiceScope scope = _apiFactory.Services.CreateScope(); - LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); - LibraryMetadataProviderConfigurationEntity? configuration = await dbContext.LibraryMetadataProviderConfigurations - .FirstOrDefaultAsync(config => config.LibraryId == libraryId && config.PluginId == pluginId); - Assert.NotNull(configuration); - Assert.True(configuration!.IsEnabled); - } - - /// - /// Seeds a owned by . - /// - /// The Id of the library to seed. - /// The Id of the user that owns the library. - /// A task representing the asynchronous operation. - private async Task SeedLibraryAsync(Guid libraryId, Guid userId) - { - using IServiceScope scope = _apiFactory.Services.CreateScope(); - LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); - dbContext.Libraries.Add(_libraryEntityFixture.Create(id: libraryId, userId: userId, title: "Test Library", libraryType: LibraryType.EBook, contentLocations: [])); - await dbContext.SaveChangesAsync(); - } - - /// - /// Seeds a in the database. - /// - /// The Id of the media library. - /// The Id of the plugin. - /// Whether the provider is enabled. - /// The rank of the provider. - /// A task representing the asynchronous operation. - private async Task SeedConfigurationAsync(Guid libraryId, Guid pluginId, bool isEnabled, int rank) - { - using IServiceScope scope = _apiFactory.Services.CreateScope(); - LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); - dbContext.LibraryMetadataProviderConfigurations.Add(_libraryMetadataProviderConfigurationEntityFixture.Create(libraryId: libraryId, pluginId: pluginId, rank: rank, isEnabled: isEnabled)); - await dbContext.SaveChangesAsync(); - } - - /// - /// Gets the Id of the currently authenticated test user. - /// - /// The Id of the authenticated test user. - private Guid GetCurrentUserId() - { - using IServiceScope scope = _apiFactory.Services.CreateScope(); - LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); - UserEntity user = dbContext.Users.First(user => user.Username == _apiFactory.TestUsername); - return user.Id; - } - - /// - /// Disposes API factory resources. - /// - public async Task DisposeAsync() - { - await _apiFactory.RemoveTestUserAsync(); - } -} diff --git a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/Management/GetLibraryTypeArtworkProviders/GetLibraryTypeArtworkProvidersEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/Management/GetLibraryTypeArtworkProviders/GetLibraryTypeArtworkProvidersEndpointTests.cs new file mode 100644 index 00000000..483c38ec --- /dev/null +++ b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/Management/GetLibraryTypeArtworkProviders/GetLibraryTypeArtworkProvidersEndpointTests.cs @@ -0,0 +1,96 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Common.DTO.Plugins; +using Lumina.Presentation.Web.Core.Endpoints.Library.Management.GetLibraryTypeArtworkProviders; +using Lumina.Presentation.Web.Fixtures.Common.DTO.Plugins; +using Lumina.Presentation.Web.Fixtures.Common.TestHelpers; +using Lumina.Presentation.Web.IntegrationTests.Common.Setup; +using System; +using System.Diagnostics.CodeAnalysis; +using System.Net; +using System.Net.Http; +using System.Net.Http.Headers; +using System.Text.Json; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.Library.Management.GetLibraryTypeArtworkProviders; + +/// +/// Contains integration tests for the class. +/// +[ExcludeFromCodeCoverage] +public class GetLibraryTypeArtworkProvidersEndpointTests : IClassFixture +{ + private readonly LuminaWebFactory _apiFactory; + private readonly LibraryArtworkProviderDtoFixture _libraryArtworkProviderDtoFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + /// Injected Web application factory. + public GetLibraryTypeArtworkProvidersEndpointTests(LuminaWebFactory apiFactory) + { + _apiFactory = apiFactory; + } + + [Fact] + public async Task GetLibraryTypeArtworkProviders_WhenCalledByAuthenticatedUser_ShouldReturnProvidersJson() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + string libraryType = "Book"; + LibraryArtworkProviderDto[] expectedProviders = + [ + _libraryArtworkProviderDtoFixture.Create(name: "EPUB Reader", isEnabled: false) + ]; + _apiFactory.ApiClientStub.RegisterGetResponse($"libraries/artwork-providers/{libraryType}", expectedProviders); + AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); + HttpRequestMessage getRequest = new(HttpMethod.Get, $"/en-us/libraries/manage/api-get-library-type-artwork-providers/{libraryType}"); + getRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); + + // Act + HttpResponseMessage response = await webClient.Client.SendAsync(getRequest); + string content = await response.Content.ReadAsStringAsync(); + + // Assert + response.EnsureSuccessStatusCode(); + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + using JsonDocument json = JsonDocument.Parse(content); + Assert.True(json.RootElement.GetProperty("success").GetBoolean()); + JsonElement data = json.RootElement.GetProperty("data"); + Assert.Equal(1, data.GetArrayLength()); + Assert.Equal("EPUB Reader", data[0].GetProperty("name").GetString()); + } + + [Fact] + public async Task GetLibraryTypeArtworkProviders_WhenCalled_ShouldRequestProvidersFromApi() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + string libraryType = "Book"; + _apiFactory.ApiClientStub.RegisterGetResponse($"libraries/artwork-providers/{libraryType}", Array.Empty()); + AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); + HttpRequestMessage getRequest = new(HttpMethod.Get, $"/en-us/libraries/manage/api-get-library-type-artwork-providers/{libraryType}"); + getRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); + + // Act + HttpResponseMessage response = await webClient.Client.SendAsync(getRequest); + + // Assert + response.EnsureSuccessStatusCode(); + Assert.Contains($"libraries/artwork-providers/{libraryType}", _apiFactory.ApiClientStub.GetEndpointsCalled); + } + + [Fact] + public async Task GetLibraryTypeArtworkProviders_WhenNotAuthenticated_ShouldRedirectToLogin() + { + // Arrange + HttpClient anonymousClient = WebTestHelpers.CreateAnonymousClient(_apiFactory); + + // Act + HttpResponseMessage response = await anonymousClient.GetAsync("/en-us/libraries/manage/api-get-library-type-artwork-providers/Book"); + + // Assert + Assert.Equal(HttpStatusCode.Redirect, response.StatusCode); + } +} diff --git a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/Management/GetLibraryTypeBookReaders/GetLibraryTypeBookReadersEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/Management/GetLibraryTypeBookReaders/GetLibraryTypeBookReadersEndpointTests.cs new file mode 100644 index 00000000..a7a62af6 --- /dev/null +++ b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/Management/GetLibraryTypeBookReaders/GetLibraryTypeBookReadersEndpointTests.cs @@ -0,0 +1,96 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Common.DTO.Plugins; +using Lumina.Presentation.Web.Core.Endpoints.Library.Management.GetLibraryTypeBookReaders; +using Lumina.Presentation.Web.Fixtures.Common.DTO.Plugins; +using Lumina.Presentation.Web.Fixtures.Common.TestHelpers; +using Lumina.Presentation.Web.IntegrationTests.Common.Setup; +using System; +using System.Diagnostics.CodeAnalysis; +using System.Net; +using System.Net.Http; +using System.Net.Http.Headers; +using System.Text.Json; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.Library.Management.GetLibraryTypeBookReaders; + +/// +/// Contains integration tests for the class. +/// +[ExcludeFromCodeCoverage] +public class GetLibraryTypeBookReadersEndpointTests : IClassFixture +{ + private readonly LuminaWebFactory _apiFactory; + private readonly LibraryBookReaderDtoFixture _libraryBookReaderDtoFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + /// Injected Web application factory. + public GetLibraryTypeBookReadersEndpointTests(LuminaWebFactory apiFactory) + { + _apiFactory = apiFactory; + } + + [Fact] + public async Task GetLibraryTypeBookReaders_WhenCalledByAuthenticatedUser_ShouldReturnBookReadersJson() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + string libraryType = "Book"; + LibraryBookReaderDto[] expectedReaders = + [ + _libraryBookReaderDtoFixture.Create(name: "EPUB Reader", isEnabled: false) + ]; + _apiFactory.ApiClientStub.RegisterGetResponse($"libraries/book-readers/{libraryType}", expectedReaders); + AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); + HttpRequestMessage getRequest = new(HttpMethod.Get, $"/en-us/libraries/manage/api-get-library-type-book-readers/{libraryType}"); + getRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); + + // Act + HttpResponseMessage response = await webClient.Client.SendAsync(getRequest); + string content = await response.Content.ReadAsStringAsync(); + + // Assert + response.EnsureSuccessStatusCode(); + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + using JsonDocument json = JsonDocument.Parse(content); + Assert.True(json.RootElement.GetProperty("success").GetBoolean()); + JsonElement data = json.RootElement.GetProperty("data"); + Assert.Equal(1, data.GetArrayLength()); + Assert.Equal("EPUB Reader", data[0].GetProperty("name").GetString()); + } + + [Fact] + public async Task GetLibraryTypeBookReaders_WhenCalled_ShouldRequestBookReadersFromApi() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + string libraryType = "Book"; + _apiFactory.ApiClientStub.RegisterGetResponse($"libraries/book-readers/{libraryType}", Array.Empty()); + AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); + HttpRequestMessage getRequest = new(HttpMethod.Get, $"/en-us/libraries/manage/api-get-library-type-book-readers/{libraryType}"); + getRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); + + // Act + HttpResponseMessage response = await webClient.Client.SendAsync(getRequest); + + // Assert + response.EnsureSuccessStatusCode(); + Assert.Contains($"libraries/book-readers/{libraryType}", _apiFactory.ApiClientStub.GetEndpointsCalled); + } + + [Fact] + public async Task GetLibraryTypeBookReaders_WhenNotAuthenticated_ShouldRedirectToLogin() + { + // Arrange + HttpClient anonymousClient = WebTestHelpers.CreateAnonymousClient(_apiFactory); + + // Act + HttpResponseMessage response = await anonymousClient.GetAsync("/en-us/libraries/manage/api-get-library-type-book-readers/Book"); + + // Assert + Assert.Equal(HttpStatusCode.Redirect, response.StatusCode); + } +} diff --git a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/Management/GetLibraryTypeMetadataProviders/GetLibraryTypeMetadataProvidersEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/Management/GetLibraryTypeMetadataProviders/GetLibraryTypeMetadataProvidersEndpointTests.cs new file mode 100644 index 00000000..49f27f3b --- /dev/null +++ b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/Management/GetLibraryTypeMetadataProviders/GetLibraryTypeMetadataProvidersEndpointTests.cs @@ -0,0 +1,96 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Common.DTO.Plugins; +using Lumina.Presentation.Web.Core.Endpoints.Library.Management.GetLibraryTypeMetadataProviders; +using Lumina.Presentation.Web.Fixtures.Common.DTO.Plugins; +using Lumina.Presentation.Web.Fixtures.Common.TestHelpers; +using Lumina.Presentation.Web.IntegrationTests.Common.Setup; +using System; +using System.Diagnostics.CodeAnalysis; +using System.Net; +using System.Net.Http; +using System.Net.Http.Headers; +using System.Text.Json; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.Library.Management.GetLibraryTypeMetadataProviders; + +/// +/// Contains integration tests for the class. +/// +[ExcludeFromCodeCoverage] +public class GetLibraryTypeMetadataProvidersEndpointTests : IClassFixture +{ + private readonly LuminaWebFactory _apiFactory; + private readonly LibraryMetadataProviderDtoFixture _libraryMetadataProviderDtoFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + /// Injected Web application factory. + public GetLibraryTypeMetadataProvidersEndpointTests(LuminaWebFactory apiFactory) + { + _apiFactory = apiFactory; + } + + [Fact] + public async Task GetLibraryTypeMetadataProviders_WhenCalledByAuthenticatedUser_ShouldReturnProvidersJson() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + string libraryType = "Book"; + LibraryMetadataProviderDto[] expectedProviders = + [ + _libraryMetadataProviderDtoFixture.Create(name: "EPUB Reader", isEnabled: false) + ]; + _apiFactory.ApiClientStub.RegisterGetResponse($"libraries/metadata-providers/{libraryType}", expectedProviders); + AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); + HttpRequestMessage getRequest = new(HttpMethod.Get, $"/en-us/libraries/manage/api-get-library-type-metadata-providers/{libraryType}"); + getRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); + + // Act + HttpResponseMessage response = await webClient.Client.SendAsync(getRequest); + string content = await response.Content.ReadAsStringAsync(); + + // Assert + response.EnsureSuccessStatusCode(); + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + using JsonDocument json = JsonDocument.Parse(content); + Assert.True(json.RootElement.GetProperty("success").GetBoolean()); + JsonElement data = json.RootElement.GetProperty("data"); + Assert.Equal(1, data.GetArrayLength()); + Assert.Equal("EPUB Reader", data[0].GetProperty("name").GetString()); + } + + [Fact] + public async Task GetLibraryTypeMetadataProviders_WhenCalled_ShouldRequestProvidersFromApi() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + string libraryType = "Book"; + _apiFactory.ApiClientStub.RegisterGetResponse($"libraries/metadata-providers/{libraryType}", Array.Empty()); + AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); + HttpRequestMessage getRequest = new(HttpMethod.Get, $"/en-us/libraries/manage/api-get-library-type-metadata-providers/{libraryType}"); + getRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); + + // Act + HttpResponseMessage response = await webClient.Client.SendAsync(getRequest); + + // Assert + response.EnsureSuccessStatusCode(); + Assert.Contains($"libraries/metadata-providers/{libraryType}", _apiFactory.ApiClientStub.GetEndpointsCalled); + } + + [Fact] + public async Task GetLibraryTypeMetadataProviders_WhenNotAuthenticated_ShouldRedirectToLogin() + { + // Arrange + HttpClient anonymousClient = WebTestHelpers.CreateAnonymousClient(_apiFactory); + + // Act + HttpResponseMessage response = await anonymousClient.GetAsync("/en-us/libraries/manage/api-get-library-type-metadata-providers/Book"); + + // Assert + Assert.Equal(HttpStatusCode.Redirect, response.StatusCode); + } +} diff --git a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/Management/Index/LibrariesIndexViewEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/Management/Index/LibrariesIndexViewEndpointTests.cs index af5eeff6..0095e77d 100644 --- a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/Management/Index/LibrariesIndexViewEndpointTests.cs +++ b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/Management/Index/LibrariesIndexViewEndpointTests.cs @@ -1,7 +1,10 @@ #region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Common.Enums.Authorization; using Lumina.Presentation.Web.Core.Endpoints.Library.Management.Index; +using Lumina.Presentation.Web.Fixtures.Common.Responses.Authorization; using Lumina.Presentation.Web.Fixtures.Common.TestHelpers; using Lumina.Presentation.Web.IntegrationTests.Common.Setup; +using System; using System.Diagnostics.CodeAnalysis; using System.Net; using System.Net.Http; @@ -17,6 +20,7 @@ namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.Library.Manage public class LibrariesIndexViewEndpointTests : IClassFixture { private readonly LuminaWebFactory _apiFactory; + private readonly GetAuthorizationResponseFixture _getAuthorizationResponseFixture = new(); /// /// Initializes a new instance of the class. @@ -44,8 +48,8 @@ public class LibrariesIndexViewEndpointTests : IClassFixture } [Theory] - [InlineData("/en-us/libraries/manage", "%2Fen-us%2Flibraries%2Fmanage")] // plain page - [InlineData("/en-us/libraries/manage?tab=scans", "%2Fen-us%2Flibraries%2Fmanage%3Ftab%3Dscans")] // query string is kept + [InlineData("/en-us/libraries/manage", "%2Fen-us%2Flibraries%2Fmanage")] // Plain page. + [InlineData("/en-us/libraries/manage?tab=scans", "%2Fen-us%2Flibraries%2Fmanage%3Ftab%3Dscans")] // Query string is kept. public async Task LibrariesIndexView_WhenNavigatedToWithoutAuthentication_ShouldRedirectToLoginWithRequestedPageAsReturnUrl(string requestedUrl, string expectedEncodedReturnUrl) { // Arrange @@ -60,4 +64,45 @@ public class LibrariesIndexViewEndpointTests : IClassFixture Assert.Equal(HttpStatusCode.Redirect, response.StatusCode); Assert.Equal($"http://localhost/en-us/auth/login?returnUrl={expectedEncodedReturnUrl}", response.Headers.Location!.ToString()); } + + [Theory] + [InlineData("User", true, "true")] // The permission lets a user manage the libraries they own. + [InlineData("User", false, "false")] // Without the permission, a user cannot change even the libraries they own. + [InlineData("Admin", false, "true")] // An administrator can manage every library, with or without the permission. + public async Task LibrariesIndexView_WhenRendered_ShouldOfferTheEditAndDeleteActionsOnlyToUsersAllowedToManageLibraries(string role, bool hasManagePermission, string expectedCanManageLibraries) + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + _apiFactory.ApiClientStub.AuthorizationResponse = _getAuthorizationResponseFixture.Create( + userId: Guid.NewGuid(), + role: role, + permissions: hasManagePermission ? [AuthorizationPermission.CanCreateLibraries] : []); + AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); + + // Act + HttpResponseMessage response = await webClient.Client.GetAsync("/en-us/libraries/manage"); + + // Assert + response.EnsureSuccessStatusCode(); + string content = await response.Content.ReadAsStringAsync(); + Assert.Contains($"const canManageLibraries = {expectedCanManageLibraries};", content); + } + + [Fact] + public async Task LibrariesIndexView_WhenRenderedInACultureWithNonAsciiLabels_ShouldInjectTheScriptLabelsAsJson() + { + // Arrange + // Razor would encode the non-ASCII letters of a raw label as HTML entities, which the browser shows literally inside a script, while JSON escapes them + _apiFactory.ApiClientStub.Reset(); + AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); + + // Act + HttpResponseMessage response = await webClient.Client.GetAsync("/ro-ro/libraries/manage"); + + // Assert + response.EnsureSuccessStatusCode(); + string content = await response.Content.ReadAsStringAsync(); + Assert.Contains("\"LibraryDeleted\":\"Biblioteca a fost \\u0219tears\\u0103!\"", content); + Assert.DoesNotContain("ștears", content); + } } diff --git a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/Management/ReorderArtworkProviders/ReorderArtworkProvidersEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/Management/ReorderArtworkProviders/ReorderArtworkProvidersEndpointTests.cs deleted file mode 100644 index 940c6cf0..00000000 --- a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/Management/ReorderArtworkProviders/ReorderArtworkProvidersEndpointTests.cs +++ /dev/null @@ -1,71 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using Lumina.Presentation.Web.Common.Requests.Plugins; -using Lumina.Presentation.Web.Core.Endpoints.Library.Management.ReorderArtworkProviders; -using Lumina.Presentation.Web.Fixtures.Common.Requests.Plugins; -using Lumina.Presentation.Web.Fixtures.Common.TestHelpers; -using Lumina.Presentation.Web.IntegrationTests.Common.Setup; -using System; -using System.Diagnostics.CodeAnalysis; -using System.Net; -using System.Net.Http; -using System.Net.Http.Headers; -using System.Net.Http.Json; -using System.Text.Json; -using System.Threading.Tasks; -#endregion - -namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.Library.Management.ReorderArtworkProviders; - -/// -/// Contains integration tests for the class. -/// -[ExcludeFromCodeCoverage] -public class ReorderArtworkProvidersEndpointTests : IClassFixture -{ - private readonly LuminaWebFactory _apiFactory; - private readonly ReorderLibraryArtworkProvidersRequestFixture _reorderLibraryArtworkProvidersRequestFixture = new(); - - /// - /// Initializes a new instance of the class. - /// - /// Injected Web application factory. - public ReorderArtworkProvidersEndpointTests(LuminaWebFactory apiFactory) - { - _apiFactory = apiFactory; - } - - [Fact] - public async Task ReorderArtworkProviders_WhenCalledByAuthenticatedUserWithAntiforgeryToken_ShouldReorderProvidersAndReturnSuccess() - { - // Arrange - _apiFactory.ApiClientStub.Reset(); - Guid libraryId = Guid.NewGuid(); - Guid firstPluginId = Guid.NewGuid(); - Guid secondPluginId = Guid.NewGuid(); - ReorderLibraryArtworkProvidersRequest request = _reorderLibraryArtworkProvidersRequestFixture.Create( - libraryId: libraryId, - pluginIds: [firstPluginId, secondPluginId] - ); - string expectedEndpoint = $"libraries/{libraryId}/artwork-providers/reorder"; - _apiFactory.ApiClientStub.RegisterPutResponseFactory(expectedEndpoint, _ => new Lumina.Presentation.Web.Common.Requests.Common.EmptyRequest()); - AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); - HttpRequestMessage updateRequest = new(HttpMethod.Put, "/en-us/libraries/manage/api-reorder-artwork-providers") - { - Content = JsonContent.Create(request) - }; - updateRequest.Content!.Headers.ContentType = new MediaTypeHeaderValue("application/json"); - updateRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); - updateRequest.Headers.Add("RequestVerificationToken", webClient.AntiforgeryToken); - - // Act - HttpResponseMessage response = await webClient.Client.SendAsync(updateRequest); - string content = await response.Content.ReadAsStringAsync(); - - // Assert - response.EnsureSuccessStatusCode(); - Assert.Equal(HttpStatusCode.OK, response.StatusCode); - using JsonDocument json = JsonDocument.Parse(content); - Assert.True(json.RootElement.GetProperty("success").GetBoolean()); - Assert.Contains(_apiFactory.ApiClientStub.PutRequests, putRequest => putRequest.Endpoint == expectedEndpoint); - } -} diff --git a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/Management/ReorderMetadataProviders/ReorderMetadataProvidersEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/Management/ReorderMetadataProviders/ReorderMetadataProvidersEndpointTests.cs deleted file mode 100644 index 059ebed5..00000000 --- a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/Management/ReorderMetadataProviders/ReorderMetadataProvidersEndpointTests.cs +++ /dev/null @@ -1,71 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using Lumina.Presentation.Web.Common.Requests.Plugins; -using Lumina.Presentation.Web.Core.Endpoints.Library.Management.ReorderMetadataProviders; -using Lumina.Presentation.Web.Fixtures.Common.Requests.Plugins; -using Lumina.Presentation.Web.Fixtures.Common.TestHelpers; -using Lumina.Presentation.Web.IntegrationTests.Common.Setup; -using System; -using System.Diagnostics.CodeAnalysis; -using System.Net; -using System.Net.Http; -using System.Net.Http.Headers; -using System.Net.Http.Json; -using System.Text.Json; -using System.Threading.Tasks; -#endregion - -namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.Library.Management.ReorderMetadataProviders; - -/// -/// Contains integration tests for the class. -/// -[ExcludeFromCodeCoverage] -public class ReorderMetadataProvidersEndpointTests : IClassFixture -{ - private readonly LuminaWebFactory _apiFactory; - private readonly ReorderLibraryMetadataProvidersRequestFixture _reorderLibraryMetadataProvidersRequestFixture = new(); - - /// - /// Initializes a new instance of the class. - /// - /// Injected Web application factory. - public ReorderMetadataProvidersEndpointTests(LuminaWebFactory apiFactory) - { - _apiFactory = apiFactory; - } - - [Fact] - public async Task ReorderMetadataProviders_WhenCalledByAuthenticatedUserWithAntiforgeryToken_ShouldReorderProvidersAndReturnSuccess() - { - // Arrange - _apiFactory.ApiClientStub.Reset(); - Guid libraryId = Guid.NewGuid(); - Guid firstPluginId = Guid.NewGuid(); - Guid secondPluginId = Guid.NewGuid(); - ReorderLibraryMetadataProvidersRequest request = _reorderLibraryMetadataProvidersRequestFixture.Create( - libraryId: libraryId, - pluginIds: [firstPluginId, secondPluginId] - ); - string expectedEndpoint = $"libraries/{libraryId}/metadata-providers/reorder"; - _apiFactory.ApiClientStub.RegisterPutResponseFactory(expectedEndpoint, _ => new Lumina.Presentation.Web.Common.Requests.Common.EmptyRequest()); - AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); - HttpRequestMessage updateRequest = new(HttpMethod.Put, "/en-us/libraries/manage/api-reorder-metadata-providers") - { - Content = JsonContent.Create(request) - }; - updateRequest.Content!.Headers.ContentType = new MediaTypeHeaderValue("application/json"); - updateRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); - updateRequest.Headers.Add("RequestVerificationToken", webClient.AntiforgeryToken); - - // Act - HttpResponseMessage response = await webClient.Client.SendAsync(updateRequest); - string content = await response.Content.ReadAsStringAsync(); - - // Assert - response.EnsureSuccessStatusCode(); - Assert.Equal(HttpStatusCode.OK, response.StatusCode); - using JsonDocument json = JsonDocument.Parse(content); - Assert.True(json.RootElement.GetProperty("success").GetBoolean()); - Assert.Contains(_apiFactory.ApiClientStub.PutRequests, putRequest => putRequest.Endpoint == expectedEndpoint); - } -} diff --git a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/Management/SaveLibrary/SaveLibraryEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/Management/SaveLibrary/SaveLibraryEndpointTests.cs index 121701e4..f06d0cc4 100644 --- a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/Management/SaveLibrary/SaveLibraryEndpointTests.cs +++ b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/Management/SaveLibrary/SaveLibraryEndpointTests.cs @@ -64,6 +64,43 @@ public class SaveLibraryEndpointTests : IClassFixture Assert.Contains(_apiFactory.ApiClientStub.PostRequests, postRequest => postRequest.Endpoint == "libraries"); } + [Fact] + public async Task SaveLibrary_WhenAProviderChoiceHasNoEnabledState_ShouldForwardItWithoutAState() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + Guid pluginId = Guid.NewGuid(); + LibraryDto request = _libraryDtoFixture.Create(title: "New Books Library", libraryType: "Book"); + request.Id = null; + _apiFactory.ApiClientStub.RegisterPostResponse("libraries", _libraryDtoFixture.Create(id: Guid.NewGuid(), title: request.Title, libraryType: request.LibraryType)); + AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); + // The choice is sent without its enabled state, the way a caller that only reorders the providers would send it. + HttpRequestMessage saveRequest = new(HttpMethod.Post, "/en-us/libraries/manage/api-item") + { + Content = JsonContent.Create(new + { + request.Title, + request.LibraryType, + request.ContentLocations, + MetadataProviders = new[] { new { PluginId = pluginId } } + }) + }; + 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); + + // Assert + response.EnsureSuccessStatusCode(); + (string _, object? data) = Assert.Single(_apiFactory.ApiClientStub.PostRequests, postRequest => postRequest.Endpoint == "libraries"); + LibraryDto forwardedLibrary = Assert.IsType(data); + LibraryProviderSelectionDto forwardedChoice = Assert.Single(forwardedLibrary.MetadataProviders!); + Assert.Equal(pluginId, forwardedChoice.PluginId); + Assert.Null(forwardedChoice.IsEnabled); + } + [Fact] public async Task SaveLibrary_WhenCalledWithoutAntiforgeryToken_ShouldReturnBadRequest() { diff --git a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/Management/SetArtworkProviderEnabled/SetArtworkProviderEnabledEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/Management/SetArtworkProviderEnabled/SetArtworkProviderEnabledEndpointTests.cs deleted file mode 100644 index 2a2c9995..00000000 --- a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/Management/SetArtworkProviderEnabled/SetArtworkProviderEnabledEndpointTests.cs +++ /dev/null @@ -1,71 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using Lumina.Presentation.Web.Common.Requests.Plugins; -using Lumina.Presentation.Web.Core.Endpoints.Library.Management.SetArtworkProviderEnabled; -using Lumina.Presentation.Web.Fixtures.Common.Requests.Plugins; -using Lumina.Presentation.Web.Fixtures.Common.TestHelpers; -using Lumina.Presentation.Web.IntegrationTests.Common.Setup; -using System; -using System.Diagnostics.CodeAnalysis; -using System.Net; -using System.Net.Http; -using System.Net.Http.Headers; -using System.Net.Http.Json; -using System.Text.Json; -using System.Threading.Tasks; -#endregion - -namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.Library.Management.SetArtworkProviderEnabled; - -/// -/// Contains integration tests for the class. -/// -[ExcludeFromCodeCoverage] -public class SetArtworkProviderEnabledEndpointTests : IClassFixture -{ - private readonly LuminaWebFactory _apiFactory; - private readonly SetLibraryArtworkProviderEnabledRequestFixture _setLibraryArtworkProviderEnabledRequestFixture = new(); - - /// - /// Initializes a new instance of the class. - /// - /// Injected Web application factory. - public SetArtworkProviderEnabledEndpointTests(LuminaWebFactory apiFactory) - { - _apiFactory = apiFactory; - } - - [Fact] - public async Task SetArtworkProviderEnabled_WhenCalledByAuthenticatedUserWithAntiforgeryToken_ShouldEnableProviderAndReturnSuccess() - { - // Arrange - _apiFactory.ApiClientStub.Reset(); - Guid libraryId = Guid.NewGuid(); - Guid pluginId = Guid.NewGuid(); - SetLibraryArtworkProviderEnabledRequest request = _setLibraryArtworkProviderEnabledRequestFixture.Create( - libraryId: libraryId, - pluginId: pluginId, - isEnabled: true - ); - string expectedEndpoint = $"libraries/{libraryId}/artwork-providers/{pluginId}/enabled"; - _apiFactory.ApiClientStub.RegisterPutResponseFactory(expectedEndpoint, _ => new Lumina.Presentation.Web.Common.Requests.Common.EmptyRequest()); - AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); - HttpRequestMessage updateRequest = new(HttpMethod.Put, "/en-us/libraries/manage/api-set-artwork-provider-enabled") - { - Content = JsonContent.Create(request) - }; - updateRequest.Content!.Headers.ContentType = new MediaTypeHeaderValue("application/json"); - updateRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); - updateRequest.Headers.Add("RequestVerificationToken", webClient.AntiforgeryToken); - - // Act - HttpResponseMessage response = await webClient.Client.SendAsync(updateRequest); - string content = await response.Content.ReadAsStringAsync(); - - // Assert - response.EnsureSuccessStatusCode(); - Assert.Equal(HttpStatusCode.OK, response.StatusCode); - using JsonDocument json = JsonDocument.Parse(content); - Assert.True(json.RootElement.GetProperty("success").GetBoolean()); - Assert.Contains(_apiFactory.ApiClientStub.PutRequests, putRequest => putRequest.Endpoint == expectedEndpoint); - } -} diff --git a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/Management/SetBookReaderEnabled/SetBookReaderEnabledEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/Management/SetBookReaderEnabled/SetBookReaderEnabledEndpointTests.cs deleted file mode 100644 index 11aa7902..00000000 --- a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/Management/SetBookReaderEnabled/SetBookReaderEnabledEndpointTests.cs +++ /dev/null @@ -1,87 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using Lumina.Presentation.Web.Common.Requests.Common; -using Lumina.Presentation.Web.Common.Requests.Plugins; -using Lumina.Presentation.Web.Core.Endpoints.Library.Management.SetBookReaderEnabled; -using Lumina.Presentation.Web.Fixtures.Common.Requests.Plugins; -using Lumina.Presentation.Web.Fixtures.Common.TestHelpers; -using Lumina.Presentation.Web.IntegrationTests.Common.Setup; -using System; -using System.Diagnostics.CodeAnalysis; -using System.Net; -using System.Net.Http; -using System.Net.Http.Headers; -using System.Net.Http.Json; -using System.Text.Json; -using System.Threading.Tasks; -#endregion - -namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.Library.Management.SetBookReaderEnabled; - -/// -/// Contains integration tests for the class. -/// -[ExcludeFromCodeCoverage] -public class SetBookReaderEnabledEndpointTests : IClassFixture -{ - private readonly LuminaWebFactory _apiFactory; - private readonly SetBookReaderEnabledRequestFixture _setBookReaderEnabledRequestFixture = new(); - - /// - /// Initializes a new instance of the class. - /// - /// Injected Web application factory. - public SetBookReaderEnabledEndpointTests(LuminaWebFactory apiFactory) - { - _apiFactory = apiFactory; - } - - [Fact] - public async Task SetBookReaderEnabled_WhenCalledByAuthenticatedUserWithAntiforgeryToken_ShouldEnableReaderAndReturnSuccess() - { - // Arrange - _apiFactory.ApiClientStub.Reset(); - Guid libraryId = Guid.NewGuid(); - Guid pluginId = Guid.NewGuid(); - SetBookReaderEnabledRequest request = _setBookReaderEnabledRequestFixture.Create(libraryId: libraryId, pluginId: pluginId, isEnabled: true); - string expectedEndpoint = $"libraries/{libraryId}/book-readers/{pluginId}/enabled"; - _apiFactory.ApiClientStub.RegisterPutResponseFactory(expectedEndpoint, _ => new EmptyRequest()); - AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); - HttpRequestMessage updateRequest = new(HttpMethod.Put, "/en-us/libraries/manage/api-set-book-reader-enabled") - { - Content = JsonContent.Create(request) - }; - updateRequest.Content!.Headers.ContentType = new MediaTypeHeaderValue("application/json"); - updateRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); - updateRequest.Headers.Add("RequestVerificationToken", webClient.AntiforgeryToken); - - // Act - HttpResponseMessage response = await webClient.Client.SendAsync(updateRequest); - string content = await response.Content.ReadAsStringAsync(); - - // Assert - response.EnsureSuccessStatusCode(); - Assert.Equal(HttpStatusCode.OK, response.StatusCode); - using JsonDocument json = JsonDocument.Parse(content); - Assert.True(json.RootElement.GetProperty("success").GetBoolean()); - Assert.Contains(_apiFactory.ApiClientStub.PutRequests, putRequest => putRequest.Endpoint == expectedEndpoint); - } - - [Fact] - public async Task SetBookReaderEnabled_WhenNotAuthenticated_ShouldRedirectToLogin() - { - // Arrange - HttpClient anonymousClient = WebTestHelpers.CreateAnonymousClient(_apiFactory); - SetBookReaderEnabledRequest request = _setBookReaderEnabledRequestFixture.Create(); - HttpRequestMessage updateRequest = new(HttpMethod.Put, "/en-us/libraries/manage/api-set-book-reader-enabled") - { - Content = JsonContent.Create(request) - }; - updateRequest.Content!.Headers.ContentType = new MediaTypeHeaderValue("application/json"); - - // Act - HttpResponseMessage response = await anonymousClient.SendAsync(updateRequest); - - // Assert - Assert.Equal(HttpStatusCode.Redirect, response.StatusCode); - } -} diff --git a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/Management/SetMetadataProviderEnabled/SetMetadataProviderEnabledEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/Management/SetMetadataProviderEnabled/SetMetadataProviderEnabledEndpointTests.cs deleted file mode 100644 index ad6752ac..00000000 --- a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/Management/SetMetadataProviderEnabled/SetMetadataProviderEnabledEndpointTests.cs +++ /dev/null @@ -1,71 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using Lumina.Presentation.Web.Common.Requests.Plugins; -using Lumina.Presentation.Web.Core.Endpoints.Library.Management.SetMetadataProviderEnabled; -using Lumina.Presentation.Web.Fixtures.Common.Requests.Plugins; -using Lumina.Presentation.Web.Fixtures.Common.TestHelpers; -using Lumina.Presentation.Web.IntegrationTests.Common.Setup; -using System; -using System.Diagnostics.CodeAnalysis; -using System.Net; -using System.Net.Http; -using System.Net.Http.Headers; -using System.Net.Http.Json; -using System.Text.Json; -using System.Threading.Tasks; -#endregion - -namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.Library.Management.SetMetadataProviderEnabled; - -/// -/// Contains integration tests for the class. -/// -[ExcludeFromCodeCoverage] -public class SetMetadataProviderEnabledEndpointTests : IClassFixture -{ - private readonly LuminaWebFactory _apiFactory; - private readonly SetLibraryMetadataProviderEnabledRequestFixture _setLibraryMetadataProviderEnabledRequestFixture = new(); - - /// - /// Initializes a new instance of the class. - /// - /// Injected Web application factory. - public SetMetadataProviderEnabledEndpointTests(LuminaWebFactory apiFactory) - { - _apiFactory = apiFactory; - } - - [Fact] - public async Task SetMetadataProviderEnabled_WhenCalledByAuthenticatedUserWithAntiforgeryToken_ShouldEnableProviderAndReturnSuccess() - { - // Arrange - _apiFactory.ApiClientStub.Reset(); - Guid libraryId = Guid.NewGuid(); - Guid pluginId = Guid.NewGuid(); - SetLibraryMetadataProviderEnabledRequest request = _setLibraryMetadataProviderEnabledRequestFixture.Create( - libraryId: libraryId, - pluginId: pluginId, - isEnabled: true - ); - string expectedEndpoint = $"libraries/{libraryId}/metadata-providers/{pluginId}/enabled"; - _apiFactory.ApiClientStub.RegisterPutResponseFactory(expectedEndpoint, _ => new Lumina.Presentation.Web.Common.Requests.Common.EmptyRequest()); - AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); - HttpRequestMessage updateRequest = new(HttpMethod.Put, "/en-us/libraries/manage/api-set-metadata-provider-enabled") - { - Content = JsonContent.Create(request) - }; - updateRequest.Content!.Headers.ContentType = new MediaTypeHeaderValue("application/json"); - updateRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); - updateRequest.Headers.Add("RequestVerificationToken", webClient.AntiforgeryToken); - - // Act - HttpResponseMessage response = await webClient.Client.SendAsync(updateRequest); - string content = await response.Content.ReadAsStringAsync(); - - // Assert - response.EnsureSuccessStatusCode(); - Assert.Equal(HttpStatusCode.OK, response.StatusCode); - using JsonDocument json = JsonDocument.Parse(content); - Assert.True(json.RootElement.GetProperty("success").GetBoolean()); - Assert.Contains(_apiFactory.ApiClientStub.PutRequests, putRequest => putRequest.Endpoint == expectedEndpoint); - } -} diff --git a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Common/Setup/LuminaApiFactory.cs b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Common/Setup/LuminaApiFactory.cs index 659b8547..b16c27a1 100644 --- a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Common/Setup/LuminaApiFactory.cs +++ b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Common/Setup/LuminaApiFactory.cs @@ -9,6 +9,7 @@ using Lumina.Contracts.Fixtures.Core.Requests.Authentication; using Lumina.Contracts.Responses.Authentication; using Lumina.DataAccess.Common.Interceptors; using Lumina.DataAccess.Core.UoW; +using Lumina.Domain.SharedKernel.Common.Enums.Authorization; using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; using Lumina.Infrastructure.Core.Security; using Microsoft.AspNetCore.Authentication.JwtBearer; @@ -45,6 +46,8 @@ public class LuminaApiFactory : WebApplicationFactory, IDisposable private readonly UserEntityFixture _userEntityFixture = new(); private readonly RoleEntityFixture _roleEntityFixture = new(); private readonly UserRoleEntityFixture _userRoleEntityFixture = new(); + private readonly PermissionEntityFixture _permissionEntityFixture = new(); + private readonly UserPermissionEntityFixture _userPermissionEntityFixture = new(); private readonly LibraryEntityFixture _libraryEntityFixture = new(); private readonly BookEntityFixture _bookEntityFixture = new(); private const string TEST_ENCRYPTION_KEY = "MTIzNDU2Nzg5MDEyMzQ1Njc4OTAxMjM0NTY3ODkwMTI="; @@ -55,11 +58,11 @@ public class LuminaApiFactory : WebApplicationFactory, IDisposable /// public LuminaApiFactory() { - // each factory gets its own uniquely named shared in-memory database, so that parallel test classes remain isolated from one another; + // Each factory gets its own uniquely named shared in-memory database, so that parallel test classes remain isolated from one another; // the shared cache allows each DbContext to open its own pooled connection to the same database, instead of sharing a single connection, - // which would otherwise serialize every request on one connection and cause nested transaction errors between requests + // which would otherwise serialize every request on one connection and cause nested transaction errors between requests. _sharedInMemoryConnectionString = string.Format(SHARED_IN_MEMORY_CONNECTION_STRING_PREFIX, Guid.NewGuid()); - // keep a single anchor connection open, so that the shared in-memory database it refers to is not dropped + // Keep a single anchor connection open, so that the shared in-memory database it refers to is not dropped. _connection = new SqliteConnection(_sharedInMemoryConnectionString); _connection.Open(); } @@ -202,6 +205,40 @@ public class LuminaApiFactory : WebApplicationFactory, IDisposable return (userId, username); } + /// + /// Creates a test user that holds a single permission directly, authenticates it on , and returns its Id and username. + /// + /// The HTTP client to configure with authentication headers. + /// The permission granted to the created user. + /// The Id and username of the created test user. + public async Task<(Guid UserId, string Username)> CreateAndAuthenticateUserWithPermissionAsync(HttpClient client, AuthorizationPermission permission) + { + // A unique X-Forwarded-For isolates rate limiting state per test. + client.DefaultRequestHeaders.Clear(); + client.DefaultRequestHeaders.Add("X-Forwarded-For", GetUniqueTestIp()); + + using IServiceScope scope = Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + + Guid userId = Guid.NewGuid(); + string username = $"testuser_{Guid.NewGuid()}"; + UserEntity user = _userEntityFixture.Create(id: userId, username: username, password: _hashService.HashString("TestPass123!")); + user.TotpSecret = null; + dbContext.Users.Add(user); + + PermissionEntity permissionEntity = _permissionEntityFixture.Create(permissionName: permission); + dbContext.Permissions.Add(permissionEntity); + dbContext.UserPermissions.Add(_userPermissionEntityFixture.Create(user, permissionEntity)); + await dbContext.SaveChangesAsync(); + + HttpResponseMessage loginResponse = await client.PostAsJsonAsync("/api/v1/auth/login", _loginRequestFixture.Create(username: username, password: "TestPass123!")); + string content = await loginResponse.Content.ReadAsStringAsync(); + LoginResponse? loginResult = JsonSerializer.Deserialize(content, _jsonOptions); + client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", loginResult!.Token); + + return (userId, username); + } + /// /// Removes a test user and its owned libraries from the database. /// diff --git a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Library/Management/DeleteLibrary/DeleteLibraryEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Library/Management/DeleteLibrary/DeleteLibraryEndpointTests.cs index a400aa53..562f164c 100644 --- a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Library/Management/DeleteLibrary/DeleteLibraryEndpointTests.cs +++ b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Library/Management/DeleteLibrary/DeleteLibraryEndpointTests.cs @@ -1,6 +1,7 @@ #region ========================================================================= USING ===================================================================================== using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management; using Lumina.DataAccess.Core.UoW; +using Lumina.Domain.SharedKernel.Common.Enums.Authorization; using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; using Lumina.Presentation.Api.SecurityTests.Common.Setup; using Microsoft.AspNetCore.Http; @@ -60,12 +61,12 @@ public class DeleteLibraryEndpointTests : IClassFixture } [Theory] - [InlineData("' OR '1'='1")] // basic SQL injection - [InlineData("'; DROP TABLE Libraries--")] // destructive injection + [InlineData("' OR '1'='1")] // Basic SQL injection. + [InlineData("'; DROP TABLE Libraries--")] // Destructive injection. public async Task DeleteLibrary_WithSQLInjectionInLibraryId_ShouldNotLeakOrError(string maliciousLibraryId) { // Arrange - // authenticate with an admin user and seed a library, so a valid id would reach the handler and be authorized + // Authenticate with an admin user and seed a library, so a valid id would reach the handler and be authorized. HttpClient client = _apiFactory.CreateClient(); Guid userId = await _apiFactory.CreateAndAuthenticateAdminUserAsync(client); await SeedLibraryAsync(userId); @@ -74,10 +75,9 @@ public class DeleteLibraryEndpointTests : IClassFixture HttpResponseMessage response = await client.DeleteAsync($"/api/v1/libraries/{Uri.EscapeDataString(maliciousLibraryId)}"); // Assert - // note: the {id} route parameter is Guid-typed, so the malicious value fails model binding before it reaches the handler - // note: observed status is 500 because FastEndpoints, combined with DontCatchExceptions(), turns the binding - // ValidationFailureException into a 500 response instead of 400/422 (pre-existing production bug, not fixed here) - // note: that 500 body leaks the ValidationFailureException details, so no DoesNotContain("Exception") is asserted here + // Note: the {id} route parameter is Guid-typed, so the malicious value fails model binding before it reaches the handler. + // The observed status is 500 because FastEndpoints, combined with DontCatchExceptions(), turns the binding ValidationFailureException into a 500 response instead of 400/422 (pre-existing production bug, not fixed here). + // That 500 body leaks the ValidationFailureException details, so no DoesNotContain("Exception") is asserted here. Assert.Equal(HttpStatusCode.InternalServerError, response.StatusCode); string content = await response.Content.ReadAsStringAsync(); Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase); @@ -86,6 +86,68 @@ public class DeleteLibraryEndpointTests : IClassFixture Assert.DoesNotContain("salt", content, StringComparison.OrdinalIgnoreCase); } + [Fact] + public async Task DeleteLibrary_WhenTheOwnerLacksTheManagePermission_ShouldReturnForbiddenAndKeepTheLibrary() + { + // Arrange + // The created user holds no permission, so it owns the library without being allowed to change it. + HttpClient client = _apiFactory.CreateClient(); + (Guid ownerId, string ownerUsername) = await _apiFactory.CreateAndAuthenticateUserAsync(client); + Guid libraryId = Guid.NewGuid(); + await _apiFactory.SeedLibraryAsync(libraryId, ownerId); + + // Act + HttpResponseMessage response = await client.DeleteAsync($"/api/v1/libraries/{libraryId}"); + + // Assert + Assert.Equal(HttpStatusCode.Forbidden, response.StatusCode); + string content = await response.Content.ReadAsStringAsync(); + Dictionary? problemDetails = JsonSerializer.Deserialize>(content, _jsonOptions); + Assert.NotNull(problemDetails); + Assert.Equal(StatusCodes.Status403Forbidden, problemDetails!["status"].GetInt32()); + Assert.Equal("NotAuthorized", problemDetails["detail"].GetString()); + Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase); + using (IServiceScope scope = _apiFactory.Services.CreateScope()) + { + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + Assert.NotNull(await dbContext.Libraries.FindAsync(libraryId)); + } + + await _apiFactory.RemoveTestUserAsync(ownerUsername); + } + + [Fact] + public async Task DeleteLibrary_WhenNonOwnerHoldsTheManagePermission_ShouldReturnForbiddenAndKeepTheLibrary() + { + // Arrange + // Ownership and the manage permission are both required, so a user that holds the permission must not delete a library it does not own. + HttpClient client = _apiFactory.CreateClient(); + (Guid ownerId, string ownerUsername) = await _apiFactory.CreateAndAuthenticateUserAsync(client); + Guid libraryId = Guid.NewGuid(); + await _apiFactory.SeedLibraryAsync(libraryId, ownerId); + (Guid _, string attackerUsername) = await _apiFactory.CreateAndAuthenticateUserWithPermissionAsync(client, AuthorizationPermission.CanCreateLibraries); + + // Act + HttpResponseMessage response = await client.DeleteAsync($"/api/v1/libraries/{libraryId}"); + + // Assert + Assert.Equal(HttpStatusCode.Forbidden, response.StatusCode); + string content = await response.Content.ReadAsStringAsync(); + Dictionary? problemDetails = JsonSerializer.Deserialize>(content, _jsonOptions); + Assert.NotNull(problemDetails); + Assert.Equal(StatusCodes.Status403Forbidden, problemDetails!["status"].GetInt32()); + Assert.Equal("NotAuthorized", problemDetails["detail"].GetString()); + Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase); + using (IServiceScope scope = _apiFactory.Services.CreateScope()) + { + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + Assert.NotNull(await dbContext.Libraries.FindAsync(libraryId)); + } + + await _apiFactory.RemoveTestUserAsync(ownerUsername); + await _apiFactory.RemoveTestUserAsync(attackerUsername); + } + /// /// Seeds a owned by . /// diff --git a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Library/Management/UpdateLibrary/UpdateLibraryEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Library/Management/UpdateLibrary/UpdateLibraryEndpointTests.cs index 2204a24c..d0abcadf 100644 --- a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Library/Management/UpdateLibrary/UpdateLibraryEndpointTests.cs +++ b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Library/Management/UpdateLibrary/UpdateLibraryEndpointTests.cs @@ -4,6 +4,7 @@ using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Manage using Lumina.Contracts.Fixtures.Core.Requests.MediaLibrary.Management; using Lumina.Contracts.Requests.MediaLibrary.Management; using Lumina.DataAccess.Core.UoW; +using Lumina.Domain.SharedKernel.Common.Enums.Authorization; using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; using Lumina.Presentation.Api.SecurityTests.Common.Setup; using Microsoft.AspNetCore.Http; @@ -13,6 +14,7 @@ using System.Diagnostics.CodeAnalysis; using System.Net; using System.Net.Http.Json; using System.Text.Json; +using System.Text.Json.Nodes; #endregion namespace Lumina.Presentation.Api.SecurityTests.Core.Endpoints.Library.Management.UpdateLibrary; @@ -49,7 +51,6 @@ public class UpdateLibraryEndpointTests : IClassFixture string libraryId = Guid.NewGuid().ToString(); UpdateLibraryRequest request = _updateLibraryRequestFixture.Create( id: Guid.NewGuid(), - userId: Guid.NewGuid(), title: "Updated Library", libraryType: "EBook", contentLocations: ["C:/Media"], @@ -79,8 +80,8 @@ public class UpdateLibraryEndpointTests : IClassFixture } [Theory] - [InlineData("' OR '1'='1")] // basic SQL injection - [InlineData("'; DROP TABLE Libraries--")] // destructive injection + [InlineData("' OR '1'='1")] // Basic SQL injection. + [InlineData("'; DROP TABLE Libraries--")] // Destructive injection. public async Task UpdateLibrary_WithSQLInjectionInTitle_ShouldNotLeakOrError(string maliciousTitle) { // Arrange @@ -90,7 +91,6 @@ public class UpdateLibraryEndpointTests : IClassFixture await SeedLibraryAsync(libraryId, userId); UpdateLibraryRequest request = _updateLibraryRequestFixture.Create( id: libraryId, - userId: userId, title: maliciousTitle, libraryType: "EBook", contentLocations: ["C:/Media"], @@ -106,7 +106,7 @@ public class UpdateLibraryEndpointTests : IClassFixture HttpResponseMessage response = await client.PutAsJsonAsync($"/api/v1/libraries/{libraryId}", request); // Assert - // the malicious title passes the authenticated handler, reaches the parameterized data access, and is persisted verbatim + // The malicious title passes the authenticated handler, reaches the parameterized data access, and is persisted verbatim. Assert.Equal(HttpStatusCode.OK, response.StatusCode); string content = await response.Content.ReadAsStringAsync(); Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase); @@ -123,10 +123,10 @@ public class UpdateLibraryEndpointTests : IClassFixture } [Theory] - [InlineData(-1)] // just below the allowed range - [InlineData(101)] // just above the allowed range - [InlineData(int.MinValue)] // lowest possible value - [InlineData(int.MaxValue)] // highest possible value + [InlineData(-1)] // Just below the allowed range. + [InlineData(101)] // Just above the allowed range. + [InlineData(int.MinValue)] // Lowest possible value. + [InlineData(int.MaxValue)] // Highest possible value. public async Task UpdateLibrary_WhenThresholdIsOutsideAllowedRange_ShouldRejectTheRequestAndKeepTheStoredSettings(int completionThresholdPercentage) { // Arrange @@ -136,7 +136,6 @@ public class UpdateLibraryEndpointTests : IClassFixture await SeedLibraryAsync(libraryId, userId, shouldTrackConsumptionProgress: true, completionThresholdPercentage: 70); UpdateLibraryRequest request = _updateLibraryRequestFixture.Create( id: libraryId, - userId: userId, title: "Test Library", libraryType: "EBook", contentLocations: ["C:/Media"], @@ -177,7 +176,6 @@ public class UpdateLibraryEndpointTests : IClassFixture await SeedLibraryAsync(libraryId, userId, shouldTrackConsumptionProgress: true, completionThresholdPercentage: 70); UpdateLibraryRequest request = _updateLibraryRequestFixture.Create( id: libraryId, - userId: userId, title: "Test Library", libraryType: "EBook", contentLocations: ["C:/Media"], @@ -223,7 +221,6 @@ public class UpdateLibraryEndpointTests : IClassFixture (Guid _, string attackerUsername) = await _apiFactory.CreateAndAuthenticateUserAsync(client); UpdateLibraryRequest request = _updateLibraryRequestFixture.Create( id: libraryId, - userId: ownerId, title: "Test Library", libraryType: "EBook", contentLocations: ["C:/Media"], @@ -275,6 +272,129 @@ public class UpdateLibraryEndpointTests : IClassFixture await _apiFactory.RemoveTestUserAsync(ownerUsername); } + [Fact] + public async Task UpdateLibrary_WhenNonOwnerHoldsTheManagePermission_ShouldReturnForbiddenAndKeepTheLibrary() + { + // Arrange + // Ownership and the manage permission are both required, so a user that holds the permission must not update a library it does not own. + HttpClient client = _apiFactory.CreateClient(); + (Guid ownerId, string ownerUsername) = await _apiFactory.CreateAndAuthenticateUserAsync(client); + Guid libraryId = Guid.NewGuid(); + await SeedLibraryAsync(libraryId, ownerId, title: "Original Title"); + (Guid _, string attackerUsername) = await _apiFactory.CreateAndAuthenticateUserWithPermissionAsync(client, AuthorizationPermission.CanCreateLibraries); + UpdateLibraryRequest request = _updateLibraryRequestFixture.Create( + id: libraryId, + title: "Updated Title", + libraryType: "EBook", + contentLocations: ["C:/Media"], + coverImage: null); + + // Act + HttpResponseMessage response = await client.PutAsJsonAsync($"/api/v1/libraries/{libraryId}", request); + + // Assert + Assert.Equal(HttpStatusCode.Forbidden, response.StatusCode); + string content = await response.Content.ReadAsStringAsync(); + Dictionary? problemDetails = JsonSerializer.Deserialize>(content, _jsonOptions); + Assert.NotNull(problemDetails); + Assert.Equal(StatusCodes.Status403Forbidden, problemDetails!["status"].GetInt32()); + Assert.Equal("NotAuthorized", problemDetails["detail"].GetString()); + Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase); + using (IServiceScope scope = _apiFactory.Services.CreateScope()) + { + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + LibraryEntity? storedLibrary = await dbContext.Libraries.FirstOrDefaultAsync(library => library.Id == libraryId); + Assert.NotNull(storedLibrary); + Assert.Equal("Original Title", storedLibrary!.Title); + } + + await _apiFactory.RemoveTestUserAsync(ownerUsername); + await _apiFactory.RemoveTestUserAsync(attackerUsername); + } + + [Fact] + public async Task UpdateLibrary_WhenTheOwnerLacksTheManagePermission_ShouldReturnForbiddenAndKeepTheLibrary() + { + // Arrange + // The created user holds no permission, so it owns the library without being allowed to change it. + HttpClient client = _apiFactory.CreateClient(); + (Guid ownerId, string ownerUsername) = await _apiFactory.CreateAndAuthenticateUserAsync(client); + Guid libraryId = Guid.NewGuid(); + await SeedLibraryAsync(libraryId, ownerId, title: "Original Title"); + UpdateLibraryRequest request = _updateLibraryRequestFixture.Create( + id: libraryId, + title: "Updated Title", + libraryType: "Book", + contentLocations: ["C:/Media"], + coverImage: null + ); + + // Act + HttpResponseMessage response = await client.PutAsJsonAsync($"/api/v1/libraries/{libraryId}", request); + + // Assert + Assert.Equal(HttpStatusCode.Forbidden, response.StatusCode); + string content = await response.Content.ReadAsStringAsync(); + Dictionary? problemDetails = JsonSerializer.Deserialize>(content, _jsonOptions); + Assert.NotNull(problemDetails); + Assert.Equal(StatusCodes.Status403Forbidden, problemDetails!["status"].GetInt32()); + Assert.Equal("NotAuthorized", problemDetails["detail"].GetString()); + Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase); + using (IServiceScope scope = _apiFactory.Services.CreateScope()) + { + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + LibraryEntity? storedLibrary = await dbContext.Libraries.FirstOrDefaultAsync(library => library.Id == libraryId); + Assert.NotNull(storedLibrary); + Assert.Equal("Original Title", storedLibrary!.Title); + Assert.Equal(LibraryType.EBook, storedLibrary.LibraryType); + } + + await _apiFactory.RemoveTestUserAsync(ownerUsername); + } + + [Fact] + public async Task UpdateLibrary_WhenBodyNamesAnotherOwner_ShouldKeepTheStoredOwner() + { + // Arrange + HttpClient ownerClient = _apiFactory.CreateClient(); + (Guid ownerId, string ownerUsername) = await _apiFactory.CreateAndAuthenticateUserAsync(ownerClient); + Guid libraryId = Guid.NewGuid(); + await SeedLibraryAsync(libraryId, ownerId); + HttpClient client = _apiFactory.CreateClient(); + Guid adminId = await _apiFactory.CreateAndAuthenticateAdminUserAsync(client); + UpdateLibraryRequest request = _updateLibraryRequestFixture.Create( + id: libraryId, + title: "Test Library", + libraryType: "EBook", + contentLocations: ["C:/Media"], + coverImage: null, + isEnabled: true, + isLocked: false, + canDownloadMetadataFromWeb: true, + shouldSaveMetadataInMediaDirectories: false, + shouldSkipUnchangedDirectoriesDuringScan: true + ); + // The request has no owner, so the claimed owner is added to the raw body, the way a crafted request would carry it. + JsonObject body = JsonSerializer.SerializeToNode(request, new JsonSerializerOptions(JsonSerializerDefaults.Web))!.AsObject(); + body["userId"] = adminId.ToString(); + + // Act + HttpResponseMessage response = await client.PutAsJsonAsync($"/api/v1/libraries/{libraryId}", body); + + // Assert + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + using (IServiceScope scope = _apiFactory.Services.CreateScope()) + { + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + LibraryEntity? storedLibrary = await dbContext.Libraries.FirstOrDefaultAsync(library => library.Id == libraryId); + Assert.NotNull(storedLibrary); + Assert.Equal(ownerId, storedLibrary!.UserId); + } + + await _apiFactory.RemoveTestUserAsync(ownerUsername); + await _apiFactory.RemoveAdminUserAsync(adminId); + } + /// /// Asserts that carries the standard validation problem of the update library route. /// diff --git a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Plugins/GetLibraryTypeArtworkProviders/GetLibraryTypeArtworkProvidersEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Plugins/GetLibraryTypeArtworkProviders/GetLibraryTypeArtworkProvidersEndpointTests.cs new file mode 100644 index 00000000..c7f32ee1 --- /dev/null +++ b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Plugins/GetLibraryTypeArtworkProviders/GetLibraryTypeArtworkProvidersEndpointTests.cs @@ -0,0 +1,114 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Api.Core.Endpoints.Plugins.GetLibraryTypeArtworkProviders; +using Lumina.Presentation.Api.SecurityTests.Common.Setup; +using Microsoft.AspNetCore.Http; +using System; +using System.Diagnostics.CodeAnalysis; +using System.Net; +using System.Text.Json; +#endregion + +namespace Lumina.Presentation.Api.SecurityTests.Core.Endpoints.Plugins.GetLibraryTypeArtworkProviders; + +/// +/// Contains security tests for the class. +/// +[ExcludeFromCodeCoverage] +public class GetLibraryTypeArtworkProvidersEndpointTests : IClassFixture, IDisposable +{ + private readonly LuminaApiFactory _apiFactory; + private readonly HttpClient _client; + private readonly JsonSerializerOptions _jsonOptions = new() + { + PropertyNameCaseInsensitive = true + }; + + /// + /// Initializes a new instance of the class. + /// + /// Injected in-memory API factory. + public GetLibraryTypeArtworkProvidersEndpointTests(LuminaApiFactory apiFactory) + { + _apiFactory = apiFactory; + _client = apiFactory.CreateClient(); + // A unique X-Forwarded-For isolates rate limiting state per test. + _client.DefaultRequestHeaders.Add("X-Forwarded-For", LuminaApiFactory.GetUniqueTestIp()); + } + + [Fact] + public async Task GetLibraryTypeArtworkProviders_WhenUnauthorized_ShouldReturnUnauthorizedResult() + { + // Arrange + string libraryType = "Music"; + + // Act + HttpResponseMessage response = await _client.GetAsync($"/api/v1/libraries/artwork-providers/{libraryType}"); + + // Assert + Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode); + + string content = await response.Content.ReadAsStringAsync(); + + Dictionary? problemDetails = JsonSerializer.Deserialize>(content, _jsonOptions); + Assert.NotNull(problemDetails); + Assert.Equal(StatusCodes.Status401Unauthorized, problemDetails!["status"].GetInt32()); + Assert.Equal("https://tools.ietf.org/html/rfc7235#section-3.1", problemDetails["type"].GetString()); + Assert.Equal("Unauthorized", problemDetails["title"].GetString()); + Assert.Equal($"/api/v1/libraries/artwork-providers/{libraryType}", problemDetails["instance"].GetProperty("value").GetString()); + Assert.Equal("Authentication failed", problemDetails["detail"].GetString()); + } + + [Theory] + [InlineData("' OR '1'='1")] // Basic SQL injection. + [InlineData("'; DROP TABLE Libraries--")] // Destructive SQL injection. + [InlineData("Music; rm -rf /")] // Command injection. + [InlineData("$(whoami)")] // Command substitution injection. + [InlineData("`whoami`")] // Backtick command injection. + [InlineData("{0}{1}{0}")] // Template/placeholder injection. + [InlineData("..\\..\\..\\Windows\\System32\\config\\SAM")] // Windows path traversal. + [InlineData("%2e%2e%2fetc%2fpasswd")] // Encoded path traversal. + public async Task GetLibraryTypeArtworkProviders_WithInjectionInLibraryType_ShouldNotLeakOrError(string maliciousLibraryType) + { + // Arrange + HttpClient client = _apiFactory.CreateClient(); + await _apiFactory.CreateAndAuthenticateAdminUserAsync(client); + + // Act + HttpResponseMessage response = await client.GetAsync($"/api/v1/libraries/artwork-providers/{Uri.EscapeDataString(maliciousLibraryType)}"); + string content = await response.Content.ReadAsStringAsync(); + + // Assert + // An unrecognized library type fails the validation of the query, so it is reported as a validation problem, and the response + // must stay generic: the failed request leaks no database, filesystem or framework internals. + Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode); + + Dictionary? problemDetails = JsonSerializer.Deserialize>(content, _jsonOptions); + Assert.NotNull(problemDetails); + Assert.Equal(StatusCodes.Status422UnprocessableEntity, problemDetails!["status"].GetInt32()); + Assert.Equal("https://tools.ietf.org/html/rfc4918#section-11.2", problemDetails["type"].GetString()); + Assert.Equal("General.Validation", problemDetails["title"].GetString()); + Assert.Equal("OneOrMoreValidationErrorsOccurred", problemDetails["detail"].GetString()); + Dictionary? errors = problemDetails["errors"].Deserialize>(_jsonOptions); + Assert.NotNull(errors); + Assert.Contains("UnknownLibraryType", errors!["General.Validation"]); + Assert.StartsWith("/api/v1/libraries/artwork-providers/", problemDetails["instance"].GetString()); + Assert.NotNull(problemDetails["traceId"].GetString()); + Assert.NotEmpty(problemDetails["traceId"].GetString()!); + + Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("stack trace", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain(AppContext.BaseDirectory, content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("password", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("hash", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("salt", content, StringComparison.OrdinalIgnoreCase); + } + + /// + /// Disposes the API factory resources. + /// + public void Dispose() + { + _client.Dispose(); + } +} diff --git a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Plugins/GetLibraryTypeBookReaders/GetLibraryTypeBookReadersEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Plugins/GetLibraryTypeBookReaders/GetLibraryTypeBookReadersEndpointTests.cs new file mode 100644 index 00000000..ea29c351 --- /dev/null +++ b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Plugins/GetLibraryTypeBookReaders/GetLibraryTypeBookReadersEndpointTests.cs @@ -0,0 +1,114 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Api.Core.Endpoints.Plugins.GetLibraryTypeBookReaders; +using Lumina.Presentation.Api.SecurityTests.Common.Setup; +using Microsoft.AspNetCore.Http; +using System; +using System.Diagnostics.CodeAnalysis; +using System.Net; +using System.Text.Json; +#endregion + +namespace Lumina.Presentation.Api.SecurityTests.Core.Endpoints.Plugins.GetLibraryTypeBookReaders; + +/// +/// Contains security tests for the class. +/// +[ExcludeFromCodeCoverage] +public class GetLibraryTypeBookReadersEndpointTests : IClassFixture, IDisposable +{ + private readonly LuminaApiFactory _apiFactory; + private readonly HttpClient _client; + private readonly JsonSerializerOptions _jsonOptions = new() + { + PropertyNameCaseInsensitive = true + }; + + /// + /// Initializes a new instance of the class. + /// + /// Injected in-memory API factory. + public GetLibraryTypeBookReadersEndpointTests(LuminaApiFactory apiFactory) + { + _apiFactory = apiFactory; + _client = apiFactory.CreateClient(); + // A unique X-Forwarded-For isolates rate limiting state per test. + _client.DefaultRequestHeaders.Add("X-Forwarded-For", LuminaApiFactory.GetUniqueTestIp()); + } + + [Fact] + public async Task GetLibraryTypeBookReaders_WhenUnauthorized_ShouldReturnUnauthorizedResult() + { + // Arrange + string libraryType = "Music"; + + // Act + HttpResponseMessage response = await _client.GetAsync($"/api/v1/libraries/book-readers/{libraryType}"); + + // Assert + Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode); + + string content = await response.Content.ReadAsStringAsync(); + + Dictionary? problemDetails = JsonSerializer.Deserialize>(content, _jsonOptions); + Assert.NotNull(problemDetails); + Assert.Equal(StatusCodes.Status401Unauthorized, problemDetails!["status"].GetInt32()); + Assert.Equal("https://tools.ietf.org/html/rfc7235#section-3.1", problemDetails["type"].GetString()); + Assert.Equal("Unauthorized", problemDetails["title"].GetString()); + Assert.Equal($"/api/v1/libraries/book-readers/{libraryType}", problemDetails["instance"].GetProperty("value").GetString()); + Assert.Equal("Authentication failed", problemDetails["detail"].GetString()); + } + + [Theory] + [InlineData("' OR '1'='1")] // Basic SQL injection. + [InlineData("'; DROP TABLE Libraries--")] // Destructive SQL injection. + [InlineData("Music; rm -rf /")] // Command injection. + [InlineData("$(whoami)")] // Command substitution injection. + [InlineData("`whoami`")] // Backtick command injection. + [InlineData("{0}{1}{0}")] // Template/placeholder injection. + [InlineData("..\\..\\..\\Windows\\System32\\config\\SAM")] // Windows path traversal. + [InlineData("%2e%2e%2fetc%2fpasswd")] // Encoded path traversal. + public async Task GetLibraryTypeBookReaders_WithInjectionInLibraryType_ShouldNotLeakOrError(string maliciousLibraryType) + { + // Arrange + HttpClient client = _apiFactory.CreateClient(); + await _apiFactory.CreateAndAuthenticateAdminUserAsync(client); + + // Act + HttpResponseMessage response = await client.GetAsync($"/api/v1/libraries/book-readers/{Uri.EscapeDataString(maliciousLibraryType)}"); + string content = await response.Content.ReadAsStringAsync(); + + // Assert + // An unrecognized library type fails the validation of the query, so it is reported as a validation problem, and the response + // must stay generic: the failed request leaks no database, filesystem or framework internals. + Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode); + + Dictionary? problemDetails = JsonSerializer.Deserialize>(content, _jsonOptions); + Assert.NotNull(problemDetails); + Assert.Equal(StatusCodes.Status422UnprocessableEntity, problemDetails!["status"].GetInt32()); + Assert.Equal("https://tools.ietf.org/html/rfc4918#section-11.2", problemDetails["type"].GetString()); + Assert.Equal("General.Validation", problemDetails["title"].GetString()); + Assert.Equal("OneOrMoreValidationErrorsOccurred", problemDetails["detail"].GetString()); + Dictionary? errors = problemDetails["errors"].Deserialize>(_jsonOptions); + Assert.NotNull(errors); + Assert.Contains("UnknownLibraryType", errors!["General.Validation"]); + Assert.StartsWith("/api/v1/libraries/book-readers/", problemDetails["instance"].GetString()); + Assert.NotNull(problemDetails["traceId"].GetString()); + Assert.NotEmpty(problemDetails["traceId"].GetString()!); + + Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("stack trace", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain(AppContext.BaseDirectory, content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("password", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("hash", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("salt", content, StringComparison.OrdinalIgnoreCase); + } + + /// + /// Disposes the API factory resources. + /// + public void Dispose() + { + _client.Dispose(); + } +} diff --git a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Plugins/GetLibraryTypeMetadataProviders/GetLibraryTypeMetadataProvidersEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Plugins/GetLibraryTypeMetadataProviders/GetLibraryTypeMetadataProvidersEndpointTests.cs new file mode 100644 index 00000000..7b5563e3 --- /dev/null +++ b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Plugins/GetLibraryTypeMetadataProviders/GetLibraryTypeMetadataProvidersEndpointTests.cs @@ -0,0 +1,114 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Api.Core.Endpoints.Plugins.GetLibraryTypeMetadataProviders; +using Lumina.Presentation.Api.SecurityTests.Common.Setup; +using Microsoft.AspNetCore.Http; +using System; +using System.Diagnostics.CodeAnalysis; +using System.Net; +using System.Text.Json; +#endregion + +namespace Lumina.Presentation.Api.SecurityTests.Core.Endpoints.Plugins.GetLibraryTypeMetadataProviders; + +/// +/// Contains security tests for the class. +/// +[ExcludeFromCodeCoverage] +public class GetLibraryTypeMetadataProvidersEndpointTests : IClassFixture, IDisposable +{ + private readonly LuminaApiFactory _apiFactory; + private readonly HttpClient _client; + private readonly JsonSerializerOptions _jsonOptions = new() + { + PropertyNameCaseInsensitive = true + }; + + /// + /// Initializes a new instance of the class. + /// + /// Injected in-memory API factory. + public GetLibraryTypeMetadataProvidersEndpointTests(LuminaApiFactory apiFactory) + { + _apiFactory = apiFactory; + _client = apiFactory.CreateClient(); + // A unique X-Forwarded-For isolates rate limiting state per test. + _client.DefaultRequestHeaders.Add("X-Forwarded-For", LuminaApiFactory.GetUniqueTestIp()); + } + + [Fact] + public async Task GetLibraryTypeMetadataProviders_WhenUnauthorized_ShouldReturnUnauthorizedResult() + { + // Arrange + string libraryType = "Music"; + + // Act + HttpResponseMessage response = await _client.GetAsync($"/api/v1/libraries/metadata-providers/{libraryType}"); + + // Assert + Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode); + + string content = await response.Content.ReadAsStringAsync(); + + Dictionary? problemDetails = JsonSerializer.Deserialize>(content, _jsonOptions); + Assert.NotNull(problemDetails); + Assert.Equal(StatusCodes.Status401Unauthorized, problemDetails!["status"].GetInt32()); + Assert.Equal("https://tools.ietf.org/html/rfc7235#section-3.1", problemDetails["type"].GetString()); + Assert.Equal("Unauthorized", problemDetails["title"].GetString()); + Assert.Equal($"/api/v1/libraries/metadata-providers/{libraryType}", problemDetails["instance"].GetProperty("value").GetString()); + Assert.Equal("Authentication failed", problemDetails["detail"].GetString()); + } + + [Theory] + [InlineData("' OR '1'='1")] // Basic SQL injection. + [InlineData("'; DROP TABLE Libraries--")] // Destructive SQL injection. + [InlineData("Music; rm -rf /")] // Command injection. + [InlineData("$(whoami)")] // Command substitution injection. + [InlineData("`whoami`")] // Backtick command injection. + [InlineData("{0}{1}{0}")] // Template/placeholder injection. + [InlineData("..\\..\\..\\Windows\\System32\\config\\SAM")] // Windows path traversal. + [InlineData("%2e%2e%2fetc%2fpasswd")] // Encoded path traversal. + public async Task GetLibraryTypeMetadataProviders_WithInjectionInLibraryType_ShouldNotLeakOrError(string maliciousLibraryType) + { + // Arrange + HttpClient client = _apiFactory.CreateClient(); + await _apiFactory.CreateAndAuthenticateAdminUserAsync(client); + + // Act + HttpResponseMessage response = await client.GetAsync($"/api/v1/libraries/metadata-providers/{Uri.EscapeDataString(maliciousLibraryType)}"); + string content = await response.Content.ReadAsStringAsync(); + + // Assert + // An unrecognized library type fails the validation of the query, so it is reported as a validation problem, and the response + // must stay generic: the failed request leaks no database, filesystem or framework internals. + Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode); + + Dictionary? problemDetails = JsonSerializer.Deserialize>(content, _jsonOptions); + Assert.NotNull(problemDetails); + Assert.Equal(StatusCodes.Status422UnprocessableEntity, problemDetails!["status"].GetInt32()); + Assert.Equal("https://tools.ietf.org/html/rfc4918#section-11.2", problemDetails["type"].GetString()); + Assert.Equal("General.Validation", problemDetails["title"].GetString()); + Assert.Equal("OneOrMoreValidationErrorsOccurred", problemDetails["detail"].GetString()); + Dictionary? errors = problemDetails["errors"].Deserialize>(_jsonOptions); + Assert.NotNull(errors); + Assert.Contains("UnknownLibraryType", errors!["General.Validation"]); + Assert.StartsWith("/api/v1/libraries/metadata-providers/", problemDetails["instance"].GetString()); + Assert.NotNull(problemDetails["traceId"].GetString()); + Assert.NotEmpty(problemDetails["traceId"].GetString()!); + + Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("stack trace", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain(AppContext.BaseDirectory, content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("password", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("hash", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("salt", content, StringComparison.OrdinalIgnoreCase); + } + + /// + /// Disposes the API factory resources. + /// + public void Dispose() + { + _client.Dispose(); + } +} diff --git a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Plugins/ReorderLibraryArtworkProviders/ReorderLibraryArtworkProvidersEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Plugins/ReorderLibraryArtworkProviders/ReorderLibraryArtworkProvidersEndpointTests.cs deleted file mode 100644 index ac511655..00000000 --- a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Plugins/ReorderLibraryArtworkProviders/ReorderLibraryArtworkProvidersEndpointTests.cs +++ /dev/null @@ -1,133 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management; -using Lumina.Application.Fixtures.Common.DataAccess.Entities.Plugins; -using Lumina.Contracts.Fixtures.Core.Requests.Plugins; -using Lumina.Contracts.Requests.Plugins; -using Lumina.DataAccess.Core.UoW; -using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; -using Lumina.Presentation.Api.SecurityTests.Common.Setup; -using Microsoft.AspNetCore.Http; -using Microsoft.Extensions.DependencyInjection; -using System.Diagnostics.CodeAnalysis; -using System.Net; -using System.Net.Http.Json; -using System.Text.Json; -#endregion - -namespace Lumina.Presentation.Api.SecurityTests.Core.Endpoints.Plugins.ReorderLibraryArtworkProviders; - -/// -/// Contains security tests for the class. -/// -[ExcludeFromCodeCoverage] -public class ReorderLibraryArtworkProvidersEndpointTests : IClassFixture -{ - private readonly HttpClient _client; - private readonly LuminaApiFactory _apiFactory; - private readonly JsonSerializerOptions _jsonOptions = new() - { - PropertyNameCaseInsensitive = true - }; - private readonly LibraryEntityFixture _libraryEntityFixture = new(); - private readonly LibraryArtworkProviderConfigurationEntityFixture _libraryArtworkProviderConfigurationEntityFixture = new(); - private readonly ReorderLibraryArtworkProvidersRequestFixture _reorderLibraryArtworkProvidersRequestFixture = new(); - - /// - /// Initializes a new instance of the class. - /// - /// Injected in-memory API factory. - public ReorderLibraryArtworkProvidersEndpointTests(LuminaApiFactory apiFactory) - { - _apiFactory = apiFactory; - _client = apiFactory.CreateClient(); - } - - [Fact] - public async Task ReorderLibraryArtworkProviders_WhenUnauthorized_ShouldReturnUnauthorizedResult() - { - // Arrange - string libraryId = Guid.NewGuid().ToString(); - ReorderLibraryArtworkProvidersRequest request = _reorderLibraryArtworkProvidersRequestFixture.Create( - libraryId: Guid.NewGuid(), - pluginIds: [Guid.NewGuid()] - ); - - // Act - HttpResponseMessage response = await _client.PutAsJsonAsync($"/api/v1/libraries/{libraryId}/artwork-providers/reorder", request); - - // Assert - Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode); - - string content = await response.Content.ReadAsStringAsync(); - - Dictionary? problemDetails = JsonSerializer.Deserialize>(content, _jsonOptions); - Assert.NotNull(problemDetails); - Assert.Equal(StatusCodes.Status401Unauthorized, problemDetails!["status"].GetInt32()); - Assert.Equal("https://tools.ietf.org/html/rfc7235#section-3.1", problemDetails["type"].GetString()); - Assert.Equal("Unauthorized", problemDetails["title"].GetString()); - Assert.Equal($"/api/v1/libraries/{libraryId}/artwork-providers/reorder", problemDetails["instance"].GetProperty("value").GetString()); - Assert.Equal("Authentication failed", problemDetails["detail"].GetString()); - } - - [Theory] - [InlineData("' OR '1'='1")] // basic SQL injection - [InlineData("'; DROP TABLE Plugins--")] // destructive injection - public async Task ReorderLibraryArtworkProviders_WithSQLInjectionInPluginIds_ShouldNotLeakOrError(string maliciousPluginId) - { - // Arrange - // authenticate with an admin user and seed a library with artwork provider configurations, so valid ids would reach the handler - HttpClient client = _apiFactory.CreateClient(); - Guid userId = await _apiFactory.CreateAndAuthenticateAdminUserAsync(client); - Guid libraryId = await SeedLibraryAsync(userId); - await SeedConfigurationAsync(libraryId, rank: 1); - await SeedConfigurationAsync(libraryId, rank: 2); - - // Act - // the malicious value cannot bind to the Guid-typed PluginIds request property, so the body fails JSON deserialization - // before it ever reaches the endpoint handler - HttpResponseMessage response = await client.PutAsJsonAsync( - $"/api/v1/libraries/{libraryId}/artwork-providers/reorder", - new { libraryId, pluginIds = new[] { maliciousPluginId } }); - - // Assert - // note: observed status is 500 because the JSON body cannot be deserialized into the Guid-typed PluginIds property, and - // FastEndpoints, combined with DontCatchExceptions(), turns the resulting JsonException into a 500 response instead of 400 - // (pre-existing production bug, not fixed here) - // note: that 500 body leaks the JsonException details, so no DoesNotContain("Exception") is asserted here - Assert.Equal(HttpStatusCode.InternalServerError, response.StatusCode); - string content = await response.Content.ReadAsStringAsync(); - Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase); - Assert.DoesNotContain("password", content, StringComparison.OrdinalIgnoreCase); - Assert.DoesNotContain("hash", content, StringComparison.OrdinalIgnoreCase); - Assert.DoesNotContain("salt", content, StringComparison.OrdinalIgnoreCase); - } - - /// - /// Seeds a owned by . - /// - /// The Id of the user that owns the library. - /// The Id of the seeded library. - private async Task SeedLibraryAsync(Guid userId) - { - using IServiceScope scope = _apiFactory.Services.CreateScope(); - LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); - Guid libraryId = Guid.NewGuid(); - dbContext.Libraries.Add(_libraryEntityFixture.Create(id: libraryId, userId: userId, title: "Test Library", libraryType: LibraryType.EBook, contentLocations: [])); - await dbContext.SaveChangesAsync(); - return libraryId; - } - - /// - /// Seeds a for the library identified by . - /// - /// The Id of the media library. - /// The rank of the provider. - /// A task representing the asynchronous operation. - private async Task SeedConfigurationAsync(Guid libraryId, int rank) - { - using IServiceScope scope = _apiFactory.Services.CreateScope(); - LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); - dbContext.LibraryArtworkProviderConfigurations.Add(_libraryArtworkProviderConfigurationEntityFixture.Create(libraryId: libraryId, pluginId: Guid.NewGuid(), rank: rank)); - await dbContext.SaveChangesAsync(); - } -} diff --git a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Plugins/ReorderLibraryMetadataProviders/ReorderLibraryMetadataProvidersEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Plugins/ReorderLibraryMetadataProviders/ReorderLibraryMetadataProvidersEndpointTests.cs deleted file mode 100644 index d7604735..00000000 --- a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Plugins/ReorderLibraryMetadataProviders/ReorderLibraryMetadataProvidersEndpointTests.cs +++ /dev/null @@ -1,133 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management; -using Lumina.Application.Fixtures.Common.DataAccess.Entities.Plugins; -using Lumina.Contracts.Fixtures.Core.Requests.Plugins; -using Lumina.Contracts.Requests.Plugins; -using Lumina.DataAccess.Core.UoW; -using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; -using Lumina.Presentation.Api.SecurityTests.Common.Setup; -using Microsoft.AspNetCore.Http; -using Microsoft.Extensions.DependencyInjection; -using System.Diagnostics.CodeAnalysis; -using System.Net; -using System.Net.Http.Json; -using System.Text.Json; -#endregion - -namespace Lumina.Presentation.Api.SecurityTests.Core.Endpoints.Plugins.ReorderLibraryMetadataProviders; - -/// -/// Contains security tests for the class. -/// -[ExcludeFromCodeCoverage] -public class ReorderLibraryMetadataProvidersEndpointTests : IClassFixture -{ - private readonly HttpClient _client; - private readonly LuminaApiFactory _apiFactory; - private readonly JsonSerializerOptions _jsonOptions = new() - { - PropertyNameCaseInsensitive = true - }; - private readonly LibraryEntityFixture _libraryEntityFixture = new(); - private readonly LibraryMetadataProviderConfigurationEntityFixture _libraryMetadataProviderConfigurationEntityFixture = new(); - private readonly ReorderLibraryMetadataProvidersRequestFixture _reorderLibraryMetadataProvidersRequestFixture = new(); - - /// - /// Initializes a new instance of the class. - /// - /// Injected in-memory API factory. - public ReorderLibraryMetadataProvidersEndpointTests(LuminaApiFactory apiFactory) - { - _apiFactory = apiFactory; - _client = apiFactory.CreateClient(); - } - - [Fact] - public async Task ReorderLibraryMetadataProviders_WhenUnauthorized_ShouldReturnUnauthorizedResult() - { - // Arrange - string libraryId = Guid.NewGuid().ToString(); - ReorderLibraryMetadataProvidersRequest request = _reorderLibraryMetadataProvidersRequestFixture.Create( - libraryId: Guid.NewGuid(), - pluginIds: [Guid.NewGuid()] - ); - - // Act - HttpResponseMessage response = await _client.PutAsJsonAsync($"/api/v1/libraries/{libraryId}/metadata-providers/reorder", request); - - // Assert - Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode); - - string content = await response.Content.ReadAsStringAsync(); - - Dictionary? problemDetails = JsonSerializer.Deserialize>(content, _jsonOptions); - Assert.NotNull(problemDetails); - Assert.Equal(StatusCodes.Status401Unauthorized, problemDetails!["status"].GetInt32()); - Assert.Equal("https://tools.ietf.org/html/rfc7235#section-3.1", problemDetails["type"].GetString()); - Assert.Equal("Unauthorized", problemDetails["title"].GetString()); - Assert.Equal($"/api/v1/libraries/{libraryId}/metadata-providers/reorder", problemDetails["instance"].GetProperty("value").GetString()); - Assert.Equal("Authentication failed", problemDetails["detail"].GetString()); - } - - [Theory] - [InlineData("' OR '1'='1")] // basic SQL injection - [InlineData("'; DROP TABLE Plugins--")] // destructive injection - public async Task ReorderLibraryMetadataProviders_WithSQLInjectionInPluginIds_ShouldNotLeakOrError(string maliciousPluginId) - { - // Arrange - // authenticate with an admin user and seed a library with metadata provider configurations, so valid ids would reach the handler - HttpClient client = _apiFactory.CreateClient(); - Guid userId = await _apiFactory.CreateAndAuthenticateAdminUserAsync(client); - Guid libraryId = await SeedLibraryAsync(userId); - await SeedConfigurationAsync(libraryId, rank: 1); - await SeedConfigurationAsync(libraryId, rank: 2); - - // Act - // the malicious value cannot bind to the Guid-typed PluginIds request property, so the body fails JSON deserialization - // before it ever reaches the endpoint handler - HttpResponseMessage response = await client.PutAsJsonAsync( - $"/api/v1/libraries/{libraryId}/metadata-providers/reorder", - new { libraryId = libraryId, pluginIds = new[] { maliciousPluginId } }); - - // Assert - // note: observed status is 500 because the JSON body cannot be deserialized into the Guid-typed PluginIds property, and - // FastEndpoints, combined with DontCatchExceptions(), turns the resulting JsonException into a 500 response instead of 400 - // (pre-existing production bug, not fixed here) - // note: that 500 body leaks the JsonException details, so no DoesNotContain("Exception") is asserted here - Assert.Equal(HttpStatusCode.InternalServerError, response.StatusCode); - string content = await response.Content.ReadAsStringAsync(); - Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase); - Assert.DoesNotContain("password", content, StringComparison.OrdinalIgnoreCase); - Assert.DoesNotContain("hash", content, StringComparison.OrdinalIgnoreCase); - Assert.DoesNotContain("salt", content, StringComparison.OrdinalIgnoreCase); - } - - /// - /// Seeds a owned by . - /// - /// The Id of the user that owns the library. - /// The Id of the seeded library. - private async Task SeedLibraryAsync(Guid userId) - { - using IServiceScope scope = _apiFactory.Services.CreateScope(); - LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); - Guid libraryId = Guid.NewGuid(); - dbContext.Libraries.Add(_libraryEntityFixture.Create(id: libraryId, userId: userId, title: "Test Library", libraryType: LibraryType.EBook, contentLocations: [])); - await dbContext.SaveChangesAsync(); - return libraryId; - } - - /// - /// Seeds a for the library identified by . - /// - /// The Id of the media library. - /// The rank of the provider. - /// A task representing the asynchronous operation. - private async Task SeedConfigurationAsync(Guid libraryId, int rank) - { - using IServiceScope scope = _apiFactory.Services.CreateScope(); - LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); - dbContext.LibraryMetadataProviderConfigurations.Add(_libraryMetadataProviderConfigurationEntityFixture.Create(libraryId: libraryId, pluginId: Guid.NewGuid(), rank: rank)); - await dbContext.SaveChangesAsync(); - } -} diff --git a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Plugins/SetLibraryArtworkProviderEnabled/SetLibraryArtworkProviderEnabledEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Plugins/SetLibraryArtworkProviderEnabled/SetLibraryArtworkProviderEnabledEndpointTests.cs deleted file mode 100644 index ad92bf3c..00000000 --- a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Plugins/SetLibraryArtworkProviderEnabled/SetLibraryArtworkProviderEnabledEndpointTests.cs +++ /dev/null @@ -1,126 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management; -using Lumina.Application.Fixtures.Common.DataAccess.Entities.Plugins; -using Lumina.Contracts.Fixtures.Core.Requests.Plugins; -using Lumina.Contracts.Requests.Plugins; -using Lumina.DataAccess.Core.UoW; -using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; -using Lumina.Presentation.Api.SecurityTests.Common.Setup; -using Microsoft.AspNetCore.Http; -using Microsoft.Extensions.DependencyInjection; -using System.Diagnostics.CodeAnalysis; -using System.Net; -using System.Net.Http.Json; -using System.Text.Json; -#endregion - -namespace Lumina.Presentation.Api.SecurityTests.Core.Endpoints.Plugins.SetLibraryArtworkProviderEnabled; - -/// -/// Contains security tests for the class. -/// -[ExcludeFromCodeCoverage] -public class SetLibraryArtworkProviderEnabledEndpointTests : IClassFixture -{ - private readonly HttpClient _client; - private readonly LuminaApiFactory _apiFactory; - private readonly JsonSerializerOptions _jsonOptions = new() - { - PropertyNameCaseInsensitive = true - }; - private readonly LibraryEntityFixture _libraryEntityFixture = new(); - private readonly LibraryArtworkProviderConfigurationEntityFixture _libraryArtworkProviderConfigurationEntityFixture = new(); - private readonly SetLibraryArtworkProviderEnabledRequestFixture _setLibraryArtworkProviderEnabledRequestFixture = new(); - - /// - /// Initializes a new instance of the class. - /// - /// Injected in-memory API factory. - public SetLibraryArtworkProviderEnabledEndpointTests(LuminaApiFactory apiFactory) - { - _apiFactory = apiFactory; - _client = apiFactory.CreateClient(); - } - - [Fact] - public async Task SetLibraryArtworkProviderEnabled_WhenUnauthorized_ShouldReturnUnauthorizedResult() - { - // Arrange - string libraryId = Guid.NewGuid().ToString(); - string pluginId = Guid.NewGuid().ToString(); - SetLibraryArtworkProviderEnabledRequest request = _setLibraryArtworkProviderEnabledRequestFixture.Create(); - - // Act - HttpResponseMessage response = await _client.PutAsJsonAsync($"/api/v1/libraries/{libraryId}/artwork-providers/{pluginId}/enabled", request); - - // Assert - Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode); - - string content = await response.Content.ReadAsStringAsync(); - - Dictionary? problemDetails = JsonSerializer.Deserialize>(content, _jsonOptions); - Assert.NotNull(problemDetails); - Assert.Equal(StatusCodes.Status401Unauthorized, problemDetails!["status"].GetInt32()); - Assert.Equal("https://tools.ietf.org/html/rfc7235#section-3.1", problemDetails["type"].GetString()); - Assert.Equal("Unauthorized", problemDetails["title"].GetString()); - Assert.Equal($"/api/v1/libraries/{libraryId}/artwork-providers/{pluginId}/enabled", problemDetails["instance"].GetProperty("value").GetString()); - Assert.Equal("Authentication failed", problemDetails["detail"].GetString()); - } - - [Theory] - [InlineData("' OR '1'='1")] // basic SQL injection - [InlineData("'; DROP TABLE Libraries--")] // destructive injection - public async Task SetLibraryArtworkProviderEnabled_WithSQLInjectionInRouteParameters_ShouldNotLeakOrError(string maliciousId) - { - // Arrange - // authenticate with an admin user and seed a library with an artwork provider configuration, so valid ids would reach the handler - HttpClient client = _apiFactory.CreateClient(); - Guid userId = await _apiFactory.CreateAndAuthenticateAdminUserAsync(client); - Guid libraryId = await SeedLibraryAsync(userId); - await SeedConfigurationAsync(libraryId); - SetLibraryArtworkProviderEnabledRequest request = _setLibraryArtworkProviderEnabledRequestFixture.Create(libraryId: libraryId, pluginId: Guid.NewGuid(), isEnabled: true); - - // Act - HttpResponseMessage response = await client.PutAsJsonAsync($"/api/v1/libraries/{Uri.EscapeDataString(maliciousId)}/artwork-providers/{Guid.NewGuid()}/enabled", request); - - // Assert - // note: the {libraryId} route parameter is Guid-typed, so the malicious value fails model binding before it reaches the handler - // note: observed status is 500 because FastEndpoints, combined with DontCatchExceptions(), turns the binding - // ValidationFailureException into a 500 response instead of 400/422 (pre-existing production bug, not fixed here) - // note: that 500 body leaks the ValidationFailureException details, so no DoesNotContain("Exception") is asserted here - Assert.Equal(HttpStatusCode.InternalServerError, response.StatusCode); - string content = await response.Content.ReadAsStringAsync(); - Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase); - Assert.DoesNotContain("password", content, StringComparison.OrdinalIgnoreCase); - Assert.DoesNotContain("hash", content, StringComparison.OrdinalIgnoreCase); - Assert.DoesNotContain("salt", content, StringComparison.OrdinalIgnoreCase); - } - - /// - /// Seeds a owned by . - /// - /// The Id of the user that owns the library. - /// The Id of the seeded library. - private async Task SeedLibraryAsync(Guid userId) - { - using IServiceScope scope = _apiFactory.Services.CreateScope(); - LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); - Guid libraryId = Guid.NewGuid(); - dbContext.Libraries.Add(_libraryEntityFixture.Create(id: libraryId, userId: userId, title: "Test Library", libraryType: LibraryType.EBook, contentLocations: [])); - await dbContext.SaveChangesAsync(); - return libraryId; - } - - /// - /// Seeds a for the library identified by . - /// - /// The Id of the media library. - /// A task representing the asynchronous operation. - private async Task SeedConfigurationAsync(Guid libraryId) - { - using IServiceScope scope = _apiFactory.Services.CreateScope(); - LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); - dbContext.LibraryArtworkProviderConfigurations.Add(_libraryArtworkProviderConfigurationEntityFixture.Create(libraryId: libraryId, pluginId: Guid.NewGuid(), rank: 1, isEnabled: false)); - await dbContext.SaveChangesAsync(); - } -} diff --git a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Plugins/SetLibraryBookReaderEnabled/SetLibraryBookReaderEnabledEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Plugins/SetLibraryBookReaderEnabled/SetLibraryBookReaderEnabledEndpointTests.cs deleted file mode 100644 index 8a5ccf4c..00000000 --- a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Plugins/SetLibraryBookReaderEnabled/SetLibraryBookReaderEnabledEndpointTests.cs +++ /dev/null @@ -1,77 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using Lumina.Contracts.Fixtures.Core.Requests.Plugins; -using Lumina.Contracts.Requests.Plugins; -using Lumina.Presentation.Api.SecurityTests.Common.Setup; -using Microsoft.AspNetCore.Http; -using System.Diagnostics.CodeAnalysis; -using System.Net; -using System.Net.Http.Json; -using System.Text.Json; -#endregion - -namespace Lumina.Presentation.Api.SecurityTests.Core.Endpoints.Plugins.SetLibraryBookReaderEnabled; - -/// -/// Contains security tests for the class. -/// -[ExcludeFromCodeCoverage] -public class SetLibraryBookReaderEnabledEndpointTests : IClassFixture -{ - private readonly HttpClient _client; - private readonly JsonSerializerOptions _jsonOptions = new() - { - PropertyNameCaseInsensitive = true - }; - private readonly SetLibraryBookReaderEnabledRequestFixture _setLibraryBookReaderEnabledRequestFixture = new(); - - /// - /// Initializes a new instance of the class. - /// - /// Injected in-memory API factory. - public SetLibraryBookReaderEnabledEndpointTests(LuminaApiFactory apiFactory) - { - _client = apiFactory.CreateClient(); - } - - [Fact] - public async Task SetLibraryBookReaderEnabled_WhenUnauthorized_ShouldReturnUnauthorizedResult() - { - // Arrange - Guid libraryId = Guid.NewGuid(); - Guid pluginId = Guid.NewGuid(); - SetLibraryBookReaderEnabledRequest request = _setLibraryBookReaderEnabledRequestFixture.Create(libraryId: libraryId, pluginId: pluginId, isEnabled: true); - - // Act - HttpResponseMessage response = await _client.PutAsJsonAsync($"/api/v1/libraries/{libraryId}/book-readers/{pluginId}/enabled", request); - - // Assert - Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode); - string content = await response.Content.ReadAsStringAsync(); - Dictionary? problemDetails = JsonSerializer.Deserialize>(content, _jsonOptions); - Assert.NotNull(problemDetails); - Assert.Equal(StatusCodes.Status401Unauthorized, problemDetails!["status"].GetInt32()); - Assert.Equal("https://tools.ietf.org/html/rfc7235#section-3.1", problemDetails["type"].GetString()); - Assert.Equal("Unauthorized", problemDetails["title"].GetString()); - Assert.Equal("Authentication failed", problemDetails["detail"].GetString()); - Assert.DoesNotContain("Exception", content, StringComparison.Ordinal); - } - - [Theory] - [InlineData("' OR '1'='1")] // basic SQL injection - [InlineData("'; DROP TABLE LibraryBookReaderConfigurations--")] // destructive injection - public async Task SetLibraryBookReaderEnabled_WithSQLInjectionInPluginId_ShouldNotLeakDatabaseDetails(string maliciousPluginId) - { - // Arrange - SetLibraryBookReaderEnabledRequest request = _setLibraryBookReaderEnabledRequestFixture.Create(libraryId: Guid.NewGuid(), pluginId: Guid.NewGuid(), isEnabled: true); - - // Act - HttpResponseMessage response = await _client.PutAsJsonAsync($"/api/v1/libraries/{Guid.NewGuid()}/book-readers/{Uri.EscapeDataString(maliciousPluginId)}/enabled", request); - string content = await response.Content.ReadAsStringAsync(); - - // Assert - Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase); - Assert.DoesNotContain("password", content, StringComparison.OrdinalIgnoreCase); - Assert.DoesNotContain("hash", content, StringComparison.OrdinalIgnoreCase); - Assert.DoesNotContain("salt", content, StringComparison.OrdinalIgnoreCase); - } -} diff --git a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Plugins/SetLibraryMetadataProviderEnabled/SetLibraryMetadataProviderEnabledEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Plugins/SetLibraryMetadataProviderEnabled/SetLibraryMetadataProviderEnabledEndpointTests.cs deleted file mode 100644 index 29fe12c0..00000000 --- a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Plugins/SetLibraryMetadataProviderEnabled/SetLibraryMetadataProviderEnabledEndpointTests.cs +++ /dev/null @@ -1,126 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management; -using Lumina.Application.Fixtures.Common.DataAccess.Entities.Plugins; -using Lumina.Contracts.Fixtures.Core.Requests.Plugins; -using Lumina.Contracts.Requests.Plugins; -using Lumina.DataAccess.Core.UoW; -using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; -using Lumina.Presentation.Api.SecurityTests.Common.Setup; -using Microsoft.AspNetCore.Http; -using Microsoft.Extensions.DependencyInjection; -using System.Diagnostics.CodeAnalysis; -using System.Net; -using System.Net.Http.Json; -using System.Text.Json; -#endregion - -namespace Lumina.Presentation.Api.SecurityTests.Core.Endpoints.Plugins.SetLibraryMetadataProviderEnabled; - -/// -/// Contains security tests for the class. -/// -[ExcludeFromCodeCoverage] -public class SetLibraryMetadataProviderEnabledEndpointTests : IClassFixture -{ - private readonly HttpClient _client; - private readonly LuminaApiFactory _apiFactory; - private readonly JsonSerializerOptions _jsonOptions = new() - { - PropertyNameCaseInsensitive = true - }; - private readonly LibraryEntityFixture _libraryEntityFixture = new(); - private readonly LibraryMetadataProviderConfigurationEntityFixture _libraryMetadataProviderConfigurationEntityFixture = new(); - private readonly SetLibraryMetadataProviderEnabledRequestFixture _setLibraryMetadataProviderEnabledRequestFixture = new(); - - /// - /// Initializes a new instance of the class. - /// - /// Injected in-memory API factory. - public SetLibraryMetadataProviderEnabledEndpointTests(LuminaApiFactory apiFactory) - { - _apiFactory = apiFactory; - _client = apiFactory.CreateClient(); - } - - [Fact] - public async Task SetLibraryMetadataProviderEnabled_WhenUnauthorized_ShouldReturnUnauthorizedResult() - { - // Arrange - string libraryId = Guid.NewGuid().ToString(); - string pluginId = Guid.NewGuid().ToString(); - SetLibraryMetadataProviderEnabledRequest request = _setLibraryMetadataProviderEnabledRequestFixture.Create(); - - // Act - HttpResponseMessage response = await _client.PutAsJsonAsync($"/api/v1/libraries/{libraryId}/metadata-providers/{pluginId}/enabled", request); - - // Assert - Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode); - - string content = await response.Content.ReadAsStringAsync(); - - Dictionary? problemDetails = JsonSerializer.Deserialize>(content, _jsonOptions); - Assert.NotNull(problemDetails); - Assert.Equal(StatusCodes.Status401Unauthorized, problemDetails!["status"].GetInt32()); - Assert.Equal("https://tools.ietf.org/html/rfc7235#section-3.1", problemDetails["type"].GetString()); - Assert.Equal("Unauthorized", problemDetails["title"].GetString()); - Assert.Equal($"/api/v1/libraries/{libraryId}/metadata-providers/{pluginId}/enabled", problemDetails["instance"].GetProperty("value").GetString()); - Assert.Equal("Authentication failed", problemDetails["detail"].GetString()); - } - - [Theory] - [InlineData("' OR '1'='1")] // basic SQL injection - [InlineData("'; DROP TABLE Libraries--")] // destructive injection - public async Task SetLibraryMetadataProviderEnabled_WithSQLInjectionInRouteParameters_ShouldNotLeakOrError(string maliciousId) - { - // Arrange - // authenticate with an admin user and seed a library with a metadata provider configuration, so valid ids would reach the handler - HttpClient client = _apiFactory.CreateClient(); - Guid userId = await _apiFactory.CreateAndAuthenticateAdminUserAsync(client); - Guid libraryId = await SeedLibraryAsync(userId); - await SeedConfigurationAsync(libraryId); - SetLibraryMetadataProviderEnabledRequest request = _setLibraryMetadataProviderEnabledRequestFixture.Create(libraryId: libraryId, pluginId: Guid.NewGuid(), isEnabled: true); - - // Act - HttpResponseMessage response = await client.PutAsJsonAsync($"/api/v1/libraries/{Uri.EscapeDataString(maliciousId)}/metadata-providers/{Guid.NewGuid()}/enabled", request); - - // Assert - // note: the {libraryId} route parameter is Guid-typed, so the malicious value fails model binding before it reaches the handler - // note: observed status is 500 because FastEndpoints, combined with DontCatchExceptions(), turns the binding - // ValidationFailureException into a 500 response instead of 400/422 (pre-existing production bug, not fixed here) - // note: that 500 body leaks the ValidationFailureException details, so no DoesNotContain("Exception") is asserted here - Assert.Equal(HttpStatusCode.InternalServerError, response.StatusCode); - string content = await response.Content.ReadAsStringAsync(); - Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase); - Assert.DoesNotContain("password", content, StringComparison.OrdinalIgnoreCase); - Assert.DoesNotContain("hash", content, StringComparison.OrdinalIgnoreCase); - Assert.DoesNotContain("salt", content, StringComparison.OrdinalIgnoreCase); - } - - /// - /// Seeds a owned by . - /// - /// The Id of the user that owns the library. - /// The Id of the seeded library. - private async Task SeedLibraryAsync(Guid userId) - { - using IServiceScope scope = _apiFactory.Services.CreateScope(); - LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); - Guid libraryId = Guid.NewGuid(); - dbContext.Libraries.Add(_libraryEntityFixture.Create(id: libraryId, userId: userId, title: "Test Library", libraryType: LibraryType.EBook, contentLocations: [])); - await dbContext.SaveChangesAsync(); - return libraryId; - } - - /// - /// Seeds a for the library identified by . - /// - /// The Id of the media library. - /// A task representing the asynchronous operation. - private async Task SeedConfigurationAsync(Guid libraryId) - { - using IServiceScope scope = _apiFactory.Services.CreateScope(); - LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); - dbContext.LibraryMetadataProviderConfigurations.Add(_libraryMetadataProviderConfigurationEntityFixture.Create(libraryId: libraryId, pluginId: Guid.NewGuid(), rank: 1, isEnabled: false)); - await dbContext.SaveChangesAsync(); - } -} diff --git a/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Library/Management/AddLibrary/AddLibraryViewEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Library/Management/AddLibrary/AddLibraryViewEndpointTests.cs index 90e1620e..fbe67979 100644 --- a/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Library/Management/AddLibrary/AddLibraryViewEndpointTests.cs +++ b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Library/Management/AddLibrary/AddLibraryViewEndpointTests.cs @@ -1,5 +1,6 @@ #region ========================================================================= USING ===================================================================================== using Lumina.Presentation.Web.Core.Endpoints.Library.Management.AddLibrary; +using Lumina.Presentation.Web.Fixtures.Common.Responses.Authorization; using Lumina.Presentation.Web.Fixtures.Common.TestHelpers; using Lumina.Presentation.Web.SecurityTests.Common.Setup; using System.Diagnostics.CodeAnalysis; @@ -15,6 +16,7 @@ namespace Lumina.Presentation.Web.SecurityTests.Core.Endpoints.Library.Managemen public class AddLibraryViewEndpointTests : IClassFixture { private readonly LuminaWebFactory _apiFactory; + private readonly GetAuthorizationResponseFixture _getAuthorizationResponseFixture = new(); /// /// Initializes a new instance of the class. @@ -39,4 +41,20 @@ public class AddLibraryViewEndpointTests : IClassFixture Assert.Equal(HttpStatusCode.Redirect, response.StatusCode); Assert.Equal("http://localhost/en-us/auth/login", response.Headers.Location!.ToString()); } + + [Fact] + public async Task AddLibraryView_WhenTheUserLacksTheManagePermission_ShouldRedirectToAccessDenied() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + _apiFactory.ApiClientStub.AuthorizationResponse = _getAuthorizationResponseFixture.Create(userId: Guid.NewGuid(), role: "User", permissions: []); + AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); + + // Act + HttpResponseMessage response = await webClient.Client.GetAsync("/en-us/libraries/manage/item"); + + // Assert + Assert.Equal(HttpStatusCode.Redirect, response.StatusCode); + Assert.Contains("access-denied", response.Headers.Location!.ToString()); + } } diff --git a/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Library/Management/DeleteLibrary/DeleteLibraryEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Library/Management/DeleteLibrary/DeleteLibraryEndpointTests.cs index b0718dd1..ad8bc125 100644 --- a/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Library/Management/DeleteLibrary/DeleteLibraryEndpointTests.cs +++ b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Library/Management/DeleteLibrary/DeleteLibraryEndpointTests.cs @@ -1,5 +1,6 @@ #region ========================================================================= USING ===================================================================================== using Lumina.Presentation.Web.Core.Endpoints.Library.Management.DeleteLibrary; +using Lumina.Presentation.Web.Fixtures.Common.Responses.Authorization; using Lumina.Presentation.Web.Fixtures.Common.TestHelpers; using Lumina.Presentation.Web.SecurityTests.Common.Setup; using System.Diagnostics.CodeAnalysis; @@ -17,6 +18,7 @@ namespace Lumina.Presentation.Web.SecurityTests.Core.Endpoints.Library.Managemen public class DeleteLibraryEndpointTests : IClassFixture { private readonly LuminaWebFactory _apiFactory; + private readonly GetAuthorizationResponseFixture _getAuthorizationResponseFixture = new(); /// /// Initializes a new instance of the class. @@ -64,6 +66,47 @@ public class DeleteLibraryEndpointTests : IClassFixture Assert.DoesNotContain(_apiFactory.ApiClientStub.DeleteEndpointsCalled, endpoint => endpoint == $"libraries/{libraryId}"); } + [Fact] + public async Task DeleteLibrary_WhenTheUserLacksTheManagePermission_ShouldRedirectToAccessDeniedWithoutDeletingTheLibrary() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + _apiFactory.ApiClientStub.AuthorizationResponse = _getAuthorizationResponseFixture.Create(userId: Guid.NewGuid(), role: "User", permissions: []); + AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); + Guid libraryId = Guid.NewGuid(); + HttpRequestMessage deleteRequest = CreateDeleteRequest(libraryId); + deleteRequest.Headers.Add("RequestVerificationToken", webClient.AntiforgeryToken); + + // Act + HttpResponseMessage response = await webClient.Client.SendAsync(deleteRequest); + + // Assert + Assert.Equal(HttpStatusCode.Redirect, response.StatusCode); + Assert.Contains("access-denied", response.Headers.Location!.ToString()); + Assert.DoesNotContain(_apiFactory.ApiClientStub.DeleteEndpointsCalled, endpoint => endpoint == $"libraries/{libraryId}"); + } + + [Fact] + public async Task DeleteLibrary_WhenAnAdministratorLacksTheManagePermission_ShouldForwardTheDeletion() + { + // Arrange + // The API lets administrators delete any library, so the Web must not refuse them for lacking the permission. + _apiFactory.ApiClientStub.Reset(); + _apiFactory.ApiClientStub.AuthorizationResponse = _getAuthorizationResponseFixture.Create(userId: Guid.NewGuid(), role: "Admin", permissions: []); + AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); + Guid libraryId = Guid.NewGuid(); + _apiFactory.ApiClientStub.RegisterDeleteSuccess($"libraries/{libraryId}"); + HttpRequestMessage deleteRequest = CreateDeleteRequest(libraryId); + deleteRequest.Headers.Add("RequestVerificationToken", webClient.AntiforgeryToken); + + // Act + HttpResponseMessage response = await webClient.Client.SendAsync(deleteRequest); + + // Assert + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + Assert.Contains(_apiFactory.ApiClientStub.DeleteEndpointsCalled, endpoint => endpoint == $"libraries/{libraryId}"); + } + /// /// Builds the delete request for the library identified by . /// diff --git a/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Library/Management/EditLibrary/EditLibraryViewEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Library/Management/EditLibrary/EditLibraryViewEndpointTests.cs index 6d9e3879..f39b1aa6 100644 --- a/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Library/Management/EditLibrary/EditLibraryViewEndpointTests.cs +++ b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Library/Management/EditLibrary/EditLibraryViewEndpointTests.cs @@ -1,5 +1,6 @@ #region ========================================================================= USING ===================================================================================== using Lumina.Presentation.Web.Core.Endpoints.Library.Management.EditLibrary; +using Lumina.Presentation.Web.Fixtures.Common.Responses.Authorization; using Lumina.Presentation.Web.Fixtures.Common.TestHelpers; using Lumina.Presentation.Web.SecurityTests.Common.Setup; using System.Diagnostics.CodeAnalysis; @@ -15,6 +16,7 @@ namespace Lumina.Presentation.Web.SecurityTests.Core.Endpoints.Library.Managemen public class EditLibraryViewEndpointTests : IClassFixture { private readonly LuminaWebFactory _apiFactory; + private readonly GetAuthorizationResponseFixture _getAuthorizationResponseFixture = new(); /// /// Initializes a new instance of the class. @@ -41,4 +43,22 @@ public class EditLibraryViewEndpointTests : IClassFixture Assert.Equal("http://localhost/en-us/auth/login", response.Headers.Location!.ToString()); Assert.DoesNotContain(_apiFactory.ApiClientStub.GetEndpointsCalled, endpoint => endpoint == $"libraries/{libraryId}"); } + + [Fact] + public async Task EditLibraryView_WhenTheUserLacksTheManagePermission_ShouldRedirectToAccessDeniedWithoutLoadingTheLibrary() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + _apiFactory.ApiClientStub.AuthorizationResponse = _getAuthorizationResponseFixture.Create(userId: Guid.NewGuid(), role: "User", permissions: []); + AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); + Guid libraryId = Guid.NewGuid(); + + // Act + HttpResponseMessage response = await webClient.Client.GetAsync($"/en-us/libraries/manage/item/{libraryId}"); + + // Assert + Assert.Equal(HttpStatusCode.Redirect, response.StatusCode); + Assert.Contains("access-denied", response.Headers.Location!.ToString()); + Assert.DoesNotContain(_apiFactory.ApiClientStub.GetEndpointsCalled, endpoint => endpoint == $"libraries/{libraryId}"); + } } diff --git a/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Library/Management/GetLibraryTypeArtworkProviders/GetLibraryTypeArtworkProvidersEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Library/Management/GetLibraryTypeArtworkProviders/GetLibraryTypeArtworkProvidersEndpointTests.cs new file mode 100644 index 00000000..2b309332 --- /dev/null +++ b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Library/Management/GetLibraryTypeArtworkProviders/GetLibraryTypeArtworkProvidersEndpointTests.cs @@ -0,0 +1,67 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Common.DTO.Plugins; +using Lumina.Presentation.Web.Core.Endpoints.Library.Management.GetLibraryTypeArtworkProviders; +using Lumina.Presentation.Web.Fixtures.Common.TestHelpers; +using Lumina.Presentation.Web.SecurityTests.Common.Setup; +using System.Diagnostics.CodeAnalysis; +using System.Net; +#endregion + +namespace Lumina.Presentation.Web.SecurityTests.Core.Endpoints.Library.Management.GetLibraryTypeArtworkProviders; + +/// +/// Contains security tests for the class. +/// +[ExcludeFromCodeCoverage] +public class GetLibraryTypeArtworkProvidersEndpointTests : IClassFixture +{ + private readonly LuminaWebFactory _apiFactory; + + /// + /// Initializes a new instance of the class. + /// + /// Injected Web application factory. + public GetLibraryTypeArtworkProvidersEndpointTests(LuminaWebFactory apiFactory) + { + _apiFactory = apiFactory; + } + + [Fact] + public async Task GetLibraryTypeArtworkProviders_WhenCalledWithoutAuthentication_ShouldRedirectToLogin() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + HttpClient client = WebTestHelpers.CreateAnonymousClient(_apiFactory); + + // Act + HttpResponseMessage response = await client.GetAsync("/en-us/libraries/manage/api-get-library-type-artwork-providers/Book"); + + // Assert + Assert.Equal(HttpStatusCode.Redirect, response.StatusCode); + Assert.Equal("http://localhost/en-us/auth/login", response.Headers.Location!.ToString()); + Assert.DoesNotContain(_apiFactory.ApiClientStub.GetEndpointsCalled, endpoint => endpoint.Contains("artwork-providers", StringComparison.Ordinal)); + } + + [Theory] + [InlineData("' OR '1'='1")] // Basic SQL injection. + [InlineData("'; DROP TABLE Libraries--")] // Destructive injection. + public async Task GetLibraryTypeArtworkProviders_WhenCalledWithInjectionInLibraryType_ShouldRemainSecure(string maliciousLibraryType) + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + _apiFactory.ApiClientStub.RegisterGetResponse($"libraries/artwork-providers/{Uri.EscapeDataString(maliciousLibraryType)}", Array.Empty()); + AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); + + // Act + HttpResponseMessage response = await webClient.Client.GetAsync($"/en-us/libraries/manage/api-get-library-type-artwork-providers/{Uri.EscapeDataString(maliciousLibraryType)}"); + string content = await response.Content.ReadAsStringAsync(); + + // Assert + Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("stack trace", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("password", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("hash", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("salt", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain(AppContext.BaseDirectory, content, StringComparison.OrdinalIgnoreCase); + } +} diff --git a/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Library/Management/GetLibraryTypeBookReaders/GetLibraryTypeBookReadersEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Library/Management/GetLibraryTypeBookReaders/GetLibraryTypeBookReadersEndpointTests.cs new file mode 100644 index 00000000..065f247d --- /dev/null +++ b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Library/Management/GetLibraryTypeBookReaders/GetLibraryTypeBookReadersEndpointTests.cs @@ -0,0 +1,67 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Common.DTO.Plugins; +using Lumina.Presentation.Web.Core.Endpoints.Library.Management.GetLibraryTypeBookReaders; +using Lumina.Presentation.Web.Fixtures.Common.TestHelpers; +using Lumina.Presentation.Web.SecurityTests.Common.Setup; +using System.Diagnostics.CodeAnalysis; +using System.Net; +#endregion + +namespace Lumina.Presentation.Web.SecurityTests.Core.Endpoints.Library.Management.GetLibraryTypeBookReaders; + +/// +/// Contains security tests for the class. +/// +[ExcludeFromCodeCoverage] +public class GetLibraryTypeBookReadersEndpointTests : IClassFixture +{ + private readonly LuminaWebFactory _apiFactory; + + /// + /// Initializes a new instance of the class. + /// + /// Injected Web application factory. + public GetLibraryTypeBookReadersEndpointTests(LuminaWebFactory apiFactory) + { + _apiFactory = apiFactory; + } + + [Fact] + public async Task GetLibraryTypeBookReaders_WhenCalledWithoutAuthentication_ShouldRedirectToLogin() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + HttpClient client = WebTestHelpers.CreateAnonymousClient(_apiFactory); + + // Act + HttpResponseMessage response = await client.GetAsync("/en-us/libraries/manage/api-get-library-type-book-readers/Book"); + + // Assert + Assert.Equal(HttpStatusCode.Redirect, response.StatusCode); + Assert.Equal("http://localhost/en-us/auth/login", response.Headers.Location!.ToString()); + Assert.DoesNotContain(_apiFactory.ApiClientStub.GetEndpointsCalled, endpoint => endpoint.Contains("book-readers", StringComparison.Ordinal)); + } + + [Theory] + [InlineData("' OR '1'='1")] // Basic SQL injection. + [InlineData("'; DROP TABLE Libraries--")] // Destructive injection. + public async Task GetLibraryTypeBookReaders_WhenCalledWithInjectionInLibraryType_ShouldRemainSecure(string maliciousLibraryType) + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + _apiFactory.ApiClientStub.RegisterGetResponse($"libraries/book-readers/{Uri.EscapeDataString(maliciousLibraryType)}", Array.Empty()); + AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); + + // Act + HttpResponseMessage response = await webClient.Client.GetAsync($"/en-us/libraries/manage/api-get-library-type-book-readers/{Uri.EscapeDataString(maliciousLibraryType)}"); + string content = await response.Content.ReadAsStringAsync(); + + // Assert + Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("stack trace", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("password", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("hash", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("salt", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain(AppContext.BaseDirectory, content, StringComparison.OrdinalIgnoreCase); + } +} diff --git a/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Library/Management/GetLibraryTypeMetadataProviders/GetLibraryTypeMetadataProvidersEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Library/Management/GetLibraryTypeMetadataProviders/GetLibraryTypeMetadataProvidersEndpointTests.cs new file mode 100644 index 00000000..fe75a189 --- /dev/null +++ b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Library/Management/GetLibraryTypeMetadataProviders/GetLibraryTypeMetadataProvidersEndpointTests.cs @@ -0,0 +1,67 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Common.DTO.Plugins; +using Lumina.Presentation.Web.Core.Endpoints.Library.Management.GetLibraryTypeMetadataProviders; +using Lumina.Presentation.Web.Fixtures.Common.TestHelpers; +using Lumina.Presentation.Web.SecurityTests.Common.Setup; +using System.Diagnostics.CodeAnalysis; +using System.Net; +#endregion + +namespace Lumina.Presentation.Web.SecurityTests.Core.Endpoints.Library.Management.GetLibraryTypeMetadataProviders; + +/// +/// Contains security tests for the class. +/// +[ExcludeFromCodeCoverage] +public class GetLibraryTypeMetadataProvidersEndpointTests : IClassFixture +{ + private readonly LuminaWebFactory _apiFactory; + + /// + /// Initializes a new instance of the class. + /// + /// Injected Web application factory. + public GetLibraryTypeMetadataProvidersEndpointTests(LuminaWebFactory apiFactory) + { + _apiFactory = apiFactory; + } + + [Fact] + public async Task GetLibraryTypeMetadataProviders_WhenCalledWithoutAuthentication_ShouldRedirectToLogin() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + HttpClient client = WebTestHelpers.CreateAnonymousClient(_apiFactory); + + // Act + HttpResponseMessage response = await client.GetAsync("/en-us/libraries/manage/api-get-library-type-metadata-providers/Book"); + + // Assert + Assert.Equal(HttpStatusCode.Redirect, response.StatusCode); + Assert.Equal("http://localhost/en-us/auth/login", response.Headers.Location!.ToString()); + Assert.DoesNotContain(_apiFactory.ApiClientStub.GetEndpointsCalled, endpoint => endpoint.Contains("metadata-providers", StringComparison.Ordinal)); + } + + [Theory] + [InlineData("' OR '1'='1")] // Basic SQL injection. + [InlineData("'; DROP TABLE Libraries--")] // Destructive injection. + public async Task GetLibraryTypeMetadataProviders_WhenCalledWithInjectionInLibraryType_ShouldRemainSecure(string maliciousLibraryType) + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + _apiFactory.ApiClientStub.RegisterGetResponse($"libraries/metadata-providers/{Uri.EscapeDataString(maliciousLibraryType)}", Array.Empty()); + AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); + + // Act + HttpResponseMessage response = await webClient.Client.GetAsync($"/en-us/libraries/manage/api-get-library-type-metadata-providers/{Uri.EscapeDataString(maliciousLibraryType)}"); + string content = await response.Content.ReadAsStringAsync(); + + // Assert + Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("stack trace", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("password", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("hash", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("salt", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain(AppContext.BaseDirectory, content, StringComparison.OrdinalIgnoreCase); + } +} diff --git a/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Library/Management/ReorderMetadataProviders/ReorderMetadataProvidersEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Library/Management/ReorderMetadataProviders/ReorderMetadataProvidersEndpointTests.cs deleted file mode 100644 index 2fc62af3..00000000 --- a/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Library/Management/ReorderMetadataProviders/ReorderMetadataProvidersEndpointTests.cs +++ /dev/null @@ -1,89 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using Lumina.Presentation.Web.Common.Requests.Plugins; -using Lumina.Presentation.Web.Core.Endpoints.Library.Management.ReorderMetadataProviders; -using Lumina.Presentation.Web.Fixtures.Common.Requests.Plugins; -using Lumina.Presentation.Web.Fixtures.Common.TestHelpers; -using Lumina.Presentation.Web.SecurityTests.Common.Setup; -using System.Diagnostics.CodeAnalysis; -using System.Net; -using System.Net.Http.Headers; -using System.Net.Http.Json; -#endregion - -namespace Lumina.Presentation.Web.SecurityTests.Core.Endpoints.Library.Management.ReorderMetadataProviders; - -/// -/// Contains security tests for the class. -/// -[ExcludeFromCodeCoverage] -public class ReorderMetadataProvidersEndpointTests : IClassFixture -{ - private readonly LuminaWebFactory _apiFactory; - private readonly ReorderLibraryMetadataProvidersRequestFixture _reorderLibraryMetadataProvidersRequestFixture = new(); - - /// - /// Initializes a new instance of the class. - /// - /// Injected Web application factory. - public ReorderMetadataProvidersEndpointTests(LuminaWebFactory apiFactory) - { - _apiFactory = apiFactory; - } - - [Fact] - public async Task ReorderMetadataProviders_WhenCalledWithoutAuthentication_ShouldRedirectToLogin() - { - // Arrange - _apiFactory.ApiClientStub.Reset(); - HttpClient client = WebTestHelpers.CreateAnonymousClient(_apiFactory); - string antiforgeryToken = await WebTestHelpers.GetAntiforgeryTokenAsync(client); - Guid libraryId = Guid.NewGuid(); - HttpRequestMessage updateRequest = CreateUpdateRequest(libraryId); - updateRequest.Headers.Add("RequestVerificationToken", antiforgeryToken); - - // Act - HttpResponseMessage response = await client.SendAsync(updateRequest); - - // Assert - Assert.Equal(HttpStatusCode.Redirect, response.StatusCode); - Assert.Equal("http://localhost/en-us/auth/login", response.Headers.Location!.ToString()); - Assert.DoesNotContain(_apiFactory.ApiClientStub.PutRequests, putRequest => putRequest.Endpoint == $"libraries/{libraryId}/metadata-providers/reorder"); - } - - [Fact] - public async Task ReorderMetadataProviders_WhenCalledWithoutAntiforgeryToken_ShouldRejectRequest() - { - // Arrange - _apiFactory.ApiClientStub.Reset(); - AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); - Guid libraryId = Guid.NewGuid(); - HttpRequestMessage updateRequest = CreateUpdateRequest(libraryId); - - // Act - HttpResponseMessage response = await webClient.Client.SendAsync(updateRequest); - - // Assert - Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode); - Assert.DoesNotContain(_apiFactory.ApiClientStub.PutRequests, putRequest => putRequest.Endpoint == $"libraries/{libraryId}/metadata-providers/reorder"); - } - - /// - /// Builds the update request that reorders the metadata providers of the library identified by . - /// - /// The Id of the media library. - /// The configured update request. - private HttpRequestMessage CreateUpdateRequest(Guid libraryId) - { - ReorderLibraryMetadataProvidersRequest request = _reorderLibraryMetadataProvidersRequestFixture.Create( - libraryId: libraryId, - pluginIds: [Guid.NewGuid(), Guid.NewGuid()] - ); - HttpRequestMessage updateRequest = new(HttpMethod.Put, "/en-us/libraries/manage/api-reorder-metadata-providers") - { - Content = JsonContent.Create(request) - }; - updateRequest.Content!.Headers.ContentType = new MediaTypeHeaderValue("application/json"); - updateRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); - return updateRequest; - } -} diff --git a/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Library/Management/SaveLibrary/SaveLibraryEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Library/Management/SaveLibrary/SaveLibraryEndpointTests.cs index b47dd931..03761e5f 100644 --- a/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Library/Management/SaveLibrary/SaveLibraryEndpointTests.cs +++ b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Library/Management/SaveLibrary/SaveLibraryEndpointTests.cs @@ -1,7 +1,9 @@ #region ========================================================================= USING ===================================================================================== using Lumina.Presentation.Web.Common.DTO.Libraries; +using Lumina.Presentation.Web.Common.Enums.Authorization; using Lumina.Presentation.Web.Core.Endpoints.Library.Management.SaveLibrary; using Lumina.Presentation.Web.Fixtures.Common.DTO.Libraries; +using Lumina.Presentation.Web.Fixtures.Common.Responses.Authorization; using Lumina.Presentation.Web.Fixtures.Common.TestHelpers; using Lumina.Presentation.Web.SecurityTests.Common.Setup; using System.Diagnostics.CodeAnalysis; @@ -20,6 +22,7 @@ public class SaveLibraryEndpointTests : IClassFixture { private readonly LuminaWebFactory _apiFactory; private readonly LibraryDtoFixture _libraryDtoFixture = new(); + private readonly GetAuthorizationResponseFixture _getAuthorizationResponseFixture = new(); /// /// Initializes a new instance of the class. @@ -34,7 +37,7 @@ public class SaveLibraryEndpointTests : IClassFixture public async Task SaveLibrary_WhenCalledWithoutAntiforgeryToken_ShouldRejectRequest() { // Arrange - _apiFactory.ApiClientStub.Reset(); + ResetApiStub(); AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); HttpRequestMessage saveRequest = CreateSaveRequest(_libraryDtoFixture.Create(title: "New Books Library", libraryType: "Book")); @@ -50,7 +53,7 @@ public class SaveLibraryEndpointTests : IClassFixture public async Task SaveLibrary_WhenCalledWithInvalidAntiforgeryToken_ShouldRejectRequest() { // Arrange - _apiFactory.ApiClientStub.Reset(); + ResetApiStub(); AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); HttpRequestMessage saveRequest = CreateSaveRequest(_libraryDtoFixture.Create(title: "New Books Library", libraryType: "Book")); saveRequest.Headers.Remove("RequestVerificationToken"); @@ -64,11 +67,52 @@ public class SaveLibraryEndpointTests : IClassFixture Assert.DoesNotContain(_apiFactory.ApiClientStub.PostRequests, postRequest => postRequest.Endpoint == "libraries"); } + [Fact] + public async Task SaveLibrary_WhenTheUserLacksTheManagePermission_ShouldRedirectToAccessDeniedWithoutSaving() + { + // Arrange + ResetApiStub(); + _apiFactory.ApiClientStub.AuthorizationResponse = _getAuthorizationResponseFixture.Create(userId: Guid.NewGuid(), role: "User", permissions: []); + AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); + HttpRequestMessage saveRequest = CreateSaveRequest(_libraryDtoFixture.Create(title: "New Books Library", libraryType: "Book")); + saveRequest.Headers.Add("RequestVerificationToken", webClient.AntiforgeryToken); + + // Act + HttpResponseMessage response = await webClient.Client.SendAsync(saveRequest); + + // Assert + Assert.Equal(HttpStatusCode.Redirect, response.StatusCode); + Assert.Contains("access-denied", response.Headers.Location!.ToString()); + Assert.DoesNotContain(_apiFactory.ApiClientStub.PostRequests, postRequest => postRequest.Endpoint == "libraries"); + } + + [Fact] + public async Task SaveLibrary_WhenAnAdministratorLacksTheManagePermission_ShouldForwardTheSave() + { + // Arrange + // The API lets administrators save any library, so the Web must not refuse them for lacking the permission. + ResetApiStub(); + _apiFactory.ApiClientStub.AuthorizationResponse = _getAuthorizationResponseFixture.Create(userId: Guid.NewGuid(), role: "Admin", permissions: []); + AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); + LibraryDto request = _libraryDtoFixture.Create(title: "New Books Library", libraryType: "Book"); + request.Id = null; + _apiFactory.ApiClientStub.RegisterPostResponse("libraries", _libraryDtoFixture.Create(id: Guid.NewGuid(), title: request.Title, libraryType: request.LibraryType)); + HttpRequestMessage saveRequest = CreateSaveRequest(request); + saveRequest.Headers.Add("RequestVerificationToken", webClient.AntiforgeryToken); + + // Act + HttpResponseMessage response = await webClient.Client.SendAsync(saveRequest); + + // Assert + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + Assert.Contains(_apiFactory.ApiClientStub.PostRequests, postRequest => postRequest.Endpoint == "libraries"); + } + [Fact] public async Task SaveLibrary_WhenCalledWithInjectionInLibraryTitle_ShouldRemainSecure() { // Arrange - _apiFactory.ApiClientStub.Reset(); + ResetApiStub(); LibraryDto request = _libraryDtoFixture.Create(title: "'; DROP TABLE Libraries--", libraryType: "Book"); request.Id = null; _apiFactory.ApiClientStub.RegisterPostResponse("libraries", _libraryDtoFixture.Create(id: Guid.NewGuid(), title: request.Title, libraryType: request.LibraryType)); @@ -85,6 +129,18 @@ public class SaveLibraryEndpointTests : IClassFixture Assert.DoesNotContain("Exception", content); } + /// + /// Resets the stubbed API client and restores the authorization state of an administrator with every permission, because the stub is shared by all the tests of the class. + /// + private void ResetApiStub() + { + _apiFactory.ApiClientStub.Reset(); + _apiFactory.ApiClientStub.AuthorizationResponse = _getAuthorizationResponseFixture.Create( + userId: Guid.NewGuid(), + role: "Admin", + permissions: Enum.GetValues()); + } + /// /// Builds the save request that sends the given to the library save endpoint. /// diff --git a/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Library/Management/SetBookReaderEnabled/SetBookReaderEnabledEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Library/Management/SetBookReaderEnabled/SetBookReaderEnabledEndpointTests.cs deleted file mode 100644 index add45a9f..00000000 --- a/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Library/Management/SetBookReaderEnabled/SetBookReaderEnabledEndpointTests.cs +++ /dev/null @@ -1,81 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using Lumina.Presentation.Web.Common.Requests.Plugins; -using Lumina.Presentation.Web.Core.Endpoints.Library.Management.SetBookReaderEnabled; -using Lumina.Presentation.Web.Fixtures.Common.Requests.Plugins; -using Lumina.Presentation.Web.Fixtures.Common.TestHelpers; -using Lumina.Presentation.Web.SecurityTests.Common.Setup; -using System; -using System.Diagnostics.CodeAnalysis; -using System.Net; -using System.Net.Http; -using System.Net.Http.Headers; -using System.Net.Http.Json; -using System.Threading.Tasks; -#endregion - -namespace Lumina.Presentation.Web.SecurityTests.Core.Endpoints.Library.Management.SetBookReaderEnabled; - -/// -/// Contains security tests for the class. -/// -[ExcludeFromCodeCoverage] -public class SetBookReaderEnabledEndpointTests : IClassFixture -{ - private readonly LuminaWebFactory _apiFactory; - private readonly SetBookReaderEnabledRequestFixture _setBookReaderEnabledRequestFixture = new(); - - /// - /// Initializes a new instance of the class. - /// - /// Injected Web application factory. - public SetBookReaderEnabledEndpointTests(LuminaWebFactory apiFactory) - { - _apiFactory = apiFactory; - } - - [Fact] - public async Task SetBookReaderEnabled_WhenCalledWithoutAuthentication_ShouldRedirectToLogin() - { - // Arrange - HttpClient client = WebTestHelpers.CreateAnonymousClient(_apiFactory); - SetBookReaderEnabledRequest request = _setBookReaderEnabledRequestFixture.Create(); - HttpRequestMessage updateRequest = new(HttpMethod.Put, "/en-us/libraries/manage/api-set-book-reader-enabled") - { - Content = JsonContent.Create(request) - }; - updateRequest.Content!.Headers.ContentType = new MediaTypeHeaderValue("application/json"); - - // Act - HttpResponseMessage response = await client.SendAsync(updateRequest); - - // Assert - Assert.Equal(HttpStatusCode.Redirect, response.StatusCode); - Assert.Equal("http://localhost/en-us/auth/login", response.Headers.Location!.ToString()); - } - - [Fact] - public async Task SetBookReaderEnabled_WhenCalledWithoutAntiforgeryToken_ShouldReturnBadRequest() - { - // Arrange - _apiFactory.ApiClientStub.Reset(); - AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); - SetBookReaderEnabledRequest request = _setBookReaderEnabledRequestFixture.Create(); - HttpRequestMessage updateRequest = new(HttpMethod.Put, "/en-us/libraries/manage/api-set-book-reader-enabled") - { - Content = JsonContent.Create(request) - }; - updateRequest.Content!.Headers.ContentType = new MediaTypeHeaderValue("application/json"); - - // Act - HttpResponseMessage response = await webClient.Client.SendAsync(updateRequest); - string content = await response.Content.ReadAsStringAsync(); - - // Assert - Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode); - Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase); - Assert.DoesNotContain("stack trace", content, StringComparison.OrdinalIgnoreCase); - Assert.DoesNotContain("password", content, StringComparison.OrdinalIgnoreCase); - Assert.DoesNotContain("hash", content, StringComparison.OrdinalIgnoreCase); - Assert.DoesNotContain("salt", content, StringComparison.OrdinalIgnoreCase); - } -} diff --git a/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Library/Management/SetMetadataProviderEnabled/SetMetadataProviderEnabledEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Library/Management/SetMetadataProviderEnabled/SetMetadataProviderEnabledEndpointTests.cs deleted file mode 100644 index fb13897e..00000000 --- a/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Library/Management/SetMetadataProviderEnabled/SetMetadataProviderEnabledEndpointTests.cs +++ /dev/null @@ -1,93 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using Lumina.Presentation.Web.Common.Requests.Plugins; -using Lumina.Presentation.Web.Core.Endpoints.Library.Management.SetMetadataProviderEnabled; -using Lumina.Presentation.Web.Fixtures.Common.Requests.Plugins; -using Lumina.Presentation.Web.Fixtures.Common.TestHelpers; -using Lumina.Presentation.Web.SecurityTests.Common.Setup; -using System.Diagnostics.CodeAnalysis; -using System.Net; -using System.Net.Http.Headers; -using System.Net.Http.Json; -#endregion - -namespace Lumina.Presentation.Web.SecurityTests.Core.Endpoints.Library.Management.SetMetadataProviderEnabled; - -/// -/// Contains security tests for the class. -/// -[ExcludeFromCodeCoverage] -public class SetMetadataProviderEnabledEndpointTests : IClassFixture -{ - private readonly LuminaWebFactory _apiFactory; - private readonly SetLibraryMetadataProviderEnabledRequestFixture _setLibraryMetadataProviderEnabledRequestFixture = new(); - - /// - /// Initializes a new instance of the class. - /// - /// Injected Web application factory. - public SetMetadataProviderEnabledEndpointTests(LuminaWebFactory apiFactory) - { - _apiFactory = apiFactory; - } - - [Fact] - public async Task SetMetadataProviderEnabled_WhenCalledWithoutAuthentication_ShouldRedirectToLogin() - { - // Arrange - _apiFactory.ApiClientStub.Reset(); - HttpClient client = WebTestHelpers.CreateAnonymousClient(_apiFactory); - string antiforgeryToken = await WebTestHelpers.GetAntiforgeryTokenAsync(client); - Guid libraryId = Guid.NewGuid(); - Guid pluginId = Guid.NewGuid(); - HttpRequestMessage updateRequest = CreateUpdateRequest(libraryId, pluginId); - updateRequest.Headers.Add("RequestVerificationToken", antiforgeryToken); - - // Act - HttpResponseMessage response = await client.SendAsync(updateRequest); - - // Assert - Assert.Equal(HttpStatusCode.Redirect, response.StatusCode); - Assert.Equal("http://localhost/en-us/auth/login", response.Headers.Location!.ToString()); - Assert.DoesNotContain(_apiFactory.ApiClientStub.PutRequests, putRequest => putRequest.Endpoint == $"libraries/{libraryId}/metadata-providers/{pluginId}/enabled"); - } - - [Fact] - public async Task SetMetadataProviderEnabled_WhenCalledWithoutAntiforgeryToken_ShouldRejectRequest() - { - // Arrange - _apiFactory.ApiClientStub.Reset(); - AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); - Guid libraryId = Guid.NewGuid(); - Guid pluginId = Guid.NewGuid(); - HttpRequestMessage updateRequest = CreateUpdateRequest(libraryId, pluginId); - - // Act - HttpResponseMessage response = await webClient.Client.SendAsync(updateRequest); - - // Assert - Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode); - Assert.DoesNotContain(_apiFactory.ApiClientStub.PutRequests, putRequest => putRequest.Endpoint == $"libraries/{libraryId}/metadata-providers/{pluginId}/enabled"); - } - - /// - /// Builds the update request that enables the metadata provider of the library identified by and . - /// - /// The Id of the media library. - /// The Id of the plugin providing the metadata. - /// The configured update request. - private HttpRequestMessage CreateUpdateRequest(Guid libraryId, Guid pluginId) - { - SetLibraryMetadataProviderEnabledRequest request = _setLibraryMetadataProviderEnabledRequestFixture.Create( - libraryId: libraryId, - pluginId: pluginId, - isEnabled: true - ); - HttpRequestMessage updateRequest = new(HttpMethod.Put, "/en-us/libraries/manage/api-set-metadata-provider-enabled") - { - Content = JsonContent.Create(request) - }; - updateRequest.Content!.Headers.ContentType = new MediaTypeHeaderValue("application/json"); - updateRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); - return updateRequest; - } -} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/Management/AddMediaLibraryRequestMappingTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/Management/AddMediaLibraryRequestMappingTests.cs index 427a8c83..594d14a9 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/Management/AddMediaLibraryRequestMappingTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/Management/AddMediaLibraryRequestMappingTests.cs @@ -1,10 +1,13 @@ #region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DTO.MediaLibrary.Management; using Lumina.Application.Common.Mapping.MediaLibrary.Management; using Lumina.Application.Core.MediaLibrary.Management.Commands.AddLibrary; using Lumina.Contracts.Fixtures.Core.Requests.MediaLibrary.Management; using Lumina.Contracts.Requests.MediaLibrary.Management; using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; +using System; using System.Diagnostics.CodeAnalysis; +using System.Linq; #endregion namespace Lumina.Application.UnitTests.Common.Mapping.MediaLibrary.Management; @@ -16,6 +19,7 @@ namespace Lumina.Application.UnitTests.Common.Mapping.MediaLibrary.Management; public class AddMediaLibraryRequestMappingTests { private readonly AddLibraryRequestFixture _addLibraryRequestFixture = new(); + private readonly LibraryProviderSelectionRequestFixture _libraryProviderSelectionRequestFixture = new(); private readonly LibraryPathTemplatePartRequestFixture _libraryPathTemplatePartRequestFixture = new(); [Fact] @@ -245,4 +249,85 @@ public class AddMediaLibraryRequestMappingTests Assert.False(result.ShouldTrackConsumptionProgress.Value); Assert.Null(result.CompletionThresholdPercentage); } + + [Fact] + public void ToCommand_WhenProviderChoicesAreProvided_ShouldMapThemInOrder() + { + // Arrange + LibraryProviderSelectionRequest[] metadataProviders = [_libraryProviderSelectionRequestFixture.Create(isEnabled: true), _libraryProviderSelectionRequestFixture.Create(isEnabled: false)]; + LibraryProviderSelectionRequest[] artworkProviders = [_libraryProviderSelectionRequestFixture.Create(isEnabled: false)]; + LibraryProviderSelectionRequest[] bookReaders = [_libraryProviderSelectionRequestFixture.Create(isEnabled: true)]; + AddLibraryRequest request = _addLibraryRequestFixture.Create(metadataProviders: metadataProviders, artworkProviders: artworkProviders, bookReaders: bookReaders); + + // Act + AddLibraryCommand result = request.ToCommand(); + + // Assert + Assert.Equal(metadataProviders.Select(selection => (selection.PluginId, selection.IsEnabled)), result.MetadataProviders!.Select(selection => (selection.PluginId, selection.IsEnabled))); + Assert.Equal(artworkProviders.Select(selection => (selection.PluginId, selection.IsEnabled)), result.ArtworkProviders!.Select(selection => (selection.PluginId, selection.IsEnabled))); + Assert.Equal(bookReaders.Select(selection => (selection.PluginId, selection.IsEnabled)), result.BookReaders!.Select(selection => (selection.PluginId, selection.IsEnabled))); + } + + [Fact] + public void ToCommand_WhenProviderChoicesAreNotProvided_ShouldMapThemAsNull() + { + // Arrange + AddLibraryRequest request = _addLibraryRequestFixture.Create(metadataProviders: null, artworkProviders: null, bookReaders: null); + + // Act + AddLibraryCommand result = request.ToCommand(); + + // Assert + Assert.Null(result.MetadataProviders); + Assert.Null(result.ArtworkProviders); + Assert.Null(result.BookReaders); + } + + [Fact] + public void ToCommand_WhenAProviderChoiceIsNull_ShouldMapItToAChoiceWithoutPluginId() + { + // Arrange + AddLibraryRequest request = _addLibraryRequestFixture.Create(metadataProviders: [null], artworkProviders: [null], bookReaders: [null]); + + // Act + AddLibraryCommand result = request.ToCommand(); + + // Assert + Assert.Equal(Guid.Empty, Assert.Single(result.MetadataProviders!).PluginId); + Assert.Null(result.MetadataProviders![0].IsEnabled); + Assert.Equal(Guid.Empty, Assert.Single(result.ArtworkProviders!).PluginId); + Assert.Equal(Guid.Empty, Assert.Single(result.BookReaders!).PluginId); + } + + [Fact] + public void ToCommand_WhenAPathTemplatePartIsNull_ShouldMapItToAPartWithoutKind() + { + // Arrange + AddLibraryRequest request = _addLibraryRequestFixture.Create(pathTemplateParts: [null]); + + // Act + AddLibraryCommand result = request.ToCommand(); + + // Assert + LibraryPathTemplatePartDto part = Assert.Single(result.PathTemplateParts!); + Assert.Null(part.Kind); + Assert.Null(part.Representation); + Assert.False(part.IsOptional); + } + + [Fact] + public void ToCommand_WhenAProviderChoiceHasNoEnabledState_ShouldMapTheStateAsNull() + { + // Arrange + LibraryProviderSelectionRequest choice = _libraryProviderSelectionRequestFixture.Create(includeIsEnabled: false); + AddLibraryRequest request = _addLibraryRequestFixture.Create(metadataProviders: [choice]); + + // Act + AddLibraryCommand result = request.ToCommand(); + + // Assert + LibraryProviderSelectionDto mappedChoice = Assert.Single(result.MetadataProviders!); + Assert.Equal(choice.PluginId, mappedChoice.PluginId); + Assert.Null(mappedChoice.IsEnabled); + } } diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/Management/UpdateLibraryRequestMappingTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/Management/UpdateLibraryRequestMappingTests.cs index 9675c2b9..e160d948 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/Management/UpdateLibraryRequestMappingTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/Management/UpdateLibraryRequestMappingTests.cs @@ -1,10 +1,13 @@ #region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DTO.MediaLibrary.Management; using Lumina.Application.Common.Mapping.MediaLibrary.Management; using Lumina.Application.Core.MediaLibrary.Management.Commands.UpdateLibrary; using Lumina.Contracts.Fixtures.Core.Requests.MediaLibrary.Management; using Lumina.Contracts.Requests.MediaLibrary.Management; using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; +using System; using System.Diagnostics.CodeAnalysis; +using System.Linq; #endregion namespace Lumina.Application.UnitTests.Common.Mapping.MediaLibrary.Management; @@ -16,6 +19,7 @@ namespace Lumina.Application.UnitTests.Common.Mapping.MediaLibrary.Management; public class UpdateLibraryRequestMappingTests { private readonly UpdateLibraryRequestFixture _updateLibraryRequestFixture = new(); + private readonly LibraryProviderSelectionRequestFixture _libraryProviderSelectionRequestFixture = new(); private readonly LibraryPathTemplatePartRequestFixture _libraryPathTemplatePartRequestFixture = new(); [Fact] @@ -148,4 +152,85 @@ public class UpdateLibraryRequestMappingTests Assert.False(result.ShouldTrackConsumptionProgress.Value); Assert.Null(result.CompletionThresholdPercentage); } + + [Fact] + public void ToCommand_WhenProviderChoicesAreProvided_ShouldMapThemInOrder() + { + // Arrange + LibraryProviderSelectionRequest[] metadataProviders = [_libraryProviderSelectionRequestFixture.Create(isEnabled: true), _libraryProviderSelectionRequestFixture.Create(isEnabled: false)]; + LibraryProviderSelectionRequest[] artworkProviders = [_libraryProviderSelectionRequestFixture.Create(isEnabled: false)]; + LibraryProviderSelectionRequest[] bookReaders = [_libraryProviderSelectionRequestFixture.Create(isEnabled: true)]; + UpdateLibraryRequest request = _updateLibraryRequestFixture.Create(metadataProviders: metadataProviders, artworkProviders: artworkProviders, bookReaders: bookReaders); + + // Act + UpdateLibraryCommand result = request.ToCommand(); + + // Assert + Assert.Equal(metadataProviders.Select(selection => (selection.PluginId, selection.IsEnabled)), result.MetadataProviders!.Select(selection => (selection.PluginId, selection.IsEnabled))); + Assert.Equal(artworkProviders.Select(selection => (selection.PluginId, selection.IsEnabled)), result.ArtworkProviders!.Select(selection => (selection.PluginId, selection.IsEnabled))); + Assert.Equal(bookReaders.Select(selection => (selection.PluginId, selection.IsEnabled)), result.BookReaders!.Select(selection => (selection.PluginId, selection.IsEnabled))); + } + + [Fact] + public void ToCommand_WhenProviderChoicesAreNotProvided_ShouldMapThemAsNull() + { + // Arrange + UpdateLibraryRequest request = _updateLibraryRequestFixture.Create(metadataProviders: null, artworkProviders: null, bookReaders: null); + + // Act + UpdateLibraryCommand result = request.ToCommand(); + + // Assert + Assert.Null(result.MetadataProviders); + Assert.Null(result.ArtworkProviders); + Assert.Null(result.BookReaders); + } + + [Fact] + public void ToCommand_WhenAProviderChoiceIsNull_ShouldMapItToAChoiceWithoutPluginId() + { + // Arrange + UpdateLibraryRequest request = _updateLibraryRequestFixture.Create(metadataProviders: [null], artworkProviders: [null], bookReaders: [null]); + + // Act + UpdateLibraryCommand result = request.ToCommand(); + + // Assert + Assert.Equal(Guid.Empty, Assert.Single(result.MetadataProviders!).PluginId); + Assert.Null(result.MetadataProviders![0].IsEnabled); + Assert.Equal(Guid.Empty, Assert.Single(result.ArtworkProviders!).PluginId); + Assert.Equal(Guid.Empty, Assert.Single(result.BookReaders!).PluginId); + } + + [Fact] + public void ToCommand_WhenAPathTemplatePartIsNull_ShouldMapItToAPartWithoutKind() + { + // Arrange + UpdateLibraryRequest request = _updateLibraryRequestFixture.Create(pathTemplateParts: [null]); + + // Act + UpdateLibraryCommand result = request.ToCommand(); + + // Assert + LibraryPathTemplatePartDto part = Assert.Single(result.PathTemplateParts!); + Assert.Null(part.Kind); + Assert.Null(part.Representation); + Assert.False(part.IsOptional); + } + + [Fact] + public void ToCommand_WhenAProviderChoiceHasNoEnabledState_ShouldMapTheStateAsNull() + { + // Arrange + LibraryProviderSelectionRequest choice = _libraryProviderSelectionRequestFixture.Create(includeIsEnabled: false); + UpdateLibraryRequest request = _updateLibraryRequestFixture.Create(metadataProviders: [choice]); + + // Act + UpdateLibraryCommand result = request.ToCommand(); + + // Assert + LibraryProviderSelectionDto mappedChoice = Assert.Single(result.MetadataProviders!); + Assert.Equal(choice.PluginId, mappedChoice.PluginId); + Assert.Null(mappedChoice.IsEnabled); + } } diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Plugins/GetLibraryTypeArtworkProvidersRequestMappingTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Plugins/GetLibraryTypeArtworkProvidersRequestMappingTests.cs new file mode 100644 index 00000000..79126c8a --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Plugins/GetLibraryTypeArtworkProvidersRequestMappingTests.cs @@ -0,0 +1,32 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.Mapping.Plugins; +using Lumina.Application.Core.Plugins.Queries.GetLibraryTypeArtworkProviders; +using Lumina.Contracts.Fixtures.Core.Requests.Plugins; +using Lumina.Contracts.Requests.Plugins; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Application.UnitTests.Common.Mapping.Plugins; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class GetLibraryTypeArtworkProvidersRequestMappingTests +{ + private readonly GetLibraryTypeArtworkProvidersRequestFixture _getLibraryTypeArtworkProvidersRequestFixture = new(); + + [Fact] + public void ToQuery_WhenMappingValidRequest_ShouldMapCorrectly() + { + // Arrange + GetLibraryTypeArtworkProvidersRequest request = _getLibraryTypeArtworkProvidersRequestFixture.Create(libraryType: "Music"); + + // Act + GetLibraryTypeArtworkProvidersQuery result = request.ToQuery(); + + // Assert + Assert.NotNull(result); + Assert.Equal(request.LibraryType, result.LibraryType); + } +} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Plugins/GetLibraryTypeBookReadersRequestMappingTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Plugins/GetLibraryTypeBookReadersRequestMappingTests.cs new file mode 100644 index 00000000..76595851 --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Plugins/GetLibraryTypeBookReadersRequestMappingTests.cs @@ -0,0 +1,32 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.Mapping.Plugins; +using Lumina.Application.Core.Plugins.Queries.GetLibraryTypeBookReaders; +using Lumina.Contracts.Fixtures.Core.Requests.Plugins; +using Lumina.Contracts.Requests.Plugins; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Application.UnitTests.Common.Mapping.Plugins; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class GetLibraryTypeBookReadersRequestMappingTests +{ + private readonly GetLibraryTypeBookReadersRequestFixture _getLibraryTypeBookReadersRequestFixture = new(); + + [Fact] + public void ToQuery_WhenMappingValidRequest_ShouldMapCorrectly() + { + // Arrange + GetLibraryTypeBookReadersRequest request = _getLibraryTypeBookReadersRequestFixture.Create(libraryType: "Music"); + + // Act + GetLibraryTypeBookReadersQuery result = request.ToQuery(); + + // Assert + Assert.NotNull(result); + Assert.Equal(request.LibraryType, result.LibraryType); + } +} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Plugins/GetLibraryTypeMetadataProvidersRequestMappingTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Plugins/GetLibraryTypeMetadataProvidersRequestMappingTests.cs new file mode 100644 index 00000000..32629e3b --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Plugins/GetLibraryTypeMetadataProvidersRequestMappingTests.cs @@ -0,0 +1,32 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.Mapping.Plugins; +using Lumina.Application.Core.Plugins.Queries.GetLibraryTypeMetadataProviders; +using Lumina.Contracts.Fixtures.Core.Requests.Plugins; +using Lumina.Contracts.Requests.Plugins; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Application.UnitTests.Common.Mapping.Plugins; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class GetLibraryTypeMetadataProvidersRequestMappingTests +{ + private readonly GetLibraryTypeMetadataProvidersRequestFixture _getLibraryTypeMetadataProvidersRequestFixture = new(); + + [Fact] + public void ToQuery_WhenMappingValidRequest_ShouldMapCorrectly() + { + // Arrange + GetLibraryTypeMetadataProvidersRequest request = _getLibraryTypeMetadataProvidersRequestFixture.Create(libraryType: "Music"); + + // Act + GetLibraryTypeMetadataProvidersQuery result = request.ToQuery(); + + // Assert + Assert.NotNull(result); + Assert.Equal(request.LibraryType, result.LibraryType); + } +} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Plugins/ReorderLibraryArtworkProvidersRequestMappingTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Plugins/ReorderLibraryArtworkProvidersRequestMappingTests.cs deleted file mode 100644 index eb922a18..00000000 --- a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Plugins/ReorderLibraryArtworkProvidersRequestMappingTests.cs +++ /dev/null @@ -1,32 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using Lumina.Application.Common.Mapping.Plugins; -using Lumina.Application.Core.Plugins.Commands.ReorderLibraryArtworkProviders; -using Lumina.Contracts.Fixtures.Core.Requests.Plugins; -using Lumina.Contracts.Requests.Plugins; -using System.Diagnostics.CodeAnalysis; -#endregion - -namespace Lumina.Application.UnitTests.Common.Mapping.Plugins; - -/// -/// Contains unit tests for the class. -/// -[ExcludeFromCodeCoverage] -public class ReorderLibraryArtworkProvidersRequestMappingTests -{ - private readonly ReorderLibraryArtworkProvidersRequestFixture _reorderLibraryArtworkProvidersRequestFixture = new(); - - [Fact] - public void ToCommand_WhenMappingValidRequest_ShouldMapCorrectly() - { - // Arrange - ReorderLibraryArtworkProvidersRequest request = _reorderLibraryArtworkProvidersRequestFixture.Create(); - - // Act - ReorderLibraryArtworkProvidersCommand result = request.ToCommand(); - - // Assert - Assert.Equal(request.LibraryId, result.LibraryId); - Assert.Equal(request.PluginIds, result.PluginIds); - } -} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Plugins/ReorderLibraryMetadataProvidersRequestMappingTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Plugins/ReorderLibraryMetadataProvidersRequestMappingTests.cs deleted file mode 100644 index d88564a1..00000000 --- a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Plugins/ReorderLibraryMetadataProvidersRequestMappingTests.cs +++ /dev/null @@ -1,35 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using Lumina.Application.Common.Mapping.Plugins; -using Lumina.Application.Core.Plugins.Commands.ReorderLibraryMetadataProviders; -using Lumina.Contracts.Fixtures.Core.Requests.Plugins; -using Lumina.Contracts.Requests.Plugins; -using System; -using System.Collections.Generic; -using System.Diagnostics.CodeAnalysis; -#endregion - -namespace Lumina.Application.UnitTests.Common.Mapping.Plugins; - -/// -/// Contains unit tests for the class. -/// -[ExcludeFromCodeCoverage] -public class ReorderLibraryMetadataProvidersRequestMappingTests -{ - private readonly ReorderLibraryMetadataProvidersRequestFixture _reorderLibraryMetadataProvidersRequestFixture = new(); - - [Fact] - public void ToCommand_WhenMappingValidRequest_ShouldMapCorrectly() - { - // Arrange - ReorderLibraryMetadataProvidersRequest request = _reorderLibraryMetadataProvidersRequestFixture.Create(Guid.NewGuid(), [Guid.NewGuid(), Guid.NewGuid()]); - - // Act - ReorderLibraryMetadataProvidersCommand result = request.ToCommand(); - - // Assert - Assert.NotNull(result); - Assert.Equal(request.LibraryId, result.LibraryId); - Assert.Equal(request.PluginIds, result.PluginIds); - } -} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Plugins/SetLibraryArtworkProviderEnabledRequestMappingTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Plugins/SetLibraryArtworkProviderEnabledRequestMappingTests.cs deleted file mode 100644 index b4ce861a..00000000 --- a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Plugins/SetLibraryArtworkProviderEnabledRequestMappingTests.cs +++ /dev/null @@ -1,33 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using Lumina.Application.Common.Mapping.Plugins; -using Lumina.Application.Core.Plugins.Commands.SetLibraryArtworkProviderEnabled; -using Lumina.Contracts.Fixtures.Core.Requests.Plugins; -using Lumina.Contracts.Requests.Plugins; -using System.Diagnostics.CodeAnalysis; -#endregion - -namespace Lumina.Application.UnitTests.Common.Mapping.Plugins; - -/// -/// Contains unit tests for the class. -/// -[ExcludeFromCodeCoverage] -public class SetLibraryArtworkProviderEnabledRequestMappingTests -{ - private readonly SetLibraryArtworkProviderEnabledRequestFixture _setLibraryArtworkProviderEnabledRequestFixture = new(); - - [Fact] - public void ToCommand_WhenMappingValidRequest_ShouldMapCorrectly() - { - // Arrange - SetLibraryArtworkProviderEnabledRequest request = _setLibraryArtworkProviderEnabledRequestFixture.Create(isEnabled: true); - - // Act - SetLibraryArtworkProviderEnabledCommand result = request.ToCommand(); - - // Assert - Assert.Equal(request.LibraryId, result.LibraryId); - Assert.Equal(request.PluginId, result.PluginId); - Assert.Equal(request.IsEnabled, result.IsEnabled); - } -} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Plugins/SetLibraryBookReaderEnabledRequestMappingTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Plugins/SetLibraryBookReaderEnabledRequestMappingTests.cs deleted file mode 100644 index cec75047..00000000 --- a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Plugins/SetLibraryBookReaderEnabledRequestMappingTests.cs +++ /dev/null @@ -1,34 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using Lumina.Application.Common.Mapping.Plugins; -using Lumina.Application.Core.Plugins.Commands.SetLibraryBookReaderEnabled; -using Lumina.Contracts.Fixtures.Core.Requests.Plugins; -using Lumina.Contracts.Requests.Plugins; -using System.Diagnostics.CodeAnalysis; -#endregion - -namespace Lumina.Application.UnitTests.Common.Mapping.Plugins; - -/// -/// Contains unit tests for the class. -/// -[ExcludeFromCodeCoverage] -public class SetLibraryBookReaderEnabledRequestMappingTests -{ - private readonly SetLibraryBookReaderEnabledRequestFixture _setLibraryBookReaderEnabledRequestFixture = new(); - - [Fact] - public void ToCommand_WhenMappingValidRequest_ShouldMapCorrectly() - { - // Arrange - SetLibraryBookReaderEnabledRequest request = _setLibraryBookReaderEnabledRequestFixture.Create(); - - // Act - SetLibraryBookReaderEnabledCommand result = request.ToCommand(); - - // Assert - Assert.NotNull(result); - Assert.Equal(request.LibraryId, result.LibraryId); - Assert.Equal(request.PluginId, result.PluginId); - Assert.Equal(request.IsEnabled, result.IsEnabled); - } -} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Plugins/SetLibraryMetadataProviderEnabledRequestMappingTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Plugins/SetLibraryMetadataProviderEnabledRequestMappingTests.cs deleted file mode 100644 index 26376d27..00000000 --- a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Plugins/SetLibraryMetadataProviderEnabledRequestMappingTests.cs +++ /dev/null @@ -1,35 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using Lumina.Application.Common.Mapping.Plugins; -using Lumina.Application.Core.Plugins.Commands.SetLibraryMetadataProviderEnabled; -using Lumina.Contracts.Fixtures.Core.Requests.Plugins; -using Lumina.Contracts.Requests.Plugins; -using System; -using System.Diagnostics.CodeAnalysis; -#endregion - -namespace Lumina.Application.UnitTests.Common.Mapping.Plugins; - -/// -/// Contains unit tests for the class. -/// -[ExcludeFromCodeCoverage] -public class SetLibraryMetadataProviderEnabledRequestMappingTests -{ - private readonly SetLibraryMetadataProviderEnabledRequestFixture _setLibraryMetadataProviderEnabledRequestFixture = new(); - - [Fact] - public void ToCommand_WhenMappingValidRequest_ShouldMapCorrectly() - { - // Arrange - SetLibraryMetadataProviderEnabledRequest request = _setLibraryMetadataProviderEnabledRequestFixture.Create(Guid.NewGuid(), Guid.NewGuid(), true); - - // Act - SetLibraryMetadataProviderEnabledCommand result = request.ToCommand(); - - // Assert - Assert.NotNull(result); - Assert.Equal(request.LibraryId, result.LibraryId); - Assert.Equal(request.PluginId, result.PluginId); - Assert.Equal(request.IsEnabled, result.IsEnabled); - } -} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/Management/Commands/AddLibrary/AddLibraryCommandHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/Management/Commands/AddLibrary/AddLibraryCommandHandlerTests.cs index ded42481..677d7291 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/Management/Commands/AddLibrary/AddLibraryCommandHandlerTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/Management/Commands/AddLibrary/AddLibraryCommandHandlerTests.cs @@ -56,6 +56,7 @@ public class AddLibraryCommandHandlerTests private readonly LibraryPathPartFixture _libraryPathPartFixture = new(); private readonly LibraryPathTemplateFixture _libraryPathTemplateFixture = new(); private readonly LibraryPathTemplatePartDtoFixture _libraryPathTemplatePartDtoFixture = new(); + private readonly LibraryProviderSelectionDtoFixture _libraryProviderSelectionDtoFixture = new(); private readonly Guid _userId; /// @@ -76,14 +77,14 @@ public class AddLibraryCommandHandlerTests _mockValidator = Substitute.For>(); _userId = Guid.NewGuid(); - // default stubs: the current user is authenticated, is an admin, the cover image is a valid image, and the provider configurations are seeded successfully + // Default stubs: the current user is authenticated, is an admin, the cover image is a valid image, and the provider configurations are seeded successfully. _mockCurrentUserService.UserId.Returns(_userId); _mockAuthorizationService.IsInRoleAsync(_userId, "Admin", Arg.Any()).Returns(true); _mockEnvironmentContext.FileTypeService.GetImageTypeAsync(Arg.Any(), Arg.Any()) .Returns(Result.From(ImageType.PNG)); _mockLibraryRepository.InsertAsync(Arg.Any(), Arg.Any()) .Returns(Result.Created); - _mockProviderConfigurationStore.EnsureProviderConfigurationsAsync(Arg.Any(), Arg.Any(), Arg.Any()) + _mockProviderConfigurationStore.ConfigureProvidersAsync(Arg.Any(), Arg.Any(), Arg.Any?>(), Arg.Any?>(), Arg.Any?>(), Arg.Any(), Arg.Any()) .Returns(Result.Success); _mockValidator.Validate(Arg.Any()).Returns([]); _mockLibraryPathTemplateService.ResolveTemplate(Arg.Any(), Arg.Any>()).Returns(Result.From(LibraryPathTemplate.Empty())); @@ -107,8 +108,8 @@ public class AddLibraryCommandHandlerTests Assert.False(result.IsFailure); Assert.Equal(persistedLibrary.Id, result.Value.Id); await _mockLibraryRepository.Received(1).InsertAsync(Arg.Any(), Arg.Any()); - await _mockProviderConfigurationStore.Received(1).EnsureProviderConfigurationsAsync( - Arg.Any(), Arg.Is(libraryType => libraryType == Enum.Parse(command.LibraryType)), Arg.Any()); + await _mockProviderConfigurationStore.Received(1).ConfigureProvidersAsync( + Arg.Any(), Arg.Is(libraryType => libraryType == Enum.Parse(command.LibraryType!)), Arg.Any?>(), Arg.Any?>(), Arg.Any?>(), Arg.Is(true), Arg.Any()); await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any()); _mockDomainEventsQueue.Received(1).Enqueue(Arg.Any()); } @@ -157,12 +158,40 @@ public class AddLibraryCommandHandlerTests } [Fact] - public async Task HandleAsync_WhenProviderConfigurationSeedingFails_ShouldReturnErrorWithoutSaving() + public async Task HandleAsync_WhenProviderChoicesAreMade_ShouldConfigureProvidersWithTheChoices() + { + // Arrange + LibraryProviderSelectionDto[] metadataProviders = [.. _libraryProviderSelectionDtoFixture.CreateMany(2)]; + LibraryProviderSelectionDto[] artworkProviders = [_libraryProviderSelectionDtoFixture.Create(isEnabled: false)]; + LibraryProviderSelectionDto[] bookReaders = [_libraryProviderSelectionDtoFixture.Create()]; + AddLibraryCommand command = _addLibraryCommandFixture.Create(metadataProviders: metadataProviders, artworkProviders: artworkProviders, bookReaders: bookReaders); + LibraryEntity persistedLibrary = _libraryEntityFixture.Create(userId: _userId); + _mockLibraryRepository.GetByIdAsync(Arg.Any(), cancellationToken: Arg.Any()) + .Returns(Result.From(persistedLibrary)); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + await _mockProviderConfigurationStore.Received(1).ConfigureProvidersAsync( + Arg.Any(), + Enum.Parse(command.LibraryType!), + Arg.Is?>(selections => selections == metadataProviders), + Arg.Is?>(selections => selections == artworkProviders), + Arg.Is?>(selections => selections == bookReaders), + Arg.Is(true), + Arg.Any()); + await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenConfiguringProvidersFails_ShouldReturnErrorWithoutSaving() { // Arrange AddLibraryCommand command = _addLibraryCommandFixture.Create(); - _mockProviderConfigurationStore.EnsureProviderConfigurationsAsync(Arg.Any(), Arg.Any(), Arg.Any()) - .Returns(Error.Failure(description: "Failed to seed provider configurations")); + _mockProviderConfigurationStore.ConfigureProvidersAsync(Arg.Any(), Arg.Any(), Arg.Any?>(), Arg.Any?>(), Arg.Any?>(), Arg.Any(), Arg.Any()) + .Returns(Error.Failure(description: "Failed to configure provider configurations")); // Act Result result = await _sut.HandleAsync(command, CancellationToken.None); diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/Management/Commands/AddLibrary/AddLibraryCommandValidatorTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/Management/Commands/AddLibrary/AddLibraryCommandValidatorTests.cs index f233599a..d471c6e4 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/Management/Commands/AddLibrary/AddLibraryCommandValidatorTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/Management/Commands/AddLibrary/AddLibraryCommandValidatorTests.cs @@ -7,6 +7,7 @@ using Lumina.Application.UnitTests.Common.Setup; using Lumina.Domain.Common.Errors; using Lumina.Domain.Common.Primitives; using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; +using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; #endregion @@ -22,6 +23,7 @@ public class AddLibraryCommandValidatorTests private readonly AddLibraryCommandValidator _validator = new(); private readonly AddLibraryCommandFixture _addLibraryCommandFixture = new(); private readonly LibraryPathTemplatePartDtoFixture _libraryPathTemplatePartDtoFixture = new(); + private readonly LibraryProviderSelectionDtoFixture _libraryProviderSelectionDtoFixture = new(); [Fact] public void Validate_WhenLibraryTypeIsNull_ShouldHaveValidationError() @@ -37,12 +39,14 @@ public class AddLibraryCommandValidatorTests result.ShouldHaveValidationError(Errors.Library.LibraryTypeCannotBeNull); } - [Fact] - public void Validate_WhenLibraryTypeIsUnknown_ShouldHaveValidationError() + [Theory] + [InlineData("UnknownLibraryType")] // Not a library type. + [InlineData("999")] // A number that is not a defined library type. + public void Validate_WhenLibraryTypeIsUnknown_ShouldHaveValidationError(string libraryType) { // Arrange AddLibraryCommand command = _addLibraryCommandFixture.Create(); - command = command with { LibraryType = "UnknownLibraryType" }; + command = command with { LibraryType = libraryType }; // Act List result = _validator.TestValidate(command); @@ -65,6 +69,36 @@ public class AddLibraryCommandValidatorTests result.ShouldNotHaveValidationError(Errors.Library.UnknownLibraryType); } + [Theory] + [InlineData("book")] // The casing of the name does not matter. + [InlineData("eBook")] // The casing of the name does not matter. + public void Validate_WhenLibraryTypeDiffersInCasing_ShouldNotHaveValidationError(string libraryType) + { + // Arrange + AddLibraryCommand command = _addLibraryCommandFixture.Create(); + command = command with { LibraryType = libraryType }; + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Library.UnknownLibraryType); + } + + [Fact] + public void Validate_WhenLibraryTypeIsTheNumericValueOfADefinedMember_ShouldHaveValidationError() + { + // Arrange + AddLibraryCommand command = _addLibraryCommandFixture.Create(); + command = command with { LibraryType = "0" }; // Book + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Library.UnknownLibraryType); + } + [Fact] public void Validate_WhenContentLocationsIsNull_ShouldHaveValidationError() { @@ -220,9 +254,9 @@ public class AddLibraryCommandValidatorTests } [Theory] - [InlineData(null)] // an absent kind - [InlineData("")] // an empty kind - [InlineData(" ")] // a whitespace kind + [InlineData(null)] // An absent kind. + [InlineData("")] // An empty kind. + [InlineData(" ")] // A whitespace kind. public void Validate_WhenPathTemplatePartKindIsNullOrEmpty_ShouldHaveValidationError(string? kind) { // Arrange @@ -237,9 +271,9 @@ public class AddLibraryCommandValidatorTests } [Theory] - [InlineData(null)] // an absent representation - [InlineData("")] // an empty representation - [InlineData(" ")] // a whitespace representation + [InlineData(null)] // An absent representation. + [InlineData("")] // An empty representation. + [InlineData(" ")] // A whitespace representation. public void Validate_WhenNonSeparatorPartRepresentationIsNullOrEmpty_ShouldHaveValidationError(string? representation) { // Arrange @@ -305,8 +339,8 @@ public class AddLibraryCommandValidatorTests } [Theory] - [InlineData(-1)] // just below the allowed range - [InlineData(int.MinValue)] // the lowest possible value + [InlineData(-1)] // Just below the allowed range. + [InlineData(int.MinValue)] // The lowest possible value. public void Validate_WhenThresholdIsBelowZero_ShouldHaveValidationError(int completionThresholdPercentage) { // Arrange @@ -323,8 +357,8 @@ public class AddLibraryCommandValidatorTests } [Theory] - [InlineData(101)] // just above the allowed range - [InlineData(int.MaxValue)] // the highest possible value + [InlineData(101)] // Just above the allowed range. + [InlineData(int.MaxValue)] // The highest possible value. public void Validate_WhenThresholdIsAboveOneHundred_ShouldHaveValidationError(int completionThresholdPercentage) { // Arrange @@ -341,8 +375,8 @@ public class AddLibraryCommandValidatorTests } [Theory] - [InlineData(0)] // the lowest allowed boundary - [InlineData(100)] // the highest allowed boundary + [InlineData(0)] // The lowest allowed boundary. + [InlineData(100)] // The highest allowed boundary. public void Validate_WhenThresholdIsAtAnAllowedBoundary_ShouldNotHaveValidationError(int completionThresholdPercentage) { // Arrange @@ -408,4 +442,116 @@ public class AddLibraryCommandValidatorTests result.ShouldNotHaveValidationError(Errors.Library.CompletionThresholdPercentageMustBeNullWhenProgressTrackingIsOff); result.ShouldNotHaveValidationError(Errors.Library.CompletionThresholdPercentageMustBeBetweenZeroAndOneHundred); } + + [Fact] + public void Validate_WhenMetadataProviderPluginIdIsEmpty_ShouldHaveValidationError() + { + // Arrange + AddLibraryCommand command = _addLibraryCommandFixture.Create(metadataProviders: [_libraryProviderSelectionDtoFixture.Create(pluginId: Guid.Empty)]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Plugins.PluginIdCannotBeEmpty); + } + + [Fact] + public void Validate_WhenMetadataProviderPluginIdsAreDuplicated_ShouldHaveValidationError() + { + // Arrange + Guid pluginId = Guid.NewGuid(); + AddLibraryCommand command = _addLibraryCommandFixture.Create(metadataProviders: [_libraryProviderSelectionDtoFixture.Create(pluginId: pluginId), _libraryProviderSelectionDtoFixture.Create(pluginId: pluginId, isEnabled: false)]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Plugins.PluginIdsMustBeUnique); + } + + [Fact] + public void Validate_WhenArtworkProviderPluginIdIsEmpty_ShouldHaveValidationError() + { + // Arrange + AddLibraryCommand command = _addLibraryCommandFixture.Create(artworkProviders: [_libraryProviderSelectionDtoFixture.Create(pluginId: Guid.Empty)]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Plugins.PluginIdCannotBeEmpty); + } + + [Fact] + public void Validate_WhenArtworkProviderPluginIdsAreDuplicated_ShouldHaveValidationError() + { + // Arrange + Guid pluginId = Guid.NewGuid(); + AddLibraryCommand command = _addLibraryCommandFixture.Create(artworkProviders: [_libraryProviderSelectionDtoFixture.Create(pluginId: pluginId), _libraryProviderSelectionDtoFixture.Create(pluginId: pluginId, isEnabled: false)]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Plugins.PluginIdsMustBeUnique); + } + + [Fact] + public void Validate_WhenBookReaderPluginIdIsEmpty_ShouldHaveValidationError() + { + // Arrange + AddLibraryCommand command = _addLibraryCommandFixture.Create(bookReaders: [_libraryProviderSelectionDtoFixture.Create(pluginId: Guid.Empty)]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Plugins.PluginIdCannotBeEmpty); + } + + [Fact] + public void Validate_WhenBookReaderPluginIdsAreDuplicated_ShouldHaveValidationError() + { + // Arrange + Guid pluginId = Guid.NewGuid(); + AddLibraryCommand command = _addLibraryCommandFixture.Create(bookReaders: [_libraryProviderSelectionDtoFixture.Create(pluginId: pluginId), _libraryProviderSelectionDtoFixture.Create(pluginId: pluginId, isEnabled: false)]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Plugins.PluginIdsMustBeUnique); + } + + [Fact] + public void Validate_WhenProviderChoicesAreValid_ShouldNotHaveProviderValidationErrors() + { + // Arrange + AddLibraryCommand command = _addLibraryCommandFixture.Create( + metadataProviders: [.. _libraryProviderSelectionDtoFixture.CreateMany(2)], + artworkProviders: [.. _libraryProviderSelectionDtoFixture.CreateMany(2)], + bookReaders: [.. _libraryProviderSelectionDtoFixture.CreateMany(2)]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Plugins.PluginIdCannotBeEmpty); + result.ShouldNotHaveValidationError(Errors.Plugins.PluginIdsMustBeUnique); + } + + [Fact] + public void Validate_WhenProviderChoicesAreNotProvided_ShouldNotHaveProviderValidationErrors() + { + // Arrange + AddLibraryCommand command = _addLibraryCommandFixture.Create(metadataProviders: null, artworkProviders: null, bookReaders: null); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Plugins.PluginIdCannotBeEmpty); + result.ShouldNotHaveValidationError(Errors.Plugins.PluginIdsMustBeUnique); + } } diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/Management/Commands/DeleteLibrary/DeleteLibraryCommandHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/Management/Commands/DeleteLibrary/DeleteLibraryCommandHandlerTests.cs index 7305b45a..fcca21eb 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/Management/Commands/DeleteLibrary/DeleteLibraryCommandHandlerTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/Management/Commands/DeleteLibrary/DeleteLibraryCommandHandlerTests.cs @@ -14,6 +14,7 @@ using Lumina.Application.Fixtures.Core.MediaLibrary.Management.Commands.DeleteLi using Lumina.Domain.Common.Events; using Lumina.Domain.Common.Primitives; using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.Events; +using Lumina.Domain.SharedKernel.Common.Enums.Authorization; using NSubstitute; using System; using System.Collections.Generic; @@ -60,10 +61,12 @@ public class DeleteLibraryCommandHandlerTests _mockValidator = Substitute.For>(); _userId = Guid.NewGuid(); - // default stubs: the current user is authenticated, the ownership policy allows the deletion, and the provider configurations are removed successfully + // Default stubs: the current user is authenticated, the ownership policy allows the deletion, the user has the manage permission, and the provider configurations are removed successfully. _mockCurrentUserService.UserId.Returns(_userId); _mockAuthorizationService.EvaluatePolicyAsync(_userId, Arg.Any(), Arg.Any()) .Returns(true); + _mockAuthorizationService.HasPermissionAsync(_userId, AuthorizationPermission.CanCreateLibraries, Arg.Any()) + .Returns(true); _mockProviderConfigurationStore.RemoveProviderConfigurationsForLibraryAsync(Arg.Any(), Arg.Any()) .Returns(Result.Deleted); _mockLibraryRepository.DeleteByIdAsync(Arg.Any(), Arg.Any()) @@ -170,6 +173,49 @@ public class DeleteLibraryCommandHandlerTests await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); } + [Fact] + public async Task HandleAsync_WhenTheOwnerLacksTheManagePermission_ShouldReturnNotAuthorizedError() + { + // Arrange + DeleteLibraryCommand command = _deleteLibraryCommandFixture.Create(); + LibraryEntity library = _libraryEntityFixture.Create(id: command.Id, userId: _userId); + _mockLibraryRepository.GetByIdAsync(command.Id, cancellationToken: Arg.Any()) + .Returns(Result.From(library)); + _mockAuthorizationService.HasPermissionAsync(_userId, AuthorizationPermission.CanCreateLibraries, Arg.Any()) + .Returns(false); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(ApplicationErrors.Authorization.NotAuthorized, result.FirstError); + await _mockProviderConfigurationStore.DidNotReceive().RemoveProviderConfigurationsForLibraryAsync(Arg.Any(), Arg.Any()); + await _mockLibraryRepository.DidNotReceive().DeleteByIdAsync(Arg.Any(), Arg.Any()); + await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenAnAdminWithoutTheManagePermissionDeletesTheLibraryOfAnotherUser_ShouldDeleteIt() + { + // Arrange + DeleteLibraryCommand command = _deleteLibraryCommandFixture.Create(); + LibraryEntity library = _libraryEntityFixture.Create(id: command.Id, userId: Guid.NewGuid()); + _mockLibraryRepository.GetByIdAsync(command.Id, cancellationToken: Arg.Any()) + .Returns(Result.From(library)); + _mockAuthorizationService.HasPermissionAsync(_userId, AuthorizationPermission.CanCreateLibraries, Arg.Any()) + .Returns(false); + _mockAuthorizationService.IsInRoleAsync(_userId, AuthorizationRoles.ADMIN, Arg.Any()) + .Returns(true); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + await _mockLibraryRepository.Received(1).DeleteByIdAsync(command.Id, Arg.Any()); + } + [Fact] public async Task HandleAsync_WhenCurrentUserIsNull_ShouldReturnNotAuthorizedError() { diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/Management/Commands/UpdateLibrary/UpdateLibraryCommandHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/Management/Commands/UpdateLibrary/UpdateLibraryCommandHandlerTests.cs index d81846cd..b57afe99 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/Management/Commands/UpdateLibrary/UpdateLibraryCommandHandlerTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/Management/Commands/UpdateLibrary/UpdateLibraryCommandHandlerTests.cs @@ -58,6 +58,7 @@ public class UpdateLibraryCommandHandlerTests private readonly LibraryPathPartFixture _libraryPathPartFixture = new(); private readonly LibraryPathTemplateFixture _libraryPathTemplateFixture = new(); private readonly LibraryPathTemplatePartDtoFixture _libraryPathTemplatePartDtoFixture = new(); + private readonly LibraryProviderSelectionDtoFixture _libraryProviderSelectionDtoFixture = new(); private readonly Guid _userId; /// @@ -78,15 +79,17 @@ public class UpdateLibraryCommandHandlerTests _mockValidator = Substitute.For>(); _userId = Guid.NewGuid(); - // default stubs: the current user is authenticated, has the manage permission, the cover image is a valid image, and the provider configurations are reconciled successfully + // Default stubs: the current user is authenticated, owns the library, has the manage permission, the cover image is a valid image, and the provider configurations are configured successfully. _mockCurrentUserService.UserId.Returns(_userId); _mockAuthorizationService.HasPermissionAsync(_userId, Arg.Any(), Arg.Any()) .Returns(true); + _mockAuthorizationService.EvaluatePolicyAsync(_userId, Arg.Any(), Arg.Any()) + .Returns(true); _mockEnvironmentContext.FileTypeService.GetImageTypeAsync(Arg.Any(), Arg.Any()) .Returns(Result.From(ImageType.PNG)); _mockLibraryRepository.UpdateAsync(Arg.Any(), Arg.Any()) .Returns(Result.Updated); - _mockProviderConfigurationStore.ReconcileProviderConfigurationsAsync(Arg.Any(), Arg.Any(), Arg.Any()) + _mockProviderConfigurationStore.ConfigureProvidersAsync(Arg.Any(), Arg.Any(), Arg.Any?>(), Arg.Any?>(), Arg.Any?>(), Arg.Any(), Arg.Any()) .Returns(Result.Success); _mockValidator.Validate(Arg.Any()).Returns([]); _mockLibraryPathTemplateService.ResolveTemplate(Arg.Any(), Arg.Any>()).Returns(Result.From(LibraryPathTemplate.Empty())); @@ -99,8 +102,8 @@ public class UpdateLibraryCommandHandlerTests { // Arrange UpdateLibraryCommand command = _updateLibraryCommandFixture.Create(); - LibraryType commandLibraryType = Enum.Parse(command.LibraryType); - LibraryEntity existingLibrary = _libraryEntityFixture.Create(id: command.Id, userId: command.OwnerId); + LibraryType commandLibraryType = Enum.Parse(command.LibraryType!); + LibraryEntity existingLibrary = _libraryEntityFixture.Create(id: command.Id, userId: _userId); existingLibrary.LibraryType = commandLibraryType == LibraryType.Book ? LibraryType.EBook : LibraryType.Book; _mockLibraryRepository.GetByIdAsync(Arg.Any(), cancellationToken: Arg.Any()) .Returns(Result.From(existingLibrary)); @@ -112,8 +115,8 @@ public class UpdateLibraryCommandHandlerTests Assert.False(result.IsFailure); Assert.Equal(existingLibrary.Id, result.Value.Id); await _mockLibraryRepository.Received(1).UpdateAsync(Arg.Any(), Arg.Any()); - await _mockProviderConfigurationStore.Received(1).ReconcileProviderConfigurationsAsync( - command.Id, Arg.Is(libraryType => libraryType == commandLibraryType), Arg.Any()); + await _mockProviderConfigurationStore.Received(1).ConfigureProvidersAsync( + command.Id, Arg.Is(libraryType => libraryType == commandLibraryType), Arg.Any?>(), Arg.Any?>(), Arg.Any?>(), Arg.Is(true), Arg.Any()); await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any()); _mockDomainEventsQueue.Received(1).Enqueue(Arg.Any()); } @@ -127,7 +130,7 @@ public class UpdateLibraryCommandHandlerTests completionThresholdPercentage: 50); LibraryEntity existingLibrary = _libraryEntityFixture.Create( id: command.Id, - userId: command.OwnerId, + userId: _userId, shouldTrackConsumptionProgress: false); _mockLibraryRepository.GetByIdAsync(command.Id, cancellationToken: Arg.Any()) .Returns(Result.From(existingLibrary)); @@ -152,7 +155,7 @@ public class UpdateLibraryCommandHandlerTests completionThresholdPercentage: null); LibraryEntity existingLibrary = _libraryEntityFixture.Create( id: command.Id, - userId: command.OwnerId, + userId: _userId, libraryType: LibraryType.Music, shouldTrackConsumptionProgress: false); _mockLibraryRepository.GetByIdAsync(command.Id, cancellationToken: Arg.Any()) @@ -171,12 +174,34 @@ public class UpdateLibraryCommandHandlerTests } [Fact] - public async Task HandleAsync_WhenLibraryTypeIsUnchanged_ShouldNotReconcileProviderConfigurations() + public async Task HandleAsync_WhenAnAdminUpdatesTheLibraryOfAnotherUser_ShouldKeepTheStoredOwner() + { + // Arrange + Guid ownerId = Guid.NewGuid(); + UpdateLibraryCommand command = _updateLibraryCommandFixture.Create(); + LibraryEntity existingLibrary = _libraryEntityFixture.Create(id: command.Id, userId: ownerId); + _mockLibraryRepository.GetByIdAsync(Arg.Any(), cancellationToken: Arg.Any()) + .Returns(Result.From(existingLibrary)); + _mockAuthorizationService.IsInRoleAsync(_userId, AuthorizationRoles.ADMIN, Arg.Any()) + .Returns(true); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + await _mockLibraryRepository.Received(1).UpdateAsync( + Arg.Is(library => library.UserId == ownerId), + Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenLibraryTypeIsUnchangedAndNoProviderChoicesAreMade_ShouldNotConfigureProviders() { // Arrange UpdateLibraryCommand command = _updateLibraryCommandFixture.Create(); - LibraryEntity existingLibrary = _libraryEntityFixture.Create(id: command.Id, userId: command.OwnerId); - existingLibrary.LibraryType = Enum.Parse(command.LibraryType); + LibraryEntity existingLibrary = _libraryEntityFixture.Create(id: command.Id, userId: _userId); + existingLibrary.LibraryType = Enum.Parse(command.LibraryType!); _mockLibraryRepository.GetByIdAsync(Arg.Any(), cancellationToken: Arg.Any()) .Returns(Result.From(existingLibrary)); @@ -185,21 +210,144 @@ public class UpdateLibraryCommandHandlerTests // Assert Assert.False(result.IsFailure); - await _mockProviderConfigurationStore.DidNotReceive().ReconcileProviderConfigurationsAsync(Arg.Any(), Arg.Any(), Arg.Any()); + await _mockProviderConfigurationStore.DidNotReceive().ConfigureProvidersAsync(Arg.Any(), Arg.Any(), Arg.Any?>(), Arg.Any?>(), Arg.Any?>(), Arg.Any(), Arg.Any()); } [Fact] - public async Task HandleAsync_WhenProviderConfigurationReconciliationFails_ShouldReturnErrorWithoutSaving() + public async Task HandleAsync_WhenProviderChoicesAreMadeAndLibraryTypeIsUnchanged_ShouldConfigureProvidersWithTheChoices() + { + // Arrange + LibraryProviderSelectionDto[] metadataProviders = [.. _libraryProviderSelectionDtoFixture.CreateMany(2)]; + LibraryProviderSelectionDto[] artworkProviders = [_libraryProviderSelectionDtoFixture.Create(isEnabled: false)]; + LibraryProviderSelectionDto[] bookReaders = [_libraryProviderSelectionDtoFixture.Create()]; + UpdateLibraryCommand command = _updateLibraryCommandFixture.Create(metadataProviders: metadataProviders, artworkProviders: artworkProviders, bookReaders: bookReaders); + LibraryType commandLibraryType = Enum.Parse(command.LibraryType!); + LibraryEntity existingLibrary = _libraryEntityFixture.Create(id: command.Id, userId: _userId); + existingLibrary.LibraryType = commandLibraryType; + _mockLibraryRepository.GetByIdAsync(Arg.Any(), cancellationToken: Arg.Any()) + .Returns(Result.From(existingLibrary)); + _mockAuthorizationService.EvaluatePolicyAsync(_userId, Arg.Any(), Arg.Any()) + .Returns(true); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + await _mockProviderConfigurationStore.Received(1).ConfigureProvidersAsync( + command.Id, + commandLibraryType, + Arg.Is?>(selections => selections == metadataProviders), + Arg.Is?>(selections => selections == artworkProviders), + Arg.Is?>(selections => selections == bookReaders), + Arg.Is(false), + Arg.Any()); + await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any()); + } + + [Theory] + [InlineData(false)] + [InlineData(true)] + public async Task HandleAsync_WhenANonOwnerWithTheManagePermissionUpdatesTheLibrary_ShouldReturnNotAuthorizedWithoutChangingAnything(bool hasProviderChoices) + { + // Arrange + UpdateLibraryCommand command = _updateLibraryCommandFixture.Create(bookReaders: hasProviderChoices ? [_libraryProviderSelectionDtoFixture.Create()] : null); + LibraryEntity existingLibrary = _libraryEntityFixture.Create(id: command.Id, userId: Guid.NewGuid()); + existingLibrary.LibraryType = Enum.Parse(command.LibraryType!); + _mockLibraryRepository.GetByIdAsync(Arg.Any(), cancellationToken: Arg.Any()) + .Returns(Result.From(existingLibrary)); + _mockAuthorizationService.EvaluatePolicyAsync(_userId, Arg.Any(), Arg.Any()) + .Returns(false); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(ApplicationErrors.Authorization.NotAuthorized, result.FirstError); + await _mockLibraryRepository.DidNotReceive().UpdateAsync(Arg.Any(), Arg.Any()); + await _mockProviderConfigurationStore.DidNotReceive().ConfigureProvidersAsync( + Arg.Any(), Arg.Any(), Arg.Any?>(), Arg.Any?>(), Arg.Any?>(), Arg.Any(), Arg.Any()); + await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenANonOwnerWithTheManagePermissionChangesTheLibraryType_ShouldReturnNotAuthorizedWithoutChangingTheConfigurations() + { + // Arrange + UpdateLibraryCommand command = _updateLibraryCommandFixture.Create(libraryType: nameof(LibraryType.Book)); + LibraryEntity existingLibrary = _libraryEntityFixture.Create(id: command.Id, userId: Guid.NewGuid(), libraryType: LibraryType.Music); + _mockLibraryRepository.GetByIdAsync(Arg.Any(), cancellationToken: Arg.Any()) + .Returns(Result.From(existingLibrary)); + _mockAuthorizationService.EvaluatePolicyAsync(_userId, Arg.Any(), Arg.Any()) + .Returns(false); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(ApplicationErrors.Authorization.NotAuthorized, result.FirstError); + await _mockProviderConfigurationStore.DidNotReceive().ConfigureProvidersAsync( + Arg.Any(), Arg.Any(), Arg.Any?>(), Arg.Any?>(), Arg.Any?>(), Arg.Any(), Arg.Any()); + await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenTheOwnerLacksTheManagePermission_ShouldReturnNotAuthorizedWithoutChangingAnything() { // Arrange UpdateLibraryCommand command = _updateLibraryCommandFixture.Create(); - LibraryType commandLibraryType = Enum.Parse(command.LibraryType); - LibraryEntity existingLibrary = _libraryEntityFixture.Create(id: command.Id, userId: command.OwnerId); + LibraryEntity existingLibrary = _libraryEntityFixture.Create(id: command.Id, userId: _userId); + _mockLibraryRepository.GetByIdAsync(Arg.Any(), cancellationToken: Arg.Any()) + .Returns(Result.From(existingLibrary)); + _mockAuthorizationService.HasPermissionAsync(_userId, Arg.Any(), Arg.Any()) + .Returns(false); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(ApplicationErrors.Authorization.NotAuthorized, result.FirstError); + await _mockLibraryRepository.DidNotReceive().UpdateAsync(Arg.Any(), Arg.Any()); + await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenAnAdminWithoutTheManagePermissionUpdatesTheLibraryOfAnotherUser_ShouldUpdateIt() + { + // Arrange + UpdateLibraryCommand command = _updateLibraryCommandFixture.Create(); + LibraryEntity existingLibrary = _libraryEntityFixture.Create(id: command.Id, userId: Guid.NewGuid()); + _mockLibraryRepository.GetByIdAsync(Arg.Any(), cancellationToken: Arg.Any()) + .Returns(Result.From(existingLibrary)); + _mockAuthorizationService.HasPermissionAsync(_userId, Arg.Any(), Arg.Any()) + .Returns(false); + _mockAuthorizationService.IsInRoleAsync(_userId, AuthorizationRoles.ADMIN, Arg.Any()) + .Returns(true); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + await _mockLibraryRepository.Received(1).UpdateAsync(Arg.Any(), Arg.Any()); + await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenConfiguringProvidersFails_ShouldReturnErrorWithoutSaving() + { + // Arrange + UpdateLibraryCommand command = _updateLibraryCommandFixture.Create(); + LibraryType commandLibraryType = Enum.Parse(command.LibraryType!); + LibraryEntity existingLibrary = _libraryEntityFixture.Create(id: command.Id, userId: _userId); existingLibrary.LibraryType = commandLibraryType == LibraryType.Book ? LibraryType.EBook : LibraryType.Book; _mockLibraryRepository.GetByIdAsync(Arg.Any(), cancellationToken: Arg.Any()) .Returns(Result.From(existingLibrary)); - _mockProviderConfigurationStore.ReconcileProviderConfigurationsAsync(Arg.Any(), Arg.Any(), Arg.Any()) - .Returns(Error.Failure(description: "Failed to reconcile provider configurations")); + _mockProviderConfigurationStore.ConfigureProvidersAsync(Arg.Any(), Arg.Any(), Arg.Any?>(), Arg.Any?>(), Arg.Any?>(), Arg.Any(), Arg.Any()) + .Returns(Error.Failure(description: "Failed to configure provider configurations")); // Act Result result = await _sut.HandleAsync(command, CancellationToken.None); @@ -215,7 +363,7 @@ public class UpdateLibraryCommandHandlerTests // Arrange UpdateLibraryCommand command = _updateLibraryCommandFixture.Create(); command = command with { CoverImage = null }; - LibraryEntity existingLibrary = _libraryEntityFixture.Create(id: command.Id, userId: command.OwnerId); + LibraryEntity existingLibrary = _libraryEntityFixture.Create(id: command.Id, userId: _userId); _mockLibraryRepository.GetByIdAsync(Arg.Any(), cancellationToken: Arg.Any()) .Returns(Result.From(existingLibrary)); @@ -234,7 +382,7 @@ public class UpdateLibraryCommandHandlerTests // Arrange UpdateLibraryCommand command = _updateLibraryCommandFixture.Create(); command = command with { CoverImage = "C:/Users/user/cover.jpg" }; - LibraryEntity existingLibrary = _libraryEntityFixture.Create(id: command.Id, userId: command.OwnerId); + LibraryEntity existingLibrary = _libraryEntityFixture.Create(id: command.Id, userId: _userId); existingLibrary.CoverImage = null; _mockLibraryRepository.GetByIdAsync(command.Id, cancellationToken: Arg.Any()) .Returns(Result.From(existingLibrary)); @@ -257,7 +405,7 @@ public class UpdateLibraryCommandHandlerTests // Arrange UpdateLibraryCommand command = _updateLibraryCommandFixture.Create(); command = command with { CoverImage = "C:/Users/user/cover.jpg" }; - LibraryEntity existingLibrary = _libraryEntityFixture.Create(id: command.Id, userId: command.OwnerId); + LibraryEntity existingLibrary = _libraryEntityFixture.Create(id: command.Id, userId: _userId); existingLibrary.CoverImage = null; _mockLibraryRepository.GetByIdAsync(command.Id, cancellationToken: Arg.Any()) .Returns(Result.From(existingLibrary)); @@ -279,7 +427,7 @@ public class UpdateLibraryCommandHandlerTests // Arrange UpdateLibraryCommand command = _updateLibraryCommandFixture.Create(); command = command with { CoverImage = " " }; - LibraryEntity existingLibrary = _libraryEntityFixture.Create(id: command.Id, userId: command.OwnerId); + LibraryEntity existingLibrary = _libraryEntityFixture.Create(id: command.Id, userId: _userId); existingLibrary.CoverImage = null; _mockLibraryRepository.GetByIdAsync(command.Id, cancellationToken: Arg.Any()) .Returns(Result.From(existingLibrary)); @@ -294,12 +442,39 @@ public class UpdateLibraryCommandHandlerTests await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); } + [Fact] + public async Task HandleAsync_WhenUserLacksManagePermissionAndCoverImageIsNew_ShouldNotProbeCoverImage() + { + // Arrange + UpdateLibraryCommand command = _updateLibraryCommandFixture.Create(); + command = command with { CoverImage = @"\\server\share\cover.jpg" }; + LibraryEntity existingLibrary = _libraryEntityFixture.Create(id: command.Id, userId: _userId); + existingLibrary.CoverImage = null; + _mockLibraryRepository.GetByIdAsync(command.Id, cancellationToken: Arg.Any()) + .Returns(Result.From(existingLibrary)); + _mockAuthorizationService.IsInRoleAsync(_userId, AuthorizationRoles.ADMIN, Arg.Any()) + .Returns(false); + _mockAuthorizationService.HasPermissionAsync(_userId, AuthorizationPermission.CanCreateLibraries, Arg.Any()) + .Returns(false); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(ApplicationErrors.Authorization.NotAuthorized, result.FirstError); + await _mockEnvironmentContext.FileTypeService.DidNotReceive() + .GetImageTypeAsync(Arg.Any(), Arg.Any()); + await _mockLibraryRepository.DidNotReceive().UpdateAsync(Arg.Any(), Arg.Any()); + await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); + } + [Fact] public async Task HandleAsync_WhenCoverImageIsUnchanged_ShouldSkipImageTypeCheck() { // Arrange UpdateLibraryCommand command = _updateLibraryCommandFixture.Create(); - LibraryEntity existingLibrary = _libraryEntityFixture.Create(id: command.Id, userId: command.OwnerId); + LibraryEntity existingLibrary = _libraryEntityFixture.Create(id: command.Id, userId: _userId); existingLibrary.CoverImage = command.CoverImage; _mockLibraryRepository.GetByIdAsync(command.Id, cancellationToken: Arg.Any()) .Returns(Result.From(existingLibrary)); @@ -333,6 +508,28 @@ public class UpdateLibraryCommandHandlerTests await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); } + [Fact] + public async Task HandleAsync_WhenLibraryDoesNotExistAndUserLacksPermission_ShouldReturnNotFoundWithoutAuthorizing() + { + // Arrange + UpdateLibraryCommand command = _updateLibraryCommandFixture.Create(); + _mockLibraryRepository.GetByIdAsync(command.Id, cancellationToken: Arg.Any()) + .Returns(Result.Success(null)); + _mockAuthorizationService.IsInRoleAsync(_userId, AuthorizationRoles.ADMIN, Arg.Any()) + .Returns(false); + _mockAuthorizationService.HasPermissionAsync(_userId, AuthorizationPermission.CanCreateLibraries, Arg.Any()) + .Returns(false); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(DomainErrors.Library.LibraryNotFound, result.FirstError); + await _mockAuthorizationService.DidNotReceive().EvaluatePolicyAsync( + Arg.Any(), Arg.Any(), Arg.Any()); + } + [Fact] public async Task HandleAsync_WhenGetByIdFails_ShouldReturnError() { @@ -355,7 +552,7 @@ public class UpdateLibraryCommandHandlerTests { // Arrange UpdateLibraryCommand command = _updateLibraryCommandFixture.Create(); - LibraryEntity existingLibrary = _libraryEntityFixture.Create(id: command.Id, userId: command.OwnerId); + LibraryEntity existingLibrary = _libraryEntityFixture.Create(id: command.Id, userId: _userId); _mockLibraryRepository.GetByIdAsync(command.Id, cancellationToken: Arg.Any()) .Returns(Result.From(existingLibrary)); _mockAuthorizationService.HasPermissionAsync(_userId, Arg.Any(), Arg.Any()) @@ -395,7 +592,7 @@ public class UpdateLibraryCommandHandlerTests { // Arrange UpdateLibraryCommand command = _updateLibraryCommandFixture.Create(); - LibraryEntity existingLibrary = _libraryEntityFixture.Create(id: command.Id, userId: command.OwnerId); + LibraryEntity existingLibrary = _libraryEntityFixture.Create(id: command.Id, userId: _userId); _mockLibraryRepository.GetByIdAsync(command.Id, cancellationToken: Arg.Any()) .Returns(Result.From(existingLibrary)); command = command with { ContentLocations = [""] }; @@ -415,7 +612,7 @@ public class UpdateLibraryCommandHandlerTests { // Arrange UpdateLibraryCommand command = _updateLibraryCommandFixture.Create(); - LibraryEntity existingLibrary = _libraryEntityFixture.Create(id: command.Id, userId: command.OwnerId); + LibraryEntity existingLibrary = _libraryEntityFixture.Create(id: command.Id, userId: _userId); _mockLibraryRepository.GetByIdAsync(command.Id, cancellationToken: Arg.Any()) .Returns(Result.From(existingLibrary)); _mockLibraryRepository.UpdateAsync(Arg.Any(), Arg.Any()) @@ -434,7 +631,7 @@ public class UpdateLibraryCommandHandlerTests { // Arrange UpdateLibraryCommand command = _updateLibraryCommandFixture.Create(); - LibraryEntity existingLibrary = _libraryEntityFixture.Create(id: command.Id, userId: command.OwnerId); + LibraryEntity existingLibrary = _libraryEntityFixture.Create(id: command.Id, userId: _userId); _mockLibraryRepository.GetByIdAsync(Arg.Any(), cancellationToken: Arg.Any()) .Returns(Result.From(existingLibrary), Error.Failure(description: "Failed to retrieve updated library")); @@ -450,7 +647,7 @@ public class UpdateLibraryCommandHandlerTests { // Arrange UpdateLibraryCommand command = _updateLibraryCommandFixture.Create(); - LibraryEntity existingLibrary = _libraryEntityFixture.Create(id: command.Id, userId: command.OwnerId); + LibraryEntity existingLibrary = _libraryEntityFixture.Create(id: command.Id, userId: _userId); _mockLibraryRepository.GetByIdAsync(Arg.Any(), cancellationToken: Arg.Any()) .Returns(Result.From(existingLibrary), Result.Success(null)); @@ -486,7 +683,7 @@ public class UpdateLibraryCommandHandlerTests { // Arrange UpdateLibraryCommand command = _updateLibraryCommandFixture.Create(pathTemplateParts: null); - LibraryEntity existingLibrary = _libraryEntityFixture.Create(id: command.Id, userId: command.OwnerId); + LibraryEntity existingLibrary = _libraryEntityFixture.Create(id: command.Id, userId: _userId); _mockLibraryRepository.GetByIdAsync(Arg.Any(), cancellationToken: Arg.Any()) .Returns(Result.From(existingLibrary)); LibraryPathPart defaultPart = _libraryPathPartFixture.Create( @@ -524,7 +721,7 @@ public class UpdateLibraryCommandHandlerTests representation: "{0}", isOptional: false); UpdateLibraryCommand command = _updateLibraryCommandFixture.Create(pathTemplateParts: [providedDto]); - LibraryEntity existingLibrary = _libraryEntityFixture.Create(id: command.Id, userId: command.OwnerId); + LibraryEntity existingLibrary = _libraryEntityFixture.Create(id: command.Id, userId: _userId); _mockLibraryRepository.GetByIdAsync(Arg.Any(), cancellationToken: Arg.Any()) .Returns(Result.From(existingLibrary)); LibraryPathPart providedPart = _libraryPathPartFixture.Create( @@ -562,7 +759,7 @@ public class UpdateLibraryCommandHandlerTests // Arrange LibraryPathTemplatePartDto invalidPart = _libraryPathTemplatePartDtoFixture.Create() with { Kind = "NotARealLibraryPathPartKind" }; UpdateLibraryCommand command = _updateLibraryCommandFixture.Create(pathTemplateParts: [invalidPart]); - LibraryEntity existingLibrary = _libraryEntityFixture.Create(id: command.Id, userId: command.OwnerId); + LibraryEntity existingLibrary = _libraryEntityFixture.Create(id: command.Id, userId: _userId); _mockLibraryRepository.GetByIdAsync(Arg.Any(), cancellationToken: Arg.Any()) .Returns(Result.From(existingLibrary)); @@ -585,7 +782,7 @@ public class UpdateLibraryCommandHandlerTests kind: nameof(LibraryPathPartKind.Artist), representation: "{0}"); UpdateLibraryCommand command = _updateLibraryCommandFixture.Create(pathTemplateParts: [validPart]); - LibraryEntity existingLibrary = _libraryEntityFixture.Create(id: command.Id, userId: command.OwnerId); + LibraryEntity existingLibrary = _libraryEntityFixture.Create(id: command.Id, userId: _userId); _mockLibraryRepository.GetByIdAsync(Arg.Any(), cancellationToken: Arg.Any()) .Returns(Result.From(existingLibrary)); Error validationError = DomainErrors.Library.PathTemplateIsNotSupportedForLibraryType; @@ -611,7 +808,7 @@ public class UpdateLibraryCommandHandlerTests completionThresholdPercentage: null); LibraryEntity existingLibrary = _libraryEntityFixture.Create( id: command.Id, - userId: command.OwnerId, + userId: _userId, libraryType: LibraryType.Book, shouldTrackConsumptionProgress: true, completionThresholdPercentage: 80); @@ -641,7 +838,7 @@ public class UpdateLibraryCommandHandlerTests completionThresholdPercentage: 60); LibraryEntity existingLibrary = _libraryEntityFixture.Create( id: command.Id, - userId: command.OwnerId, + userId: _userId, libraryType: LibraryType.Book, shouldTrackConsumptionProgress: true, completionThresholdPercentage: 80); @@ -671,7 +868,7 @@ public class UpdateLibraryCommandHandlerTests completionThresholdPercentage: null); LibraryEntity existingLibrary = _libraryEntityFixture.Create( id: command.Id, - userId: command.OwnerId, + userId: _userId, libraryType: LibraryType.Book, shouldTrackConsumptionProgress: true, completionThresholdPercentage: 80); @@ -701,7 +898,7 @@ public class UpdateLibraryCommandHandlerTests completionThresholdPercentage: 50); LibraryEntity existingLibrary = _libraryEntityFixture.Create( id: command.Id, - userId: command.OwnerId, + userId: _userId, libraryType: LibraryType.Book, shouldTrackConsumptionProgress: true, completionThresholdPercentage: 80); @@ -728,7 +925,7 @@ public class UpdateLibraryCommandHandlerTests completionThresholdPercentage: null); LibraryEntity existingLibrary = _libraryEntityFixture.Create( id: command.Id, - userId: command.OwnerId, + userId: _userId, libraryType: LibraryType.Book, shouldTrackConsumptionProgress: true, completionThresholdPercentage: 80); @@ -758,7 +955,7 @@ public class UpdateLibraryCommandHandlerTests completionThresholdPercentage: null); LibraryEntity existingLibrary = _libraryEntityFixture.Create( id: command.Id, - userId: command.OwnerId, + userId: _userId, libraryType: LibraryType.Music, shouldTrackConsumptionProgress: false, completionThresholdPercentage: null); @@ -788,7 +985,7 @@ public class UpdateLibraryCommandHandlerTests completionThresholdPercentage: 65); LibraryEntity existingLibrary = _libraryEntityFixture.Create( id: command.Id, - userId: command.OwnerId, + userId: _userId, libraryType: LibraryType.Music, shouldTrackConsumptionProgress: false, completionThresholdPercentage: null); diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/Management/Commands/UpdateLibrary/UpdateLibraryCommandValidatorTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/Management/Commands/UpdateLibrary/UpdateLibraryCommandValidatorTests.cs index 572fda36..0a574acf 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/Management/Commands/UpdateLibrary/UpdateLibraryCommandValidatorTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/Management/Commands/UpdateLibrary/UpdateLibraryCommandValidatorTests.cs @@ -23,6 +23,7 @@ public class UpdateLibraryCommandValidatorTests private readonly UpdateLibraryCommandValidator _validator = new(); private readonly UpdateLibraryCommandFixture _updateLibraryCommandFixture = new(); private readonly LibraryPathTemplatePartDtoFixture _libraryPathTemplatePartDtoFixture = new(); + private readonly LibraryProviderSelectionDtoFixture _libraryProviderSelectionDtoFixture = new(); [Fact] public void Validate_WhenIdIsEmpty_ShouldHaveValidationError() @@ -51,33 +52,6 @@ public class UpdateLibraryCommandValidatorTests result.ShouldNotHaveValidationError(Errors.Library.LibraryIdCannotBeEmpty); } - [Fact] - public void Validate_WhenOwnerIdIsEmpty_ShouldHaveValidationError() - { - // Arrange - UpdateLibraryCommand command = _updateLibraryCommandFixture.Create(); - command = command with { OwnerId = Guid.Empty }; - - // Act - List result = _validator.TestValidate(command); - - // Assert - result.ShouldHaveValidationError(Errors.Users.UserIdCannotBeEmpty); - } - - [Fact] - public void Validate_WhenOwnerIdIsValid_ShouldNotHaveValidationError() - { - // Arrange - UpdateLibraryCommand command = _updateLibraryCommandFixture.Create(); - - // Act - List result = _validator.TestValidate(command); - - // Assert - result.ShouldNotHaveValidationError(Errors.Users.UserIdCannotBeEmpty); - } - [Fact] public void Validate_WhenLibraryTypeIsNull_ShouldHaveValidationError() { @@ -92,12 +66,14 @@ public class UpdateLibraryCommandValidatorTests result.ShouldHaveValidationError(Errors.Library.LibraryTypeCannotBeNull); } - [Fact] - public void Validate_WhenLibraryTypeIsUnknown_ShouldHaveValidationError() + [Theory] + [InlineData("UnknownLibraryType")] // Not a library type. + [InlineData("999")] // A number that is not a defined library type. + public void Validate_WhenLibraryTypeIsUnknown_ShouldHaveValidationError(string libraryType) { // Arrange UpdateLibraryCommand command = _updateLibraryCommandFixture.Create(); - command = command with { LibraryType = "UnknownLibraryType" }; + command = command with { LibraryType = libraryType }; // Act List result = _validator.TestValidate(command); @@ -120,6 +96,36 @@ public class UpdateLibraryCommandValidatorTests result.ShouldNotHaveValidationError(Errors.Library.UnknownLibraryType); } + [Theory] + [InlineData("book")] // The casing of the name does not matter. + [InlineData("eBook")] // The casing of the name does not matter. + public void Validate_WhenLibraryTypeDiffersInCasing_ShouldNotHaveValidationError(string libraryType) + { + // Arrange + UpdateLibraryCommand command = _updateLibraryCommandFixture.Create(); + command = command with { LibraryType = libraryType }; + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Library.UnknownLibraryType); + } + + [Fact] + public void Validate_WhenLibraryTypeIsTheNumericValueOfADefinedMember_ShouldHaveValidationError() + { + // Arrange + UpdateLibraryCommand command = _updateLibraryCommandFixture.Create(); + command = command with { LibraryType = "0" }; // Book + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Library.UnknownLibraryType); + } + [Fact] public void Validate_WhenContentLocationsIsNull_ShouldHaveValidationError() { @@ -275,9 +281,9 @@ public class UpdateLibraryCommandValidatorTests } [Theory] - [InlineData(null)] // an absent kind - [InlineData("")] // an empty kind - [InlineData(" ")] // a whitespace kind + [InlineData(null)] // An absent kind. + [InlineData("")] // An empty kind. + [InlineData(" ")] // A whitespace kind. public void Validate_WhenPathTemplatePartKindIsNullOrEmpty_ShouldHaveValidationError(string? kind) { // Arrange @@ -292,9 +298,9 @@ public class UpdateLibraryCommandValidatorTests } [Theory] - [InlineData(null)] // an absent representation - [InlineData("")] // an empty representation - [InlineData(" ")] // a whitespace representation + [InlineData(null)] // An absent representation. + [InlineData("")] // An empty representation. + [InlineData(" ")] // A whitespace representation. public void Validate_WhenNonSeparatorPartRepresentationIsNullOrEmpty_ShouldHaveValidationError(string? representation) { // Arrange @@ -360,8 +366,8 @@ public class UpdateLibraryCommandValidatorTests } [Theory] - [InlineData(-1)] // just below the allowed range - [InlineData(int.MinValue)] // the lowest possible value + [InlineData(-1)] // Just below the allowed range. + [InlineData(int.MinValue)] // The lowest possible value. public void Validate_WhenThresholdIsBelowZero_ShouldHaveValidationError(int completionThresholdPercentage) { // Arrange @@ -378,8 +384,8 @@ public class UpdateLibraryCommandValidatorTests } [Theory] - [InlineData(101)] // just above the allowed range - [InlineData(int.MaxValue)] // the highest possible value + [InlineData(101)] // Just above the allowed range. + [InlineData(int.MaxValue)] // The highest possible value. public void Validate_WhenThresholdIsAboveOneHundred_ShouldHaveValidationError(int completionThresholdPercentage) { // Arrange @@ -396,8 +402,8 @@ public class UpdateLibraryCommandValidatorTests } [Theory] - [InlineData(0)] // the lowest allowed boundary - [InlineData(100)] // the highest allowed boundary + [InlineData(0)] // The lowest allowed boundary. + [InlineData(100)] // The highest allowed boundary. public void Validate_WhenThresholdIsAtAnAllowedBoundary_ShouldNotHaveValidationError(int completionThresholdPercentage) { // Arrange @@ -463,4 +469,116 @@ public class UpdateLibraryCommandValidatorTests result.ShouldNotHaveValidationError(Errors.Library.CompletionThresholdPercentageMustBeNullWhenProgressTrackingIsOff); result.ShouldNotHaveValidationError(Errors.Library.CompletionThresholdPercentageMustBeBetweenZeroAndOneHundred); } + + [Fact] + public void Validate_WhenMetadataProviderPluginIdIsEmpty_ShouldHaveValidationError() + { + // Arrange + UpdateLibraryCommand command = _updateLibraryCommandFixture.Create(metadataProviders: [_libraryProviderSelectionDtoFixture.Create(pluginId: Guid.Empty)]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Plugins.PluginIdCannotBeEmpty); + } + + [Fact] + public void Validate_WhenMetadataProviderPluginIdsAreDuplicated_ShouldHaveValidationError() + { + // Arrange + Guid pluginId = Guid.NewGuid(); + UpdateLibraryCommand command = _updateLibraryCommandFixture.Create(metadataProviders: [_libraryProviderSelectionDtoFixture.Create(pluginId: pluginId), _libraryProviderSelectionDtoFixture.Create(pluginId: pluginId, isEnabled: false)]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Plugins.PluginIdsMustBeUnique); + } + + [Fact] + public void Validate_WhenArtworkProviderPluginIdIsEmpty_ShouldHaveValidationError() + { + // Arrange + UpdateLibraryCommand command = _updateLibraryCommandFixture.Create(artworkProviders: [_libraryProviderSelectionDtoFixture.Create(pluginId: Guid.Empty)]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Plugins.PluginIdCannotBeEmpty); + } + + [Fact] + public void Validate_WhenArtworkProviderPluginIdsAreDuplicated_ShouldHaveValidationError() + { + // Arrange + Guid pluginId = Guid.NewGuid(); + UpdateLibraryCommand command = _updateLibraryCommandFixture.Create(artworkProviders: [_libraryProviderSelectionDtoFixture.Create(pluginId: pluginId), _libraryProviderSelectionDtoFixture.Create(pluginId: pluginId, isEnabled: false)]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Plugins.PluginIdsMustBeUnique); + } + + [Fact] + public void Validate_WhenBookReaderPluginIdIsEmpty_ShouldHaveValidationError() + { + // Arrange + UpdateLibraryCommand command = _updateLibraryCommandFixture.Create(bookReaders: [_libraryProviderSelectionDtoFixture.Create(pluginId: Guid.Empty)]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Plugins.PluginIdCannotBeEmpty); + } + + [Fact] + public void Validate_WhenBookReaderPluginIdsAreDuplicated_ShouldHaveValidationError() + { + // Arrange + Guid pluginId = Guid.NewGuid(); + UpdateLibraryCommand command = _updateLibraryCommandFixture.Create(bookReaders: [_libraryProviderSelectionDtoFixture.Create(pluginId: pluginId), _libraryProviderSelectionDtoFixture.Create(pluginId: pluginId, isEnabled: false)]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Plugins.PluginIdsMustBeUnique); + } + + [Fact] + public void Validate_WhenProviderChoicesAreValid_ShouldNotHaveProviderValidationErrors() + { + // Arrange + UpdateLibraryCommand command = _updateLibraryCommandFixture.Create( + metadataProviders: [.. _libraryProviderSelectionDtoFixture.CreateMany(2)], + artworkProviders: [.. _libraryProviderSelectionDtoFixture.CreateMany(2)], + bookReaders: [.. _libraryProviderSelectionDtoFixture.CreateMany(2)]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Plugins.PluginIdCannotBeEmpty); + result.ShouldNotHaveValidationError(Errors.Plugins.PluginIdsMustBeUnique); + } + + [Fact] + public void Validate_WhenProviderChoicesAreNotProvided_ShouldNotHaveProviderValidationErrors() + { + // Arrange + UpdateLibraryCommand command = _updateLibraryCommandFixture.Create(metadataProviders: null, artworkProviders: null, bookReaders: null); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Plugins.PluginIdCannotBeEmpty); + result.ShouldNotHaveValidationError(Errors.Plugins.PluginIdsMustBeUnique); + } } diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/Management/Queries/GetLibraryPathTemplateParts/GetLibraryPathTemplatePartsQueryHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/Management/Queries/GetLibraryPathTemplateParts/GetLibraryPathTemplatePartsQueryHandlerTests.cs index 32394ae0..ef3ed900 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/Management/Queries/GetLibraryPathTemplateParts/GetLibraryPathTemplatePartsQueryHandlerTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/Management/Queries/GetLibraryPathTemplateParts/GetLibraryPathTemplatePartsQueryHandlerTests.cs @@ -51,9 +51,10 @@ public class GetLibraryPathTemplatePartsQueryHandlerTests } [Theory] - [InlineData("")] // an absent library type - [InlineData(" ")] // a whitespace library type - [InlineData("NotARealLibraryType")] // an unknown library type + [InlineData("")] // An absent library type. + [InlineData(" ")] // A whitespace library type. + [InlineData("NotARealLibraryType")] // An unknown library type. + [InlineData("999")] // A number that is not a defined library type. public async Task HandleAsync_WhenLibraryTypeIsUnknownOrAbsent_ShouldReturnUnknownLibraryTypeError(string libraryType) { // Arrange diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/Plugins/Commands/ReorderLibraryArtworkProviders/ReorderLibraryArtworkProvidersCommandHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/Plugins/Commands/ReorderLibraryArtworkProviders/ReorderLibraryArtworkProvidersCommandHandlerTests.cs deleted file mode 100644 index 30b0c080..00000000 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/Plugins/Commands/ReorderLibraryArtworkProviders/ReorderLibraryArtworkProvidersCommandHandlerTests.cs +++ /dev/null @@ -1,184 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using Lumina.Application.Common.DataAccess.Entities.Plugins; -using Lumina.Application.Common.DataAccess.Repositories.Plugins; -using Lumina.Application.Common.DataAccess.UoW; -using Lumina.Application.Common.Infrastructure.Authentication; -using Lumina.Application.Common.Infrastructure.Authorization; -using Lumina.Application.Common.Infrastructure.Authorization.Policies.LibraryOwnership; -using Lumina.Application.Common.Infrastructure.Validation; -using Lumina.Application.Core.Plugins.Commands.ReorderLibraryArtworkProviders; -using Lumina.Application.Fixtures.Common.DataAccess.Entities.Plugins; -using Lumina.Application.Fixtures.Core.Plugins.Commands.ReorderLibraryArtworkProviders; -using Lumina.Domain.Common.Errors; -using Lumina.Domain.Common.Primitives; -using NSubstitute; -using System; -using System.Collections.Generic; -using System.Diagnostics.CodeAnalysis; -using System.Threading; -using System.Threading.Tasks; -using ApplicationErrors = Lumina.Application.Common.Errors.Errors; -#endregion - -namespace Lumina.Application.UnitTests.Core.Plugins.Commands.ReorderLibraryArtworkProviders; - -/// -/// Contains unit tests for the class. -/// -[ExcludeFromCodeCoverage] -public class ReorderLibraryArtworkProvidersCommandHandlerTests -{ - private readonly IUnitOfWork _mockUnitOfWork; - private readonly IArtworkProviderConfigurationRepository _mockConfigurationRepository; - private readonly IAuthorizationService _mockAuthorizationService; - private readonly ICurrentUserService _mockCurrentUserService; - private readonly IValidator _mockValidator; - private readonly ReorderLibraryArtworkProvidersCommandHandler _sut; - private readonly LibraryArtworkProviderConfigurationEntityFixture _libraryArtworkProviderConfigurationEntityFixture = new(); - private readonly ReorderLibraryArtworkProvidersCommandFixture _reorderLibraryArtworkProvidersCommandFixture = new(); - private readonly Guid _userId; - - /// - /// Initializes a new instance of the class. - /// - public ReorderLibraryArtworkProvidersCommandHandlerTests() - { - _mockUnitOfWork = Substitute.For(); - _mockUnitOfWork.SaveChangesAsync(Arg.Any()).Returns(Result.Success); - _mockConfigurationRepository = Substitute.For(); - _mockUnitOfWork.ArtworkProviderConfigurationRepository.Returns(_mockConfigurationRepository); - _mockAuthorizationService = Substitute.For(); - _mockCurrentUserService = Substitute.For(); - _mockValidator = Substitute.For>(); - _userId = Guid.NewGuid(); - - // default stubs: the current user is authenticated and the library ownership policy allows access - _mockCurrentUserService.UserId.Returns(_userId); - _mockAuthorizationService.EvaluatePolicyAsync(_userId, Arg.Any(), Arg.Any()) - .Returns(true); - _mockValidator.Validate(Arg.Any()) - .Returns([]); - _sut = new ReorderLibraryArtworkProvidersCommandHandler(_mockAuthorizationService, _mockCurrentUserService, _mockUnitOfWork, _mockValidator); - } - - [Fact] - public async Task HandleAsync_WhenCalled_ShouldAssignRanksInTheProvidedOrder() - { - // Arrange - Guid libraryId = Guid.NewGuid(); - LibraryArtworkProviderConfigurationEntity firstProvider = _libraryArtworkProviderConfigurationEntityFixture.Create(libraryId, Guid.NewGuid(), 2); - LibraryArtworkProviderConfigurationEntity secondProvider = _libraryArtworkProviderConfigurationEntityFixture.Create(libraryId, Guid.NewGuid(), 1); - _mockConfigurationRepository.GetByLibraryIdAsync(libraryId, Arg.Any()) - .Returns(new List { firstProvider, secondProvider }); - _mockConfigurationRepository.UpsertAsync(Arg.Any(), Arg.Any()) - .Returns(Result.Updated); - - // Act - Result result = await _sut.HandleAsync(_reorderLibraryArtworkProvidersCommandFixture.Create(libraryId: libraryId, pluginIds: [secondProvider.PluginId, firstProvider.PluginId]), CancellationToken.None); - - // Assert - Assert.False(result.IsFailure); - await _mockConfigurationRepository.Received(1).UpsertAsync( - Arg.Is(configuration => configuration.PluginId == secondProvider.PluginId && configuration.Rank == 1), - Arg.Any()); - await _mockConfigurationRepository.Received(1).UpsertAsync( - Arg.Is(configuration => configuration.PluginId == firstProvider.PluginId && configuration.Rank == 2), - Arg.Any()); - await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any()); - } - - [Fact] - public async Task HandleAsync_WhenAProvidedPluginIsNotConfigured_ShouldSkipIt() - { - // Arrange - Guid libraryId = Guid.NewGuid(); - LibraryArtworkProviderConfigurationEntity configuration = _libraryArtworkProviderConfigurationEntityFixture.Create(libraryId, Guid.NewGuid(), 1); - Guid unknownPluginId = Guid.NewGuid(); - _mockConfigurationRepository.GetByLibraryIdAsync(libraryId, Arg.Any()) - .Returns(new List { configuration }); - _mockConfigurationRepository.UpsertAsync(Arg.Any(), Arg.Any()) - .Returns(Result.Updated); - - // Act - Result result = await _sut.HandleAsync(_reorderLibraryArtworkProvidersCommandFixture.Create(libraryId: libraryId, pluginIds: [unknownPluginId, configuration.PluginId]), CancellationToken.None); - - // Assert - Assert.False(result.IsFailure); - await _mockConfigurationRepository.Received(1).UpsertAsync( - Arg.Is(candidate => candidate.PluginId == configuration.PluginId && candidate.Rank == 2), - Arg.Any()); - } - - [Fact] - public async Task HandleAsync_WhenValidationFails_ShouldReturnValidationErrorsWithoutPersisting() - { - // Arrange - Guid libraryId = Guid.NewGuid(); - _mockValidator.Validate(Arg.Any()).Returns([Errors.Plugins.PluginIdsListCannotBeEmpty]); - - // Act - Result result = await _sut.HandleAsync(_reorderLibraryArtworkProvidersCommandFixture.Create(libraryId: libraryId, pluginIds: [Guid.NewGuid()]), CancellationToken.None); - - // Assert - Assert.True(result.IsFailure); - Assert.Equal(Errors.Plugins.PluginIdsListCannotBeEmpty, result.FirstError); - await _mockConfigurationRepository.DidNotReceive().GetByLibraryIdAsync(Arg.Any(), Arg.Any()); - await _mockConfigurationRepository.DidNotReceive().UpsertAsync(Arg.Any(), Arg.Any()); - await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); - } - - [Fact] - public async Task HandleAsync_WhenOwnershipPolicyDeniesAccess_ShouldReturnNotAuthorizedError() - { - // Arrange - Guid libraryId = Guid.NewGuid(); - _mockAuthorizationService.EvaluatePolicyAsync(_userId, Arg.Any(), Arg.Any()) - .Returns(false); - - // Act - Result result = await _sut.HandleAsync(_reorderLibraryArtworkProvidersCommandFixture.Create(libraryId: libraryId, pluginIds: [Guid.NewGuid()]), CancellationToken.None); - - // Assert - Assert.True(result.IsFailure); - Assert.Equal(ApplicationErrors.Authorization.NotAuthorized, result.FirstError); - await _mockAuthorizationService.Received(1).EvaluatePolicyAsync( - _userId, Arg.Is(context => context.LibraryId == libraryId), Arg.Any()); - await _mockConfigurationRepository.DidNotReceive().GetByLibraryIdAsync(Arg.Any(), Arg.Any()); - await _mockConfigurationRepository.DidNotReceive().UpsertAsync(Arg.Any(), Arg.Any()); - await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); - } - - [Fact] - public async Task HandleAsync_WhenUserIsNotAuthenticated_ShouldReturnNotAuthorizedError() - { - // Arrange - _mockCurrentUserService.UserId.Returns((Guid?)null); - - // Act - Result result = await _sut.HandleAsync(_reorderLibraryArtworkProvidersCommandFixture.Create(pluginIds: [Guid.NewGuid()]), CancellationToken.None); - - // Assert - Assert.True(result.IsFailure); - Assert.Equal(ApplicationErrors.Authorization.NotAuthorized, result.FirstError); - await _mockAuthorizationService.DidNotReceive().EvaluatePolicyAsync(Arg.Any(), Arg.Any(), Arg.Any()); - await _mockConfigurationRepository.DidNotReceive().GetByLibraryIdAsync(Arg.Any(), Arg.Any()); - await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); - } - - [Fact] - public async Task HandleAsync_WhenGetConfigurationsFails_ShouldReturnError() - { - // Arrange - Guid libraryId = Guid.NewGuid(); - _mockConfigurationRepository.GetByLibraryIdAsync(libraryId, Arg.Any()) - .Returns(Error.Failure(description: "Failed to get configurations")); - - // Act - Result result = await _sut.HandleAsync(_reorderLibraryArtworkProvidersCommandFixture.Create(libraryId: libraryId, pluginIds: [Guid.NewGuid()]), CancellationToken.None); - - // Assert - Assert.True(result.IsFailure); - await _mockConfigurationRepository.DidNotReceive().UpsertAsync(Arg.Any(), Arg.Any()); - await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); - } -} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/Plugins/Commands/ReorderLibraryArtworkProviders/ReorderLibraryArtworkProvidersCommandValidatorTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/Plugins/Commands/ReorderLibraryArtworkProviders/ReorderLibraryArtworkProvidersCommandValidatorTests.cs deleted file mode 100644 index cdaa5549..00000000 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/Plugins/Commands/ReorderLibraryArtworkProviders/ReorderLibraryArtworkProvidersCommandValidatorTests.cs +++ /dev/null @@ -1,104 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using Lumina.Application.Core.Plugins.Commands.ReorderLibraryArtworkProviders; -using Lumina.Application.Fixtures.Core.Plugins.Commands.ReorderLibraryArtworkProviders; -using Lumina.Application.UnitTests.Common.Setup; -using Lumina.Domain.Common.Errors; -using Lumina.Domain.Common.Primitives; -using System; -using System.Collections.Generic; -using System.Diagnostics.CodeAnalysis; -#endregion - -namespace Lumina.Application.UnitTests.Core.Plugins.Commands.ReorderLibraryArtworkProviders; - -/// -/// Contains unit tests for the class. -/// -[ExcludeFromCodeCoverage] -public class ReorderLibraryArtworkProvidersCommandValidatorTests -{ - private readonly ReorderLibraryArtworkProvidersCommandValidator _validator = new(); - private readonly ReorderLibraryArtworkProvidersCommandFixture _reorderLibraryArtworkProvidersCommandFixture = new(); - - [Fact] - public void Validate_WhenLibraryIdIsEmpty_ShouldHaveValidationError() - { - // Arrange - ReorderLibraryArtworkProvidersCommand command = _reorderLibraryArtworkProvidersCommandFixture.Create(); - command = command with { LibraryId = Guid.Empty }; - - // Act - List result = _validator.TestValidate(command); - - // Assert - result.ShouldHaveValidationError(Errors.Plugins.LibraryIdCannotBeEmpty); - } - - [Fact] - public void Validate_WhenLibraryIdIsValid_ShouldNotHaveValidationError() - { - // Arrange - ReorderLibraryArtworkProvidersCommand command = _reorderLibraryArtworkProvidersCommandFixture.Create(); - - // Act - List result = _validator.TestValidate(command); - - // Assert - result.ShouldNotHaveValidationError(Errors.Plugins.LibraryIdCannotBeEmpty); - } - - [Fact] - public void Validate_WhenPluginIdsIsNull_ShouldHaveValidationError() - { - // Arrange - ReorderLibraryArtworkProvidersCommand command = _reorderLibraryArtworkProvidersCommandFixture.Create(); - command = command with { PluginIds = null! }; - - // Act - List result = _validator.TestValidate(command); - - // Assert - result.ShouldHaveValidationError(Errors.Plugins.PluginIdsListCannotBeNull); - } - - [Fact] - public void Validate_WhenPluginIdsIsEmpty_ShouldHaveValidationError() - { - // Arrange - ReorderLibraryArtworkProvidersCommand command = _reorderLibraryArtworkProvidersCommandFixture.Create(); - command = command with { PluginIds = [] }; - - // Act - List result = _validator.TestValidate(command); - - // Assert - result.ShouldHaveValidationError(Errors.Plugins.PluginIdsListCannotBeEmpty); - } - - [Fact] - public void Validate_WhenPluginIdsAreValid_ShouldNotHaveValidationError() - { - // Arrange - ReorderLibraryArtworkProvidersCommand command = _reorderLibraryArtworkProvidersCommandFixture.Create(); - - // Act - List result = _validator.TestValidate(command); - - // Assert - result.ShouldNotHaveValidationError(Errors.Plugins.PluginIdsListCannotBeNull); - result.ShouldNotHaveValidationError(Errors.Plugins.PluginIdsListCannotBeEmpty); - } - - [Fact] - public void Validate_WhenCommandIsValid_ShouldNotHaveValidationError() - { - // Arrange - ReorderLibraryArtworkProvidersCommand command = _reorderLibraryArtworkProvidersCommandFixture.Create(); - - // Act - List result = _validator.TestValidate(command); - - // Assert - result.ShouldNotHaveAnyValidationErrors(); - } -} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/Plugins/Commands/ReorderLibraryMetadataProviders/ReorderLibraryMetadataProvidersCommandHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/Plugins/Commands/ReorderLibraryMetadataProviders/ReorderLibraryMetadataProvidersCommandHandlerTests.cs deleted file mode 100644 index a69c80e9..00000000 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/Plugins/Commands/ReorderLibraryMetadataProviders/ReorderLibraryMetadataProvidersCommandHandlerTests.cs +++ /dev/null @@ -1,144 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using Lumina.Application.Common.DataAccess.Entities.Plugins; -using Lumina.Application.Common.DataAccess.Repositories.Plugins; -using Lumina.Application.Common.DataAccess.UoW; -using Lumina.Application.Common.Infrastructure.Authentication; -using Lumina.Application.Common.Infrastructure.Authorization; -using Lumina.Application.Common.Infrastructure.Authorization.Policies.LibraryOwnership; -using Lumina.Application.Common.Infrastructure.Validation; -using Lumina.Application.Core.Plugins.Commands.ReorderLibraryMetadataProviders; -using Lumina.Application.Fixtures.Common.DataAccess.Entities.Plugins; -using Lumina.Application.Fixtures.Core.Plugins.Commands.ReorderLibraryMetadataProviders; -using Lumina.Domain.Common.Errors; -using Lumina.Domain.Common.Primitives; -using NSubstitute; -using System; -using System.Collections.Generic; -using System.Diagnostics.CodeAnalysis; -using System.Threading; -using System.Threading.Tasks; -using ApplicationErrors = Lumina.Application.Common.Errors.Errors; -#endregion - -namespace Lumina.Application.UnitTests.Core.Plugins.Commands.ReorderLibraryMetadataProviders; - -/// -/// Contains unit tests for the class. -/// -[ExcludeFromCodeCoverage] -public class ReorderLibraryMetadataProvidersCommandHandlerTests -{ - private readonly IUnitOfWork _mockUnitOfWork; - private readonly ILibraryMetadataProviderConfigurationRepository _mockConfigurationRepository; - private readonly IAuthorizationService _mockAuthorizationService; - private readonly ICurrentUserService _mockCurrentUserService; - private readonly IValidator _mockValidator; - private readonly ReorderLibraryMetadataProvidersCommandHandler _sut; - private readonly LibraryMetadataProviderConfigurationEntityFixture _libraryMetadataProviderConfigurationEntityFixture = new(); - private readonly ReorderLibraryMetadataProvidersCommandFixture _reorderLibraryMetadataProvidersCommandFixture = new(); - private readonly Guid _userId; - - /// - /// Initializes a new instance of the class. - /// - public ReorderLibraryMetadataProvidersCommandHandlerTests() - { - _mockUnitOfWork = Substitute.For(); - _mockUnitOfWork.SaveChangesAsync(Arg.Any()).Returns(Result.Success); - _mockConfigurationRepository = Substitute.For(); - _mockUnitOfWork.LibraryMetadataProviderConfigurationRepository.Returns(_mockConfigurationRepository); - _mockAuthorizationService = Substitute.For(); - _mockCurrentUserService = Substitute.For(); - _mockValidator = Substitute.For>(); - _userId = Guid.NewGuid(); - - // default stubs: the current user is authenticated and the library ownership policy allows access - _mockCurrentUserService.UserId.Returns(_userId); - _mockAuthorizationService.EvaluatePolicyAsync(_userId, Arg.Any(), Arg.Any()) - .Returns(true); - _mockValidator.Validate(Arg.Any()) - .Returns([]); - _sut = new ReorderLibraryMetadataProvidersCommandHandler(_mockAuthorizationService, _mockCurrentUserService, _mockUnitOfWork, _mockValidator); - } - - [Fact] - public async Task HandleAsync_WhenCalled_ShouldAssignRanksInTheProvidedOrder() - { - // Arrange - Guid libraryId = Guid.NewGuid(); - LibraryMetadataProviderConfigurationEntity firstProvider = _libraryMetadataProviderConfigurationEntityFixture.Create(libraryId, Guid.NewGuid(), 2); - LibraryMetadataProviderConfigurationEntity secondProvider = _libraryMetadataProviderConfigurationEntityFixture.Create(libraryId, Guid.NewGuid(), 1); - _mockConfigurationRepository.GetByLibraryIdAsync(libraryId, Arg.Any()) - .Returns(new List { firstProvider, secondProvider }); - _mockConfigurationRepository.UpsertAsync(Arg.Any(), Arg.Any()) - .Returns(Result.Updated); - - // Act - Result result = await _sut.HandleAsync(_reorderLibraryMetadataProvidersCommandFixture.Create(libraryId: libraryId, pluginIds: [secondProvider.PluginId, firstProvider.PluginId]), CancellationToken.None); - - // Assert - Assert.False(result.IsFailure); - await _mockConfigurationRepository.Received(1).UpsertAsync( - Arg.Is(configuration => configuration.PluginId == secondProvider.PluginId && configuration.Rank == 1), - Arg.Any()); - await _mockConfigurationRepository.Received(1).UpsertAsync( - Arg.Is(configuration => configuration.PluginId == firstProvider.PluginId && configuration.Rank == 2), - Arg.Any()); - } - - [Fact] - public async Task HandleAsync_WhenValidationFails_ShouldReturnValidationErrorsWithoutPersisting() - { - // Arrange - Guid libraryId = Guid.NewGuid(); - _mockValidator.Validate(Arg.Any()).Returns([Errors.Plugins.PluginIdsListCannotBeEmpty]); - - // Act - Result result = await _sut.HandleAsync(_reorderLibraryMetadataProvidersCommandFixture.Create(libraryId: libraryId, pluginIds: [Guid.NewGuid()]), CancellationToken.None); - - // Assert - Assert.True(result.IsFailure); - Assert.Equal(Errors.Plugins.PluginIdsListCannotBeEmpty, result.FirstError); - await _mockConfigurationRepository.DidNotReceive().GetByLibraryIdAsync(Arg.Any(), Arg.Any()); - await _mockConfigurationRepository.DidNotReceive().UpsertAsync(Arg.Any(), Arg.Any()); - await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); - } - - [Fact] - public async Task HandleAsync_WhenOwnershipPolicyDeniesAccess_ShouldReturnNotAuthorizedError() - { - // Arrange - Guid libraryId = Guid.NewGuid(); - _mockAuthorizationService.EvaluatePolicyAsync(_userId, Arg.Any(), Arg.Any()) - .Returns(false); - - // Act - Result result = await _sut.HandleAsync(_reorderLibraryMetadataProvidersCommandFixture.Create(libraryId: libraryId, pluginIds: [Guid.NewGuid()]), CancellationToken.None); - - // Assert - Assert.True(result.IsFailure); - Assert.Equal(ApplicationErrors.Authorization.NotAuthorized, result.FirstError); - await _mockAuthorizationService.Received(1).EvaluatePolicyAsync( - _userId, Arg.Is(context => context.LibraryId == libraryId), Arg.Any()); - await _mockConfigurationRepository.DidNotReceive().GetByLibraryIdAsync(Arg.Any(), Arg.Any()); - await _mockConfigurationRepository.DidNotReceive().UpsertAsync(Arg.Any(), Arg.Any()); - await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); - } - - [Fact] - public async Task HandleAsync_WhenUserIsNotAuthenticated_ShouldReturnNotAuthorizedError() - { - // Arrange - _mockCurrentUserService.UserId.Returns((Guid?)null); - - // Act - Result result = await _sut.HandleAsync(_reorderLibraryMetadataProvidersCommandFixture.Create(pluginIds: [Guid.NewGuid()]), CancellationToken.None); - - // Assert - Assert.True(result.IsFailure); - Assert.Equal(ApplicationErrors.Authorization.NotAuthorized, result.FirstError); - await _mockAuthorizationService.DidNotReceive().EvaluatePolicyAsync(Arg.Any(), Arg.Any(), Arg.Any()); - await _mockConfigurationRepository.DidNotReceive().GetByLibraryIdAsync(Arg.Any(), Arg.Any()); - await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); - } -} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/Plugins/Commands/ReorderLibraryMetadataProviders/ReorderLibraryMetadataProvidersCommandValidatorTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/Plugins/Commands/ReorderLibraryMetadataProviders/ReorderLibraryMetadataProvidersCommandValidatorTests.cs deleted file mode 100644 index 8f40ca9a..00000000 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/Plugins/Commands/ReorderLibraryMetadataProviders/ReorderLibraryMetadataProvidersCommandValidatorTests.cs +++ /dev/null @@ -1,104 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using Lumina.Application.Core.Plugins.Commands.ReorderLibraryMetadataProviders; -using Lumina.Application.Fixtures.Core.Plugins.Commands.ReorderLibraryMetadataProviders; -using Lumina.Application.UnitTests.Common.Setup; -using Lumina.Domain.Common.Errors; -using Lumina.Domain.Common.Primitives; -using System; -using System.Collections.Generic; -using System.Diagnostics.CodeAnalysis; -#endregion - -namespace Lumina.Application.UnitTests.Core.Plugins.Commands.ReorderLibraryMetadataProviders; - -/// -/// Contains unit tests for the class. -/// -[ExcludeFromCodeCoverage] -public class ReorderLibraryMetadataProvidersCommandValidatorTests -{ - private readonly ReorderLibraryMetadataProvidersCommandValidator _validator = new(); - private readonly ReorderLibraryMetadataProvidersCommandFixture _reorderLibraryMetadataProvidersCommandFixture = new(); - - [Fact] - public void Validate_WhenLibraryIdIsEmpty_ShouldHaveValidationError() - { - // Arrange - ReorderLibraryMetadataProvidersCommand command = _reorderLibraryMetadataProvidersCommandFixture.Create(); - command = command with { LibraryId = Guid.Empty }; - - // Act - List result = _validator.TestValidate(command); - - // Assert - result.ShouldHaveValidationError(Errors.Plugins.LibraryIdCannotBeEmpty); - } - - [Fact] - public void Validate_WhenLibraryIdIsValid_ShouldNotHaveValidationError() - { - // Arrange - ReorderLibraryMetadataProvidersCommand command = _reorderLibraryMetadataProvidersCommandFixture.Create(); - - // Act - List result = _validator.TestValidate(command); - - // Assert - result.ShouldNotHaveValidationError(Errors.Plugins.LibraryIdCannotBeEmpty); - } - - [Fact] - public void Validate_WhenPluginIdsIsNull_ShouldHaveValidationError() - { - // Arrange - ReorderLibraryMetadataProvidersCommand command = _reorderLibraryMetadataProvidersCommandFixture.Create(); - command = command with { PluginIds = null! }; - - // Act - List result = _validator.TestValidate(command); - - // Assert - result.ShouldHaveValidationError(Errors.Plugins.PluginIdsListCannotBeNull); - } - - [Fact] - public void Validate_WhenPluginIdsIsEmpty_ShouldHaveValidationError() - { - // Arrange - ReorderLibraryMetadataProvidersCommand command = _reorderLibraryMetadataProvidersCommandFixture.Create(); - command = command with { PluginIds = [] }; - - // Act - List result = _validator.TestValidate(command); - - // Assert - result.ShouldHaveValidationError(Errors.Plugins.PluginIdsListCannotBeEmpty); - } - - [Fact] - public void Validate_WhenPluginIdsAreValid_ShouldNotHaveValidationError() - { - // Arrange - ReorderLibraryMetadataProvidersCommand command = _reorderLibraryMetadataProvidersCommandFixture.Create(); - - // Act - List result = _validator.TestValidate(command); - - // Assert - result.ShouldNotHaveValidationError(Errors.Plugins.PluginIdsListCannotBeNull); - result.ShouldNotHaveValidationError(Errors.Plugins.PluginIdsListCannotBeEmpty); - } - - [Fact] - public void Validate_WhenCommandIsValid_ShouldNotHaveValidationError() - { - // Arrange - ReorderLibraryMetadataProvidersCommand command = _reorderLibraryMetadataProvidersCommandFixture.Create(); - - // Act - List result = _validator.TestValidate(command); - - // Assert - result.ShouldNotHaveAnyValidationErrors(); - } -} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/Plugins/Commands/SetLibraryArtworkProviderEnabled/SetLibraryArtworkProviderEnabledCommandHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/Plugins/Commands/SetLibraryArtworkProviderEnabled/SetLibraryArtworkProviderEnabledCommandHandlerTests.cs deleted file mode 100644 index 246bf924..00000000 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/Plugins/Commands/SetLibraryArtworkProviderEnabled/SetLibraryArtworkProviderEnabledCommandHandlerTests.cs +++ /dev/null @@ -1,243 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using Lumina.Application.Common.DataAccess.Entities.Plugins; -using Lumina.Application.Common.DataAccess.Repositories.Plugins; -using Lumina.Application.Common.DataAccess.UoW; -using Lumina.Application.Common.Infrastructure.Authentication; -using Lumina.Application.Common.Infrastructure.Authorization; -using Lumina.Application.Common.Infrastructure.Authorization.Policies.LibraryOwnership; -using Lumina.Application.Common.Infrastructure.Validation; -using Lumina.Application.Core.Plugins.Commands.SetLibraryArtworkProviderEnabled; -using Lumina.Application.Fixtures.Common.DataAccess.Entities.Plugins; -using Lumina.Application.Fixtures.Core.Plugins.Commands.SetLibraryArtworkProviderEnabled; -using Lumina.Domain.Common.Errors; -using Lumina.Domain.Common.Primitives; -using NSubstitute; -using System; -using System.Collections.Generic; -using System.Diagnostics.CodeAnalysis; -using System.Threading; -using System.Threading.Tasks; -using ApplicationErrors = Lumina.Application.Common.Errors.Errors; -#endregion - -namespace Lumina.Application.UnitTests.Core.Plugins.Commands.SetLibraryArtworkProviderEnabled; - -/// -/// Contains unit tests for the class. -/// -[ExcludeFromCodeCoverage] -public class SetLibraryArtworkProviderEnabledCommandHandlerTests -{ - private readonly IUnitOfWork _mockUnitOfWork; - private readonly IArtworkProviderConfigurationRepository _mockConfigurationRepository; - private readonly IAuthorizationService _mockAuthorizationService; - private readonly ICurrentUserService _mockCurrentUserService; - private readonly IValidator _mockValidator; - private readonly SetLibraryArtworkProviderEnabledCommandHandler _sut; - private readonly SetLibraryArtworkProviderEnabledCommandFixture _setLibraryArtworkProviderEnabledCommandFixture = new(); - private readonly Guid _userId; - - /// - /// Fixture for generating test data. - /// - private readonly LibraryArtworkProviderConfigurationEntityFixture _libraryArtworkProviderConfigurationEntityFixture = new(); - - /// - /// Initializes a new instance of the class. - /// - public SetLibraryArtworkProviderEnabledCommandHandlerTests() - { - _mockUnitOfWork = Substitute.For(); - _mockUnitOfWork.SaveChangesAsync(Arg.Any()).Returns(Result.Success); - _mockConfigurationRepository = Substitute.For(); - _mockUnitOfWork.ArtworkProviderConfigurationRepository.Returns(_mockConfigurationRepository); - _mockAuthorizationService = Substitute.For(); - _mockCurrentUserService = Substitute.For(); - _mockValidator = Substitute.For>(); - _userId = Guid.NewGuid(); - - // default stubs: the current user is authenticated and the library ownership policy allows access - _mockCurrentUserService.UserId.Returns(_userId); - _mockAuthorizationService.EvaluatePolicyAsync(_userId, Arg.Any(), Arg.Any()) - .Returns(true); - _mockValidator.Validate(Arg.Any()) - .Returns([]); - _sut = new SetLibraryArtworkProviderEnabledCommandHandler(_mockAuthorizationService, _mockCurrentUserService, _mockUnitOfWork, _mockValidator); - } - - [Fact] - public async Task HandleAsync_WhenConfigurationDoesNotExist_ShouldCreateEnabledConfigurationWithNextRank() - { - // Arrange - Guid libraryId = Guid.NewGuid(); - Guid pluginId = Guid.NewGuid(); - _mockConfigurationRepository.GetByLibraryAndPluginIdAsync(libraryId, pluginId, Arg.Any()) - .Returns((LibraryArtworkProviderConfigurationEntity?)null); - _mockConfigurationRepository.GetByLibraryIdAsync(libraryId, Arg.Any()) - .Returns(new List()); - _mockConfigurationRepository.UpsertAsync(Arg.Any(), Arg.Any()) - .Returns(Result.Updated); - - // Act - Result result = await _sut.HandleAsync(_setLibraryArtworkProviderEnabledCommandFixture.Create(libraryId: libraryId, pluginId: pluginId, isEnabled: true), CancellationToken.None); - - // Assert - Assert.False(result.IsFailure); - await _mockConfigurationRepository.Received(1).UpsertAsync( - Arg.Is(configuration => configuration.IsEnabled && configuration.Rank == 1), - Arg.Any()); - await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any()); - } - - [Fact] - public async Task HandleAsync_WhenConfigurationDoesNotExistAndOthersExist_ShouldAppendAfterTheHighestRank() - { - // Arrange - Guid libraryId = Guid.NewGuid(); - Guid pluginId = Guid.NewGuid(); - _mockConfigurationRepository.GetByLibraryAndPluginIdAsync(libraryId, pluginId, Arg.Any()) - .Returns((LibraryArtworkProviderConfigurationEntity?)null); - _mockConfigurationRepository.GetByLibraryIdAsync(libraryId, Arg.Any()) - .Returns(new List - { - _libraryArtworkProviderConfigurationEntityFixture.Create( - libraryId: libraryId, - pluginId: Guid.NewGuid(), - rank: 3, - isEnabled: true) - }); - _mockConfigurationRepository.UpsertAsync(Arg.Any(), Arg.Any()) - .Returns(Result.Updated); - - // Act - Result result = await _sut.HandleAsync(_setLibraryArtworkProviderEnabledCommandFixture.Create(libraryId: libraryId, pluginId: pluginId, isEnabled: false), CancellationToken.None); - - // Assert - Assert.False(result.IsFailure); - await _mockConfigurationRepository.Received(1).UpsertAsync( - Arg.Is(configuration => !configuration.IsEnabled && configuration.Rank == 4), - Arg.Any()); - } - - [Fact] - public async Task HandleAsync_WhenConfigurationExists_ShouldUpdateItsEnabledState() - { - // Arrange - LibraryArtworkProviderConfigurationEntity existingConfiguration = _libraryArtworkProviderConfigurationEntityFixture.Create( - libraryId: Guid.NewGuid(), - pluginId: Guid.NewGuid(), - rank: 2, - isEnabled: false); - _mockConfigurationRepository.GetByLibraryAndPluginIdAsync(existingConfiguration.LibraryId, existingConfiguration.PluginId, Arg.Any()) - .Returns(existingConfiguration); - _mockConfigurationRepository.UpsertAsync(Arg.Any(), Arg.Any()) - .Returns(Result.Updated); - - // Act - Result result = await _sut.HandleAsync(_setLibraryArtworkProviderEnabledCommandFixture.Create(libraryId: existingConfiguration.LibraryId, pluginId: existingConfiguration.PluginId, isEnabled: true), CancellationToken.None); - - // Assert - Assert.False(result.IsFailure); - await _mockConfigurationRepository.Received(1).UpsertAsync( - Arg.Is(configuration => configuration.IsEnabled && configuration.Rank == 2), - Arg.Any()); - await _mockConfigurationRepository.DidNotReceive().GetByLibraryIdAsync(Arg.Any(), Arg.Any()); - } - - [Fact] - public async Task HandleAsync_WhenValidationFails_ShouldReturnValidationErrorsWithoutPersisting() - { - // Arrange - Guid libraryId = Guid.NewGuid(); - Guid pluginId = Guid.NewGuid(); - _mockValidator.Validate(Arg.Any()).Returns([Errors.Plugins.PluginIdCannotBeEmpty]); - - // Act - Result result = await _sut.HandleAsync(_setLibraryArtworkProviderEnabledCommandFixture.Create(libraryId: libraryId, pluginId: pluginId, isEnabled: true), CancellationToken.None); - - // Assert - Assert.True(result.IsFailure); - Assert.Equal(Errors.Plugins.PluginIdCannotBeEmpty, result.FirstError); - await _mockConfigurationRepository.DidNotReceive().GetByLibraryAndPluginIdAsync(Arg.Any(), Arg.Any(), Arg.Any()); - await _mockConfigurationRepository.DidNotReceive().UpsertAsync(Arg.Any(), Arg.Any()); - await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); - } - - [Fact] - public async Task HandleAsync_WhenOwnershipPolicyDeniesAccess_ShouldReturnNotAuthorizedError() - { - // Arrange - Guid libraryId = Guid.NewGuid(); - Guid pluginId = Guid.NewGuid(); - _mockAuthorizationService.EvaluatePolicyAsync(_userId, Arg.Any(), Arg.Any()) - .Returns(false); - - // Act - Result result = await _sut.HandleAsync(_setLibraryArtworkProviderEnabledCommandFixture.Create(libraryId: libraryId, pluginId: pluginId, isEnabled: true), CancellationToken.None); - - // Assert - Assert.True(result.IsFailure); - Assert.Equal(ApplicationErrors.Authorization.NotAuthorized, result.FirstError); - await _mockAuthorizationService.Received(1).EvaluatePolicyAsync( - _userId, Arg.Is(context => context.LibraryId == libraryId), Arg.Any()); - await _mockConfigurationRepository.DidNotReceive().GetByLibraryAndPluginIdAsync(Arg.Any(), Arg.Any(), Arg.Any()); - await _mockConfigurationRepository.DidNotReceive().UpsertAsync(Arg.Any(), Arg.Any()); - await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); - } - - [Fact] - public async Task HandleAsync_WhenUserIsNotAuthenticated_ShouldReturnNotAuthorizedError() - { - // Arrange - _mockCurrentUserService.UserId.Returns((Guid?)null); - - // Act - Result result = await _sut.HandleAsync(_setLibraryArtworkProviderEnabledCommandFixture.Create(), CancellationToken.None); - - // Assert - Assert.True(result.IsFailure); - Assert.Equal(ApplicationErrors.Authorization.NotAuthorized, result.FirstError); - await _mockAuthorizationService.DidNotReceive().EvaluatePolicyAsync(Arg.Any(), Arg.Any(), Arg.Any()); - await _mockConfigurationRepository.DidNotReceive().GetByLibraryAndPluginIdAsync(Arg.Any(), Arg.Any(), Arg.Any()); - await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); - } - - [Fact] - public async Task HandleAsync_WhenGetByLibraryAndPluginIdFails_ShouldReturnError() - { - // Arrange - Guid libraryId = Guid.NewGuid(); - Guid pluginId = Guid.NewGuid(); - _mockConfigurationRepository.GetByLibraryAndPluginIdAsync(libraryId, pluginId, Arg.Any()) - .Returns(Error.Failure(description: "Failed to get configuration")); - - // Act - Result result = await _sut.HandleAsync(_setLibraryArtworkProviderEnabledCommandFixture.Create(libraryId: libraryId, pluginId: pluginId, isEnabled: true), CancellationToken.None); - - // Assert - Assert.True(result.IsFailure); - await _mockConfigurationRepository.DidNotReceive().UpsertAsync(Arg.Any(), Arg.Any()); - await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); - } - - [Fact] - public async Task HandleAsync_WhenUpsertFails_ShouldReturnError() - { - // Arrange - Guid libraryId = Guid.NewGuid(); - Guid pluginId = Guid.NewGuid(); - _mockConfigurationRepository.GetByLibraryAndPluginIdAsync(libraryId, pluginId, Arg.Any()) - .Returns((LibraryArtworkProviderConfigurationEntity?)null); - _mockConfigurationRepository.GetByLibraryIdAsync(libraryId, Arg.Any()) - .Returns(new List()); - _mockConfigurationRepository.UpsertAsync(Arg.Any(), Arg.Any()) - .Returns(Error.Failure(description: "Failed to upsert configuration")); - - // Act - Result result = await _sut.HandleAsync(_setLibraryArtworkProviderEnabledCommandFixture.Create(libraryId: libraryId, pluginId: pluginId, isEnabled: true), CancellationToken.None); - - // Assert - Assert.True(result.IsFailure); - await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); - } -} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/Plugins/Commands/SetLibraryArtworkProviderEnabled/SetLibraryArtworkProviderEnabledCommandValidatorTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/Plugins/Commands/SetLibraryArtworkProviderEnabled/SetLibraryArtworkProviderEnabledCommandValidatorTests.cs deleted file mode 100644 index df6d5a97..00000000 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/Plugins/Commands/SetLibraryArtworkProviderEnabled/SetLibraryArtworkProviderEnabledCommandValidatorTests.cs +++ /dev/null @@ -1,89 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using Lumina.Application.Core.Plugins.Commands.SetLibraryArtworkProviderEnabled; -using Lumina.Application.Fixtures.Core.Plugins.Commands.SetLibraryArtworkProviderEnabled; -using Lumina.Application.UnitTests.Common.Setup; -using Lumina.Domain.Common.Errors; -using Lumina.Domain.Common.Primitives; -using System; -using System.Collections.Generic; -using System.Diagnostics.CodeAnalysis; -#endregion - -namespace Lumina.Application.UnitTests.Core.Plugins.Commands.SetLibraryArtworkProviderEnabled; - -/// -/// Contains unit tests for the class. -/// -[ExcludeFromCodeCoverage] -public class SetLibraryArtworkProviderEnabledCommandValidatorTests -{ - private readonly SetLibraryArtworkProviderEnabledCommandValidator _validator = new(); - private readonly SetLibraryArtworkProviderEnabledCommandFixture _setLibraryArtworkProviderEnabledCommandFixture = new(); - - [Fact] - public void Validate_WhenLibraryIdIsEmpty_ShouldHaveValidationError() - { - // Arrange - SetLibraryArtworkProviderEnabledCommand command = _setLibraryArtworkProviderEnabledCommandFixture.Create(); - command = command with { LibraryId = Guid.Empty }; - - // Act - List result = _validator.TestValidate(command); - - // Assert - result.ShouldHaveValidationError(Errors.Plugins.LibraryIdCannotBeEmpty); - } - - [Fact] - public void Validate_WhenLibraryIdIsValid_ShouldNotHaveValidationError() - { - // Arrange - SetLibraryArtworkProviderEnabledCommand command = _setLibraryArtworkProviderEnabledCommandFixture.Create(); - - // Act - List result = _validator.TestValidate(command); - - // Assert - result.ShouldNotHaveValidationError(Errors.Plugins.LibraryIdCannotBeEmpty); - } - - [Fact] - public void Validate_WhenPluginIdIsEmpty_ShouldHaveValidationError() - { - // Arrange - SetLibraryArtworkProviderEnabledCommand command = _setLibraryArtworkProviderEnabledCommandFixture.Create(); - command = command with { PluginId = Guid.Empty }; - - // Act - List result = _validator.TestValidate(command); - - // Assert - result.ShouldHaveValidationError(Errors.Plugins.PluginIdCannotBeEmpty); - } - - [Fact] - public void Validate_WhenPluginIdIsValid_ShouldNotHaveValidationError() - { - // Arrange - SetLibraryArtworkProviderEnabledCommand command = _setLibraryArtworkProviderEnabledCommandFixture.Create(); - - // Act - List result = _validator.TestValidate(command); - - // Assert - result.ShouldNotHaveValidationError(Errors.Plugins.PluginIdCannotBeEmpty); - } - - [Fact] - public void Validate_WhenCommandIsValid_ShouldNotHaveValidationError() - { - // Arrange - SetLibraryArtworkProviderEnabledCommand command = _setLibraryArtworkProviderEnabledCommandFixture.Create(); - - // Act - List result = _validator.TestValidate(command); - - // Assert - result.ShouldNotHaveAnyValidationErrors(); - } -} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/Plugins/Commands/SetLibraryBookReaderEnabled/SetLibraryBookReaderEnabledCommandHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/Plugins/Commands/SetLibraryBookReaderEnabled/SetLibraryBookReaderEnabledCommandHandlerTests.cs deleted file mode 100644 index 45b02578..00000000 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/Plugins/Commands/SetLibraryBookReaderEnabled/SetLibraryBookReaderEnabledCommandHandlerTests.cs +++ /dev/null @@ -1,210 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using Lumina.Application.Common.DataAccess.Entities.Plugins; -using Lumina.Application.Common.DataAccess.Repositories.Plugins; -using Lumina.Application.Common.DataAccess.UoW; -using Lumina.Application.Common.Infrastructure.Authentication; -using Lumina.Application.Common.Infrastructure.Authorization; -using Lumina.Application.Common.Infrastructure.Authorization.Policies.LibraryOwnership; -using Lumina.Application.Common.Infrastructure.Reading; -using Lumina.Application.Common.Infrastructure.Validation; -using Lumina.Application.Core.Plugins.Commands.SetLibraryBookReaderEnabled; -using Lumina.Application.Fixtures.Common.DataAccess.Entities.Plugins; -using Lumina.Application.Fixtures.Core.Plugins.Commands.SetLibraryBookReaderEnabled; -using Lumina.Domain.Common.Errors; -using Lumina.Domain.Common.Primitives; -using NSubstitute; -using System; -using System.Diagnostics.CodeAnalysis; -using System.Threading; -using System.Threading.Tasks; -using ApplicationErrors = Lumina.Application.Common.Errors.Errors; -#endregion - -namespace Lumina.Application.UnitTests.Core.Plugins.Commands.SetLibraryBookReaderEnabled; - -/// -/// Contains unit tests for the class. -/// -[ExcludeFromCodeCoverage] -public class SetLibraryBookReaderEnabledCommandHandlerTests -{ - private readonly IUnitOfWork _mockUnitOfWork; - private readonly ILibraryBookReaderConfigurationRepository _mockLibraryBookReaderConfigurationRepository; - private readonly IAuthorizationService _mockAuthorizationService; - private readonly ICurrentUserService _mockCurrentUserService; - private readonly IBookReaderEnablementCache _mockEnablementCache; - private readonly IValidator _mockValidator; - private readonly SetLibraryBookReaderEnabledCommandHandler _sut; - private readonly SetLibraryBookReaderEnabledCommandFixture _setLibraryBookReaderEnabledCommandFixture = new(); - private readonly LibraryBookReaderConfigurationEntityFixture _libraryBookReaderConfigurationEntityFixture = new(); - private readonly Guid _userId; - - /// - /// Initializes a new instance of the class. - /// - public SetLibraryBookReaderEnabledCommandHandlerTests() - { - _mockUnitOfWork = Substitute.For(); - _mockUnitOfWork.SaveChangesAsync(Arg.Any()).Returns(Result.Success); - _mockLibraryBookReaderConfigurationRepository = Substitute.For(); - _mockUnitOfWork.LibraryBookReaderConfigurationRepository.Returns(_mockLibraryBookReaderConfigurationRepository); - _mockAuthorizationService = Substitute.For(); - _mockCurrentUserService = Substitute.For(); - _mockEnablementCache = Substitute.For(); - _mockValidator = Substitute.For>(); - _userId = Guid.NewGuid(); - - // Default stubs: the current user is authenticated and the library ownership policy allows access. - _mockCurrentUserService.UserId.Returns(_userId); - _mockAuthorizationService.EvaluatePolicyAsync(_userId, Arg.Any(), Arg.Any()) - .Returns(true); - _mockValidator.Validate(Arg.Any()).Returns([]); - _mockLibraryBookReaderConfigurationRepository.UpsertAsync(Arg.Any(), Arg.Any()) - .Returns(Result.Updated); - - _sut = new SetLibraryBookReaderEnabledCommandHandler(_mockAuthorizationService, _mockCurrentUserService, _mockEnablementCache, _mockUnitOfWork, _mockValidator); - } - - [Fact] - public async Task HandleAsync_WhenConfigurationDoesNotExist_ShouldInsertNewConfigurationAndPersist() - { - // Arrange - SetLibraryBookReaderEnabledCommand command = _setLibraryBookReaderEnabledCommandFixture.Create(isEnabled: false); - _mockLibraryBookReaderConfigurationRepository.GetByLibraryAndPluginIdAsync(command.LibraryId, command.PluginId, Arg.Any()) - .Returns(Result.From(null)); - - // Act - Result result = await _sut.HandleAsync(command, CancellationToken.None); - - // Assert - Assert.False(result.IsFailure); - await _mockLibraryBookReaderConfigurationRepository.Received(1).UpsertAsync( - Arg.Is(configuration => - configuration.LibraryId == command.LibraryId && - configuration.PluginId == command.PluginId && - configuration.IsEnabled == command.IsEnabled), - Arg.Any()); - await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any()); - _mockEnablementCache.Received(1).Invalidate(command.LibraryId, command.PluginId); - } - - [Fact] - public async Task HandleAsync_WhenConfigurationExists_ShouldUpdateItsEnabledStateAndPersist() - { - // Arrange - SetLibraryBookReaderEnabledCommand command = _setLibraryBookReaderEnabledCommandFixture.Create(isEnabled: true); - LibraryBookReaderConfigurationEntity existingConfiguration = _libraryBookReaderConfigurationEntityFixture.Create( - libraryId: command.LibraryId, - pluginId: command.PluginId, - isEnabled: false); - _mockLibraryBookReaderConfigurationRepository.GetByLibraryAndPluginIdAsync(command.LibraryId, command.PluginId, Arg.Any()) - .Returns(Result.From(existingConfiguration)); - - // Act - Result result = await _sut.HandleAsync(command, CancellationToken.None); - - // Assert - Assert.False(result.IsFailure); - Assert.True(existingConfiguration.IsEnabled); - await _mockLibraryBookReaderConfigurationRepository.Received(1).UpsertAsync(existingConfiguration, Arg.Any()); - await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any()); - _mockEnablementCache.Received(1).Invalidate(command.LibraryId, command.PluginId); - } - - [Fact] - public async Task HandleAsync_WhenValidatorReturnsError_ShouldReturnValidationErrorAndNotPersist() - { - // Arrange - SetLibraryBookReaderEnabledCommand command = _setLibraryBookReaderEnabledCommandFixture.Create(); - _mockValidator.Validate(Arg.Any()).Returns([Errors.Plugins.PluginIdCannotBeEmpty]); - - // Act - Result result = await _sut.HandleAsync(command, CancellationToken.None); - - // Assert - Assert.True(result.IsFailure); - Assert.Equal(Errors.Plugins.PluginIdCannotBeEmpty, result.FirstError); - await _mockLibraryBookReaderConfigurationRepository.DidNotReceive().GetByLibraryAndPluginIdAsync(Arg.Any(), Arg.Any(), Arg.Any()); - await _mockLibraryBookReaderConfigurationRepository.DidNotReceive().UpsertAsync(Arg.Any(), Arg.Any()); - await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); - _mockEnablementCache.DidNotReceive().Invalidate(Arg.Any(), Arg.Any()); - } - - [Fact] - public async Task HandleAsync_WhenOwnershipPolicyDeniesAccess_ShouldReturnNotAuthorizedErrorAndNotPersist() - { - // Arrange - SetLibraryBookReaderEnabledCommand command = _setLibraryBookReaderEnabledCommandFixture.Create(); - _mockAuthorizationService.EvaluatePolicyAsync(_userId, Arg.Any(), Arg.Any()) - .Returns(false); - - // Act - Result result = await _sut.HandleAsync(command, CancellationToken.None); - - // Assert - Assert.True(result.IsFailure); - Assert.Equal(ApplicationErrors.Authorization.NotAuthorized, result.FirstError); - await _mockLibraryBookReaderConfigurationRepository.DidNotReceive().GetByLibraryAndPluginIdAsync(Arg.Any(), Arg.Any(), Arg.Any()); - await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); - _mockEnablementCache.DidNotReceive().Invalidate(Arg.Any(), Arg.Any()); - } - - [Fact] - public async Task HandleAsync_WhenUserIsNotAuthenticated_ShouldReturnNotAuthorizedErrorAndNotPersist() - { - // Arrange - SetLibraryBookReaderEnabledCommand command = _setLibraryBookReaderEnabledCommandFixture.Create(); - _mockCurrentUserService.UserId.Returns((Guid?)null); - - // Act - Result result = await _sut.HandleAsync(command, CancellationToken.None); - - // Assert - Assert.True(result.IsFailure); - Assert.Equal(ApplicationErrors.Authorization.NotAuthorized, result.FirstError); - await _mockLibraryBookReaderConfigurationRepository.DidNotReceive().GetByLibraryAndPluginIdAsync(Arg.Any(), Arg.Any(), Arg.Any()); - await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); - _mockEnablementCache.DidNotReceive().Invalidate(Arg.Any(), Arg.Any()); - } - - [Fact] - public async Task HandleAsync_WhenGetConfigurationFails_ShouldReturnErrorAndNotPersist() - { - // Arrange - SetLibraryBookReaderEnabledCommand command = _setLibraryBookReaderEnabledCommandFixture.Create(); - Error error = Error.Failure(description: "Failed to get configuration"); - _mockLibraryBookReaderConfigurationRepository.GetByLibraryAndPluginIdAsync(command.LibraryId, command.PluginId, Arg.Any()) - .Returns(error); - - // Act - Result result = await _sut.HandleAsync(command, CancellationToken.None); - - // Assert - Assert.True(result.IsFailure); - Assert.Equal(error, result.FirstError); - await _mockLibraryBookReaderConfigurationRepository.DidNotReceive().UpsertAsync(Arg.Any(), Arg.Any()); - await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); - _mockEnablementCache.DidNotReceive().Invalidate(Arg.Any(), Arg.Any()); - } - - [Fact] - public async Task HandleAsync_WhenUpsertFails_ShouldReturnErrorAndNotPersist() - { - // Arrange - SetLibraryBookReaderEnabledCommand command = _setLibraryBookReaderEnabledCommandFixture.Create(); - Error error = Error.Failure(description: "Failed to upsert configuration"); - _mockLibraryBookReaderConfigurationRepository.GetByLibraryAndPluginIdAsync(command.LibraryId, command.PluginId, Arg.Any()) - .Returns(Result.From(null)); - _mockLibraryBookReaderConfigurationRepository.UpsertAsync(Arg.Any(), Arg.Any()) - .Returns(error); - - // Act - Result result = await _sut.HandleAsync(command, CancellationToken.None); - - // Assert - Assert.True(result.IsFailure); - Assert.Equal(error, result.FirstError); - await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); - _mockEnablementCache.DidNotReceive().Invalidate(Arg.Any(), Arg.Any()); - } -} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/Plugins/Commands/SetLibraryBookReaderEnabled/SetLibraryBookReaderEnabledCommandValidatorTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/Plugins/Commands/SetLibraryBookReaderEnabled/SetLibraryBookReaderEnabledCommandValidatorTests.cs deleted file mode 100644 index 2d8b82d1..00000000 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/Plugins/Commands/SetLibraryBookReaderEnabled/SetLibraryBookReaderEnabledCommandValidatorTests.cs +++ /dev/null @@ -1,62 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using Lumina.Application.Core.Plugins.Commands.SetLibraryBookReaderEnabled; -using Lumina.Application.Fixtures.Core.Plugins.Commands.SetLibraryBookReaderEnabled; -using Lumina.Application.UnitTests.Common.Setup; -using Lumina.Domain.Common.Errors; -using Lumina.Domain.Common.Primitives; -using System; -using System.Collections.Generic; -using System.Diagnostics.CodeAnalysis; -#endregion - -namespace Lumina.Application.UnitTests.Core.Plugins.Commands.SetLibraryBookReaderEnabled; - -/// -/// Contains unit tests for the class. -/// -[ExcludeFromCodeCoverage] -public class SetLibraryBookReaderEnabledCommandValidatorTests -{ - private readonly SetLibraryBookReaderEnabledCommandValidator _validator = new(); - private readonly SetLibraryBookReaderEnabledCommandFixture _setLibraryBookReaderEnabledCommandFixture = new(); - - [Fact] - public void Validate_WhenLibraryIdIsEmpty_ShouldHaveValidationError() - { - // Arrange - SetLibraryBookReaderEnabledCommand command = _setLibraryBookReaderEnabledCommandFixture.Create(libraryId: Guid.Empty); - - // Act - List result = _validator.TestValidate(command); - - // Assert - result.ShouldHaveValidationError(Errors.Plugins.LibraryIdCannotBeEmpty); - } - - [Fact] - public void Validate_WhenPluginIdIsEmpty_ShouldHaveValidationError() - { - // Arrange - SetLibraryBookReaderEnabledCommand command = _setLibraryBookReaderEnabledCommandFixture.Create(pluginId: Guid.Empty); - - // Act - List result = _validator.TestValidate(command); - - // Assert - result.ShouldHaveValidationError(Errors.Plugins.PluginIdCannotBeEmpty); - } - - [Fact] - public void Validate_WhenCommandIsValid_ShouldNotHaveValidationError() - { - // Arrange - SetLibraryBookReaderEnabledCommand command = _setLibraryBookReaderEnabledCommandFixture.Create(); - - // Act - List result = _validator.TestValidate(command); - - // Assert - result.ShouldNotHaveValidationError(Errors.Plugins.LibraryIdCannotBeEmpty); - result.ShouldNotHaveValidationError(Errors.Plugins.PluginIdCannotBeEmpty); - } -} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/Plugins/Commands/SetLibraryMetadataProviderEnabled/SetLibraryMetadataProviderEnabledCommandHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/Plugins/Commands/SetLibraryMetadataProviderEnabled/SetLibraryMetadataProviderEnabledCommandHandlerTests.cs deleted file mode 100644 index d53f845c..00000000 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/Plugins/Commands/SetLibraryMetadataProviderEnabled/SetLibraryMetadataProviderEnabledCommandHandlerTests.cs +++ /dev/null @@ -1,172 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using Lumina.Application.Common.DataAccess.Entities.Plugins; -using Lumina.Application.Common.DataAccess.Repositories.Plugins; -using Lumina.Application.Common.DataAccess.UoW; -using Lumina.Application.Common.Infrastructure.Authentication; -using Lumina.Application.Common.Infrastructure.Authorization; -using Lumina.Application.Common.Infrastructure.Authorization.Policies.LibraryOwnership; -using Lumina.Application.Common.Infrastructure.Validation; -using Lumina.Application.Core.Plugins.Commands.SetLibraryMetadataProviderEnabled; -using Lumina.Application.Fixtures.Common.DataAccess.Entities.Plugins; -using Lumina.Application.Fixtures.Core.Plugins.Commands.SetLibraryMetadataProviderEnabled; -using Lumina.Domain.Common.Errors; -using Lumina.Domain.Common.Primitives; -using NSubstitute; -using System; -using System.Collections.Generic; -using System.Diagnostics.CodeAnalysis; -using System.Threading; -using System.Threading.Tasks; -using ApplicationErrors = Lumina.Application.Common.Errors.Errors; -#endregion - -namespace Lumina.Application.UnitTests.Core.Plugins.Commands.SetLibraryMetadataProviderEnabled; - -/// -/// Contains unit tests for the class. -/// -[ExcludeFromCodeCoverage] -public class SetLibraryMetadataProviderEnabledCommandHandlerTests -{ - private readonly IUnitOfWork _mockUnitOfWork; - private readonly ILibraryMetadataProviderConfigurationRepository _mockConfigurationRepository; - private readonly IAuthorizationService _mockAuthorizationService; - private readonly ICurrentUserService _mockCurrentUserService; - private readonly IValidator _mockValidator; - private readonly SetLibraryMetadataProviderEnabledCommandHandler _sut; - private readonly SetLibraryMetadataProviderEnabledCommandFixture _setLibraryMetadataProviderEnabledCommandFixture = new(); - private readonly Guid _userId; - - /// - /// Fixture for generating test data. - /// - private readonly LibraryMetadataProviderConfigurationEntityFixture _libraryMetadataProviderConfigurationEntityFixture = new(); - - /// - /// Initializes a new instance of the class. - /// - public SetLibraryMetadataProviderEnabledCommandHandlerTests() - { - _mockUnitOfWork = Substitute.For(); - _mockUnitOfWork.SaveChangesAsync(Arg.Any()).Returns(Result.Success); - _mockConfigurationRepository = Substitute.For(); - _mockUnitOfWork.LibraryMetadataProviderConfigurationRepository.Returns(_mockConfigurationRepository); - _mockAuthorizationService = Substitute.For(); - _mockCurrentUserService = Substitute.For(); - _mockValidator = Substitute.For>(); - _userId = Guid.NewGuid(); - - // default stubs: the current user is authenticated and the library ownership policy allows access - _mockCurrentUserService.UserId.Returns(_userId); - _mockAuthorizationService.EvaluatePolicyAsync(_userId, Arg.Any(), Arg.Any()) - .Returns(true); - _mockValidator.Validate(Arg.Any()) - .Returns([]); - _sut = new SetLibraryMetadataProviderEnabledCommandHandler(_mockAuthorizationService, _mockCurrentUserService, _mockUnitOfWork, _mockValidator); - } - - [Fact] - public async Task HandleAsync_WhenConfigurationDoesNotExist_ShouldCreateEnabledConfigurationWithNextRank() - { - // Arrange - Guid libraryId = Guid.NewGuid(); - Guid pluginId = Guid.NewGuid(); - _mockConfigurationRepository.GetByLibraryAndPluginIdAsync(libraryId, pluginId, Arg.Any()) - .Returns((LibraryMetadataProviderConfigurationEntity?)null); - _mockConfigurationRepository.GetByLibraryIdAsync(libraryId, Arg.Any()) - .Returns(new List()); - _mockConfigurationRepository.UpsertAsync(Arg.Any(), Arg.Any()) - .Returns(Result.Updated); - - // Act - Result result = await _sut.HandleAsync(_setLibraryMetadataProviderEnabledCommandFixture.Create(libraryId: libraryId, pluginId: pluginId, isEnabled: true), CancellationToken.None); - - // Assert - Assert.False(result.IsFailure); - await _mockConfigurationRepository.Received(1).UpsertAsync( - Arg.Is(configuration => configuration.IsEnabled && configuration.Rank == 1), - Arg.Any()); - } - - [Fact] - public async Task HandleAsync_WhenConfigurationExists_ShouldUpdateItsEnabledState() - { - // Arrange - LibraryMetadataProviderConfigurationEntity existingConfiguration = _libraryMetadataProviderConfigurationEntityFixture.Create( - libraryId: Guid.NewGuid(), - pluginId: Guid.NewGuid(), - rank: 2, - isEnabled: false); - _mockConfigurationRepository.GetByLibraryAndPluginIdAsync(existingConfiguration.LibraryId, existingConfiguration.PluginId, Arg.Any()) - .Returns(existingConfiguration); - _mockConfigurationRepository.UpsertAsync(Arg.Any(), Arg.Any()) - .Returns(Result.Updated); - - // Act - Result result = await _sut.HandleAsync(_setLibraryMetadataProviderEnabledCommandFixture.Create(libraryId: existingConfiguration.LibraryId, pluginId: existingConfiguration.PluginId, isEnabled: true), CancellationToken.None); - - // Assert - Assert.False(result.IsFailure); - await _mockConfigurationRepository.Received(1).UpsertAsync( - Arg.Is(configuration => configuration.IsEnabled && configuration.Rank == 2), - Arg.Any()); - } - - [Fact] - public async Task HandleAsync_WhenValidationFails_ShouldReturnValidationErrorsWithoutPersisting() - { - // Arrange - Guid libraryId = Guid.NewGuid(); - Guid pluginId = Guid.NewGuid(); - _mockValidator.Validate(Arg.Any()).Returns([Errors.Plugins.PluginIdCannotBeEmpty]); - - // Act - Result result = await _sut.HandleAsync(_setLibraryMetadataProviderEnabledCommandFixture.Create(libraryId: libraryId, pluginId: pluginId, isEnabled: true), CancellationToken.None); - - // Assert - Assert.True(result.IsFailure); - Assert.Equal(Errors.Plugins.PluginIdCannotBeEmpty, result.FirstError); - await _mockConfigurationRepository.DidNotReceive().GetByLibraryAndPluginIdAsync(Arg.Any(), Arg.Any(), Arg.Any()); - await _mockConfigurationRepository.DidNotReceive().UpsertAsync(Arg.Any(), Arg.Any()); - await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); - } - - [Fact] - public async Task HandleAsync_WhenOwnershipPolicyDeniesAccess_ShouldReturnNotAuthorizedError() - { - // Arrange - Guid libraryId = Guid.NewGuid(); - Guid pluginId = Guid.NewGuid(); - _mockAuthorizationService.EvaluatePolicyAsync(_userId, Arg.Any(), Arg.Any()) - .Returns(false); - - // Act - Result result = await _sut.HandleAsync(_setLibraryMetadataProviderEnabledCommandFixture.Create(libraryId: libraryId, pluginId: pluginId, isEnabled: true), CancellationToken.None); - - // Assert - Assert.True(result.IsFailure); - Assert.Equal(ApplicationErrors.Authorization.NotAuthorized, result.FirstError); - await _mockAuthorizationService.Received(1).EvaluatePolicyAsync( - _userId, Arg.Is(context => context.LibraryId == libraryId), Arg.Any()); - await _mockConfigurationRepository.DidNotReceive().GetByLibraryAndPluginIdAsync(Arg.Any(), Arg.Any(), Arg.Any()); - await _mockConfigurationRepository.DidNotReceive().UpsertAsync(Arg.Any(), Arg.Any()); - await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); - } - - [Fact] - public async Task HandleAsync_WhenUserIsNotAuthenticated_ShouldReturnNotAuthorizedError() - { - // Arrange - _mockCurrentUserService.UserId.Returns((Guid?)null); - - // Act - Result result = await _sut.HandleAsync(_setLibraryMetadataProviderEnabledCommandFixture.Create(), CancellationToken.None); - - // Assert - Assert.True(result.IsFailure); - Assert.Equal(ApplicationErrors.Authorization.NotAuthorized, result.FirstError); - await _mockAuthorizationService.DidNotReceive().EvaluatePolicyAsync(Arg.Any(), Arg.Any(), Arg.Any()); - await _mockConfigurationRepository.DidNotReceive().GetByLibraryAndPluginIdAsync(Arg.Any(), Arg.Any(), Arg.Any()); - await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); - } -} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/Plugins/Commands/SetLibraryMetadataProviderEnabled/SetLibraryMetadataProviderEnabledCommandValidatorTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/Plugins/Commands/SetLibraryMetadataProviderEnabled/SetLibraryMetadataProviderEnabledCommandValidatorTests.cs deleted file mode 100644 index 15c0aa5c..00000000 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/Plugins/Commands/SetLibraryMetadataProviderEnabled/SetLibraryMetadataProviderEnabledCommandValidatorTests.cs +++ /dev/null @@ -1,89 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using Lumina.Application.Core.Plugins.Commands.SetLibraryMetadataProviderEnabled; -using Lumina.Application.Fixtures.Core.Plugins.Commands.SetLibraryMetadataProviderEnabled; -using Lumina.Application.UnitTests.Common.Setup; -using Lumina.Domain.Common.Errors; -using Lumina.Domain.Common.Primitives; -using System; -using System.Collections.Generic; -using System.Diagnostics.CodeAnalysis; -#endregion - -namespace Lumina.Application.UnitTests.Core.Plugins.Commands.SetLibraryMetadataProviderEnabled; - -/// -/// Contains unit tests for the class. -/// -[ExcludeFromCodeCoverage] -public class SetLibraryMetadataProviderEnabledCommandValidatorTests -{ - private readonly SetLibraryMetadataProviderEnabledCommandValidator _validator = new(); - private readonly SetLibraryMetadataProviderEnabledCommandFixture _setLibraryMetadataProviderEnabledCommandFixture = new(); - - [Fact] - public void Validate_WhenLibraryIdIsEmpty_ShouldHaveValidationError() - { - // Arrange - SetLibraryMetadataProviderEnabledCommand command = _setLibraryMetadataProviderEnabledCommandFixture.Create(); - command = command with { LibraryId = Guid.Empty }; - - // Act - List result = _validator.TestValidate(command); - - // Assert - result.ShouldHaveValidationError(Errors.Plugins.LibraryIdCannotBeEmpty); - } - - [Fact] - public void Validate_WhenLibraryIdIsValid_ShouldNotHaveValidationError() - { - // Arrange - SetLibraryMetadataProviderEnabledCommand command = _setLibraryMetadataProviderEnabledCommandFixture.Create(); - - // Act - List result = _validator.TestValidate(command); - - // Assert - result.ShouldNotHaveValidationError(Errors.Plugins.LibraryIdCannotBeEmpty); - } - - [Fact] - public void Validate_WhenPluginIdIsEmpty_ShouldHaveValidationError() - { - // Arrange - SetLibraryMetadataProviderEnabledCommand command = _setLibraryMetadataProviderEnabledCommandFixture.Create(); - command = command with { PluginId = Guid.Empty }; - - // Act - List result = _validator.TestValidate(command); - - // Assert - result.ShouldHaveValidationError(Errors.Plugins.PluginIdCannotBeEmpty); - } - - [Fact] - public void Validate_WhenPluginIdIsValid_ShouldNotHaveValidationError() - { - // Arrange - SetLibraryMetadataProviderEnabledCommand command = _setLibraryMetadataProviderEnabledCommandFixture.Create(); - - // Act - List result = _validator.TestValidate(command); - - // Assert - result.ShouldNotHaveValidationError(Errors.Plugins.PluginIdCannotBeEmpty); - } - - [Fact] - public void Validate_WhenCommandIsValid_ShouldNotHaveValidationError() - { - // Arrange - SetLibraryMetadataProviderEnabledCommand command = _setLibraryMetadataProviderEnabledCommandFixture.Create(); - - // Act - List result = _validator.TestValidate(command); - - // Assert - result.ShouldNotHaveAnyValidationErrors(); - } -} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/Plugins/Queries/GetLibraryTypeArtworkProviders/GetLibraryTypeArtworkProvidersQueryHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/Plugins/Queries/GetLibraryTypeArtworkProviders/GetLibraryTypeArtworkProvidersQueryHandlerTests.cs new file mode 100644 index 00000000..9f25ef79 --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/Plugins/Queries/GetLibraryTypeArtworkProviders/GetLibraryTypeArtworkProvidersQueryHandlerTests.cs @@ -0,0 +1,184 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Entities.Plugins; +using Lumina.Application.Common.DataAccess.Repositories.Plugins; +using Lumina.Application.Common.DataAccess.UoW; +using Lumina.Application.Common.DTO.Filtering; +using Lumina.Application.Common.Infrastructure.Authentication; +using Lumina.Application.Common.Infrastructure.Plugins; +using Lumina.Application.Common.Infrastructure.Validation; +using Lumina.Application.Core.Plugins.Queries.GetLibraryTypeArtworkProviders; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.Plugins; +using Lumina.Application.Fixtures.Common.DTO.Pagination; +using Lumina.Application.Fixtures.Core.Plugins.Queries.GetLibraryTypeArtworkProviders; +using Lumina.Contracts.Responses.Plugins; +using Lumina.Domain.Common.Errors; +using Lumina.Domain.Common.Primitives; +using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; +using NSubstitute; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Threading; +using System.Threading.Tasks; +using ApplicationErrors = Lumina.Application.Common.Errors.Errors; +#endregion + +namespace Lumina.Application.UnitTests.Core.Plugins.Queries.GetLibraryTypeArtworkProviders; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class GetLibraryTypeArtworkProvidersQueryHandlerTests +{ + private readonly IUnitOfWork _mockUnitOfWork; + private readonly IPluginRepository _mockPluginRepository; + private readonly ICurrentUserService _mockCurrentUserService; + private readonly IMediaLibraryProviderConfigurationStore _mockProviderConfigurationStore; + private readonly IValidator _mockValidator; + private readonly GetLibraryTypeArtworkProvidersQueryHandler _sut; + private readonly GetLibraryTypeArtworkProvidersQueryFixture _getLibraryTypeArtworkProvidersQueryFixture = new(); + private readonly PluginEntityFixture _pluginEntityFixture = new(); + private readonly PaginatedResultDtoFixture _paginatedResultDtoFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + public GetLibraryTypeArtworkProvidersQueryHandlerTests() + { + _mockUnitOfWork = Substitute.For(); + _mockPluginRepository = Substitute.For(); + _mockUnitOfWork.PluginRepository.Returns(_mockPluginRepository); + _mockCurrentUserService = Substitute.For(); + _mockProviderConfigurationStore = Substitute.For(); + _mockValidator = Substitute.For>(); + + // Default stubs: the query is valid, the current user is authenticated, no plugin supports the library type, and no plugin is detected. + _mockValidator.Validate(Arg.Any()).Returns([]); + _mockCurrentUserService.UserId.Returns(Guid.NewGuid()); + _mockProviderConfigurationStore.GetSupportedArtworkProviderPluginIds(Arg.Any()).Returns([]); + _mockPluginRepository.GetAllAsync(cancellationToken: Arg.Any()) + .Returns(Result.From(_paginatedResultDtoFixture.Create(data: [], currentPage: 1, perPage: 0, count: 0, numberOfPages: 1))); + + _sut = new GetLibraryTypeArtworkProvidersQueryHandler(_mockCurrentUserService, _mockProviderConfigurationStore, _mockUnitOfWork, _mockValidator); + } + + [Fact] + public async Task HandleAsync_WhenValidationFails_ShouldReturnValidationErrorWithoutReadingPlugins() + { + // Arrange + GetLibraryTypeArtworkProvidersQuery query = _getLibraryTypeArtworkProvidersQueryFixture.Create(); + _mockValidator.Validate(Arg.Any()).Returns([Errors.Library.UnknownLibraryType]); + + // Act + Result> result = await _sut.HandleAsync(query, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.Library.UnknownLibraryType, result.FirstError); + _mockProviderConfigurationStore.DidNotReceive().GetSupportedArtworkProviderPluginIds(Arg.Any()); + await _mockPluginRepository.DidNotReceive().GetAllAsync(cancellationToken: Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenUserIsNotAuthenticated_ShouldReturnNotAuthorizedError() + { + // Arrange + GetLibraryTypeArtworkProvidersQuery query = _getLibraryTypeArtworkProvidersQueryFixture.Create(); + _mockCurrentUserService.UserId.Returns((Guid?)null); + + // Act + Result> result = await _sut.HandleAsync(query, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(ApplicationErrors.Authorization.NotAuthorized, result.FirstError); + _mockProviderConfigurationStore.DidNotReceive().GetSupportedArtworkProviderPluginIds(Arg.Any()); + await _mockPluginRepository.DidNotReceive().GetAllAsync(cancellationToken: Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenPluginsSupportTheLibraryType_ShouldReturnThemDisabledAndRankedInTheSupportedOrder() + { + // Arrange + GetLibraryTypeArtworkProvidersQuery query = _getLibraryTypeArtworkProvidersQueryFixture.Create(libraryType: nameof(LibraryType.Book)); + Guid alphaPluginId = Guid.NewGuid(); + Guid betaPluginId = Guid.NewGuid(); + _mockProviderConfigurationStore.GetSupportedArtworkProviderPluginIds(LibraryType.Book).Returns([alphaPluginId, betaPluginId]); + List plugins = [_pluginEntityFixture.Create(betaPluginId, "Beta"), _pluginEntityFixture.Create(alphaPluginId, "Alpha")]; + _mockPluginRepository.GetAllAsync(cancellationToken: Arg.Any()) + .Returns(Result.From(_paginatedResultDtoFixture.Create(data: plugins, currentPage: 1, perPage: plugins.Count, count: plugins.Count, numberOfPages: 1))); + + // Act + Result> result = await _sut.HandleAsync(query, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal(2, result.Value.Count); + Assert.Equal(new LibraryArtworkProviderResponse(alphaPluginId, "Alpha", false, 1), result.Value[0]); + Assert.Equal(new LibraryArtworkProviderResponse(betaPluginId, "Beta", false, 2), result.Value[1]); + } + + [Fact] + public async Task HandleAsync_WhenLibraryTypeCasingDiffers_ShouldStillResolveTheLibraryType() + { + // Arrange + GetLibraryTypeArtworkProvidersQuery query = _getLibraryTypeArtworkProvidersQueryFixture.Create(libraryType: "music"); + + // Act + Result> result = await _sut.HandleAsync(query, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + _mockProviderConfigurationStore.Received(1).GetSupportedArtworkProviderPluginIds(LibraryType.Music); + } + + [Fact] + public async Task HandleAsync_WhenPluginIsMissingFromDetectedPlugins_ShouldUseEmptyName() + { + // Arrange + GetLibraryTypeArtworkProvidersQuery query = _getLibraryTypeArtworkProvidersQueryFixture.Create(libraryType: nameof(LibraryType.Book)); + Guid unknownPluginId = Guid.NewGuid(); + _mockProviderConfigurationStore.GetSupportedArtworkProviderPluginIds(LibraryType.Book).Returns([unknownPluginId]); + + // Act + Result> result = await _sut.HandleAsync(query, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + LibraryArtworkProviderResponse response = Assert.Single(result.Value); + Assert.Equal(unknownPluginId, response.PluginId); + Assert.Equal(string.Empty, response.Name); + } + + [Fact] + public async Task HandleAsync_WhenNoPluginSupportsTheLibraryType_ShouldReturnEmptyList() + { + // Arrange + GetLibraryTypeArtworkProvidersQuery query = _getLibraryTypeArtworkProvidersQueryFixture.Create(); + + // Act + Result> result = await _sut.HandleAsync(query, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + Assert.Empty(result.Value); + } + + [Fact] + public async Task HandleAsync_WhenGetPluginsFails_ShouldReturnError() + { + // Arrange + GetLibraryTypeArtworkProvidersQuery query = _getLibraryTypeArtworkProvidersQueryFixture.Create(); + Error error = Error.Failure(description: "Failed to get plugins"); + _mockPluginRepository.GetAllAsync(cancellationToken: Arg.Any()) + .Returns(error); + + // Act + Result> result = await _sut.HandleAsync(query, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(error, result.FirstError); + } +} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/Plugins/Queries/GetLibraryTypeArtworkProviders/GetLibraryTypeArtworkProvidersQueryValidatorTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/Plugins/Queries/GetLibraryTypeArtworkProviders/GetLibraryTypeArtworkProvidersQueryValidatorTests.cs new file mode 100644 index 00000000..2a08a287 --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/Plugins/Queries/GetLibraryTypeArtworkProviders/GetLibraryTypeArtworkProvidersQueryValidatorTests.cs @@ -0,0 +1,67 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Core.Plugins.Queries.GetLibraryTypeArtworkProviders; +using Lumina.Application.Fixtures.Core.Plugins.Queries.GetLibraryTypeArtworkProviders; +using Lumina.Application.UnitTests.Common.Setup; +using Lumina.Domain.Common.Errors; +using Lumina.Domain.Common.Primitives; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Application.UnitTests.Core.Plugins.Queries.GetLibraryTypeArtworkProviders; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class GetLibraryTypeArtworkProvidersQueryValidatorTests +{ + private readonly GetLibraryTypeArtworkProvidersQueryValidator _validator = new(); + private readonly GetLibraryTypeArtworkProvidersQueryFixture _getLibraryTypeArtworkProvidersQueryFixture = new(); + + [Fact] + public void Validate_WhenLibraryTypeIsNull_ShouldHaveValidationError() + { + // Arrange + GetLibraryTypeArtworkProvidersQuery query = _getLibraryTypeArtworkProvidersQueryFixture.Create() with { LibraryType = null }; + + // Act + List result = _validator.TestValidate(query); + + // Assert + result.ShouldHaveValidationError(Errors.Library.LibraryTypeCannotBeNull); + } + + [Theory] + [InlineData("UnknownLibraryType")] // Not a library type. + [InlineData("999")] // A number that is not a defined library type. + [InlineData("0")] // The numeric value of a defined library type, which is not a member name. + [InlineData("")] // Empty. + public void Validate_WhenLibraryTypeIsUnknown_ShouldHaveValidationError(string libraryType) + { + // Arrange + GetLibraryTypeArtworkProvidersQuery query = _getLibraryTypeArtworkProvidersQueryFixture.Create(libraryType: libraryType); + + // Act + List result = _validator.TestValidate(query); + + // Assert + result.ShouldHaveValidationError(Errors.Library.UnknownLibraryType); + } + + [Theory] + [InlineData("Book")] + [InlineData("music")] // The casing of the type is ignored. + public void Validate_WhenLibraryTypeIsValid_ShouldNotHaveValidationError(string libraryType) + { + // Arrange + GetLibraryTypeArtworkProvidersQuery query = _getLibraryTypeArtworkProvidersQueryFixture.Create(libraryType: libraryType); + + // Act + List result = _validator.TestValidate(query); + + // Assert + result.ShouldNotHaveValidationError(Errors.Library.LibraryTypeCannotBeNull); + result.ShouldNotHaveValidationError(Errors.Library.UnknownLibraryType); + } +} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/Plugins/Queries/GetLibraryTypeBookReaders/GetLibraryTypeBookReadersQueryHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/Plugins/Queries/GetLibraryTypeBookReaders/GetLibraryTypeBookReadersQueryHandlerTests.cs new file mode 100644 index 00000000..4bd8855e --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/Plugins/Queries/GetLibraryTypeBookReaders/GetLibraryTypeBookReadersQueryHandlerTests.cs @@ -0,0 +1,187 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Entities.Plugins; +using Lumina.Application.Common.DataAccess.Repositories.Plugins; +using Lumina.Application.Common.DataAccess.UoW; +using Lumina.Application.Common.DTO.Filtering; +using Lumina.Application.Common.Infrastructure.Authentication; +using Lumina.Application.Common.Infrastructure.Plugins; +using Lumina.Application.Common.Infrastructure.Reading; +using Lumina.Application.Common.Infrastructure.Validation; +using Lumina.Application.Core.Plugins.Queries.GetLibraryTypeBookReaders; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.Plugins; +using Lumina.Application.Fixtures.Common.DTO.Pagination; +using Lumina.Application.Fixtures.Core.Plugins.Queries.GetLibraryTypeBookReaders; +using Lumina.Contracts.Responses.Plugins; +using Lumina.Domain.Common.Errors; +using Lumina.Domain.Common.Primitives; +using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; +using NSubstitute; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Threading; +using System.Threading.Tasks; +using ApplicationErrors = Lumina.Application.Common.Errors.Errors; +#endregion + +namespace Lumina.Application.UnitTests.Core.Plugins.Queries.GetLibraryTypeBookReaders; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class GetLibraryTypeBookReadersQueryHandlerTests +{ + private readonly IUnitOfWork _mockUnitOfWork; + private readonly IPluginRepository _mockPluginRepository; + private readonly ICurrentUserService _mockCurrentUserService; + private readonly IMediaLibraryProviderConfigurationStore _mockProviderConfigurationStore; + private readonly IBookReaderRegistry _mockBookReaderRegistry; + private readonly IValidator _mockValidator; + private readonly GetLibraryTypeBookReadersQueryHandler _sut; + private readonly GetLibraryTypeBookReadersQueryFixture _getLibraryTypeBookReadersQueryFixture = new(); + private readonly PluginEntityFixture _pluginEntityFixture = new(); + private readonly PaginatedResultDtoFixture _paginatedResultDtoFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + public GetLibraryTypeBookReadersQueryHandlerTests() + { + _mockUnitOfWork = Substitute.For(); + _mockPluginRepository = Substitute.For(); + _mockUnitOfWork.PluginRepository.Returns(_mockPluginRepository); + _mockCurrentUserService = Substitute.For(); + _mockProviderConfigurationStore = Substitute.For(); + _mockBookReaderRegistry = Substitute.For(); + _mockValidator = Substitute.For>(); + + // Default stubs: the query is valid, the current user is authenticated, no reader supports the library type, and no plugin is detected. + _mockValidator.Validate(Arg.Any()).Returns([]); + _mockCurrentUserService.UserId.Returns(Guid.NewGuid()); + _mockProviderConfigurationStore.GetSupportedBookReaderPluginIds(Arg.Any()).Returns([]); + _mockBookReaderRegistry.GetSupportedExtensionsByPluginId().Returns(new Dictionary>()); + _mockPluginRepository.GetAllAsync(cancellationToken: Arg.Any()) + .Returns(Result.From(_paginatedResultDtoFixture.Create(data: [], currentPage: 1, perPage: 0, count: 0, numberOfPages: 1))); + + _sut = new GetLibraryTypeBookReadersQueryHandler(_mockCurrentUserService, _mockProviderConfigurationStore, _mockBookReaderRegistry, _mockUnitOfWork, _mockValidator); + } + + [Fact] + public async Task HandleAsync_WhenValidationFails_ShouldReturnValidationErrorWithoutReadingPlugins() + { + // Arrange + GetLibraryTypeBookReadersQuery query = _getLibraryTypeBookReadersQueryFixture.Create(); + _mockValidator.Validate(Arg.Any()).Returns([Errors.Library.LibraryTypeCannotBeNull]); + + // Act + Result> result = await _sut.HandleAsync(query, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.Library.LibraryTypeCannotBeNull, result.FirstError); + _mockProviderConfigurationStore.DidNotReceive().GetSupportedBookReaderPluginIds(Arg.Any()); + await _mockPluginRepository.DidNotReceive().GetAllAsync(cancellationToken: Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenUserIsNotAuthenticated_ShouldReturnNotAuthorizedError() + { + // Arrange + GetLibraryTypeBookReadersQuery query = _getLibraryTypeBookReadersQueryFixture.Create(); + _mockCurrentUserService.UserId.Returns((Guid?)null); + + // Act + Result> result = await _sut.HandleAsync(query, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(ApplicationErrors.Authorization.NotAuthorized, result.FirstError); + _mockProviderConfigurationStore.DidNotReceive().GetSupportedBookReaderPluginIds(Arg.Any()); + await _mockPluginRepository.DidNotReceive().GetAllAsync(cancellationToken: Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenReadersSupportTheLibraryType_ShouldReturnThemDisabledWithTheirNamesAndExtensions() + { + // Arrange + GetLibraryTypeBookReadersQuery query = _getLibraryTypeBookReadersQueryFixture.Create(libraryType: nameof(LibraryType.Book)); + Guid epubPluginId = Guid.NewGuid(); + Guid pdfPluginId = Guid.NewGuid(); + _mockProviderConfigurationStore.GetSupportedBookReaderPluginIds(LibraryType.Book).Returns([epubPluginId, pdfPluginId]); + List plugins = [_pluginEntityFixture.Create(pdfPluginId, "PDF Reader"), _pluginEntityFixture.Create(epubPluginId, "EPUB Reader")]; + _mockPluginRepository.GetAllAsync(cancellationToken: Arg.Any()) + .Returns(Result.From(_paginatedResultDtoFixture.Create(data: plugins, currentPage: 1, perPage: plugins.Count, count: plugins.Count, numberOfPages: 1))); + _mockBookReaderRegistry.GetSupportedExtensionsByPluginId().Returns(new Dictionary> + { + [epubPluginId] = [".epub"], + [pdfPluginId] = [".pdf"] + }); + + // Act + Result> result = await _sut.HandleAsync(query, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal(2, result.Value.Count); + Assert.Equal(epubPluginId, result.Value[0].PluginId); + Assert.Equal("EPUB Reader", result.Value[0].Name); + Assert.Equal(".epub", Assert.Single(result.Value[0].SupportedExtensions)); + Assert.False(result.Value[0].IsEnabled); + Assert.Equal(pdfPluginId, result.Value[1].PluginId); + Assert.Equal("PDF Reader", result.Value[1].Name); + Assert.Equal(".pdf", Assert.Single(result.Value[1].SupportedExtensions)); + Assert.False(result.Value[1].IsEnabled); + } + + [Fact] + public async Task HandleAsync_WhenReaderIsMissingFromDetectedPluginsAndRegistry_ShouldUseEmptyNameAndNoExtensions() + { + // Arrange + GetLibraryTypeBookReadersQuery query = _getLibraryTypeBookReadersQueryFixture.Create(libraryType: nameof(LibraryType.Book)); + Guid unknownPluginId = Guid.NewGuid(); + _mockProviderConfigurationStore.GetSupportedBookReaderPluginIds(LibraryType.Book).Returns([unknownPluginId]); + + // Act + Result> result = await _sut.HandleAsync(query, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + LibraryBookReaderResponse response = Assert.Single(result.Value); + Assert.Equal(unknownPluginId, response.PluginId); + Assert.Equal(string.Empty, response.Name); + Assert.Empty(response.SupportedExtensions); + } + + [Fact] + public async Task HandleAsync_WhenNoReaderSupportsTheLibraryType_ShouldReturnEmptyList() + { + // Arrange + GetLibraryTypeBookReadersQuery query = _getLibraryTypeBookReadersQueryFixture.Create(libraryType: nameof(LibraryType.Music)); + + // Act + Result> result = await _sut.HandleAsync(query, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + Assert.Empty(result.Value); + _mockProviderConfigurationStore.Received(1).GetSupportedBookReaderPluginIds(LibraryType.Music); + } + + [Fact] + public async Task HandleAsync_WhenGetPluginsFails_ShouldReturnError() + { + // Arrange + GetLibraryTypeBookReadersQuery query = _getLibraryTypeBookReadersQueryFixture.Create(); + Error error = Error.Failure(description: "Failed to get plugins"); + _mockPluginRepository.GetAllAsync(cancellationToken: Arg.Any()) + .Returns(error); + + // Act + Result> result = await _sut.HandleAsync(query, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(error, result.FirstError); + } +} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/Plugins/Queries/GetLibraryTypeBookReaders/GetLibraryTypeBookReadersQueryValidatorTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/Plugins/Queries/GetLibraryTypeBookReaders/GetLibraryTypeBookReadersQueryValidatorTests.cs new file mode 100644 index 00000000..4c19fb5c --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/Plugins/Queries/GetLibraryTypeBookReaders/GetLibraryTypeBookReadersQueryValidatorTests.cs @@ -0,0 +1,67 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Core.Plugins.Queries.GetLibraryTypeBookReaders; +using Lumina.Application.Fixtures.Core.Plugins.Queries.GetLibraryTypeBookReaders; +using Lumina.Application.UnitTests.Common.Setup; +using Lumina.Domain.Common.Errors; +using Lumina.Domain.Common.Primitives; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Application.UnitTests.Core.Plugins.Queries.GetLibraryTypeBookReaders; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class GetLibraryTypeBookReadersQueryValidatorTests +{ + private readonly GetLibraryTypeBookReadersQueryValidator _validator = new(); + private readonly GetLibraryTypeBookReadersQueryFixture _getLibraryTypeBookReadersQueryFixture = new(); + + [Fact] + public void Validate_WhenLibraryTypeIsNull_ShouldHaveValidationError() + { + // Arrange + GetLibraryTypeBookReadersQuery query = _getLibraryTypeBookReadersQueryFixture.Create() with { LibraryType = null }; + + // Act + List result = _validator.TestValidate(query); + + // Assert + result.ShouldHaveValidationError(Errors.Library.LibraryTypeCannotBeNull); + } + + [Theory] + [InlineData("UnknownLibraryType")] // Not a library type. + [InlineData("999")] // A number that is not a defined library type. + [InlineData("0")] // The numeric value of a defined library type, which is not a member name. + [InlineData("")] // Empty. + public void Validate_WhenLibraryTypeIsUnknown_ShouldHaveValidationError(string libraryType) + { + // Arrange + GetLibraryTypeBookReadersQuery query = _getLibraryTypeBookReadersQueryFixture.Create(libraryType: libraryType); + + // Act + List result = _validator.TestValidate(query); + + // Assert + result.ShouldHaveValidationError(Errors.Library.UnknownLibraryType); + } + + [Theory] + [InlineData("Book")] + [InlineData("music")] // The casing of the type is ignored. + public void Validate_WhenLibraryTypeIsValid_ShouldNotHaveValidationError(string libraryType) + { + // Arrange + GetLibraryTypeBookReadersQuery query = _getLibraryTypeBookReadersQueryFixture.Create(libraryType: libraryType); + + // Act + List result = _validator.TestValidate(query); + + // Assert + result.ShouldNotHaveValidationError(Errors.Library.LibraryTypeCannotBeNull); + result.ShouldNotHaveValidationError(Errors.Library.UnknownLibraryType); + } +} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/Plugins/Queries/GetLibraryTypeMetadataProviders/GetLibraryTypeMetadataProvidersQueryHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/Plugins/Queries/GetLibraryTypeMetadataProviders/GetLibraryTypeMetadataProvidersQueryHandlerTests.cs new file mode 100644 index 00000000..f979c4c9 --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/Plugins/Queries/GetLibraryTypeMetadataProviders/GetLibraryTypeMetadataProvidersQueryHandlerTests.cs @@ -0,0 +1,184 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Entities.Plugins; +using Lumina.Application.Common.DataAccess.Repositories.Plugins; +using Lumina.Application.Common.DataAccess.UoW; +using Lumina.Application.Common.DTO.Filtering; +using Lumina.Application.Common.Infrastructure.Authentication; +using Lumina.Application.Common.Infrastructure.Plugins; +using Lumina.Application.Common.Infrastructure.Validation; +using Lumina.Application.Core.Plugins.Queries.GetLibraryTypeMetadataProviders; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.Plugins; +using Lumina.Application.Fixtures.Common.DTO.Pagination; +using Lumina.Application.Fixtures.Core.Plugins.Queries.GetLibraryTypeMetadataProviders; +using Lumina.Contracts.Responses.Plugins; +using Lumina.Domain.Common.Errors; +using Lumina.Domain.Common.Primitives; +using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; +using NSubstitute; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Threading; +using System.Threading.Tasks; +using ApplicationErrors = Lumina.Application.Common.Errors.Errors; +#endregion + +namespace Lumina.Application.UnitTests.Core.Plugins.Queries.GetLibraryTypeMetadataProviders; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class GetLibraryTypeMetadataProvidersQueryHandlerTests +{ + private readonly IUnitOfWork _mockUnitOfWork; + private readonly IPluginRepository _mockPluginRepository; + private readonly ICurrentUserService _mockCurrentUserService; + private readonly IMediaLibraryProviderConfigurationStore _mockProviderConfigurationStore; + private readonly IValidator _mockValidator; + private readonly GetLibraryTypeMetadataProvidersQueryHandler _sut; + private readonly GetLibraryTypeMetadataProvidersQueryFixture _getLibraryTypeMetadataProvidersQueryFixture = new(); + private readonly PluginEntityFixture _pluginEntityFixture = new(); + private readonly PaginatedResultDtoFixture _paginatedResultDtoFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + public GetLibraryTypeMetadataProvidersQueryHandlerTests() + { + _mockUnitOfWork = Substitute.For(); + _mockPluginRepository = Substitute.For(); + _mockUnitOfWork.PluginRepository.Returns(_mockPluginRepository); + _mockCurrentUserService = Substitute.For(); + _mockProviderConfigurationStore = Substitute.For(); + _mockValidator = Substitute.For>(); + + // Default stubs: the query is valid, the current user is authenticated, no plugin supports the library type, and no plugin is detected. + _mockValidator.Validate(Arg.Any()).Returns([]); + _mockCurrentUserService.UserId.Returns(Guid.NewGuid()); + _mockProviderConfigurationStore.GetSupportedMetadataProviderPluginIds(Arg.Any()).Returns([]); + _mockPluginRepository.GetAllAsync(cancellationToken: Arg.Any()) + .Returns(Result.From(_paginatedResultDtoFixture.Create(data: [], currentPage: 1, perPage: 0, count: 0, numberOfPages: 1))); + + _sut = new GetLibraryTypeMetadataProvidersQueryHandler(_mockCurrentUserService, _mockProviderConfigurationStore, _mockUnitOfWork, _mockValidator); + } + + [Fact] + public async Task HandleAsync_WhenValidationFails_ShouldReturnValidationErrorWithoutReadingPlugins() + { + // Arrange + GetLibraryTypeMetadataProvidersQuery query = _getLibraryTypeMetadataProvidersQueryFixture.Create(); + _mockValidator.Validate(Arg.Any()).Returns([Errors.Library.UnknownLibraryType]); + + // Act + Result> result = await _sut.HandleAsync(query, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.Library.UnknownLibraryType, result.FirstError); + _mockProviderConfigurationStore.DidNotReceive().GetSupportedMetadataProviderPluginIds(Arg.Any()); + await _mockPluginRepository.DidNotReceive().GetAllAsync(cancellationToken: Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenUserIsNotAuthenticated_ShouldReturnNotAuthorizedError() + { + // Arrange + GetLibraryTypeMetadataProvidersQuery query = _getLibraryTypeMetadataProvidersQueryFixture.Create(); + _mockCurrentUserService.UserId.Returns((Guid?)null); + + // Act + Result> result = await _sut.HandleAsync(query, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(ApplicationErrors.Authorization.NotAuthorized, result.FirstError); + _mockProviderConfigurationStore.DidNotReceive().GetSupportedMetadataProviderPluginIds(Arg.Any()); + await _mockPluginRepository.DidNotReceive().GetAllAsync(cancellationToken: Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenPluginsSupportTheLibraryType_ShouldReturnThemDisabledAndRankedInTheSupportedOrder() + { + // Arrange + GetLibraryTypeMetadataProvidersQuery query = _getLibraryTypeMetadataProvidersQueryFixture.Create(libraryType: nameof(LibraryType.Book)); + Guid alphaPluginId = Guid.NewGuid(); + Guid betaPluginId = Guid.NewGuid(); + _mockProviderConfigurationStore.GetSupportedMetadataProviderPluginIds(LibraryType.Book).Returns([alphaPluginId, betaPluginId]); + List plugins = [_pluginEntityFixture.Create(betaPluginId, "Beta"), _pluginEntityFixture.Create(alphaPluginId, "Alpha")]; + _mockPluginRepository.GetAllAsync(cancellationToken: Arg.Any()) + .Returns(Result.From(_paginatedResultDtoFixture.Create(data: plugins, currentPage: 1, perPage: plugins.Count, count: plugins.Count, numberOfPages: 1))); + + // Act + Result> result = await _sut.HandleAsync(query, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal(2, result.Value.Count); + Assert.Equal(new LibraryMetadataProviderResponse(alphaPluginId, "Alpha", false, 1), result.Value[0]); + Assert.Equal(new LibraryMetadataProviderResponse(betaPluginId, "Beta", false, 2), result.Value[1]); + } + + [Fact] + public async Task HandleAsync_WhenLibraryTypeCasingDiffers_ShouldStillResolveTheLibraryType() + { + // Arrange + GetLibraryTypeMetadataProvidersQuery query = _getLibraryTypeMetadataProvidersQueryFixture.Create(libraryType: "music"); + + // Act + Result> result = await _sut.HandleAsync(query, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + _mockProviderConfigurationStore.Received(1).GetSupportedMetadataProviderPluginIds(LibraryType.Music); + } + + [Fact] + public async Task HandleAsync_WhenPluginIsMissingFromDetectedPlugins_ShouldUseEmptyName() + { + // Arrange + GetLibraryTypeMetadataProvidersQuery query = _getLibraryTypeMetadataProvidersQueryFixture.Create(libraryType: nameof(LibraryType.Book)); + Guid unknownPluginId = Guid.NewGuid(); + _mockProviderConfigurationStore.GetSupportedMetadataProviderPluginIds(LibraryType.Book).Returns([unknownPluginId]); + + // Act + Result> result = await _sut.HandleAsync(query, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + LibraryMetadataProviderResponse response = Assert.Single(result.Value); + Assert.Equal(unknownPluginId, response.PluginId); + Assert.Equal(string.Empty, response.Name); + } + + [Fact] + public async Task HandleAsync_WhenNoPluginSupportsTheLibraryType_ShouldReturnEmptyList() + { + // Arrange + GetLibraryTypeMetadataProvidersQuery query = _getLibraryTypeMetadataProvidersQueryFixture.Create(); + + // Act + Result> result = await _sut.HandleAsync(query, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + Assert.Empty(result.Value); + } + + [Fact] + public async Task HandleAsync_WhenGetPluginsFails_ShouldReturnError() + { + // Arrange + GetLibraryTypeMetadataProvidersQuery query = _getLibraryTypeMetadataProvidersQueryFixture.Create(); + Error error = Error.Failure(description: "Failed to get plugins"); + _mockPluginRepository.GetAllAsync(cancellationToken: Arg.Any()) + .Returns(error); + + // Act + Result> result = await _sut.HandleAsync(query, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(error, result.FirstError); + } +} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/Plugins/Queries/GetLibraryTypeMetadataProviders/GetLibraryTypeMetadataProvidersQueryValidatorTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/Plugins/Queries/GetLibraryTypeMetadataProviders/GetLibraryTypeMetadataProvidersQueryValidatorTests.cs new file mode 100644 index 00000000..30e5d773 --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/Plugins/Queries/GetLibraryTypeMetadataProviders/GetLibraryTypeMetadataProvidersQueryValidatorTests.cs @@ -0,0 +1,67 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Core.Plugins.Queries.GetLibraryTypeMetadataProviders; +using Lumina.Application.Fixtures.Core.Plugins.Queries.GetLibraryTypeMetadataProviders; +using Lumina.Application.UnitTests.Common.Setup; +using Lumina.Domain.Common.Errors; +using Lumina.Domain.Common.Primitives; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Application.UnitTests.Core.Plugins.Queries.GetLibraryTypeMetadataProviders; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class GetLibraryTypeMetadataProvidersQueryValidatorTests +{ + private readonly GetLibraryTypeMetadataProvidersQueryValidator _validator = new(); + private readonly GetLibraryTypeMetadataProvidersQueryFixture _getLibraryTypeMetadataProvidersQueryFixture = new(); + + [Fact] + public void Validate_WhenLibraryTypeIsNull_ShouldHaveValidationError() + { + // Arrange + GetLibraryTypeMetadataProvidersQuery query = _getLibraryTypeMetadataProvidersQueryFixture.Create() with { LibraryType = null }; + + // Act + List result = _validator.TestValidate(query); + + // Assert + result.ShouldHaveValidationError(Errors.Library.LibraryTypeCannotBeNull); + } + + [Theory] + [InlineData("UnknownLibraryType")] // Not a library type. + [InlineData("999")] // A number that is not a defined library type. + [InlineData("0")] // The numeric value of a defined library type, which is not a member name. + [InlineData("")] // Empty. + public void Validate_WhenLibraryTypeIsUnknown_ShouldHaveValidationError(string libraryType) + { + // Arrange + GetLibraryTypeMetadataProvidersQuery query = _getLibraryTypeMetadataProvidersQueryFixture.Create(libraryType: libraryType); + + // Act + List result = _validator.TestValidate(query); + + // Assert + result.ShouldHaveValidationError(Errors.Library.UnknownLibraryType); + } + + [Theory] + [InlineData("Book")] + [InlineData("music")] // The casing of the type is ignored. + public void Validate_WhenLibraryTypeIsValid_ShouldNotHaveValidationError(string libraryType) + { + // Arrange + GetLibraryTypeMetadataProvidersQuery query = _getLibraryTypeMetadataProvidersQueryFixture.Create(libraryType: libraryType); + + // Act + List result = _validator.TestValidate(query); + + // Assert + result.ShouldNotHaveValidationError(Errors.Library.LibraryTypeCannotBeNull); + result.ShouldNotHaveValidationError(Errors.Library.UnknownLibraryType); + } +} diff --git a/tests/UnitTests/Lumina.Domain.UnitTests/Common/Errors/ErrorsTests.cs b/tests/UnitTests/Lumina.Domain.UnitTests/Common/Errors/ErrorsTests.cs index 702123cc..18192ffa 100644 --- a/tests/UnitTests/Lumina.Domain.UnitTests/Common/Errors/ErrorsTests.cs +++ b/tests/UnitTests/Lumina.Domain.UnitTests/Common/Errors/ErrorsTests.cs @@ -348,8 +348,8 @@ public class ErrorsTests AssertError(DomainErrors.Plugins.PluginIdCannotBeEmpty, ErrorType.Validation); AssertError(DomainErrors.Plugins.PluginSettingsCannotBeNull, ErrorType.Validation); AssertError(DomainErrors.Plugins.LibraryIdCannotBeEmpty, ErrorType.Validation); - AssertError(DomainErrors.Plugins.PluginIdsListCannotBeNull, ErrorType.Validation); - AssertError(DomainErrors.Plugins.PluginIdsListCannotBeEmpty, ErrorType.Validation); + AssertError(DomainErrors.Plugins.PluginIdsMustBeUnique, ErrorType.Validation); + AssertError(DomainErrors.Plugins.PluginNotSupportedForLibraryType, ErrorType.Validation); AssertError(DomainErrors.Plugins.LibraryMetadataProviderConfigurationNotFound, ErrorType.NotFound); AssertError(DomainErrors.Plugins.PluginArchiveCannotBeNull, ErrorType.Validation); AssertError(DomainErrors.Plugins.PluginFileNameCannotBeEmpty, ErrorType.Validation); diff --git a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/MediaLibrary/Management/Scanning/Queue/MediaLibraryScanProcessorJobTests.cs b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/MediaLibrary/Management/Scanning/Queue/MediaLibraryScanProcessorJobTests.cs index 937c54c5..a78b2f23 100644 --- a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/MediaLibrary/Management/Scanning/Queue/MediaLibraryScanProcessorJobTests.cs +++ b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/MediaLibrary/Management/Scanning/Queue/MediaLibraryScanProcessorJobTests.cs @@ -84,10 +84,13 @@ public class MediaLibraryScanProcessorJobTests : IDisposable RegisterScan(firstScanId, LibraryScanJobStatus.Pending); RegisterScan(secondScanId, LibraryScanJobStatus.Pending); TaskCompletionSource releaseFirstScan = new(TaskCreationOptions.RunContinuationsAsynchronously); + // ExecutionStarted is signaled before the callback runs, and resumes the test on another thread, so the test waits for the callback itself to record the scan + TaskCompletionSource firstScanRecorded = new(TaskCreationOptions.RunContinuationsAsynchronously); List startedScanIds = []; FakeMediaLibraryScanDiscoveryJob firstRootJob = _mediaLibraryScanDiscoveryJobFixture.Create(onExecute: async _ => { startedScanIds.Add(firstScanId.ScanId.Value); + firstScanRecorded.SetResult(); await releaseFirstScan.Task; }); FakeMediaLibraryScanDiscoveryJob secondRootJob = _mediaLibraryScanDiscoveryJobFixture.Create(onExecute: _ => @@ -102,7 +105,7 @@ public class MediaLibraryScanProcessorJobTests : IDisposable // Act _queue.Writer.TryWrite(firstScanId); _queue.Writer.TryWrite(secondScanId); - await firstRootJob.ExecutionStarted.WaitAsync(s_testTimeout); + await firstScanRecorded.Task.WaitAsync(s_testTimeout); // Assert // The second scan must not start while the job graph of the first one is still executing. diff --git a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Plugins/MediaLibraryProviderConfigurationStoreTests.cs b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Plugins/MediaLibraryProviderConfigurationStoreTests.cs index 762ff669..0880b85e 100644 --- a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Plugins/MediaLibraryProviderConfigurationStoreTests.cs +++ b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Plugins/MediaLibraryProviderConfigurationStoreTests.cs @@ -2,6 +2,7 @@ using Lumina.Application.Common.DataAccess.Entities.Plugins; using Lumina.Application.Common.DataAccess.Repositories.Plugins; using Lumina.Application.Common.DataAccess.UoW; +using Lumina.Application.Common.DTO.MediaLibrary.Management; using Lumina.Application.Common.Infrastructure.Plugins; using Lumina.Application.Common.Infrastructure.Reading; using Lumina.Application.Fixtures.Common.DataAccess.Entities.Plugins; @@ -19,6 +20,7 @@ using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Threading; using System.Threading.Tasks; +using DomainErrors = Lumina.Domain.Common.Errors.Errors; #endregion namespace Lumina.Infrastructure.UnitTests.Core.Plugins; @@ -173,7 +175,7 @@ public class MediaLibraryProviderConfigurationStoreTests } [Fact] - public async Task ReconcileProviderConfigurationsAsync_WhenCalled_ShouldRemoveStaleConfigurationsAndAddTheSupportedOnes() + public async Task ConfigureProvidersAsync_WhenNoChoicesAreMade_ShouldRemoveStaleConfigurationsAndAddTheSupportedOnes() { // Arrange Guid libraryId = Guid.NewGuid(); @@ -198,7 +200,7 @@ public class MediaLibraryProviderConfigurationStoreTests .Returns(Result.Updated); // Act - Result result = await sut.ReconcileProviderConfigurationsAsync(libraryId, LibraryType.EBook, CancellationToken.None); + Result result = await sut.ConfigureProvidersAsync(libraryId, LibraryType.EBook, null, null, null, shouldReconcileOmittedKinds: true, CancellationToken.None); // Assert Assert.False(result.IsFailure); @@ -339,7 +341,7 @@ public class MediaLibraryProviderConfigurationStoreTests } [Fact] - public async Task EnsureBookReaderConfigurationsAsync_WhenBookReaderSupportsTheLibraryType_ShouldAddDisabledConfiguration() + public async Task EnsureProviderConfigurationsAsync_WhenABookReaderSupportsTheLibraryType_ShouldAddADisabledBookReaderConfiguration() { // Arrange Guid libraryId = Guid.NewGuid(); @@ -353,17 +355,20 @@ public class MediaLibraryProviderConfigurationStoreTests .Returns(Result.Updated); // Act - Result result = await sut.EnsureBookReaderConfigurationsAsync(libraryId, LibraryType.EBook, CancellationToken.None); + Result result = await sut.EnsureProviderConfigurationsAsync(libraryId, LibraryType.EBook, CancellationToken.None); // Assert Assert.False(result.IsFailure); await _mockBookReaderConfigurationRepository.Received(1).UpsertAsync( Arg.Is(configuration => configuration.PluginId == pluginId && !configuration.IsEnabled), Arg.Any()); + // The reader is ensured exactly once, since a second ensure in the same scope would not see the staged row and would add a duplicate. + await _mockBookReaderConfigurationRepository.Received(1).GetByLibraryIdAsync(libraryId, Arg.Any()); + await _mockBookReaderConfigurationRepository.Received(1).UpsertAsync(Arg.Any(), Arg.Any()); } [Fact] - public async Task EnsureBookReaderConfigurationsAsync_WhenConfigurationAlreadyExists_ShouldNotAddAnotherOne() + public async Task EnsureProviderConfigurationsAsync_WhenTheBookReaderConfigurationAlreadyExists_ShouldNotAddAnotherBookReaderConfiguration() { // Arrange Guid libraryId = Guid.NewGuid(); @@ -376,7 +381,7 @@ public class MediaLibraryProviderConfigurationStoreTests .Returns(Result.From>([existingConfiguration])); // Act - Result result = await sut.EnsureBookReaderConfigurationsAsync(libraryId, LibraryType.EBook, CancellationToken.None); + Result result = await sut.EnsureProviderConfigurationsAsync(libraryId, LibraryType.EBook, CancellationToken.None); // Assert Assert.False(result.IsFailure); @@ -384,7 +389,7 @@ public class MediaLibraryProviderConfigurationStoreTests } [Fact] - public async Task EnsureBookReaderConfigurationsAsync_WhenNoBookReaderSupportsTheLibraryType_ShouldNotAddConfiguration() + public async Task EnsureProviderConfigurationsAsync_WhenNoBookReaderSupportsTheLibraryType_ShouldNotAddABookReaderConfiguration() { // Arrange Guid libraryId = Guid.NewGuid(); @@ -394,7 +399,7 @@ public class MediaLibraryProviderConfigurationStoreTests MediaLibraryProviderConfigurationStore sut = CreateSut((pluginId, null, null, CreateBookReader(LibraryType.Movie, ".epub"))); // Act - Result result = await sut.EnsureBookReaderConfigurationsAsync(libraryId, LibraryType.EBook, CancellationToken.None); + Result result = await sut.EnsureProviderConfigurationsAsync(libraryId, LibraryType.EBook, CancellationToken.None); // Assert Assert.False(result.IsFailure); @@ -403,7 +408,7 @@ public class MediaLibraryProviderConfigurationStoreTests } [Fact] - public async Task EnsureBookReaderConfigurationsAsync_WhenReaderDeclaresNoExtension_ShouldNotAddConfiguration() + public async Task EnsureProviderConfigurationsAsync_WhenTheBookReaderDeclaresNoExtension_ShouldNotAddABookReaderConfiguration() { // Arrange Guid libraryId = Guid.NewGuid(); @@ -413,7 +418,7 @@ public class MediaLibraryProviderConfigurationStoreTests MediaLibraryProviderConfigurationStore sut = CreateSut((pluginId, null, null, CreateBookReader(LibraryType.EBook, supportedExtension: null))); // Act - Result result = await sut.EnsureBookReaderConfigurationsAsync(libraryId, LibraryType.EBook, CancellationToken.None); + Result result = await sut.EnsureProviderConfigurationsAsync(libraryId, LibraryType.EBook, CancellationToken.None); // Assert Assert.False(result.IsFailure); @@ -421,7 +426,7 @@ public class MediaLibraryProviderConfigurationStoreTests } [Fact] - public async Task EnsureBookReaderConfigurationsAsync_WhenReadingConfigurationsFails_ShouldReturnError() + public async Task EnsureProviderConfigurationsAsync_WhenReadingBookReaderConfigurationsFails_ShouldReturnError() { // Arrange Guid libraryId = Guid.NewGuid(); @@ -433,14 +438,14 @@ public class MediaLibraryProviderConfigurationStoreTests .Returns(Error.Failure(description: "Failed to read configurations")); // Act - Result result = await sut.EnsureBookReaderConfigurationsAsync(libraryId, LibraryType.EBook, CancellationToken.None); + Result result = await sut.EnsureProviderConfigurationsAsync(libraryId, LibraryType.EBook, CancellationToken.None); // Assert Assert.True(result.IsFailure); } [Fact] - public async Task EnsureBookReaderConfigurationsAsync_WhenUpsertFails_ShouldReturnError() + public async Task EnsureProviderConfigurationsAsync_WhenUpsertingBookReaderConfigurationFails_ShouldReturnError() { // Arrange Guid libraryId = Guid.NewGuid(); @@ -454,14 +459,14 @@ public class MediaLibraryProviderConfigurationStoreTests .Returns(Error.Failure(description: "Failed to persist the configuration")); // Act - Result result = await sut.EnsureBookReaderConfigurationsAsync(libraryId, LibraryType.EBook, CancellationToken.None); + Result result = await sut.EnsureProviderConfigurationsAsync(libraryId, LibraryType.EBook, CancellationToken.None); // Assert Assert.True(result.IsFailure); } [Fact] - public async Task ReconcileBookReaderConfigurationsAsync_WhenCalled_ShouldRemoveStaleAndAddTheSupportedBookReaders() + public async Task ConfigureProvidersAsync_WhenOmittedBookReadersAreReconciled_ShouldRemoveStaleAndAddTheSupportedBookReaders() { // Arrange Guid libraryId = Guid.NewGuid(); @@ -474,6 +479,7 @@ public class MediaLibraryProviderConfigurationStoreTests (alphaPluginId, null, null, CreateBookReader(LibraryType.Book, ".pdf")), (betaPluginId, null, null, CreateBookReader(LibraryType.EBook, ".epub"))); LibraryBookReaderConfigurationEntity existingConfiguration = _libraryBookReaderConfigurationEntityFixture.Create(libraryId: libraryId, pluginId: alphaPluginId); + StubConfigurations(libraryId, [], [], []); _mockBookReaderConfigurationRepository.GetByLibraryIdAsync(libraryId, Arg.Any()) .Returns(Result.From>([existingConfiguration])); _mockBookReaderConfigurationRepository.DeleteByLibraryIdAndPluginIdsAsync(libraryId, Arg.Any>(), Arg.Any()) @@ -482,7 +488,7 @@ public class MediaLibraryProviderConfigurationStoreTests .Returns(Result.Updated); // Act - Result result = await sut.ReconcileBookReaderConfigurationsAsync(libraryId, LibraryType.EBook, CancellationToken.None); + Result result = await sut.ConfigureProvidersAsync(libraryId, LibraryType.EBook, null, null, null, shouldReconcileOmittedKinds: true, CancellationToken.None); // Assert Assert.False(result.IsFailure); @@ -493,10 +499,11 @@ public class MediaLibraryProviderConfigurationStoreTests Arg.Any()); await _mockBookReaderConfigurationRepository.DidNotReceive().UpsertAsync( Arg.Is(configuration => configuration.PluginId == alphaPluginId), Arg.Any()); + _mockEnablementCache.Received(1).InvalidateLibrary(libraryId); } [Fact] - public async Task ReconcileBookReaderConfigurationsAsync_WhenReadingConfigurationsFails_ShouldReturnError() + public async Task ConfigureProvidersAsync_WhenReconcilingBookReadersFailsToReadTheirConfigurations_ShouldReturnError() { // Arrange Guid libraryId = Guid.NewGuid(); @@ -504,18 +511,19 @@ public class MediaLibraryProviderConfigurationStoreTests IPlugin plugin = CreatePlugin(pluginId, "Reader Plugin"); _mockPluginManager.GetPlugins().Returns([plugin]); MediaLibraryProviderConfigurationStore sut = CreateSut((pluginId, null, null, CreateBookReader(LibraryType.EBook, ".epub"))); + StubConfigurations(libraryId, [], [], []); _mockBookReaderConfigurationRepository.GetByLibraryIdAsync(libraryId, Arg.Any()) .Returns(Error.Failure(description: "Failed to read configurations")); // Act - Result result = await sut.ReconcileBookReaderConfigurationsAsync(libraryId, LibraryType.EBook, CancellationToken.None); + Result result = await sut.ConfigureProvidersAsync(libraryId, LibraryType.EBook, null, null, null, shouldReconcileOmittedKinds: true, CancellationToken.None); // Assert Assert.True(result.IsFailure); } [Fact] - public async Task ReconcileBookReaderConfigurationsAsync_WhenDeletingStaleConfigurationsFails_ShouldReturnError() + public async Task ConfigureProvidersAsync_WhenReconcilingBookReadersFailsToDeleteStaleConfigurations_ShouldReturnError() { // Arrange Guid libraryId = Guid.NewGuid(); @@ -525,20 +533,21 @@ public class MediaLibraryProviderConfigurationStoreTests _mockPluginManager.GetPlugins().Returns([plugin]); MediaLibraryProviderConfigurationStore sut = CreateSut((pluginId, null, null, CreateBookReader(LibraryType.EBook, ".epub"))); LibraryBookReaderConfigurationEntity staleConfiguration = _libraryBookReaderConfigurationEntityFixture.Create(libraryId: libraryId, pluginId: stalePluginId); + StubConfigurations(libraryId, [], [], []); _mockBookReaderConfigurationRepository.GetByLibraryIdAsync(libraryId, Arg.Any()) .Returns(Result.From>([staleConfiguration])); _mockBookReaderConfigurationRepository.DeleteByLibraryIdAndPluginIdsAsync(libraryId, Arg.Any>(), Arg.Any()) .Returns(Error.Failure(description: "Failed to delete the configurations")); // Act - Result result = await sut.ReconcileBookReaderConfigurationsAsync(libraryId, LibraryType.EBook, CancellationToken.None); + Result result = await sut.ConfigureProvidersAsync(libraryId, LibraryType.EBook, null, null, null, shouldReconcileOmittedKinds: true, CancellationToken.None); // Assert Assert.True(result.IsFailure); } [Fact] - public async Task ReconcileBookReaderConfigurationsAsync_WhenUpsertFails_ShouldReturnError() + public async Task ConfigureProvidersAsync_WhenReconcilingBookReadersFailsToUpsertAConfiguration_ShouldReturnError() { // Arrange Guid libraryId = Guid.NewGuid(); @@ -546,90 +555,21 @@ public class MediaLibraryProviderConfigurationStoreTests IPlugin plugin = CreatePlugin(pluginId, "Reader Plugin"); _mockPluginManager.GetPlugins().Returns([plugin]); MediaLibraryProviderConfigurationStore sut = CreateSut((pluginId, null, null, CreateBookReader(LibraryType.EBook, ".epub"))); + StubConfigurations(libraryId, [], [], []); _mockBookReaderConfigurationRepository.GetByLibraryIdAsync(libraryId, Arg.Any()) .Returns(Result.From>([])); _mockBookReaderConfigurationRepository.UpsertAsync(Arg.Any(), Arg.Any()) .Returns(Error.Failure(description: "Failed to persist the configuration")); // Act - Result result = await sut.ReconcileBookReaderConfigurationsAsync(libraryId, LibraryType.EBook, CancellationToken.None); + Result result = await sut.ConfigureProvidersAsync(libraryId, LibraryType.EBook, null, null, null, shouldReconcileOmittedKinds: true, CancellationToken.None); // Assert Assert.True(result.IsFailure); } [Fact] - public async Task RemoveBookReaderConfigurationsForLibraryAsync_WhenCalled_ShouldDeleteTheConfigurationsOfTheLibrary() - { - // Arrange - Guid libraryId = Guid.NewGuid(); - _mockBookReaderConfigurationRepository.DeleteByLibraryIdAsync(libraryId, Arg.Any()) - .Returns(Result.Deleted); - MediaLibraryProviderConfigurationStore sut = CreateSut(); - - // Act - Result result = await sut.RemoveBookReaderConfigurationsForLibraryAsync(libraryId, CancellationToken.None); - - // Assert - Assert.False(result.IsFailure); - await _mockBookReaderConfigurationRepository.Received(1).DeleteByLibraryIdAsync(libraryId, Arg.Any()); - _mockEnablementCache.Received(1).InvalidateLibrary(libraryId); - } - - [Fact] - public async Task RemoveBookReaderConfigurationsForLibraryAsync_WhenDeletionFails_ShouldReturnError() - { - // Arrange - Guid libraryId = Guid.NewGuid(); - _mockBookReaderConfigurationRepository.DeleteByLibraryIdAsync(libraryId, Arg.Any()) - .Returns(Error.Failure(description: "Failed to delete the configurations")); - MediaLibraryProviderConfigurationStore sut = CreateSut(); - - // Act - Result result = await sut.RemoveBookReaderConfigurationsForLibraryAsync(libraryId, CancellationToken.None); - - // Assert - Assert.True(result.IsFailure); - _mockEnablementCache.DidNotReceive().InvalidateLibrary(Arg.Any()); - } - - [Fact] - public async Task RemoveBookReaderConfigurationsAsync_WhenCalled_ShouldDeleteTheConfigurationsOfThePlugin() - { - // Arrange - Guid pluginId = Guid.NewGuid(); - _mockBookReaderConfigurationRepository.DeleteByPluginIdAsync(pluginId, Arg.Any()) - .Returns(Result.Deleted); - MediaLibraryProviderConfigurationStore sut = CreateSut(); - - // Act - Result result = await sut.RemoveBookReaderConfigurationsAsync(pluginId, CancellationToken.None); - - // Assert - Assert.False(result.IsFailure); - await _mockBookReaderConfigurationRepository.Received(1).DeleteByPluginIdAsync(pluginId, Arg.Any()); - _mockEnablementCache.Received(1).InvalidatePlugin(pluginId); - } - - [Fact] - public async Task RemoveBookReaderConfigurationsAsync_WhenDeletionFails_ShouldReturnError() - { - // Arrange - Guid pluginId = Guid.NewGuid(); - _mockBookReaderConfigurationRepository.DeleteByPluginIdAsync(pluginId, Arg.Any()) - .Returns(Error.Failure(description: "Failed to delete the configurations")); - MediaLibraryProviderConfigurationStore sut = CreateSut(); - - // Act - Result result = await sut.RemoveBookReaderConfigurationsAsync(pluginId, CancellationToken.None); - - // Assert - Assert.True(result.IsFailure); - _mockEnablementCache.DidNotReceive().InvalidatePlugin(Arg.Any()); - } - - [Fact] - public async Task ReconcileProviderConfigurationsAsync_WhenArtworkConfigurationsAreStale_ShouldDeleteAndAddThem() + public async Task ConfigureProvidersAsync_WhenNoChoicesAreMadeAndArtworkConfigurationsAreStale_ShouldDeleteAndAddThem() { // Arrange Guid libraryId = Guid.NewGuid(); @@ -654,7 +594,7 @@ public class MediaLibraryProviderConfigurationStoreTests .Returns(Result.Updated); // Act - Result result = await sut.ReconcileProviderConfigurationsAsync(libraryId, LibraryType.EBook, CancellationToken.None); + Result result = await sut.ConfigureProvidersAsync(libraryId, LibraryType.EBook, null, null, null, shouldReconcileOmittedKinds: true, CancellationToken.None); // Assert Assert.False(result.IsFailure); @@ -666,7 +606,7 @@ public class MediaLibraryProviderConfigurationStoreTests } [Fact] - public async Task ReconcileProviderConfigurationsAsync_WhenDeletingStaleArtworkConfigurationsFails_ShouldReturnError() + public async Task ConfigureProvidersAsync_WhenNoChoicesAreMadeAndDeletingStaleArtworkConfigurationsFails_ShouldReturnError() { // Arrange Guid libraryId = Guid.NewGuid(); @@ -683,7 +623,7 @@ public class MediaLibraryProviderConfigurationStoreTests .Returns(Error.Failure(description: "Failed to delete the configurations")); // Act - Result result = await sut.ReconcileProviderConfigurationsAsync(libraryId, LibraryType.EBook, CancellationToken.None); + Result result = await sut.ConfigureProvidersAsync(libraryId, LibraryType.EBook, null, null, null, shouldReconcileOmittedKinds: true, CancellationToken.None); // Assert Assert.True(result.IsFailure); @@ -780,7 +720,7 @@ public class MediaLibraryProviderConfigurationStoreTests } [Fact] - public async Task ReconcileProviderConfigurationsAsync_WhenMetadataProviderIsAlreadyConfigured_ShouldKeepItWithoutUpserting() + public async Task ConfigureProvidersAsync_WhenNoChoicesAreMadeAndMetadataProviderIsAlreadyConfigured_ShouldKeepItWithoutUpserting() { // Arrange Guid libraryId = Guid.NewGuid(); @@ -797,7 +737,7 @@ public class MediaLibraryProviderConfigurationStoreTests .Returns(Result.From>([])); // Act - Result result = await sut.ReconcileProviderConfigurationsAsync(libraryId, LibraryType.EBook, CancellationToken.None); + Result result = await sut.ConfigureProvidersAsync(libraryId, LibraryType.EBook, null, null, null, shouldReconcileOmittedKinds: true, CancellationToken.None); // Assert Assert.False(result.IsFailure); @@ -806,7 +746,7 @@ public class MediaLibraryProviderConfigurationStoreTests } [Fact] - public async Task ReconcileProviderConfigurationsAsync_WhenArtworkProviderIsAlreadyConfigured_ShouldKeepItWithoutUpserting() + public async Task ConfigureProvidersAsync_WhenNoChoicesAreMadeAndArtworkProviderIsAlreadyConfigured_ShouldKeepItWithoutUpserting() { // Arrange Guid libraryId = Guid.NewGuid(); @@ -823,7 +763,7 @@ public class MediaLibraryProviderConfigurationStoreTests .Returns(Result.From>([])); // Act - Result result = await sut.ReconcileProviderConfigurationsAsync(libraryId, LibraryType.EBook, CancellationToken.None); + Result result = await sut.ConfigureProvidersAsync(libraryId, LibraryType.EBook, null, null, null, shouldReconcileOmittedKinds: true, CancellationToken.None); // Assert Assert.False(result.IsFailure); @@ -832,7 +772,7 @@ public class MediaLibraryProviderConfigurationStoreTests } [Fact] - public async Task ReconcileProviderConfigurationsAsync_WhenReadingMetadataConfigurationsFails_ShouldReturnError() + public async Task ConfigureProvidersAsync_WhenNoChoicesAreMadeAndReadingMetadataConfigurationsFails_ShouldReturnError() { // Arrange Guid libraryId = Guid.NewGuid(); @@ -844,7 +784,7 @@ public class MediaLibraryProviderConfigurationStoreTests .Returns(Error.Failure(description: "Failed to read configurations")); // Act - Result result = await sut.ReconcileProviderConfigurationsAsync(libraryId, LibraryType.EBook, CancellationToken.None); + Result result = await sut.ConfigureProvidersAsync(libraryId, LibraryType.EBook, null, null, null, shouldReconcileOmittedKinds: true, CancellationToken.None); // Assert Assert.True(result.IsFailure); @@ -853,7 +793,7 @@ public class MediaLibraryProviderConfigurationStoreTests } [Fact] - public async Task ReconcileProviderConfigurationsAsync_WhenDeletingStaleMetadataConfigurationsFails_ShouldReturnError() + public async Task ConfigureProvidersAsync_WhenNoChoicesAreMadeAndDeletingStaleMetadataConfigurationsFails_ShouldReturnError() { // Arrange Guid libraryId = Guid.NewGuid(); @@ -868,14 +808,14 @@ public class MediaLibraryProviderConfigurationStoreTests .Returns(Error.Failure(description: "Failed to delete the configurations")); // Act - Result result = await sut.ReconcileProviderConfigurationsAsync(libraryId, LibraryType.EBook, CancellationToken.None); + Result result = await sut.ConfigureProvidersAsync(libraryId, LibraryType.EBook, null, null, null, shouldReconcileOmittedKinds: true, CancellationToken.None); // Assert Assert.True(result.IsFailure); } [Fact] - public async Task ReconcileProviderConfigurationsAsync_WhenUpsertingMetadataConfigurationFails_ShouldReturnError() + public async Task ConfigureProvidersAsync_WhenNoChoicesAreMadeAndUpsertingMetadataConfigurationFails_ShouldReturnError() { // Arrange Guid libraryId = Guid.NewGuid(); @@ -889,7 +829,7 @@ public class MediaLibraryProviderConfigurationStoreTests .Returns(Error.Failure(description: "Failed to persist the configuration")); // Act - Result result = await sut.ReconcileProviderConfigurationsAsync(libraryId, LibraryType.EBook, CancellationToken.None); + Result result = await sut.ConfigureProvidersAsync(libraryId, LibraryType.EBook, null, null, null, shouldReconcileOmittedKinds: true, CancellationToken.None); // Assert Assert.True(result.IsFailure); @@ -897,7 +837,7 @@ public class MediaLibraryProviderConfigurationStoreTests } [Fact] - public async Task ReconcileProviderConfigurationsAsync_WhenReadingArtworkConfigurationsFails_ShouldReturnError() + public async Task ConfigureProvidersAsync_WhenNoChoicesAreMadeAndReadingArtworkConfigurationsFails_ShouldReturnError() { // Arrange Guid libraryId = Guid.NewGuid(); @@ -911,7 +851,7 @@ public class MediaLibraryProviderConfigurationStoreTests .Returns(Error.Failure(description: "Failed to read configurations")); // Act - Result result = await sut.ReconcileProviderConfigurationsAsync(libraryId, LibraryType.EBook, CancellationToken.None); + Result result = await sut.ConfigureProvidersAsync(libraryId, LibraryType.EBook, null, null, null, shouldReconcileOmittedKinds: true, CancellationToken.None); // Assert Assert.True(result.IsFailure); @@ -919,7 +859,7 @@ public class MediaLibraryProviderConfigurationStoreTests } [Fact] - public async Task ReconcileProviderConfigurationsAsync_WhenUpsertingArtworkConfigurationFails_ShouldReturnError() + public async Task ConfigureProvidersAsync_WhenNoChoicesAreMadeAndUpsertingArtworkConfigurationFails_ShouldReturnError() { // Arrange Guid libraryId = Guid.NewGuid(); @@ -935,7 +875,7 @@ public class MediaLibraryProviderConfigurationStoreTests .Returns(Error.Failure(description: "Failed to persist the configuration")); // Act - Result result = await sut.ReconcileProviderConfigurationsAsync(libraryId, LibraryType.EBook, CancellationToken.None); + Result result = await sut.ConfigureProvidersAsync(libraryId, LibraryType.EBook, null, null, null, shouldReconcileOmittedKinds: true, CancellationToken.None); // Assert Assert.True(result.IsFailure); @@ -943,7 +883,7 @@ public class MediaLibraryProviderConfigurationStoreTests } [Fact] - public async Task ReconcileBookReaderConfigurationsAsync_WhenConfigurationAlreadyExists_ShouldKeepItWithoutUpserting() + public async Task ConfigureProvidersAsync_WhenNoChoicesAreMadeAndBookReaderConfigurationAlreadyExists_ShouldKeepItWithoutUpserting() { // Arrange Guid libraryId = Guid.NewGuid(); @@ -960,7 +900,7 @@ public class MediaLibraryProviderConfigurationStoreTests .Returns(Result.From>([existingConfiguration])); // Act - Result result = await sut.ReconcileProviderConfigurationsAsync(libraryId, LibraryType.EBook, CancellationToken.None); + Result result = await sut.ConfigureProvidersAsync(libraryId, LibraryType.EBook, null, null, null, shouldReconcileOmittedKinds: true, CancellationToken.None); // Assert Assert.False(result.IsFailure); @@ -1010,6 +950,505 @@ public class MediaLibraryProviderConfigurationStoreTests await _mockMetadataConfigurationRepository.DidNotReceive().GetByLibraryIdAsync(Arg.Any(), Arg.Any()); } + [Fact] + public async Task ConfigureProvidersAsync_WhenMetadataProviderChoicesAreMade_ShouldApplyTheirOrderAndEnabledState() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + Guid alphaPluginId = Guid.NewGuid(); + Guid betaPluginId = Guid.NewGuid(); + IPlugin[] plugins = [CreatePlugin(alphaPluginId, "Alpha"), CreatePlugin(betaPluginId, "Beta")]; + _mockPluginManager.GetPlugins().Returns(plugins); + MediaLibraryProviderConfigurationStore sut = CreateSut( + (alphaPluginId, CreateMetadataProvider(LibraryType.Book), null, null), + (betaPluginId, CreateMetadataProvider(LibraryType.Book), null, null)); + LibraryMetadataProviderConfigurationEntity alphaConfiguration = _libraryMetadataProviderConfigurationEntityFixture.Create(libraryId, alphaPluginId, 1, isEnabled: true); + StubConfigurations(libraryId, [alphaConfiguration], [], []); + LibraryProviderSelectionDto[] metadataProviders = [new(betaPluginId, IsEnabled: true), new(alphaPluginId, IsEnabled: false)]; + + // Act + Result result = await sut.ConfigureProvidersAsync(libraryId, LibraryType.Book, metadataProviders, null, null, shouldReconcileOmittedKinds: false, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + await _mockMetadataConfigurationRepository.Received(1).UpsertAsync( + Arg.Is(configuration => configuration.PluginId == betaPluginId && configuration.LibraryId == libraryId && configuration.Rank == 1 && configuration.IsEnabled), + Arg.Any()); + await _mockMetadataConfigurationRepository.Received(1).UpsertAsync( + Arg.Is(configuration => configuration.PluginId == alphaPluginId && configuration.Id == alphaConfiguration.Id && configuration.Rank == 2 && !configuration.IsEnabled), + Arg.Any()); + await _mockMetadataConfigurationRepository.DidNotReceive().DeleteByLibraryIdAndPluginIdsAsync(Arg.Any(), Arg.Any>(), Arg.Any()); + } + + [Fact] + public async Task ConfigureProvidersAsync_WhenASupportedMetadataProviderIsNotNamed_ShouldKeepItsStoredStateAfterTheNamedProviders() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + Guid alphaPluginId = Guid.NewGuid(); + Guid betaPluginId = Guid.NewGuid(); + Guid gammaPluginId = Guid.NewGuid(); + IPlugin[] plugins = [CreatePlugin(alphaPluginId, "Alpha"), CreatePlugin(betaPluginId, "Beta"), CreatePlugin(gammaPluginId, "Gamma")]; + _mockPluginManager.GetPlugins().Returns(plugins); + MediaLibraryProviderConfigurationStore sut = CreateSut( + (alphaPluginId, CreateMetadataProvider(LibraryType.Book), null, null), + (betaPluginId, CreateMetadataProvider(LibraryType.Book), null, null), + (gammaPluginId, CreateMetadataProvider(LibraryType.Book), null, null)); + LibraryMetadataProviderConfigurationEntity gammaConfiguration = _libraryMetadataProviderConfigurationEntityFixture.Create(libraryId, gammaPluginId, 1, isEnabled: true); + StubConfigurations(libraryId, [gammaConfiguration], [], []); + LibraryProviderSelectionDto[] metadataProviders = [new(betaPluginId, IsEnabled: false)]; + + // Act + Result result = await sut.ConfigureProvidersAsync(libraryId, LibraryType.Book, metadataProviders, null, null, shouldReconcileOmittedKinds: false, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + await _mockMetadataConfigurationRepository.Received(1).UpsertAsync( + Arg.Is(configuration => configuration.PluginId == betaPluginId && configuration.Rank == 1 && !configuration.IsEnabled), + Arg.Any()); + await _mockMetadataConfigurationRepository.Received(1).UpsertAsync( + Arg.Is(configuration => configuration.PluginId == gammaPluginId && configuration.Rank == 2 && configuration.IsEnabled), + Arg.Any()); + await _mockMetadataConfigurationRepository.Received(1).UpsertAsync( + Arg.Is(configuration => configuration.PluginId == alphaPluginId && configuration.Rank == 3 && !configuration.IsEnabled), + Arg.Any()); + } + + [Fact] + public async Task ConfigureProvidersAsync_WhenAMetadataProviderChoiceNamesAnUnsupportedPlugin_ShouldReturnErrorWithoutChangingConfigurations() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + Guid pluginId = Guid.NewGuid(); + IPlugin[] plugins = [CreatePlugin(pluginId, "Alpha")]; + _mockPluginManager.GetPlugins().Returns(plugins); + MediaLibraryProviderConfigurationStore sut = CreateSut((pluginId, CreateMetadataProvider(LibraryType.Book), null, null)); + StubConfigurations(libraryId, [], [], []); + LibraryProviderSelectionDto[] metadataProviders = [new(Guid.NewGuid(), IsEnabled: true)]; + + // Act + Result result = await sut.ConfigureProvidersAsync(libraryId, LibraryType.Book, metadataProviders, null, null, shouldReconcileOmittedKinds: false, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(DomainErrors.Plugins.PluginNotSupportedForLibraryType, result.FirstError); + await _mockMetadataConfigurationRepository.DidNotReceive().UpsertAsync(Arg.Any(), Arg.Any()); + await _mockArtworkConfigurationRepository.DidNotReceive().GetByLibraryIdAsync(Arg.Any(), Arg.Any()); + } + + [Fact] + public async Task ConfigureProvidersAsync_WhenUpsertingAChosenMetadataProviderFails_ShouldReturnError() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + Guid pluginId = Guid.NewGuid(); + IPlugin[] plugins = [CreatePlugin(pluginId, "Alpha")]; + _mockPluginManager.GetPlugins().Returns(plugins); + MediaLibraryProviderConfigurationStore sut = CreateSut((pluginId, CreateMetadataProvider(LibraryType.Book), null, null)); + StubConfigurations(libraryId, [], [], []); + _mockMetadataConfigurationRepository.UpsertAsync(Arg.Any(), Arg.Any()) + .Returns(Error.Failure(description: "Upsert failed")); + LibraryProviderSelectionDto[] metadataProviders = [new(pluginId, IsEnabled: true)]; + + // Act + Result result = await sut.ConfigureProvidersAsync(libraryId, LibraryType.Book, metadataProviders, null, null, shouldReconcileOmittedKinds: false, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + await _mockArtworkConfigurationRepository.DidNotReceive().GetByLibraryIdAsync(Arg.Any(), Arg.Any()); + } + + [Fact] + public async Task ConfigureProvidersAsync_WhenArtworkProviderChoicesAreMadeAndStaleConfigurationsExist_ShouldDeleteTheStaleOnesAndApplyTheChoices() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + Guid supportedPluginId = Guid.NewGuid(); + Guid stalePluginId = Guid.NewGuid(); + IPlugin[] plugins = [CreatePlugin(supportedPluginId, "Alpha"), CreatePlugin(stalePluginId, "Beta")]; + _mockPluginManager.GetPlugins().Returns(plugins); + MediaLibraryProviderConfigurationStore sut = CreateSut( + (supportedPluginId, null, CreateArtworkProvider(LibraryType.Book), null), + (stalePluginId, null, CreateArtworkProvider(LibraryType.Music), null)); + LibraryArtworkProviderConfigurationEntity staleConfiguration = _libraryArtworkProviderConfigurationEntityFixture.Create(libraryId, stalePluginId, 1); + StubConfigurations(libraryId, [], [staleConfiguration], []); + LibraryProviderSelectionDto[] artworkProviders = [new(supportedPluginId, IsEnabled: true)]; + + // Act + Result result = await sut.ConfigureProvidersAsync(libraryId, LibraryType.Book, null, artworkProviders, null, shouldReconcileOmittedKinds: false, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + await _mockArtworkConfigurationRepository.Received(1).DeleteByLibraryIdAndPluginIdsAsync( + libraryId, Arg.Is>(pluginIds => pluginIds.SequenceEqual(new[] { stalePluginId })), Arg.Any()); + await _mockArtworkConfigurationRepository.Received(1).UpsertAsync( + Arg.Is(configuration => configuration.PluginId == supportedPluginId && configuration.Rank == 1 && configuration.IsEnabled), + Arg.Any()); + await _mockArtworkConfigurationRepository.DidNotReceive().UpsertAsync( + Arg.Is(configuration => configuration.PluginId == stalePluginId), Arg.Any()); + } + + [Fact] + public async Task ConfigureProvidersAsync_WhenAnArtworkProviderChoiceNamesAnUnsupportedPlugin_ShouldReturnError() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + Guid pluginId = Guid.NewGuid(); + IPlugin[] plugins = [CreatePlugin(pluginId, "Alpha")]; + _mockPluginManager.GetPlugins().Returns(plugins); + MediaLibraryProviderConfigurationStore sut = CreateSut((pluginId, null, CreateArtworkProvider(LibraryType.Music), null)); + StubConfigurations(libraryId, [], [], []); + LibraryProviderSelectionDto[] artworkProviders = [new(pluginId, IsEnabled: true)]; + + // Act + Result result = await sut.ConfigureProvidersAsync(libraryId, LibraryType.Book, null, artworkProviders, null, shouldReconcileOmittedKinds: false, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(DomainErrors.Plugins.PluginNotSupportedForLibraryType, result.FirstError); + await _mockArtworkConfigurationRepository.DidNotReceive().UpsertAsync(Arg.Any(), Arg.Any()); + } + + [Fact] + public async Task ConfigureProvidersAsync_WhenBookReaderChoicesAreMade_ShouldApplyTheirEnabledStateAndInvalidateTheEnablementCache() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + Guid epubPluginId = Guid.NewGuid(); + Guid pdfPluginId = Guid.NewGuid(); + IPlugin[] plugins = [CreatePlugin(epubPluginId, "EPUB Reader"), CreatePlugin(pdfPluginId, "PDF Reader")]; + _mockPluginManager.GetPlugins().Returns(plugins); + MediaLibraryProviderConfigurationStore sut = CreateSut( + (epubPluginId, null, null, CreateBookReader(LibraryType.Book, ".epub")), + (pdfPluginId, null, null, CreateBookReader(LibraryType.Book, ".pdf"))); + LibraryBookReaderConfigurationEntity pdfConfiguration = _libraryBookReaderConfigurationEntityFixture.Create(libraryId: libraryId, pluginId: pdfPluginId, isEnabled: true); + StubConfigurations(libraryId, [], [], [pdfConfiguration]); + LibraryProviderSelectionDto[] bookReaders = [new(epubPluginId, IsEnabled: true)]; + + // Act + Result result = await sut.ConfigureProvidersAsync(libraryId, LibraryType.Book, null, null, bookReaders, shouldReconcileOmittedKinds: false, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + await _mockBookReaderConfigurationRepository.Received(1).UpsertAsync( + Arg.Is(configuration => configuration.PluginId == epubPluginId && configuration.LibraryId == libraryId && configuration.IsEnabled), + Arg.Any()); + await _mockBookReaderConfigurationRepository.Received(1).UpsertAsync( + Arg.Is(configuration => configuration.PluginId == pdfPluginId && configuration.IsEnabled), + Arg.Any()); + _mockEnablementCache.Received(1).InvalidateLibrary(libraryId); + } + + [Fact] + public async Task ConfigureProvidersAsync_WhenBookReaderChoicesAreMadeAndStaleConfigurationsExist_ShouldDeleteTheStaleOnesAndApplyTheChoices() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + Guid supportedPluginId = Guid.NewGuid(); + Guid stalePluginId = Guid.NewGuid(); + IPlugin[] plugins = [CreatePlugin(supportedPluginId, "EPUB Reader"), CreatePlugin(stalePluginId, "PDF Reader")]; + _mockPluginManager.GetPlugins().Returns(plugins); + MediaLibraryProviderConfigurationStore sut = CreateSut( + (supportedPluginId, null, null, CreateBookReader(LibraryType.Book, ".epub")), + (stalePluginId, null, null, CreateBookReader(LibraryType.EBook, ".pdf"))); + LibraryBookReaderConfigurationEntity staleConfiguration = _libraryBookReaderConfigurationEntityFixture.Create(libraryId: libraryId, pluginId: stalePluginId, isEnabled: true); + StubConfigurations(libraryId, [], [], [staleConfiguration]); + LibraryProviderSelectionDto[] bookReaders = [new(supportedPluginId, IsEnabled: true)]; + + // Act + Result result = await sut.ConfigureProvidersAsync(libraryId, LibraryType.Book, null, null, bookReaders, shouldReconcileOmittedKinds: false, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + await _mockBookReaderConfigurationRepository.Received(1).DeleteByLibraryIdAndPluginIdsAsync( + libraryId, Arg.Is>(pluginIds => pluginIds.SequenceEqual(new[] { stalePluginId })), Arg.Any()); + await _mockBookReaderConfigurationRepository.Received(1).UpsertAsync( + Arg.Is(configuration => configuration.PluginId == supportedPluginId && configuration.LibraryId == libraryId && configuration.IsEnabled), + Arg.Any()); + await _mockBookReaderConfigurationRepository.DidNotReceive().UpsertAsync( + Arg.Is(configuration => configuration.PluginId == stalePluginId), Arg.Any()); + _mockEnablementCache.Received(1).InvalidateLibrary(libraryId); + } + + [Fact] + public async Task ConfigureProvidersAsync_WhenABookReaderChoiceNamesAnUnsupportedPlugin_ShouldReturnErrorWithoutInvalidatingTheEnablementCache() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + Guid pluginId = Guid.NewGuid(); + IPlugin[] plugins = [CreatePlugin(pluginId, "EPUB Reader")]; + _mockPluginManager.GetPlugins().Returns(plugins); + MediaLibraryProviderConfigurationStore sut = CreateSut((pluginId, null, null, CreateBookReader(LibraryType.Book, ".epub"))); + StubConfigurations(libraryId, [], [], []); + LibraryProviderSelectionDto[] bookReaders = [new(Guid.NewGuid(), IsEnabled: true)]; + + // Act + Result result = await sut.ConfigureProvidersAsync(libraryId, LibraryType.Book, null, null, bookReaders, shouldReconcileOmittedKinds: false, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(DomainErrors.Plugins.PluginNotSupportedForLibraryType, result.FirstError); + await _mockBookReaderConfigurationRepository.DidNotReceive().UpsertAsync(Arg.Any(), Arg.Any()); + _mockEnablementCache.DidNotReceive().InvalidateLibrary(Arg.Any()); + } + + [Fact] + public async Task ConfigureProvidersAsync_WhenNoBookReaderChoicesAreMadeAndOmittedKindsAreNotReconciled_ShouldNotInvalidateTheEnablementCache() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + MediaLibraryProviderConfigurationStore sut = CreateSut(); + StubConfigurations(libraryId, [], [], []); + + // Act + Result result = await sut.ConfigureProvidersAsync(libraryId, LibraryType.Book, null, null, null, shouldReconcileOmittedKinds: false, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + _mockEnablementCache.DidNotReceive().InvalidateLibrary(Arg.Any()); + } + + [Fact] + public async Task ConfigureProvidersAsync_WhenOmittedBookReadersAreReconciled_ShouldRemoveTheStaleReaderAndInvalidateTheEnablementCache() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + Guid stalePluginId = Guid.NewGuid(); + MediaLibraryProviderConfigurationStore sut = CreateSut(); + LibraryBookReaderConfigurationEntity staleConfiguration = _libraryBookReaderConfigurationEntityFixture.Create(libraryId: libraryId, pluginId: stalePluginId, isEnabled: true); + StubConfigurations(libraryId, [], [], [staleConfiguration]); + + // Act + Result result = await sut.ConfigureProvidersAsync(libraryId, LibraryType.Book, null, null, null, shouldReconcileOmittedKinds: true, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + await _mockBookReaderConfigurationRepository.Received(1).DeleteByLibraryIdAndPluginIdsAsync( + libraryId, Arg.Is>(pluginIds => pluginIds.SequenceEqual(new[] { stalePluginId })), Arg.Any()); + _mockEnablementCache.Received(1).InvalidateLibrary(libraryId); + } + + [Fact] + public void GetSupportedMetadataProviderPluginIds_WhenPluginsSupportTheLibraryType_ShouldReturnThemInAlphabeticalOrder() + { + // Arrange + Guid alphaPluginId = Guid.NewGuid(); + Guid betaPluginId = Guid.NewGuid(); + Guid unsupportedPluginId = Guid.NewGuid(); + IPlugin[] plugins = [CreatePlugin(betaPluginId, "Beta"), CreatePlugin(unsupportedPluginId, "Gamma"), CreatePlugin(alphaPluginId, "Alpha")]; + _mockPluginManager.GetPlugins().Returns(plugins); + MediaLibraryProviderConfigurationStore sut = CreateSut( + (alphaPluginId, CreateMetadataProvider(LibraryType.Book), null, null), + (betaPluginId, CreateMetadataProvider(LibraryType.Book), null, null), + (unsupportedPluginId, CreateMetadataProvider(LibraryType.Music), null, null)); + + // Act + IReadOnlyList result = sut.GetSupportedMetadataProviderPluginIds(LibraryType.Book); + + // Assert + Assert.Equal([alphaPluginId, betaPluginId], result); + } + + [Fact] + public void GetSupportedArtworkProviderPluginIds_WhenPluginsSupportTheLibraryType_ShouldReturnThemInAlphabeticalOrder() + { + // Arrange + Guid alphaPluginId = Guid.NewGuid(); + Guid betaPluginId = Guid.NewGuid(); + Guid metadataOnlyPluginId = Guid.NewGuid(); + IPlugin[] plugins = [CreatePlugin(betaPluginId, "Beta"), CreatePlugin(alphaPluginId, "Alpha"), CreatePlugin(metadataOnlyPluginId, "Delta")]; + _mockPluginManager.GetPlugins().Returns(plugins); + MediaLibraryProviderConfigurationStore sut = CreateSut( + (alphaPluginId, null, CreateArtworkProvider(LibraryType.Music), null), + (betaPluginId, null, CreateArtworkProvider(LibraryType.Music), null), + (metadataOnlyPluginId, CreateMetadataProvider(LibraryType.Music), null, null)); + + // Act + IReadOnlyList result = sut.GetSupportedArtworkProviderPluginIds(LibraryType.Music); + + // Assert + Assert.Equal([alphaPluginId, betaPluginId], result); + } + + [Fact] + public void GetSupportedBookReaderPluginIds_WhenAReaderDeclaresNoFileExtension_ShouldLeaveItOut() + { + // Arrange + Guid epubPluginId = Guid.NewGuid(); + Guid extensionlessPluginId = Guid.NewGuid(); + IPlugin[] plugins = [CreatePlugin(epubPluginId, "EPUB Reader"), CreatePlugin(extensionlessPluginId, "Empty Reader")]; + _mockPluginManager.GetPlugins().Returns(plugins); + MediaLibraryProviderConfigurationStore sut = CreateSut( + (epubPluginId, null, null, CreateBookReader(LibraryType.Book, ".epub")), + (extensionlessPluginId, null, null, CreateBookReader(LibraryType.Book, null))); + + // Act + IReadOnlyList result = sut.GetSupportedBookReaderPluginIds(LibraryType.Book); + + // Assert + Assert.Equal([epubPluginId], result); + } + + [Fact] + public async Task ConfigureProvidersAsync_WhenOnlyBookReaderChoicesAreMadeAndOmittedKindsAreNotReconciled_ShouldLeaveTheProviderConfigurationsUntouched() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + Guid pluginId = Guid.NewGuid(); + IPlugin[] plugins = [CreatePlugin(pluginId, "EPUB Reader")]; + _mockPluginManager.GetPlugins().Returns(plugins); + MediaLibraryProviderConfigurationStore sut = CreateSut((pluginId, null, null, CreateBookReader(LibraryType.Book, ".epub"))); + StubConfigurations(libraryId, [], [], []); + LibraryProviderSelectionDto[] bookReaders = [new(pluginId, IsEnabled: true)]; + + // Act + Result result = await sut.ConfigureProvidersAsync(libraryId, LibraryType.Book, null, null, bookReaders, shouldReconcileOmittedKinds: false, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + await _mockBookReaderConfigurationRepository.Received(1).UpsertAsync(Arg.Any(), Arg.Any()); + await _mockMetadataConfigurationRepository.DidNotReceive().GetByLibraryIdAsync(Arg.Any(), Arg.Any()); + await _mockArtworkConfigurationRepository.DidNotReceive().GetByLibraryIdAsync(Arg.Any(), Arg.Any()); + await _mockMetadataConfigurationRepository.DidNotReceive().DeleteByLibraryIdAndPluginIdsAsync(Arg.Any(), Arg.Any>(), Arg.Any()); + await _mockArtworkConfigurationRepository.DidNotReceive().DeleteByLibraryIdAndPluginIdsAsync(Arg.Any(), Arg.Any>(), Arg.Any()); + } + + [Fact] + public async Task ConfigureProvidersAsync_WhenNoChoicesAreMadeAndOmittedKindsAreNotReconciled_ShouldNotTouchAnyConfiguration() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + MediaLibraryProviderConfigurationStore sut = CreateSut(); + StubConfigurations(libraryId, [], [], []); + + // Act + Result result = await sut.ConfigureProvidersAsync(libraryId, LibraryType.Book, null, null, null, shouldReconcileOmittedKinds: false, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + await _mockMetadataConfigurationRepository.DidNotReceive().GetByLibraryIdAsync(Arg.Any(), Arg.Any()); + await _mockArtworkConfigurationRepository.DidNotReceive().GetByLibraryIdAsync(Arg.Any(), Arg.Any()); + await _mockBookReaderConfigurationRepository.DidNotReceive().GetByLibraryIdAsync(Arg.Any(), Arg.Any()); + _mockEnablementCache.DidNotReceive().InvalidateLibrary(Arg.Any()); + } + + [Fact] + public async Task ConfigureProvidersAsync_WhenAChoiceHasNoEnabledState_ShouldKeepTheStoredStateAndApplyTheOrder() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + Guid alphaPluginId = Guid.NewGuid(); + Guid betaPluginId = Guid.NewGuid(); + IPlugin[] plugins = [CreatePlugin(alphaPluginId, "Alpha"), CreatePlugin(betaPluginId, "Beta")]; + _mockPluginManager.GetPlugins().Returns(plugins); + MediaLibraryProviderConfigurationStore sut = CreateSut( + (alphaPluginId, CreateMetadataProvider(LibraryType.Book), null, null), + (betaPluginId, CreateMetadataProvider(LibraryType.Book), null, null)); + LibraryMetadataProviderConfigurationEntity alphaConfiguration = _libraryMetadataProviderConfigurationEntityFixture.Create(libraryId, alphaPluginId, 1, isEnabled: true); + StubConfigurations(libraryId, [alphaConfiguration], [], []); + LibraryProviderSelectionDto[] metadataProviders = [new(betaPluginId, IsEnabled: null), new(alphaPluginId, IsEnabled: null)]; + + // Act + Result result = await sut.ConfigureProvidersAsync(libraryId, LibraryType.Book, metadataProviders, null, null, shouldReconcileOmittedKinds: false, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + await _mockMetadataConfigurationRepository.Received(1).UpsertAsync( + Arg.Is(configuration => configuration.PluginId == betaPluginId && configuration.Rank == 1 && !configuration.IsEnabled), + Arg.Any()); + await _mockMetadataConfigurationRepository.Received(1).UpsertAsync( + Arg.Is(configuration => configuration.PluginId == alphaPluginId && configuration.Rank == 2 && configuration.IsEnabled), + Arg.Any()); + } + + [Fact] + public async Task ConfigureProvidersAsync_WhenMetadataProviderChoicesAreDuplicated_ShouldReturnErrorWithoutChangingConfigurations() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + Guid pluginId = Guid.NewGuid(); + IPlugin[] plugins = [CreatePlugin(pluginId, "Alpha")]; + _mockPluginManager.GetPlugins().Returns(plugins); + MediaLibraryProviderConfigurationStore sut = CreateSut((pluginId, CreateMetadataProvider(LibraryType.Book), null, null)); + StubConfigurations(libraryId, [], [], []); + LibraryProviderSelectionDto[] metadataProviders = [new(pluginId, IsEnabled: true), new(pluginId, IsEnabled: false)]; + + // Act + Result result = await sut.ConfigureProvidersAsync(libraryId, LibraryType.Book, metadataProviders, null, null, shouldReconcileOmittedKinds: false, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(DomainErrors.Plugins.PluginIdsMustBeUnique, result.FirstError); + await _mockMetadataConfigurationRepository.DidNotReceive().UpsertAsync(Arg.Any(), Arg.Any()); + } + + [Fact] + public async Task ConfigureProvidersAsync_WhenArtworkProviderChoicesAreDuplicated_ShouldReturnErrorWithoutChangingConfigurations() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + Guid pluginId = Guid.NewGuid(); + IPlugin[] plugins = [CreatePlugin(pluginId, "Alpha")]; + _mockPluginManager.GetPlugins().Returns(plugins); + MediaLibraryProviderConfigurationStore sut = CreateSut((pluginId, null, CreateArtworkProvider(LibraryType.Book), null)); + StubConfigurations(libraryId, [], [], []); + LibraryProviderSelectionDto[] artworkProviders = [new(pluginId, IsEnabled: true), new(pluginId, IsEnabled: true)]; + + // Act + Result result = await sut.ConfigureProvidersAsync(libraryId, LibraryType.Book, null, artworkProviders, null, shouldReconcileOmittedKinds: false, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(DomainErrors.Plugins.PluginIdsMustBeUnique, result.FirstError); + await _mockArtworkConfigurationRepository.DidNotReceive().UpsertAsync(Arg.Any(), Arg.Any()); + } + + [Fact] + public async Task ConfigureProvidersAsync_WhenBookReaderChoicesAreDuplicated_ShouldReturnErrorWithoutChangingConfigurations() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + Guid pluginId = Guid.NewGuid(); + IPlugin[] plugins = [CreatePlugin(pluginId, "EPUB Reader")]; + _mockPluginManager.GetPlugins().Returns(plugins); + MediaLibraryProviderConfigurationStore sut = CreateSut((pluginId, null, null, CreateBookReader(LibraryType.Book, ".epub"))); + StubConfigurations(libraryId, [], [], []); + LibraryProviderSelectionDto[] bookReaders = [new(pluginId, IsEnabled: false), new(pluginId, IsEnabled: true)]; + + // Act + Result result = await sut.ConfigureProvidersAsync(libraryId, LibraryType.Book, null, null, bookReaders, shouldReconcileOmittedKinds: false, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(DomainErrors.Plugins.PluginIdsMustBeUnique, result.FirstError); + await _mockBookReaderConfigurationRepository.DidNotReceive().UpsertAsync(Arg.Any(), Arg.Any()); + _mockEnablementCache.DidNotReceive().InvalidateLibrary(Arg.Any()); + } + + /// + /// Stubs the stored configurations of a media library, and lets every write to the configuration repositories succeed. + /// + /// The Id of the media library whose configurations are stubbed. + /// The stored metadata provider configurations. + /// The stored artwork provider configurations. + /// The stored book reader configurations. + private void StubConfigurations( + Guid libraryId, + IReadOnlyList metadataConfigurations, + IReadOnlyList artworkConfigurations, + IReadOnlyList bookReaderConfigurations) + { + _mockMetadataConfigurationRepository.GetByLibraryIdAsync(libraryId, Arg.Any()).Returns(Result.From(metadataConfigurations)); + _mockArtworkConfigurationRepository.GetByLibraryIdAsync(libraryId, Arg.Any()).Returns(Result.From(artworkConfigurations)); + _mockBookReaderConfigurationRepository.GetByLibraryIdAsync(libraryId, Arg.Any()).Returns(Result.From(bookReaderConfigurations)); + _mockMetadataConfigurationRepository.UpsertAsync(Arg.Any(), Arg.Any()).Returns(Result.Updated); + _mockArtworkConfigurationRepository.UpsertAsync(Arg.Any(), Arg.Any()).Returns(Result.Updated); + _mockBookReaderConfigurationRepository.UpsertAsync(Arg.Any(), Arg.Any()).Returns(Result.Updated); + _mockMetadataConfigurationRepository.DeleteByLibraryIdAndPluginIdsAsync(libraryId, Arg.Any>(), Arg.Any()).Returns(Result.Deleted); + _mockArtworkConfigurationRepository.DeleteByLibraryIdAndPluginIdsAsync(libraryId, Arg.Any>(), Arg.Any()).Returns(Result.Deleted); + _mockBookReaderConfigurationRepository.DeleteByLibraryIdAndPluginIdsAsync(libraryId, Arg.Any>(), Arg.Any()).Returns(Result.Deleted); + } + /// /// Creates the store under test wired to the mocked dependencies, optionally registering the providers and book readers of the loaded plugins. /// @@ -1021,11 +1460,11 @@ public class MediaLibraryProviderConfigurationStoreTests foreach ((Guid pluginId, IMetadataProvider? metadataProvider, IArtworkProvider? artworkProvider, IBookReader? bookReader) in pluginServices) { if (metadataProvider is not null) - services.AddKeyedSingleton(pluginId, (_, _) => metadataProvider); + services.AddKeyedSingleton(pluginId, (_, _) => metadataProvider); if (artworkProvider is not null) - services.AddKeyedSingleton(pluginId, (_, _) => artworkProvider); + services.AddKeyedSingleton(pluginId, (_, _) => artworkProvider); if (bookReader is not null) - services.AddKeyedSingleton(pluginId, (_, _) => bookReader); + services.AddKeyedSingleton(pluginId, (_, _) => bookReader); } return new MediaLibraryProviderConfigurationStore(_mockUnitOfWork, _mockPluginManager, services.BuildServiceProvider(), _mockEnablementCache); } diff --git a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Plugins/PluginDetectionSyncJobTests.cs b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Plugins/PluginDetectionSyncJobTests.cs index 6e124e1c..e1996439 100644 --- a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Plugins/PluginDetectionSyncJobTests.cs +++ b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Plugins/PluginDetectionSyncJobTests.cs @@ -77,8 +77,6 @@ public class PluginDetectionSyncJobTests .Returns(Result.Deleted); _mockProviderConfigurationStore.EnsureProviderConfigurationsAsync(Arg.Any(), Arg.Any(), Arg.Any()) .Returns(Result.Success); - _mockProviderConfigurationStore.EnsureBookReaderConfigurationsAsync(Arg.Any(), Arg.Any(), Arg.Any()) - .Returns(Result.Success); _mockServiceProvider.GetService(typeof(IUnitOfWork)).Returns(_mockUnitOfWork); _mockServiceProvider.GetService(typeof(IMediaLibraryProviderConfigurationStore)).Returns(_mockProviderConfigurationStore); @@ -229,8 +227,8 @@ public class PluginDetectionSyncJobTests await StartAndWaitForExecutionAsync(sut); // Assert + // A single ensure covers the metadata, artwork and book reader configurations, since a second one before the save would stage duplicates. await _mockProviderConfigurationStore.Received(1).EnsureProviderConfigurationsAsync(bookLibrary.Id, LibraryType.Book, Arg.Any()); - await _mockProviderConfigurationStore.Received(1).EnsureBookReaderConfigurationsAsync(bookLibrary.Id, LibraryType.Book, Arg.Any()); await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any()); } @@ -239,7 +237,7 @@ public class PluginDetectionSyncJobTests { // Arrange IPlugin previouslyLoadedPlugin = CreatePlugin(Guid.NewGuid(), "My Plugin", new Version(1, 0, 0)); - _mockPluginManager.GetPlugins().Returns([]); // the plugin assembly now fails to load + _mockPluginManager.GetPlugins().Returns([]); // The plugin assembly now fails to load. _mockPluginRepository.UpsertAsync(Arg.Any(), Arg.Any()) .Returns(Result.From(Result.Updated)); PluginLoadErrorDto loadError = _pluginLoadErrorDtoFixture.Create( diff --git a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Library/Management/UpdateLibrary/UpdateLibraryEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Library/Management/UpdateLibrary/UpdateLibraryEndpointTests.cs index ee1570b5..ba73fa21 100644 --- a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Library/Management/UpdateLibrary/UpdateLibraryEndpointTests.cs +++ b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Library/Management/UpdateLibrary/UpdateLibraryEndpointTests.cs @@ -44,7 +44,7 @@ public class UpdateLibraryEndpointTests // Arrange UpdateLibraryRequest request = _updateLibraryRequestFixture.Create(); CancellationToken cancellationToken = CancellationToken.None; - LibraryResponse expectedResponse = _libraryResponseFixture.Create(id: request.Id, userId: request.UserId); + LibraryResponse expectedResponse = _libraryResponseFixture.Create(id: request.Id); _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) .Returns(Result.From(expectedResponse)); @@ -92,7 +92,7 @@ public class UpdateLibraryEndpointTests completionThresholdPercentage: 65); CancellationToken cancellationToken = CancellationToken.None; _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) - .Returns(Result.From(_libraryResponseFixture.Create(id: request.Id, userId: request.UserId))); + .Returns(Result.From(_libraryResponseFixture.Create(id: request.Id))); // Act await _sut.ExecuteAsync(request, cancellationToken); @@ -101,7 +101,6 @@ public class UpdateLibraryEndpointTests await _mockHandler.Received(1).HandleAsync( Arg.Is(command => command.Id == request.Id && - command.OwnerId == request.UserId && command.Title == request.Title && command.LibraryType == request.LibraryType && command.ContentLocations == request.ContentLocations && @@ -126,7 +125,7 @@ public class UpdateLibraryEndpointTests completionThresholdPercentage: null); CancellationToken cancellationToken = CancellationToken.None; _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) - .Returns(Result.From(_libraryResponseFixture.Create(id: request.Id, userId: request.UserId))); + .Returns(Result.From(_libraryResponseFixture.Create(id: request.Id))); // Act await _sut.ExecuteAsync(request, cancellationToken); @@ -154,7 +153,7 @@ public class UpdateLibraryEndpointTests operationStarted.SetResult(true); await cancellationRequested.Task; callInfo.Arg().ThrowIfCancellationRequested(); - return Result.From(_libraryResponseFixture.Create(id: request.Id, userId: request.UserId)); + return Result.From(_libraryResponseFixture.Create(id: request.Id)); }, callInfo.Arg())); // Act diff --git a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Plugins/GetLibraryTypeArtworkProviders/GetLibraryTypeArtworkProvidersEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Plugins/GetLibraryTypeArtworkProviders/GetLibraryTypeArtworkProvidersEndpointTests.cs new file mode 100644 index 00000000..312dd5f8 --- /dev/null +++ b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Plugins/GetLibraryTypeArtworkProviders/GetLibraryTypeArtworkProvidersEndpointTests.cs @@ -0,0 +1,128 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Application.Common.CQRS; +using Lumina.Application.Core.Plugins.Queries.GetLibraryTypeArtworkProviders; +using Lumina.Contracts.Fixtures.Core.Requests.Plugins; +using Lumina.Contracts.Fixtures.Core.Responses.Plugins; +using Lumina.Contracts.Requests.Plugins; +using Lumina.Contracts.Responses.Plugins; +using Lumina.Domain.Common.Primitives; +using Lumina.Presentation.Api.Core.Endpoints.Plugins.GetLibraryTypeArtworkProviders; +using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Http.HttpResults; +using NSubstitute; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Api.UnitTests.Core.Endpoints.Plugins.GetLibraryTypeArtworkProviders; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class GetLibraryTypeArtworkProvidersEndpointTests +{ + private readonly IQueryHandler>> _mockHandler; + private readonly GetLibraryTypeArtworkProvidersEndpoint _sut; + private readonly GetLibraryTypeArtworkProvidersRequestFixture _getLibraryTypeArtworkProvidersRequestFixture = new(); + private readonly LibraryArtworkProviderResponseFixture _libraryArtworkProviderResponseFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + public GetLibraryTypeArtworkProvidersEndpointTests() + { + _mockHandler = Substitute.For>>>(); + _sut = Factory.Create(_mockHandler); + } + + [Fact] + public async Task ExecuteAsync_WhenSuccessful_ShouldReturnOkResultWithArtworkProviders() + { + // Arrange + GetLibraryTypeArtworkProvidersRequest request = _getLibraryTypeArtworkProvidersRequestFixture.Create(); + CancellationToken cancellationToken = CancellationToken.None; + IReadOnlyList expectedResponse = _libraryArtworkProviderResponseFixture.CreateMany(2); + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From(expectedResponse)); + + // Act + IResult result = await _sut.ExecuteAsync(request, cancellationToken); + + // Assert + Ok> okResult = Assert.IsType>>(result); + Assert.Equal(expectedResponse, okResult.Value); + } + + [Fact] + public async Task ExecuteAsync_WhenHandlerReturnsFailureError_ShouldReturnProblemResult() + { + // Arrange + GetLibraryTypeArtworkProvidersRequest request = _getLibraryTypeArtworkProvidersRequestFixture.Create(); + CancellationToken cancellationToken = CancellationToken.None; + Error expectedError = Error.Failure("Authorization.NotAuthorized", "NotAuthorized"); + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(expectedError); + + // Act + IResult result = await _sut.ExecuteAsync(request, cancellationToken); + + // Assert + ProblemHttpResult problemResult = Assert.IsType(result); + Assert.Equal(StatusCodes.Status403Forbidden, problemResult.StatusCode); + Assert.Equal("application/problem+json", problemResult.ContentType); + Assert.Equal("Authorization.NotAuthorized", problemResult.ProblemDetails.Title); + Assert.Equal("NotAuthorized", problemResult.ProblemDetails.Detail); + } + + [Fact] + public async Task ExecuteAsync_WhenCalled_ShouldSendGetLibraryTypeArtworkProvidersQueryToSender() + { + // Arrange + GetLibraryTypeArtworkProvidersRequest request = _getLibraryTypeArtworkProvidersRequestFixture.Create(); + CancellationToken cancellationToken = CancellationToken.None; + IReadOnlyList response = _libraryArtworkProviderResponseFixture.CreateMany(2); + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From(response)); + + // Act + await _sut.ExecuteAsync(request, cancellationToken); + + // Assert + await _mockHandler.Received(1).HandleAsync( + Arg.Is(query => query.LibraryType == request.LibraryType), + Arg.Is(cancellationToken)); + } + + [Fact] + public async Task ExecuteAsync_WhenCancellationRequested_ShouldCancelOperation() + { + // Arrange + GetLibraryTypeArtworkProvidersRequest request = _getLibraryTypeArtworkProvidersRequestFixture.Create(); + CancellationTokenSource cts = new(); + TaskCompletionSource operationStarted = new(); + TaskCompletionSource cancellationRequested = new(); + + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(info => Task.Run(async () => + { + operationStarted.SetResult(true); + await cancellationRequested.Task; + info.Arg().ThrowIfCancellationRequested(); + return Result.From>([]); + }, info.Arg())); + + // Act + Task operationTask = _sut.ExecuteAsync(request, cts.Token); + await operationStarted.Task; + cts.Cancel(); + cancellationRequested.SetResult(true); + + // Assert + await Assert.ThrowsAnyAsync(() => operationTask); + } +} diff --git a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Plugins/GetLibraryTypeBookReaders/GetLibraryTypeBookReadersEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Plugins/GetLibraryTypeBookReaders/GetLibraryTypeBookReadersEndpointTests.cs new file mode 100644 index 00000000..55e68314 --- /dev/null +++ b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Plugins/GetLibraryTypeBookReaders/GetLibraryTypeBookReadersEndpointTests.cs @@ -0,0 +1,128 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Application.Common.CQRS; +using Lumina.Application.Core.Plugins.Queries.GetLibraryTypeBookReaders; +using Lumina.Contracts.Fixtures.Core.Requests.Plugins; +using Lumina.Contracts.Fixtures.Core.Responses.Plugins; +using Lumina.Contracts.Requests.Plugins; +using Lumina.Contracts.Responses.Plugins; +using Lumina.Domain.Common.Primitives; +using Lumina.Presentation.Api.Core.Endpoints.Plugins.GetLibraryTypeBookReaders; +using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Http.HttpResults; +using NSubstitute; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Api.UnitTests.Core.Endpoints.Plugins.GetLibraryTypeBookReaders; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class GetLibraryTypeBookReadersEndpointTests +{ + private readonly IQueryHandler>> _mockHandler; + private readonly GetLibraryTypeBookReadersEndpoint _sut; + private readonly GetLibraryTypeBookReadersRequestFixture _getLibraryTypeBookReadersRequestFixture = new(); + private readonly LibraryBookReaderResponseFixture _libraryBookReaderResponseFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + public GetLibraryTypeBookReadersEndpointTests() + { + _mockHandler = Substitute.For>>>(); + _sut = Factory.Create(_mockHandler); + } + + [Fact] + public async Task ExecuteAsync_WhenSuccessful_ShouldReturnOkResultWithBookReaders() + { + // Arrange + GetLibraryTypeBookReadersRequest request = _getLibraryTypeBookReadersRequestFixture.Create(); + CancellationToken cancellationToken = CancellationToken.None; + IReadOnlyList expectedResponse = _libraryBookReaderResponseFixture.CreateMany(2); + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From(expectedResponse)); + + // Act + IResult result = await _sut.ExecuteAsync(request, cancellationToken); + + // Assert + Ok> okResult = Assert.IsType>>(result); + Assert.Equal(expectedResponse, okResult.Value); + } + + [Fact] + public async Task ExecuteAsync_WhenHandlerReturnsFailureError_ShouldReturnProblemResult() + { + // Arrange + GetLibraryTypeBookReadersRequest request = _getLibraryTypeBookReadersRequestFixture.Create(); + CancellationToken cancellationToken = CancellationToken.None; + Error expectedError = Error.Failure("Authorization.NotAuthorized", "NotAuthorized"); + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(expectedError); + + // Act + IResult result = await _sut.ExecuteAsync(request, cancellationToken); + + // Assert + ProblemHttpResult problemResult = Assert.IsType(result); + Assert.Equal(StatusCodes.Status403Forbidden, problemResult.StatusCode); + Assert.Equal("application/problem+json", problemResult.ContentType); + Assert.Equal("Authorization.NotAuthorized", problemResult.ProblemDetails.Title); + Assert.Equal("NotAuthorized", problemResult.ProblemDetails.Detail); + } + + [Fact] + public async Task ExecuteAsync_WhenCalled_ShouldSendGetLibraryTypeBookReadersQueryToSender() + { + // Arrange + GetLibraryTypeBookReadersRequest request = _getLibraryTypeBookReadersRequestFixture.Create(); + CancellationToken cancellationToken = CancellationToken.None; + IReadOnlyList response = _libraryBookReaderResponseFixture.CreateMany(2); + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From(response)); + + // Act + await _sut.ExecuteAsync(request, cancellationToken); + + // Assert + await _mockHandler.Received(1).HandleAsync( + Arg.Is(query => query.LibraryType == request.LibraryType), + Arg.Is(cancellationToken)); + } + + [Fact] + public async Task ExecuteAsync_WhenCancellationRequested_ShouldCancelOperation() + { + // Arrange + GetLibraryTypeBookReadersRequest request = _getLibraryTypeBookReadersRequestFixture.Create(); + CancellationTokenSource cts = new(); + TaskCompletionSource operationStarted = new(); + TaskCompletionSource cancellationRequested = new(); + + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(info => Task.Run(async () => + { + operationStarted.SetResult(true); + await cancellationRequested.Task; + info.Arg().ThrowIfCancellationRequested(); + return Result.From>([]); + }, info.Arg())); + + // Act + Task operationTask = _sut.ExecuteAsync(request, cts.Token); + await operationStarted.Task; + cts.Cancel(); + cancellationRequested.SetResult(true); + + // Assert + await Assert.ThrowsAnyAsync(() => operationTask); + } +} diff --git a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Plugins/GetLibraryTypeMetadataProviders/GetLibraryTypeMetadataProvidersEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Plugins/GetLibraryTypeMetadataProviders/GetLibraryTypeMetadataProvidersEndpointTests.cs new file mode 100644 index 00000000..727f4e27 --- /dev/null +++ b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Plugins/GetLibraryTypeMetadataProviders/GetLibraryTypeMetadataProvidersEndpointTests.cs @@ -0,0 +1,128 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Application.Common.CQRS; +using Lumina.Application.Core.Plugins.Queries.GetLibraryTypeMetadataProviders; +using Lumina.Contracts.Fixtures.Core.Requests.Plugins; +using Lumina.Contracts.Fixtures.Core.Responses.Plugins; +using Lumina.Contracts.Requests.Plugins; +using Lumina.Contracts.Responses.Plugins; +using Lumina.Domain.Common.Primitives; +using Lumina.Presentation.Api.Core.Endpoints.Plugins.GetLibraryTypeMetadataProviders; +using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Http.HttpResults; +using NSubstitute; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Api.UnitTests.Core.Endpoints.Plugins.GetLibraryTypeMetadataProviders; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class GetLibraryTypeMetadataProvidersEndpointTests +{ + private readonly IQueryHandler>> _mockHandler; + private readonly GetLibraryTypeMetadataProvidersEndpoint _sut; + private readonly GetLibraryTypeMetadataProvidersRequestFixture _getLibraryTypeMetadataProvidersRequestFixture = new(); + private readonly LibraryMetadataProviderResponseFixture _libraryMetadataProviderResponseFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + public GetLibraryTypeMetadataProvidersEndpointTests() + { + _mockHandler = Substitute.For>>>(); + _sut = Factory.Create(_mockHandler); + } + + [Fact] + public async Task ExecuteAsync_WhenSuccessful_ShouldReturnOkResultWithMetadataProviders() + { + // Arrange + GetLibraryTypeMetadataProvidersRequest request = _getLibraryTypeMetadataProvidersRequestFixture.Create(); + CancellationToken cancellationToken = CancellationToken.None; + IReadOnlyList expectedResponse = _libraryMetadataProviderResponseFixture.CreateMany(2); + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From(expectedResponse)); + + // Act + IResult result = await _sut.ExecuteAsync(request, cancellationToken); + + // Assert + Ok> okResult = Assert.IsType>>(result); + Assert.Equal(expectedResponse, okResult.Value); + } + + [Fact] + public async Task ExecuteAsync_WhenHandlerReturnsFailureError_ShouldReturnProblemResult() + { + // Arrange + GetLibraryTypeMetadataProvidersRequest request = _getLibraryTypeMetadataProvidersRequestFixture.Create(); + CancellationToken cancellationToken = CancellationToken.None; + Error expectedError = Error.Failure("Authorization.NotAuthorized", "NotAuthorized"); + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(expectedError); + + // Act + IResult result = await _sut.ExecuteAsync(request, cancellationToken); + + // Assert + ProblemHttpResult problemResult = Assert.IsType(result); + Assert.Equal(StatusCodes.Status403Forbidden, problemResult.StatusCode); + Assert.Equal("application/problem+json", problemResult.ContentType); + Assert.Equal("Authorization.NotAuthorized", problemResult.ProblemDetails.Title); + Assert.Equal("NotAuthorized", problemResult.ProblemDetails.Detail); + } + + [Fact] + public async Task ExecuteAsync_WhenCalled_ShouldSendGetLibraryTypeMetadataProvidersQueryToSender() + { + // Arrange + GetLibraryTypeMetadataProvidersRequest request = _getLibraryTypeMetadataProvidersRequestFixture.Create(); + CancellationToken cancellationToken = CancellationToken.None; + IReadOnlyList response = _libraryMetadataProviderResponseFixture.CreateMany(2); + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From(response)); + + // Act + await _sut.ExecuteAsync(request, cancellationToken); + + // Assert + await _mockHandler.Received(1).HandleAsync( + Arg.Is(query => query.LibraryType == request.LibraryType), + Arg.Is(cancellationToken)); + } + + [Fact] + public async Task ExecuteAsync_WhenCancellationRequested_ShouldCancelOperation() + { + // Arrange + GetLibraryTypeMetadataProvidersRequest request = _getLibraryTypeMetadataProvidersRequestFixture.Create(); + CancellationTokenSource cts = new(); + TaskCompletionSource operationStarted = new(); + TaskCompletionSource cancellationRequested = new(); + + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(info => Task.Run(async () => + { + operationStarted.SetResult(true); + await cancellationRequested.Task; + info.Arg().ThrowIfCancellationRequested(); + return Result.From>([]); + }, info.Arg())); + + // Act + Task operationTask = _sut.ExecuteAsync(request, cts.Token); + await operationStarted.Task; + cts.Cancel(); + cancellationRequested.SetResult(true); + + // Assert + await Assert.ThrowsAnyAsync(() => operationTask); + } +} diff --git a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Plugins/ReorderLibraryArtworkProviders/ReorderLibraryArtworkProvidersEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Plugins/ReorderLibraryArtworkProviders/ReorderLibraryArtworkProvidersEndpointTests.cs deleted file mode 100644 index 8a5d82fd..00000000 --- a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Plugins/ReorderLibraryArtworkProviders/ReorderLibraryArtworkProvidersEndpointTests.cs +++ /dev/null @@ -1,129 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using Lumina.Application.Common.CQRS; -using Lumina.Application.Core.Plugins.Commands.ReorderLibraryArtworkProviders; -using Lumina.Contracts.Fixtures.Core.Requests.Plugins; -using Lumina.Contracts.Requests.Plugins; -using Lumina.Domain.Common.Primitives; -using Lumina.Presentation.Api.Core.Endpoints.Plugins.ReorderLibraryArtworkProviders; -using Microsoft.AspNetCore.Http; -using Microsoft.AspNetCore.Http.HttpResults; -using NSubstitute; -using System; -using System.Diagnostics.CodeAnalysis; -using System.Linq; -using System.Threading; -using System.Threading.Tasks; -#endregion - -namespace Lumina.Presentation.Api.UnitTests.Core.Endpoints.Plugins.ReorderLibraryArtworkProviders; - -/// -/// Contains unit tests for the class. -/// -[ExcludeFromCodeCoverage] -public class ReorderLibraryArtworkProvidersEndpointTests -{ - private readonly ICommandHandler> _mockHandler; - private readonly ReorderLibraryArtworkProvidersEndpoint _sut; - private readonly ReorderLibraryArtworkProvidersRequestFixture _reorderLibraryArtworkProvidersRequestFixture = new(); - - /// - /// Initializes a new instance of the class. - /// - public ReorderLibraryArtworkProvidersEndpointTests() - { - _mockHandler = Substitute.For>>(); - _sut = FastEndpoints.Factory.Create(_mockHandler); - } - - [Fact] - public async Task ExecuteAsync_WhenSuccessful_ShouldReturnOkResultWithSuccess() - { - // Arrange - ReorderLibraryArtworkProvidersRequest request = _reorderLibraryArtworkProvidersRequestFixture.Create(); - CancellationToken cancellationToken = CancellationToken.None; - _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) - .Returns(Result.From(Result.Success)); - - // Act - IResult result = await _sut.ExecuteAsync(request, cancellationToken); - - // Assert - Ok okResult = Assert.IsType>(result); - Assert.Equal(Result.Success, okResult.Value); - } - - [Fact] - public async Task ExecuteAsync_WhenHandlerReturnsNotFoundError_ShouldReturnProblemResult() - { - // Arrange - ReorderLibraryArtworkProvidersRequest request = _reorderLibraryArtworkProvidersRequestFixture.Create(); - CancellationToken cancellationToken = CancellationToken.None; - Error expectedError = Error.NotFound("LibraryArtworkProviderConfiguration.NotFound", "The artwork provider configuration was not found."); - _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) - .Returns(expectedError); - - // Act - IResult result = await _sut.ExecuteAsync(request, cancellationToken); - - // Assert - ProblemHttpResult problemDetails = Assert.IsType(result); - Assert.Equal(StatusCodes.Status404NotFound, problemDetails.StatusCode); - Assert.Equal("application/problem+json", problemDetails.ContentType); - Assert.IsType(problemDetails.ProblemDetails); - - Assert.Equal("LibraryArtworkProviderConfiguration.NotFound", problemDetails.ProblemDetails.Title); - Assert.Equal("The artwork provider configuration was not found.", problemDetails.ProblemDetails.Detail); - Assert.Equal(StatusCodes.Status404NotFound, problemDetails.ProblemDetails.Status); - Assert.Equal("https://tools.ietf.org/html/rfc9110#section-15.5.5", problemDetails.ProblemDetails.Type); - Assert.NotNull(problemDetails.ProblemDetails.Extensions["traceId"]); - } - - [Fact] - public async Task ExecuteAsync_WhenCalled_ShouldSendReorderLibraryArtworkProvidersCommandToSender() - { - // Arrange - ReorderLibraryArtworkProvidersRequest request = _reorderLibraryArtworkProvidersRequestFixture.Create(); - CancellationToken cancellationToken = CancellationToken.None; - _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) - .Returns(Result.From(Result.Success)); - - // Act - await _sut.ExecuteAsync(request, cancellationToken); - - // Assert - await _mockHandler.Received(1).HandleAsync( - Arg.Is(command => - command.LibraryId == request.LibraryId && - command.PluginIds.SequenceEqual(request.PluginIds)), - Arg.Is(cancellationToken)); - } - - [Fact] - public async Task ExecuteAsync_WhenCancellationRequested_ShouldCancelOperation() - { - // Arrange - ReorderLibraryArtworkProvidersRequest request = _reorderLibraryArtworkProvidersRequestFixture.Create(); - CancellationTokenSource cts = new(); - TaskCompletionSource operationStarted = new(); - TaskCompletionSource cancellationRequested = new(); - - _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) - .Returns(callInfo => Task.Run(async () => - { - operationStarted.SetResult(true); - await cancellationRequested.Task; - callInfo.Arg().ThrowIfCancellationRequested(); - return Result.From(Result.Success); - }, callInfo.Arg())); - - // Act - Task operationTask = _sut.ExecuteAsync(request, cts.Token); - await operationStarted.Task; - cts.Cancel(); - cancellationRequested.SetResult(true); - - // Assert - await Assert.ThrowsAnyAsync(() => operationTask); - } -} diff --git a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Plugins/ReorderLibraryMetadataProviders/ReorderLibraryMetadataProvidersEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Plugins/ReorderLibraryMetadataProviders/ReorderLibraryMetadataProvidersEndpointTests.cs deleted file mode 100644 index cfb8c07a..00000000 --- a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Plugins/ReorderLibraryMetadataProviders/ReorderLibraryMetadataProvidersEndpointTests.cs +++ /dev/null @@ -1,129 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using Lumina.Application.Common.CQRS; -using Lumina.Application.Core.Plugins.Commands.ReorderLibraryMetadataProviders; -using Lumina.Contracts.Fixtures.Core.Requests.Plugins; -using Lumina.Contracts.Requests.Plugins; -using Lumina.Domain.Common.Primitives; -using Lumina.Presentation.Api.Core.Endpoints.Plugins.ReorderLibraryMetadataProviders; -using Microsoft.AspNetCore.Http; -using Microsoft.AspNetCore.Http.HttpResults; -using NSubstitute; -using System; -using System.Diagnostics.CodeAnalysis; -using System.Linq; -using System.Threading; -using System.Threading.Tasks; -#endregion - -namespace Lumina.Presentation.Api.UnitTests.Core.Endpoints.Plugins.ReorderLibraryMetadataProviders; - -/// -/// Contains unit tests for the class. -/// -[ExcludeFromCodeCoverage] -public class ReorderLibraryMetadataProvidersEndpointTests -{ - private readonly ICommandHandler> _mockHandler; - private readonly ReorderLibraryMetadataProvidersEndpoint _sut; - private readonly ReorderLibraryMetadataProvidersRequestFixture _reorderLibraryMetadataProvidersRequestFixture = new(); - - /// - /// Initializes a new instance of the class. - /// - public ReorderLibraryMetadataProvidersEndpointTests() - { - _mockHandler = Substitute.For>>(); - _sut = FastEndpoints.Factory.Create(_mockHandler); - } - - [Fact] - public async Task ExecuteAsync_WhenSuccessful_ShouldReturnOkResultWithSuccess() - { - // Arrange - ReorderLibraryMetadataProvidersRequest request = _reorderLibraryMetadataProvidersRequestFixture.Create(); - CancellationToken cancellationToken = CancellationToken.None; - _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) - .Returns(Result.From(Result.Success)); - - // Act - IResult result = await _sut.ExecuteAsync(request, cancellationToken); - - // Assert - Ok okResult = Assert.IsType>(result); - Assert.Equal(Result.Success, okResult.Value); - } - - [Fact] - public async Task ExecuteAsync_WhenHandlerReturnsNotFoundError_ShouldReturnProblemResult() - { - // Arrange - ReorderLibraryMetadataProvidersRequest request = _reorderLibraryMetadataProvidersRequestFixture.Create(); - CancellationToken cancellationToken = CancellationToken.None; - Error expectedError = Error.NotFound("LibraryMetadataProviderConfiguration.NotFound", "The metadata provider configuration was not found."); - _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) - .Returns(expectedError); - - // Act - IResult result = await _sut.ExecuteAsync(request, cancellationToken); - - // Assert - ProblemHttpResult problemDetails = Assert.IsType(result); - Assert.Equal(StatusCodes.Status404NotFound, problemDetails.StatusCode); - Assert.Equal("application/problem+json", problemDetails.ContentType); - Assert.IsType(problemDetails.ProblemDetails); - - Assert.Equal("LibraryMetadataProviderConfiguration.NotFound", problemDetails.ProblemDetails.Title); - Assert.Equal("The metadata provider configuration was not found.", problemDetails.ProblemDetails.Detail); - Assert.Equal(StatusCodes.Status404NotFound, problemDetails.ProblemDetails.Status); - Assert.Equal("https://tools.ietf.org/html/rfc9110#section-15.5.5", problemDetails.ProblemDetails.Type); - Assert.NotNull(problemDetails.ProblemDetails.Extensions["traceId"]); - } - - [Fact] - public async Task ExecuteAsync_WhenCalled_ShouldSendReorderLibraryMetadataProvidersCommandToSender() - { - // Arrange - ReorderLibraryMetadataProvidersRequest request = _reorderLibraryMetadataProvidersRequestFixture.Create(); - CancellationToken cancellationToken = CancellationToken.None; - _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) - .Returns(Result.From(Result.Success)); - - // Act - await _sut.ExecuteAsync(request, cancellationToken); - - // Assert - await _mockHandler.Received(1).HandleAsync( - Arg.Is(command => - command.LibraryId == request.LibraryId && - command.PluginIds.SequenceEqual(request.PluginIds)), - Arg.Is(cancellationToken)); - } - - [Fact] - public async Task ExecuteAsync_WhenCancellationRequested_ShouldCancelOperation() - { - // Arrange - ReorderLibraryMetadataProvidersRequest request = _reorderLibraryMetadataProvidersRequestFixture.Create(); - CancellationTokenSource cts = new(); - TaskCompletionSource operationStarted = new(); - TaskCompletionSource cancellationRequested = new(); - - _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) - .Returns(callInfo => Task.Run(async () => - { - operationStarted.SetResult(true); - await cancellationRequested.Task; - callInfo.Arg().ThrowIfCancellationRequested(); - return Result.From(Result.Success); - }, callInfo.Arg())); - - // Act - Task operationTask = _sut.ExecuteAsync(request, cts.Token); - await operationStarted.Task; - cts.Cancel(); - cancellationRequested.SetResult(true); - - // Assert - await Assert.ThrowsAnyAsync(() => operationTask); - } -} diff --git a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Plugins/SetLibraryArtworkProviderEnabled/SetLibraryArtworkProviderEnabledEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Plugins/SetLibraryArtworkProviderEnabled/SetLibraryArtworkProviderEnabledEndpointTests.cs deleted file mode 100644 index 6a898b1f..00000000 --- a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Plugins/SetLibraryArtworkProviderEnabled/SetLibraryArtworkProviderEnabledEndpointTests.cs +++ /dev/null @@ -1,129 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using Lumina.Application.Common.CQRS; -using Lumina.Application.Core.Plugins.Commands.SetLibraryArtworkProviderEnabled; -using Lumina.Contracts.Fixtures.Core.Requests.Plugins; -using Lumina.Contracts.Requests.Plugins; -using Lumina.Domain.Common.Primitives; -using Lumina.Presentation.Api.Core.Endpoints.Plugins.SetLibraryArtworkProviderEnabled; -using Microsoft.AspNetCore.Http; -using Microsoft.AspNetCore.Http.HttpResults; -using NSubstitute; -using System; -using System.Diagnostics.CodeAnalysis; -using System.Threading; -using System.Threading.Tasks; -#endregion - -namespace Lumina.Presentation.Api.UnitTests.Core.Endpoints.Plugins.SetLibraryArtworkProviderEnabled; - -/// -/// Contains unit tests for the class. -/// -[ExcludeFromCodeCoverage] -public class SetLibraryArtworkProviderEnabledEndpointTests -{ - private readonly ICommandHandler> _mockHandler; - private readonly SetLibraryArtworkProviderEnabledEndpoint _sut; - private readonly SetLibraryArtworkProviderEnabledRequestFixture _setLibraryArtworkProviderEnabledRequestFixture = new(); - - /// - /// Initializes a new instance of the class. - /// - public SetLibraryArtworkProviderEnabledEndpointTests() - { - _mockHandler = Substitute.For>>(); - _sut = FastEndpoints.Factory.Create(_mockHandler); - } - - [Fact] - public async Task ExecuteAsync_WhenSuccessful_ShouldReturnOkResultWithSuccess() - { - // Arrange - SetLibraryArtworkProviderEnabledRequest request = _setLibraryArtworkProviderEnabledRequestFixture.Create(); - CancellationToken cancellationToken = CancellationToken.None; - _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) - .Returns(Result.From(Result.Success)); - - // Act - IResult result = await _sut.ExecuteAsync(request, cancellationToken); - - // Assert - Ok okResult = Assert.IsType>(result); - Assert.Equal(Result.Success, okResult.Value); - } - - [Fact] - public async Task ExecuteAsync_WhenHandlerReturnsNotFoundError_ShouldReturnProblemResult() - { - // Arrange - SetLibraryArtworkProviderEnabledRequest request = _setLibraryArtworkProviderEnabledRequestFixture.Create(); - CancellationToken cancellationToken = CancellationToken.None; - Error expectedError = Error.NotFound("LibraryArtworkProviderConfiguration.NotFound", "The artwork provider configuration was not found."); - _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) - .Returns(expectedError); - - // Act - IResult result = await _sut.ExecuteAsync(request, cancellationToken); - - // Assert - ProblemHttpResult problemDetails = Assert.IsType(result); - Assert.Equal(StatusCodes.Status404NotFound, problemDetails.StatusCode); - Assert.Equal("application/problem+json", problemDetails.ContentType); - Assert.IsType(problemDetails.ProblemDetails); - - Assert.Equal("LibraryArtworkProviderConfiguration.NotFound", problemDetails.ProblemDetails.Title); - Assert.Equal("The artwork provider configuration was not found.", problemDetails.ProblemDetails.Detail); - Assert.Equal(StatusCodes.Status404NotFound, problemDetails.ProblemDetails.Status); - Assert.Equal("https://tools.ietf.org/html/rfc9110#section-15.5.5", problemDetails.ProblemDetails.Type); - Assert.NotNull(problemDetails.ProblemDetails.Extensions["traceId"]); - } - - [Fact] - public async Task ExecuteAsync_WhenCalled_ShouldSendSetLibraryArtworkProviderEnabledCommandToSender() - { - // Arrange - SetLibraryArtworkProviderEnabledRequest request = _setLibraryArtworkProviderEnabledRequestFixture.Create(); - CancellationToken cancellationToken = CancellationToken.None; - _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) - .Returns(Result.From(Result.Success)); - - // Act - await _sut.ExecuteAsync(request, cancellationToken); - - // Assert - await _mockHandler.Received(1).HandleAsync( - Arg.Is(command => - command.LibraryId == request.LibraryId && - command.PluginId == request.PluginId && - command.IsEnabled == request.IsEnabled), - Arg.Is(cancellationToken)); - } - - [Fact] - public async Task ExecuteAsync_WhenCancellationRequested_ShouldCancelOperation() - { - // Arrange - SetLibraryArtworkProviderEnabledRequest request = _setLibraryArtworkProviderEnabledRequestFixture.Create(); - CancellationTokenSource cts = new(); - TaskCompletionSource operationStarted = new(); - TaskCompletionSource cancellationRequested = new(); - - _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) - .Returns(callInfo => Task.Run(async () => - { - operationStarted.SetResult(true); - await cancellationRequested.Task; - callInfo.Arg().ThrowIfCancellationRequested(); - return Result.From(Result.Success); - }, callInfo.Arg())); - - // Act - Task operationTask = _sut.ExecuteAsync(request, cts.Token); - await operationStarted.Task; - cts.Cancel(); - cancellationRequested.SetResult(true); - - // Assert - await Assert.ThrowsAnyAsync(() => operationTask); - } -} diff --git a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Plugins/SetLibraryBookReaderEnabled/SetLibraryBookReaderEnabledEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Plugins/SetLibraryBookReaderEnabled/SetLibraryBookReaderEnabledEndpointTests.cs deleted file mode 100644 index 0eec00c5..00000000 --- a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Plugins/SetLibraryBookReaderEnabled/SetLibraryBookReaderEnabledEndpointTests.cs +++ /dev/null @@ -1,124 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using Lumina.Application.Common.CQRS; -using Lumina.Application.Core.Plugins.Commands.SetLibraryBookReaderEnabled; -using Lumina.Contracts.Fixtures.Core.Requests.Plugins; -using Lumina.Contracts.Requests.Plugins; -using Lumina.Domain.Common.Primitives; -using Lumina.Presentation.Api.Core.Endpoints.Plugins.SetLibraryBookReaderEnabled; -using Microsoft.AspNetCore.Http; -using Microsoft.AspNetCore.Http.HttpResults; -using NSubstitute; -using System; -using System.Diagnostics.CodeAnalysis; -using System.Threading; -using System.Threading.Tasks; -#endregion - -namespace Lumina.Presentation.Api.UnitTests.Core.Endpoints.Plugins.SetLibraryBookReaderEnabled; - -/// -/// Contains unit tests for the class. -/// -[ExcludeFromCodeCoverage] -public class SetLibraryBookReaderEnabledEndpointTests -{ - private readonly ICommandHandler> _mockHandler; - private readonly SetLibraryBookReaderEnabledEndpoint _sut; - private readonly SetLibraryBookReaderEnabledRequestFixture _setLibraryBookReaderEnabledRequestFixture = new(); - - /// - /// Initializes a new instance of the class. - /// - public SetLibraryBookReaderEnabledEndpointTests() - { - _mockHandler = Substitute.For>>(); - _sut = FastEndpoints.Factory.Create(_mockHandler); - } - - [Fact] - public async Task ExecuteAsync_WhenSuccessful_ShouldReturnOkResultWithSuccess() - { - // Arrange - SetLibraryBookReaderEnabledRequest request = _setLibraryBookReaderEnabledRequestFixture.Create(); - CancellationToken cancellationToken = CancellationToken.None; - _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) - .Returns(Result.From(Result.Success)); - - // Act - IResult result = await _sut.ExecuteAsync(request, cancellationToken); - - // Assert - Ok okResult = Assert.IsType>(result); - Assert.Equal(Result.Success, okResult.Value); - } - - [Fact] - public async Task ExecuteAsync_WhenHandlerReturnsFailureError_ShouldReturnProblemResult() - { - // Arrange - SetLibraryBookReaderEnabledRequest request = _setLibraryBookReaderEnabledRequestFixture.Create(); - CancellationToken cancellationToken = CancellationToken.None; - Error expectedError = Error.Failure("Authorization.NotAuthorized", "NotAuthorized"); - _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) - .Returns(expectedError); - - // Act - IResult result = await _sut.ExecuteAsync(request, cancellationToken); - - // Assert - ProblemHttpResult problemResult = Assert.IsType(result); - Assert.Equal(StatusCodes.Status403Forbidden, problemResult.StatusCode); - Assert.Equal("application/problem+json", problemResult.ContentType); - Assert.Equal("Authorization.NotAuthorized", problemResult.ProblemDetails.Title); - Assert.Equal("NotAuthorized", problemResult.ProblemDetails.Detail); - } - - [Fact] - public async Task ExecuteAsync_WhenCalled_ShouldSendSetLibraryBookReaderEnabledCommandToSender() - { - // Arrange - SetLibraryBookReaderEnabledRequest request = _setLibraryBookReaderEnabledRequestFixture.Create(); - CancellationToken cancellationToken = CancellationToken.None; - _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) - .Returns(Result.From(Result.Success)); - - // Act - await _sut.ExecuteAsync(request, cancellationToken); - - // Assert - await _mockHandler.Received(1).HandleAsync( - Arg.Is(command => - command.LibraryId == request.LibraryId && - command.PluginId == request.PluginId && - command.IsEnabled == request.IsEnabled), - Arg.Is(cancellationToken)); - } - - [Fact] - public async Task ExecuteAsync_WhenCancellationRequested_ShouldCancelOperation() - { - // Arrange - SetLibraryBookReaderEnabledRequest request = _setLibraryBookReaderEnabledRequestFixture.Create(); - CancellationTokenSource cts = new(); - TaskCompletionSource operationStarted = new(); - TaskCompletionSource cancellationRequested = new(); - - _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) - .Returns(callInfo => Task.Run(async () => - { - operationStarted.SetResult(true); - await cancellationRequested.Task; - callInfo.Arg().ThrowIfCancellationRequested(); - return Result.From(Result.Success); - }, callInfo.Arg())); - - // Act - Task operationTask = _sut.ExecuteAsync(request, cts.Token); - await operationStarted.Task; - cts.Cancel(); - cancellationRequested.SetResult(true); - - // Assert - await Assert.ThrowsAnyAsync(() => operationTask); - } -} diff --git a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Plugins/SetLibraryMetadataProviderEnabled/SetLibraryMetadataProviderEnabledEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Plugins/SetLibraryMetadataProviderEnabled/SetLibraryMetadataProviderEnabledEndpointTests.cs deleted file mode 100644 index 97f1e840..00000000 --- a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Plugins/SetLibraryMetadataProviderEnabled/SetLibraryMetadataProviderEnabledEndpointTests.cs +++ /dev/null @@ -1,129 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using Lumina.Application.Common.CQRS; -using Lumina.Application.Core.Plugins.Commands.SetLibraryMetadataProviderEnabled; -using Lumina.Contracts.Fixtures.Core.Requests.Plugins; -using Lumina.Contracts.Requests.Plugins; -using Lumina.Domain.Common.Primitives; -using Lumina.Presentation.Api.Core.Endpoints.Plugins.SetLibraryMetadataProviderEnabled; -using Microsoft.AspNetCore.Http; -using Microsoft.AspNetCore.Http.HttpResults; -using NSubstitute; -using System; -using System.Diagnostics.CodeAnalysis; -using System.Threading; -using System.Threading.Tasks; -#endregion - -namespace Lumina.Presentation.Api.UnitTests.Core.Endpoints.Plugins.SetLibraryMetadataProviderEnabled; - -/// -/// Contains unit tests for the class. -/// -[ExcludeFromCodeCoverage] -public class SetLibraryMetadataProviderEnabledEndpointTests -{ - private readonly ICommandHandler> _mockHandler; - private readonly SetLibraryMetadataProviderEnabledEndpoint _sut; - private readonly SetLibraryMetadataProviderEnabledRequestFixture _setLibraryMetadataProviderEnabledRequestFixture = new(); - - /// - /// Initializes a new instance of the class. - /// - public SetLibraryMetadataProviderEnabledEndpointTests() - { - _mockHandler = Substitute.For>>(); - _sut = FastEndpoints.Factory.Create(_mockHandler); - } - - [Fact] - public async Task ExecuteAsync_WhenSuccessful_ShouldReturnOkResultWithSuccess() - { - // Arrange - SetLibraryMetadataProviderEnabledRequest request = _setLibraryMetadataProviderEnabledRequestFixture.Create(); - CancellationToken cancellationToken = CancellationToken.None; - _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) - .Returns(Result.From(Result.Success)); - - // Act - IResult result = await _sut.ExecuteAsync(request, cancellationToken); - - // Assert - Ok okResult = Assert.IsType>(result); - Assert.Equal(Result.Success, okResult.Value); - } - - [Fact] - public async Task ExecuteAsync_WhenHandlerReturnsNotFoundError_ShouldReturnProblemResult() - { - // Arrange - SetLibraryMetadataProviderEnabledRequest request = _setLibraryMetadataProviderEnabledRequestFixture.Create(); - CancellationToken cancellationToken = CancellationToken.None; - Error expectedError = Error.NotFound("LibraryMetadataProviderConfiguration.NotFound", "The metadata provider configuration was not found."); - _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) - .Returns(expectedError); - - // Act - IResult result = await _sut.ExecuteAsync(request, cancellationToken); - - // Assert - ProblemHttpResult problemDetails = Assert.IsType(result); - Assert.Equal(StatusCodes.Status404NotFound, problemDetails.StatusCode); - Assert.Equal("application/problem+json", problemDetails.ContentType); - Assert.IsType(problemDetails.ProblemDetails); - - Assert.Equal("LibraryMetadataProviderConfiguration.NotFound", problemDetails.ProblemDetails.Title); - Assert.Equal("The metadata provider configuration was not found.", problemDetails.ProblemDetails.Detail); - Assert.Equal(StatusCodes.Status404NotFound, problemDetails.ProblemDetails.Status); - Assert.Equal("https://tools.ietf.org/html/rfc9110#section-15.5.5", problemDetails.ProblemDetails.Type); - Assert.NotNull(problemDetails.ProblemDetails.Extensions["traceId"]); - } - - [Fact] - public async Task ExecuteAsync_WhenCalled_ShouldSendSetLibraryMetadataProviderEnabledCommandToSender() - { - // Arrange - SetLibraryMetadataProviderEnabledRequest request = _setLibraryMetadataProviderEnabledRequestFixture.Create(); - CancellationToken cancellationToken = CancellationToken.None; - _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) - .Returns(Result.From(Result.Success)); - - // Act - await _sut.ExecuteAsync(request, cancellationToken); - - // Assert - await _mockHandler.Received(1).HandleAsync( - Arg.Is(command => - command.LibraryId == request.LibraryId && - command.PluginId == request.PluginId && - command.IsEnabled == request.IsEnabled), - Arg.Is(cancellationToken)); - } - - [Fact] - public async Task ExecuteAsync_WhenCancellationRequested_ShouldCancelOperation() - { - // Arrange - SetLibraryMetadataProviderEnabledRequest request = _setLibraryMetadataProviderEnabledRequestFixture.Create(); - CancellationTokenSource cts = new(); - TaskCompletionSource operationStarted = new(); - TaskCompletionSource cancellationRequested = new(); - - _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) - .Returns(callInfo => Task.Run(async () => - { - operationStarted.SetResult(true); - await cancellationRequested.Task; - callInfo.Arg().ThrowIfCancellationRequested(); - return Result.From(Result.Success); - }, callInfo.Arg())); - - // Act - Task operationTask = _sut.ExecuteAsync(request, cts.Token); - await operationStarted.Task; - cts.Cancel(); - cancellationRequested.SetResult(true); - - // Assert - await Assert.ThrowsAnyAsync(() => operationTask); - } -} diff --git a/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Common/Authorization/PermissionAuthorizationHandlerTests.cs b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Common/Authorization/PermissionAuthorizationHandlerTests.cs new file mode 100644 index 00000000..57f80498 --- /dev/null +++ b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Common/Authorization/PermissionAuthorizationHandlerTests.cs @@ -0,0 +1,86 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Common.Authorization; +using Lumina.Presentation.Web.Common.Enums.Authorization; +using Microsoft.AspNetCore.Authorization; +using NSubstitute; +using System.Diagnostics.CodeAnalysis; +using System.Security.Claims; +using System.Threading; +using System.Threading.Tasks; +using IAuthorizationService = Lumina.Presentation.Web.Common.Authorization.IAuthorizationService; +#endregion + +namespace Lumina.Presentation.Web.UnitTests.Common.Authorization; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class PermissionAuthorizationHandlerTests +{ + private readonly IAuthorizationService _mockAuthorizationService; + private readonly PermissionAuthorizationHandler _sut; + + /// + /// Initializes a new instance of the class. + /// + public PermissionAuthorizationHandlerTests() + { + _mockAuthorizationService = Substitute.For(); + _sut = new PermissionAuthorizationHandler(_mockAuthorizationService); + } + + [Fact] + public async Task HandleAsync_WhenTheUserHoldsTheRequiredPermission_ShouldSucceed() + { + // Arrange + _mockAuthorizationService.HasPermissionAsync(AuthorizationPermission.CanCreateLibraries, Arg.Any()).Returns(true); + AuthorizationHandlerContext context = CreateContext(); + + // Act + await _sut.HandleAsync(context); + + // Assert + Assert.True(context.HasSucceeded); + } + + [Fact] + public async Task HandleAsync_WhenAnAdministratorLacksTheRequiredPermission_ShouldSucceed() + { + // Arrange + // The API lets administrators do what the permission allows even without holding it, so the Web must not deny them. + _mockAuthorizationService.IsInRoleAsync("Admin", Arg.Any()).Returns(true); + _mockAuthorizationService.HasPermissionAsync(Arg.Any(), Arg.Any()).Returns(false); + AuthorizationHandlerContext context = CreateContext(); + + // Act + await _sut.HandleAsync(context); + + // Assert + Assert.True(context.HasSucceeded); + } + + [Fact] + public async Task HandleAsync_WhenAUserIsNeitherAnAdministratorNorHoldsTheRequiredPermission_ShouldNotSucceed() + { + // Arrange + _mockAuthorizationService.IsInRoleAsync(Arg.Any(), Arg.Any()).Returns(false); + _mockAuthorizationService.HasPermissionAsync(Arg.Any(), Arg.Any()).Returns(false); + AuthorizationHandlerContext context = CreateContext(); + + // Act + await _sut.HandleAsync(context); + + // Assert + Assert.False(context.HasSucceeded); + } + + /// + /// Creates an authorization context that evaluates a requirement for the permission to manage media libraries. + /// + /// The created authorization context. + private static AuthorizationHandlerContext CreateContext() + { + return new AuthorizationHandlerContext([new PermissionRequirement(AuthorizationPermission.CanCreateLibraries)], new ClaimsPrincipal(), resource: null); + } +} diff --git a/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Library/Management/GetLibraryTypeArtworkProviders/GetLibraryTypeArtworkProvidersEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Library/Management/GetLibraryTypeArtworkProviders/GetLibraryTypeArtworkProvidersEndpointTests.cs new file mode 100644 index 00000000..a3d5b4c5 --- /dev/null +++ b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Library/Management/GetLibraryTypeArtworkProviders/GetLibraryTypeArtworkProvidersEndpointTests.cs @@ -0,0 +1,117 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Presentation.Web.Common.Api; +using Lumina.Presentation.Web.Common.DTO.Plugins; +using Lumina.Presentation.Web.Common.Requests.Library.Management; +using Lumina.Presentation.Web.Common.Routes; +using Lumina.Presentation.Web.Core.Endpoints.Library.Management.GetLibraryTypeArtworkProviders; +using Lumina.Presentation.Web.Fixtures.Common.DTO.Plugins; +using Lumina.Presentation.Web.Fixtures.Common.Requests.Library.Management; +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.GetLibraryTypeArtworkProviders; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class GetLibraryTypeArtworkProvidersEndpointTests +{ + private readonly IApiHttpClient _mockApiHttpClient; + private readonly GetLibraryTypeArtworkProvidersEndpoint _sut; + private readonly GetLibraryTypeArtworkProvidersRequestFixture _getLibraryTypeArtworkProvidersRequestFixture = new(); + private readonly LibraryArtworkProviderDtoFixture _libraryArtworkProviderDtoFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + public GetLibraryTypeArtworkProvidersEndpointTests() + { + _mockApiHttpClient = Substitute.For(); + _sut = Factory.Create(_mockApiHttpClient); + } + + [Fact] + public async Task ExecuteAsync_WhenSuccessful_ShouldReturnSuccessJsonWithTheProviders() + { + // Arrange + GetLibraryTypeArtworkProvidersRequest request = _getLibraryTypeArtworkProvidersRequestFixture.Create(); + LibraryArtworkProviderDto[] providers = [.. _libraryArtworkProviderDtoFixture.CreateMany(2)]; + _mockApiHttpClient.GetAsync(Arg.Any(), Arg.Any()) + .Returns(providers); + + // 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(providers.Length, data.GetArrayLength()); + Assert.Equal(providers[0].PluginId, data[0].GetProperty("pluginId").GetGuid()); + Assert.Equal(providers[0].Name, data[0].GetProperty("name").GetString()); + Assert.Equal(providers[0].IsEnabled, data[0].GetProperty("isEnabled").GetBoolean()); + } + + [Fact] + public async Task ExecuteAsync_WhenCalled_ShouldRequestTheProvidersFromApiWithSubstitutedLibraryType() + { + // Arrange + GetLibraryTypeArtworkProvidersRequest request = _getLibraryTypeArtworkProvidersRequestFixture.Create(libraryType: "Music"); + _mockApiHttpClient.GetAsync(Arg.Any(), Arg.Any()) + .Returns([]); + + // Act + await _sut.ExecuteAsync(request, CancellationToken.None); + + // Assert + await _mockApiHttpClient.Received(1).GetAsync( + Arg.Is(endpoint => endpoint == ApiRoutes.Libraries.GET_LIBRARY_TYPE_ARTWORK_PROVIDERS.Replace("{libraryType}", "Music")), + Arg.Any()); + } + + [Fact] + public async Task ExecuteAsync_WhenLibraryTypeContainsPathCharacters_ShouldEscapeItInTheApiRoute() + { + // Arrange + GetLibraryTypeArtworkProvidersRequest request = _getLibraryTypeArtworkProvidersRequestFixture.Create(libraryType: "../plugins"); + _mockApiHttpClient.GetAsync(Arg.Any(), Arg.Any()) + .Returns([]); + + // Act + await _sut.ExecuteAsync(request, CancellationToken.None); + + // Assert + await _mockApiHttpClient.Received(1).GetAsync( + Arg.Is(endpoint => endpoint == ApiRoutes.Libraries.GET_LIBRARY_TYPE_ARTWORK_PROVIDERS.Replace("{libraryType}", Uri.EscapeDataString("../plugins"))), + Arg.Any()); + } + + [Fact] + public async Task ExecuteAsync_WhenCalled_ShouldForwardCancellationTokenToApi() + { + // Arrange + GetLibraryTypeArtworkProvidersRequest request = _getLibraryTypeArtworkProvidersRequestFixture.Create(); + CancellationTokenSource cancellationTokenSource = new(); + CancellationToken cancellationToken = cancellationTokenSource.Token; + _mockApiHttpClient.GetAsync(Arg.Any(), Arg.Any()) + .Returns([]); + + // Act + await _sut.ExecuteAsync(request, cancellationToken); + + // Assert + await _mockApiHttpClient.Received(1).GetAsync( + Arg.Any(), + Arg.Is(cancellationToken)); + } +} diff --git a/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Library/Management/GetLibraryTypeBookReaders/GetLibraryTypeBookReadersEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Library/Management/GetLibraryTypeBookReaders/GetLibraryTypeBookReadersEndpointTests.cs new file mode 100644 index 00000000..8f041d8b --- /dev/null +++ b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Library/Management/GetLibraryTypeBookReaders/GetLibraryTypeBookReadersEndpointTests.cs @@ -0,0 +1,117 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Presentation.Web.Common.Api; +using Lumina.Presentation.Web.Common.DTO.Plugins; +using Lumina.Presentation.Web.Common.Requests.Library.Management; +using Lumina.Presentation.Web.Common.Routes; +using Lumina.Presentation.Web.Core.Endpoints.Library.Management.GetLibraryTypeBookReaders; +using Lumina.Presentation.Web.Fixtures.Common.DTO.Plugins; +using Lumina.Presentation.Web.Fixtures.Common.Requests.Library.Management; +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.GetLibraryTypeBookReaders; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class GetLibraryTypeBookReadersEndpointTests +{ + private readonly IApiHttpClient _mockApiHttpClient; + private readonly GetLibraryTypeBookReadersEndpoint _sut; + private readonly GetLibraryTypeBookReadersRequestFixture _getLibraryTypeBookReadersRequestFixture = new(); + private readonly LibraryBookReaderDtoFixture _libraryBookReaderDtoFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + public GetLibraryTypeBookReadersEndpointTests() + { + _mockApiHttpClient = Substitute.For(); + _sut = Factory.Create(_mockApiHttpClient); + } + + [Fact] + public async Task ExecuteAsync_WhenSuccessful_ShouldReturnSuccessJsonWithTheReaders() + { + // Arrange + GetLibraryTypeBookReadersRequest request = _getLibraryTypeBookReadersRequestFixture.Create(); + LibraryBookReaderDto[] readers = [.. _libraryBookReaderDtoFixture.CreateMany(2)]; + _mockApiHttpClient.GetAsync(Arg.Any(), Arg.Any()) + .Returns(readers); + + // 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(readers.Length, data.GetArrayLength()); + Assert.Equal(readers[0].PluginId, data[0].GetProperty("pluginId").GetGuid()); + Assert.Equal(readers[0].Name, data[0].GetProperty("name").GetString()); + Assert.Equal(readers[0].IsEnabled, data[0].GetProperty("isEnabled").GetBoolean()); + } + + [Fact] + public async Task ExecuteAsync_WhenCalled_ShouldRequestTheReadersFromApiWithSubstitutedLibraryType() + { + // Arrange + GetLibraryTypeBookReadersRequest request = _getLibraryTypeBookReadersRequestFixture.Create(libraryType: "Music"); + _mockApiHttpClient.GetAsync(Arg.Any(), Arg.Any()) + .Returns([]); + + // Act + await _sut.ExecuteAsync(request, CancellationToken.None); + + // Assert + await _mockApiHttpClient.Received(1).GetAsync( + Arg.Is(endpoint => endpoint == ApiRoutes.Libraries.GET_LIBRARY_TYPE_BOOK_READERS.Replace("{libraryType}", "Music")), + Arg.Any()); + } + + [Fact] + public async Task ExecuteAsync_WhenLibraryTypeContainsPathCharacters_ShouldEscapeItInTheApiRoute() + { + // Arrange + GetLibraryTypeBookReadersRequest request = _getLibraryTypeBookReadersRequestFixture.Create(libraryType: "../plugins"); + _mockApiHttpClient.GetAsync(Arg.Any(), Arg.Any()) + .Returns([]); + + // Act + await _sut.ExecuteAsync(request, CancellationToken.None); + + // Assert + await _mockApiHttpClient.Received(1).GetAsync( + Arg.Is(endpoint => endpoint == ApiRoutes.Libraries.GET_LIBRARY_TYPE_BOOK_READERS.Replace("{libraryType}", Uri.EscapeDataString("../plugins"))), + Arg.Any()); + } + + [Fact] + public async Task ExecuteAsync_WhenCalled_ShouldForwardCancellationTokenToApi() + { + // Arrange + GetLibraryTypeBookReadersRequest request = _getLibraryTypeBookReadersRequestFixture.Create(); + CancellationTokenSource cancellationTokenSource = new(); + CancellationToken cancellationToken = cancellationTokenSource.Token; + _mockApiHttpClient.GetAsync(Arg.Any(), Arg.Any()) + .Returns([]); + + // Act + await _sut.ExecuteAsync(request, cancellationToken); + + // Assert + await _mockApiHttpClient.Received(1).GetAsync( + Arg.Any(), + Arg.Is(cancellationToken)); + } +} diff --git a/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Library/Management/GetLibraryTypeMetadataProviders/GetLibraryTypeMetadataProvidersEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Library/Management/GetLibraryTypeMetadataProviders/GetLibraryTypeMetadataProvidersEndpointTests.cs new file mode 100644 index 00000000..51fc20bd --- /dev/null +++ b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Library/Management/GetLibraryTypeMetadataProviders/GetLibraryTypeMetadataProvidersEndpointTests.cs @@ -0,0 +1,117 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Presentation.Web.Common.Api; +using Lumina.Presentation.Web.Common.DTO.Plugins; +using Lumina.Presentation.Web.Common.Requests.Library.Management; +using Lumina.Presentation.Web.Common.Routes; +using Lumina.Presentation.Web.Core.Endpoints.Library.Management.GetLibraryTypeMetadataProviders; +using Lumina.Presentation.Web.Fixtures.Common.DTO.Plugins; +using Lumina.Presentation.Web.Fixtures.Common.Requests.Library.Management; +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.GetLibraryTypeMetadataProviders; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class GetLibraryTypeMetadataProvidersEndpointTests +{ + private readonly IApiHttpClient _mockApiHttpClient; + private readonly GetLibraryTypeMetadataProvidersEndpoint _sut; + private readonly GetLibraryTypeMetadataProvidersRequestFixture _getLibraryTypeMetadataProvidersRequestFixture = new(); + private readonly LibraryMetadataProviderDtoFixture _libraryMetadataProviderDtoFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + public GetLibraryTypeMetadataProvidersEndpointTests() + { + _mockApiHttpClient = Substitute.For(); + _sut = Factory.Create(_mockApiHttpClient); + } + + [Fact] + public async Task ExecuteAsync_WhenSuccessful_ShouldReturnSuccessJsonWithTheProviders() + { + // Arrange + GetLibraryTypeMetadataProvidersRequest request = _getLibraryTypeMetadataProvidersRequestFixture.Create(); + LibraryMetadataProviderDto[] providers = [.. _libraryMetadataProviderDtoFixture.CreateMany(2)]; + _mockApiHttpClient.GetAsync(Arg.Any(), Arg.Any()) + .Returns(providers); + + // 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(providers.Length, data.GetArrayLength()); + Assert.Equal(providers[0].PluginId, data[0].GetProperty("pluginId").GetGuid()); + Assert.Equal(providers[0].Name, data[0].GetProperty("name").GetString()); + Assert.Equal(providers[0].IsEnabled, data[0].GetProperty("isEnabled").GetBoolean()); + } + + [Fact] + public async Task ExecuteAsync_WhenCalled_ShouldRequestTheProvidersFromApiWithSubstitutedLibraryType() + { + // Arrange + GetLibraryTypeMetadataProvidersRequest request = _getLibraryTypeMetadataProvidersRequestFixture.Create(libraryType: "Music"); + _mockApiHttpClient.GetAsync(Arg.Any(), Arg.Any()) + .Returns([]); + + // Act + await _sut.ExecuteAsync(request, CancellationToken.None); + + // Assert + await _mockApiHttpClient.Received(1).GetAsync( + Arg.Is(endpoint => endpoint == ApiRoutes.Libraries.GET_LIBRARY_TYPE_METADATA_PROVIDERS.Replace("{libraryType}", "Music")), + Arg.Any()); + } + + [Fact] + public async Task ExecuteAsync_WhenLibraryTypeContainsPathCharacters_ShouldEscapeItInTheApiRoute() + { + // Arrange + GetLibraryTypeMetadataProvidersRequest request = _getLibraryTypeMetadataProvidersRequestFixture.Create(libraryType: "../plugins"); + _mockApiHttpClient.GetAsync(Arg.Any(), Arg.Any()) + .Returns([]); + + // Act + await _sut.ExecuteAsync(request, CancellationToken.None); + + // Assert + await _mockApiHttpClient.Received(1).GetAsync( + Arg.Is(endpoint => endpoint == ApiRoutes.Libraries.GET_LIBRARY_TYPE_METADATA_PROVIDERS.Replace("{libraryType}", Uri.EscapeDataString("../plugins"))), + Arg.Any()); + } + + [Fact] + public async Task ExecuteAsync_WhenCalled_ShouldForwardCancellationTokenToApi() + { + // Arrange + GetLibraryTypeMetadataProvidersRequest request = _getLibraryTypeMetadataProvidersRequestFixture.Create(); + CancellationTokenSource cancellationTokenSource = new(); + CancellationToken cancellationToken = cancellationTokenSource.Token; + _mockApiHttpClient.GetAsync(Arg.Any(), Arg.Any()) + .Returns([]); + + // Act + await _sut.ExecuteAsync(request, cancellationToken); + + // Assert + await _mockApiHttpClient.Received(1).GetAsync( + Arg.Any(), + Arg.Is(cancellationToken)); + } +} diff --git a/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Library/Management/Index/LibrariesIndexViewEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Library/Management/Index/LibrariesIndexViewEndpointTests.cs new file mode 100644 index 00000000..394c3030 --- /dev/null +++ b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Library/Management/Index/LibrariesIndexViewEndpointTests.cs @@ -0,0 +1,115 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Presentation.Web.Common.Authorization; +using Lumina.Presentation.Web.Common.DTO.Libraries; +using Lumina.Presentation.Web.Common.Enums.Authorization; +using Lumina.Presentation.Web.Common.Http; +using Lumina.Presentation.Web.Core.Endpoints.Library.Management.Index; +using Lumina.Presentation.Web.Fixtures.Common.TestHelpers; +using Microsoft.AspNetCore.Http; +using NSubstitute; +using System.Diagnostics.CodeAnalysis; +using System.Reflection; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.UnitTests.Core.Endpoints.Library.Management.Index; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class LibrariesIndexViewEndpointTests +{ + private readonly IAuthorizationService _mockAuthorizationService; + private readonly LibrariesIndexViewEndpoint _sut; + + /// + /// Initializes a new instance of the class. + /// + public LibrariesIndexViewEndpointTests() + { + _mockAuthorizationService = Substitute.For(); + _sut = Factory.Create(_mockAuthorizationService); + TestHttpContextFactory.ConfigureSession(_sut.HttpContext, TestHttpContextFactory.CreateSession()); + _sut.HttpContext.Request.Path = "/en-us/libraries/manage"; + } + + [Fact] + public async Task ExecuteAsync_WhenTheUserHoldsTheManagePermission_ShouldRenderTheIndexViewWithManagementAllowed() + { + // Arrange + _mockAuthorizationService.IsInRoleAsync("Admin", Arg.Any()).Returns(false); + _mockAuthorizationService.HasPermissionAsync(AuthorizationPermission.CanCreateLibraries, Arg.Any()).Returns(true); + + // Act + IResult result = await _sut.ExecuteAsync(EmptyRequest.Instance, CancellationToken.None); + + // Assert + Assert.Equal("/Core/Views/Library/Management/Index.cshtml", GetRenderedViewName(result)); + LibrariesIndexPageDto model = Assert.IsType(GetRenderedModel(result)); + Assert.True(model.CanManageLibraries); + await _mockAuthorizationService.Received(1).IsInRoleAsync("Admin", Arg.Any()); + await _mockAuthorizationService.Received(1).HasPermissionAsync(AuthorizationPermission.CanCreateLibraries, Arg.Any()); + } + + [Fact] + public async Task ExecuteAsync_WhenTheUserIsAnAdministratorWithoutTheManagePermission_ShouldRenderTheIndexViewWithManagementAllowed() + { + // Arrange + _mockAuthorizationService.IsInRoleAsync("Admin", Arg.Any()).Returns(true); + _mockAuthorizationService.HasPermissionAsync(AuthorizationPermission.CanCreateLibraries, Arg.Any()).Returns(false); + + // Act + IResult result = await _sut.ExecuteAsync(EmptyRequest.Instance, CancellationToken.None); + + // Assert + Assert.Equal("/Core/Views/Library/Management/Index.cshtml", GetRenderedViewName(result)); + LibrariesIndexPageDto model = Assert.IsType(GetRenderedModel(result)); + Assert.True(model.CanManageLibraries); + await _mockAuthorizationService.DidNotReceive().HasPermissionAsync(AuthorizationPermission.CanCreateLibraries, Arg.Any()); + } + + [Fact] + public async Task ExecuteAsync_WhenTheUserIsNeitherAnAdministratorNorHoldsTheManagePermission_ShouldRenderTheIndexViewWithManagementDenied() + { + // Arrange + _mockAuthorizationService.IsInRoleAsync("Admin", Arg.Any()).Returns(false); + _mockAuthorizationService.HasPermissionAsync(AuthorizationPermission.CanCreateLibraries, Arg.Any()).Returns(false); + + // Act + IResult result = await _sut.ExecuteAsync(EmptyRequest.Instance, CancellationToken.None); + + // Assert + Assert.Equal("/Core/Views/Library/Management/Index.cshtml", GetRenderedViewName(result)); + LibrariesIndexPageDto model = Assert.IsType(GetRenderedModel(result)); + Assert.False(model.CanManageLibraries); + } + + /// + /// Reads the private view name of the rendered , which the result does not expose publicly. + /// + /// The result returned by the endpoint under test. + /// The name or path of the rendered view. + private static string GetRenderedViewName(IResult result) + { + RazorViewResult viewResult = Assert.IsType(result); + FieldInfo? viewNameField = typeof(RazorViewResult).GetField("_viewName", BindingFlags.Instance | BindingFlags.NonPublic); + Assert.NotNull(viewNameField); + return (string)viewNameField.GetValue(viewResult)!; + } + + /// + /// Reads the private model of the rendered , which the result does not expose publicly. + /// + /// The result returned by the endpoint under test. + /// The model passed to the rendered view. + private static object? GetRenderedModel(IResult result) + { + RazorViewResult viewResult = Assert.IsType(result); + FieldInfo? modelField = typeof(RazorViewResult).GetField("_model", BindingFlags.Instance | BindingFlags.NonPublic); + Assert.NotNull(modelField); + return modelField.GetValue(viewResult); + } +} 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 index e3f7b830..f1a52d84 100644 --- 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 @@ -26,6 +26,7 @@ public class SaveLibraryEndpointTests private readonly IApiHttpClient _mockApiHttpClient; private readonly SaveLibraryEndpoint _sut; private readonly LibraryDtoFixture _libraryDtoFixture = new(); + private readonly LibraryProviderSelectionDtoFixture _libraryProviderSelectionDtoFixture = new(); /// /// Initializes a new instance of the class. @@ -76,4 +77,29 @@ public class SaveLibraryEndpointTests using JsonDocument jsonDocument = JsonDocument.Parse(body); Assert.True(jsonDocument.RootElement.GetProperty("success").GetBoolean()); } + + [Fact] + public async Task ExecuteAsync_WhenProviderChoicesAreMade_ShouldForwardThemToTheApi() + { + // Arrange + LibraryDto request = _libraryDtoFixture.Create(); + request.Id = null; + request.MetadataProviders = _libraryProviderSelectionDtoFixture.CreateMany(2); + request.ArtworkProviders = []; + request.BookReaders = null; + _mockApiHttpClient.PostAsync(Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(_libraryDtoFixture.Create()); + + // Act + await _sut.ExecuteAsync(request, CancellationToken.None); + + // Assert + await _mockApiHttpClient.Received(1).PostAsync( + ApiRoutes.Libraries.ADD_LIBRARY, + Arg.Is(library => + library.MetadataProviders == request.MetadataProviders && + library.ArtworkProviders == request.ArtworkProviders && + library.BookReaders == null), + Arg.Any()); + } } diff --git a/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Library/Management/SetBookReaderEnabled/SetBookReaderEnabledEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Library/Management/SetBookReaderEnabled/SetBookReaderEnabledEndpointTests.cs deleted file mode 100644 index 879cee64..00000000 --- a/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Library/Management/SetBookReaderEnabled/SetBookReaderEnabledEndpointTests.cs +++ /dev/null @@ -1,80 +0,0 @@ -#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.Library.Management.SetBookReaderEnabled; -using Lumina.Presentation.Web.Fixtures.Common.Requests.Plugins; -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; -using EmptyRequest = Lumina.Presentation.Web.Common.Requests.Common.EmptyRequest; -#endregion - -namespace Lumina.Presentation.Web.UnitTests.Core.Endpoints.Library.Management.SetBookReaderEnabled; - -/// -/// Contains unit tests for the class. -/// -[ExcludeFromCodeCoverage] -public class SetBookReaderEnabledEndpointTests -{ - private readonly IApiHttpClient _mockApiHttpClient; - private readonly SetBookReaderEnabledEndpoint _sut; - private readonly SetBookReaderEnabledRequestFixture _setBookReaderEnabledRequestFixture = new(); - - /// - /// Initializes a new instance of the class. - /// - public SetBookReaderEnabledEndpointTests() - { - _mockApiHttpClient = Substitute.For(); - _sut = Factory.Create(_mockApiHttpClient); - } - - [Fact] - public async Task ExecuteAsync_WhenSuccessful_ShouldReturnSuccessJson() - { - // Arrange - SetBookReaderEnabledRequest request = _setBookReaderEnabledRequestFixture.Create(); - _mockApiHttpClient.PutAsync(Arg.Any(), Arg.Any(), Arg.Any()) - .Returns(new EmptyRequest()); - - // 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()); - } - - [Fact] - public async Task ExecuteAsync_WhenCalled_ShouldSendBookReaderEnabledChangeToApi() - { - // Arrange - SetBookReaderEnabledRequest request = _setBookReaderEnabledRequestFixture.Create(); - _mockApiHttpClient.PutAsync(Arg.Any(), Arg.Any(), Arg.Any()) - .Returns(new EmptyRequest()); - string expectedEndpoint = ApiRoutes.Libraries.SET_LIBRARY_BOOK_READER_ENABLED - .Replace("{libraryId}", request.LibraryId.ToString()) - .Replace("{pluginId}", request.PluginId.ToString()); - - // Act - await _sut.ExecuteAsync(request, CancellationToken.None); - - // Assert - await _mockApiHttpClient.Received(1).PutAsync( - expectedEndpoint, - Arg.Is(payload => - payload.LibraryId == request.LibraryId && - payload.PluginId == request.PluginId && - payload.IsEnabled == request.IsEnabled), - Arg.Any()); - } -}