From c7b8bc2f1cf565e37da771c19a88b8b478bec7bf Mon Sep 17 00:00:00 2001 From: Binary Alley Date: Wed, 23 Oct 2024 21:34:10 +0300 Subject: [PATCH 1/2] Replaces MVC with FastEndpoints in Lumina.Presentation.Api --- ....md => Aggregates.FileSystemManagement.md} | 0 docs/technical/domain/UbiquitousLanguage.md | 4 +- .../Common/Behaviors/ValidationBehavior.cs | 3 +- .../Converters/OptionalJsonConverter.cs | 44 -- .../OptionalJsonConverterFactory.cs | 38 - .../Repositories/Books/IBookRepository.cs | 9 +- .../Common/Actions/IGetAllRepositoryAction.cs | 2 +- .../Actions/IGetByIdRepositoryAction.cs | 2 +- .../Common/Actions/IInsertRepositoryAction.cs | 2 +- .../Common/Actions/IUpdateRepositoryAction.cs | 2 +- .../Repositories/Common/Base/IRepository.cs | 3 +- .../ApplicationLayerServices.cs | 10 +- .../Mapping/Common/Metadata/GenreMapping.cs | 36 + .../Common/Metadata/GenreModelMapping.cs | 37 + .../Mapping/Common/Metadata/TagMapping.cs | 36 + .../Common/Metadata/TagModelMapping.cs | 37 + .../FileManagement/DirectoryMappingConfig.cs | 50 -- .../FileManagement/FileMappingConfig.cs | 37 - .../FileSystemTreeMappingConfig.cs | 65 -- .../PathSegmentMappingConfig.cs | 24 - .../FileManagement/ThumbnailMappingConfig.cs | 25 - .../FileSystemTreeNodeResponseMapping.cs | 40 + .../Directories/DirectoryMapping.cs | 72 ++ .../GetDirectoriesRequestMapping.cs | 22 + .../GetDirectoryTreeRequestMapping.cs | 22 + .../GetTreeDirectoriesRequestMapping.cs | 22 + .../FileSystem/FileSystemItemMapping.cs | 64 ++ .../FileSystem/UnixRootItemMapping.cs | 33 + .../FileSystem/WindowsRootItemMapping.cs | 32 + .../FileSystemManagement/Files/FileMapping.cs | 68 ++ .../Files/GetFilesRequestMapping.cs | 22 + .../Files/GetTreeFilesRequestMapping.cs | 23 + .../Paths/CheckPathExistsQueryMapping.cs | 25 + .../Paths/CombinePathRequestMapping.cs | 25 + .../Paths/GetPathParentRequestMapping.cs | 24 + .../Paths/GetPathRootRequestMapping.cs | 22 + .../Paths/PathSegmentMapping.cs | 36 + .../Paths/SplitPathRequestMapping.cs | 24 + .../Paths/ValidatePathRequestMapping.cs | 24 + .../Thumbnails/GetThumbnailRequestMapping.cs | 22 + .../Thumbnails/ThumbnailMapping.cs | 25 + .../BookLibrary/BookMappingConfig.cs | 132 ---- .../Books/AddBookRequestMapping.cs | 40 + .../BookLibrary/Books/BookMapping.cs | 64 ++ .../BookLibrary/Books/BookModelMapping.cs | 223 ++++++ .../BookLibrary/Common/BookRatingMapping.cs | 39 + .../Common/BookRatingModelMapping.cs | 42 + .../BookLibrary/Common/IsbnMapping.cs | 37 + .../BookLibrary/Common/IsbnModelMapping.cs | 41 + .../GetDirectories/GetDirectoriesQuery.cs | 15 - .../GetTreeDirectoriesQuery.cs | 15 - .../Files/Queries/GetFiles/GetFilesQuery.cs | 15 - .../Queries/GetTreeFiles/GetTreeFilesQuery.cs | 15 - .../CombinePath/CombinePathCommand.cs | 16 - .../Commands/SplitPath/SplitPathCommand.cs | 16 - .../CheckPathExists/CheckPathExistsQuery.cs | 13 - .../GetPathParent/GetPathParentQuery.cs | 14 - .../Queries/GetPathRoot/GetPathRootQuery.cs | 13 - .../Queries/ValidatePath/ValidatePathQuery.cs | 12 - .../GetDirectories/GetDirectoriesQuery.cs | 20 + .../GetDirectoriesQueryHandler.cs | 20 +- .../GetDirectoriesQueryValidator.cs | 4 +- .../GetDirectoryTree/GetDirectoryTreeQuery.cs | 12 +- .../GetDirectoryTreeQueryHandler.cs | 18 +- .../GetDirectoryTreeQueryValidator.cs | 4 +- .../GetTreeDirectoriesQuery.cs | 20 + .../GetTreeDirectoriesQueryHandler.cs | 20 +- .../GetTreeDirectoriesQueryValidator.cs | 4 +- .../Queries/GetDrives/GetDrivesQuery.cs | 4 +- .../GetDrives/GetDrivesQueryHandler.cs | 18 +- .../GetFileSystem/GetFileSystemQuery.cs | 4 +- .../GetFileSystemQueryHandler.cs | 6 +- .../Files/Queries/GetFiles/GetFilesQuery.cs | 20 + .../Queries/GetFiles/GetFilesQueryHandler.cs | 20 +- .../GetFiles/GetFilesQueryValidator.cs | 4 +- .../Queries/GetTreeFiles/GetTreeFilesQuery.cs | 20 + .../GetTreeFiles/GetTreeFilesQueryHandler.cs | 20 +- .../GetTreeFilesQueryValidator.cs | 4 +- .../CombinePath/CombinePathCommand.cs | 19 + .../CombinePath/CombinePathCommandHandler.cs | 14 +- .../CombinePathCommandValidator.cs | 10 +- .../Commands/SplitPath/SplitPathCommand.cs | 18 + .../SplitPath/SplitPathCommandHandler.cs | 19 +- .../SplitPath/SplitPathCommandValidator.cs | 4 +- .../CheckPathExists/CheckPathExistsQuery.cs | 18 + .../CheckPathExistsQueryHandler.cs | 8 +- .../CheckPathExistsQueryValidator.cs | 4 +- .../GetPathParent/GetPathParentQuery.cs | 18 + .../GetPathParentQueryHandler.cs | 19 +- .../GetPathParentQueryValidator.cs | 4 +- .../Queries/GetPathRoot/GetPathRootQuery.cs | 17 + .../GetPathRoot/GetPathRootQueryHandler.cs | 19 +- .../GetPathRoot/GetPathRootQueryValidator.cs | 4 +- .../GetPathSeparator/GetPathSeparatorQuery.cs | 4 +- .../GetPathSeparatorQueryHandler.cs | 6 +- .../Queries/ValidatePath/ValidatePathQuery.cs | 16 + .../ValidatePath/ValidatePathQueryHandler.cs | 12 +- .../ValidatePathQueryValidator.cs | 4 +- .../Queries/GetThumbnail/GetThumbnailQuery.cs | 11 +- .../GetThumbnail/GetThumbnailQueryHandler.cs | 19 +- .../GetThumbnailQueryValidator.cs | 6 +- .../Books/Commands/AddBook/AddBookCommand.cs | 22 +- .../Commands/AddBook/AddBookCommandHandler.cs | 30 +- .../AddBook/AddBookCommandValidator.cs | 233 +++--- .../Books/Queries/GetBooks/GetBooksQuery.cs | 6 +- .../Queries/GetBooks/GetBooksQueryHandler.cs | 18 +- .../Lumina.Application.csproj | 3 - .../Common/GenreEntity.cs} | 8 +- .../Common/IStorageEntity.cs | 2 +- .../Common/LanguageInfoEntity.cs} | 10 +- .../Common/RatingEntity.cs} | 6 +- .../Common/ReleaseInfoEntity.cs} | 8 +- .../Common/TagEntity.cs} | 8 +- .../FileSystemItemEntity.cs} | 12 +- .../MediaContributorEntity.cs | 16 + .../MediaContributorNameEntity.cs | 16 + .../MediaContributorRoleEntity.cs | 16 + .../BookLibrary/BookEntity.cs} | 22 +- .../BookLibrary/BookRatingEntity.cs | 22 + .../BookLibrary/BookSeriesEntity.cs} | 12 +- .../BookLibrary/IsbnEntity.cs | 17 + .../WrittenContentMetadataEntity.cs | 34 + src/Lumina.Contracts/Lumina.Contracts.csproj | 4 - .../MediaContributorModel.cs | 16 - .../MediaContributorNameModel.cs | 16 - .../MediaContributorRoleModel.cs | 16 - .../BookLibrary/BookRatingModel.cs | 22 - .../BookLibrary/IsbnModel.cs | 17 - .../WrittenContentMetadataModel.cs | 34 - .../Directories/GetDirectoriesRequest.cs | 17 + .../Directories/GetDirectoryTreeRequest.cs | 19 + .../Directories/GetTreeDirectoriesRequest.cs | 17 + .../Files/GetFilesRequest.cs | 17 + .../Files/GetTreeFilesRequest.cs | 17 + .../Path/CheckPathExistsRequest.cs | 17 + .../Path/CombinePathRequest.cs | 17 + .../Path/GetPathParentRequest.cs | 15 + .../Path/GetPathRootRequest.cs | 15 + .../Path/SplitPathRequest.cs | 15 + .../Path/ValidatePathRequest.cs | 15 + .../Thumbnails/GetThumbnailRequest.cs | 17 + .../BookLibrary/{ => Books}/AddBookRequest.cs | 22 +- .../BookLibrary/Books/GetBookRequest.cs | 15 + .../FileManagement/PathExistsResponse.cs | 14 - .../FileManagement/PathSegmentResponse.cs | 14 - .../FileManagement/PathSeparatorResponse.cs | 14 - .../FileManagement/PathValidResponse.cs | 14 - .../Common}/FileSystemTreeNodeResponse.cs | 8 +- .../Directories}/DirectoryResponse.cs | 18 +- .../FileSystem}/FileSystemTypeResponse.cs | 8 +- .../Files}/FileResponse.cs | 16 +- .../Path/PathExistsResponse.cs | 14 + .../Path/PathSegmentResponse.cs | 14 + .../Path/PathSeparatorResponse.cs | 14 + .../Path/PathValidResponse.cs | 14 + .../Thumbnails}/ThumbnailResponse.cs | 6 +- .../BookLibrary/Books/BookResponse.cs | 55 ++ .../Common/Configuration/BookConfiguration.cs | 20 +- .../Configuration/GenreConfiguration.cs | 10 +- .../Common/Configuration/TagConfiguration.cs | 10 +- .../Core/Repositories/Books/BookRepository.cs | 18 +- .../Core/UoW/LuminaDbContext.cs | 6 +- .../Lumina.DataAccess.csproj | 11 +- .../DomainLayerServices.cs | 8 +- ...ment.cs => Errors.FileSystemManagement.cs} | 36 +- .../Common/Errors/Errors.MediaContributor.cs | 20 +- .../Common/Errors/Errors.Metadata.cs | 62 +- .../Common/Errors/Errors.Permission.cs | 2 +- .../Common/Errors/Errors.Thumbnails.cs | 4 +- .../Common/Errors/Errors.WrittenContent.cs | 48 +- .../Common/Models/Core/AggregateRoot.cs | 6 +- .../ValueObjects/Metadata/BaseMetadata.cs | 18 +- .../Common/ValueObjects/Metadata/Genre.cs | 2 +- .../ValueObjects/Metadata/LanguageInfo.cs | 2 +- .../Common/ValueObjects/Metadata/Tag.cs | 2 +- .../Entities/Directory.cs | 5 +- .../Entities/File.cs | 7 +- .../Entities/UnixRootItem.cs | 11 +- .../Entities/WindowsRootItem.cs | 5 +- .../FileSystemItem.cs | 10 +- .../Services/DirectoryProviderService.cs | 17 +- .../Services/DirectoryService.cs | 18 +- .../Services/DriveService.cs | 7 +- .../Services/FileProviderService.cs | 30 +- .../Services/FileService.cs | 20 +- .../Services/FileSystemPermissionsService.cs | 46 +- .../Services/FileTypeService.cs | 6 +- .../Services/IDirectoryProviderService.cs | 6 +- .../Services/IDirectoryService.cs | 8 +- .../Services/IDriveService.cs | 7 +- .../Services/IFileProviderService.cs | 8 +- .../Services/IFileService.cs | 10 +- .../Services/IFileSystemPermissionsService.cs | 8 +- .../Services/IFileTypeService.cs | 6 +- .../Services/IPathService.cs | 4 +- .../Services/IThumbnailService.cs | 4 +- .../Services/PathService.cs | 8 +- .../Services/ThumbnailService.cs | 6 +- .../Environment/EnvironmentContext.cs | 4 +- .../Environment/IEnvironmentContext.cs | 8 +- .../Strategies/Path/IPathStrategy.cs | 4 +- .../Strategies/Path/IUnixPathStrategy.cs | 4 +- .../Strategies/Path/IWindowsPathStrategy.cs | 4 +- .../Strategies/Path/UnixPathStrategy.cs | 16 +- .../Strategies/Path/WindowsPathStrategy.cs | 34 +- .../Platform/IOperatingSystemInfo.cs | 2 +- .../Strategies/Platform/IPlatformContext.cs | 8 +- .../Platform/IPlatformContextFactory.cs | 4 +- .../Platform/IPlatformContextManager.cs | 6 +- .../Platform/IUnixPlatformContext.cs | 4 +- .../Platform/IWindowsPlatformContext.cs | 4 +- .../Platform/OperatingSystemInfo.cs | 2 +- .../Platform/PlatformContextFactory.cs | 6 +- .../Platform/PlatformContextManager.cs | 4 +- .../Platform/UnixPlatformContext.cs | 4 +- .../Platform/WindowsPlatformContext.cs | 5 +- .../ValueObjects/FileSystemPathId.cs | 4 +- .../ValueObjects/PathSegment.cs | 4 +- .../ValueObjects/StreamInfo.cs | 8 +- .../ValueObjects/Thumbnail.cs | 6 +- .../BookLibraryAggregate/ValueObjects/Isbn.cs | 2 +- .../ValueObjects/WrittenContentMetadata.cs | 26 +- .../Common/Errors/Errors.Configuration.cs | 4 +- .../CommonSettingsModelValidator.cs | 2 +- .../DatabaseSettingsModelValidator.cs | 2 +- .../Lumina.Infrastructure.csproj | 6 +- .../Configuration/ConfigureSwaggerOptions.cs | 64 -- .../PresentationApiLayerServices.cs | 79 +- .../Errors/CustomProblemDetailsFactory.cs | 118 --- .../BookLibrary/BookMappingConfig.cs | 27 - .../Common/ModelBinders/UrlStringBinder.cs | 38 - .../ApiRoutes.Directories.cs | 17 + .../FileSystemManagement/ApiRoutes.Drives.cs | 15 + .../ApiRoutes.FileSystem.cs | 15 + .../FileSystemManagement/ApiRoutes.Files.cs | 16 + .../FileSystemManagement/ApiRoutes.Path.cs | 21 + .../ApiRoutes.Thumbnails.cs | 15 + .../Routes/Maintenance/ApiRoutes.Health.cs | 15 + .../BookLibrary/ApiRoutes.Books.cs | 17 + .../Core/Controllers/Common/ApiController.cs | 69 -- .../FileManagement/DirectoriesController.cs | 101 --- .../FileManagement/DrivesController.cs | 43 - .../FileManagement/FileSystemController.cs | 41 - .../FileManagement/FilesController.cs | 78 -- .../FileManagement/PathController.cs | 124 --- .../FileManagement/ThumbnailsController.cs | 46 -- .../Maintenance/HealthController.cs | 24 - .../BookLibrary/Books/BooksController.cs | 55 -- .../Core/Endpoints/Common/BaseEndpoint.cs | 102 +++ .../GetDirectories/GetDirectoriesEndpoint.cs | 57 ++ .../GetDirectoriesEndpointSummary.cs | 29 + .../GetDirectoryTreeEndpoint.cs | 57 ++ .../GetDirectoryTreeEndpointSummary.cs | 30 + .../GetTreeDirectoriesEndpoint.cs | 56 ++ .../GetTreeDirectoriesEndpointSummary.cs | 29 + .../Drives/GetDrives/GetDrivesEndpoint.cs | 54 ++ .../GetDrives/GetDrivesEndpointSummary.cs | 24 + .../FileSystem/GetType/GetTypeEndpoint.cs | 56 ++ .../GetType/GetTypeEndpointSummary.cs | 23 + .../Files/GetFiles/GetFilesEndpoint.cs | 56 ++ .../Files/GetFiles/GetFilesEndpointSummary.cs | 29 + .../GetTreeFiles/GetTreeFilesEndpoint.cs | 56 ++ .../GetTreeFilesEndpointSummary.cs | 29 + .../CheckPathExistsEndpoint.cs | 54 ++ .../CheckPathExistsEndpointSummary.cs | 29 + .../Path/CombinePath/CombinePathEndpoint.cs | 55 ++ .../CombinePath/CombinePathEndpointSummary.cs | 28 + .../GetPathParent/GetPathParentEndpoint.cs | 56 ++ .../GetPathParentEndpointSummary.cs | 28 + .../Path/GetPathRoot/GetPathRootEndpoint.cs | 55 ++ .../GetPathRoot/GetPathRootEndpointSummary.cs | 27 + .../GetPathSeparatorEndpoint.cs | 51 ++ .../GetPathSeparatorEndpointSummary.cs | 23 + .../Path/SplitPath/SplitPathEndpoint.cs | 56 ++ .../SplitPath/SplitPathEndpointSummary.cs | 28 + .../Path/ValidatePath/ValidatePathEndpoint.cs | 54 ++ .../ValidatePathEndpointSummary.cs | 27 + .../GetThumbnail/GetThumbnailEndpoint.cs | 57 ++ .../GetThumbnailEndpointSummary.cs | 27 + .../Maintenance/CheckHealthEndpoint.cs | 56 ++ .../Books/AddBook/AddBookEndpoint.cs | 55 ++ .../Books/AddBook/AddBookEndpointSummary.cs | 50 ++ .../Books/GetBooks/GetBooksEndpoint.cs | 54 ++ .../Books/GetBooks/GetBooksEndpointSummary.cs | 24 + .../BookLibrary/GetBook/GetBookEndpoint.cs | 56 ++ .../Lumina.Presentation.Api.csproj | 8 +- src/Lumina.Presentation.Api/Program.cs | 24 +- .../Common/Api/ApiHttpClient.cs | 2 +- .../Common/Api/IApiHttpClient.cs | 2 +- .../BlobDataModel.cs | 2 +- .../DirectoryModel.cs | 2 +- .../FileModel.cs | 2 +- .../FileSystemItemModel.cs | 2 +- .../FileSystemTreeNodeModel.cs | 2 +- .../FileSystemTypeModel.cs | 2 +- .../PathExistsModel.cs | 2 +- .../PathSegmentModel.cs | 2 +- .../PathSeparatorModel.cs | 2 +- .../PathValidModel.cs | 2 +- .../DirectoriesController.cs | 4 +- .../DrivesController.cs | 4 +- .../FileSystemController.cs | 4 +- .../FilesController.cs | 4 +- .../PathController.cs | 4 +- .../FileSystemBrowser/Default.cshtml | 2 +- src/Lumina.sln | 2 +- .../Lumina.DataAccess.IntegrationTests.csproj | 8 +- .../Common/Converters/BookJsonConverter.cs | 22 +- .../Common/Setup/LuminaApiFactory.cs | 2 - .../DirectoriesControllerTests.cs | 639 --------------- .../FileManagement/FilesControllerTests.cs | 329 -------- .../FileManagement/PathControllerTests.cs | 634 --------------- .../ThumbnailsControllerTests.cs | 130 --- .../GetDirectoriesEndpointTests.cs | 204 +++++ .../GetDirectoryTreeEndpointTests.cs | 411 ++++++++++ .../GetTreeDirectoriesEndpointTests.cs | 247 ++++++ .../Drives/GetDrivesEndpointTests.cs} | 36 +- .../FileSystem/GetTypeEndpointTests.cs} | 30 +- .../Files/GetFilesEndpointTests.cs | 243 ++++++ .../Files/GetTreeFilesEndpointTests.cs | 243 ++++++ .../Fixtures/FileSystemStructureFixture.cs | 14 +- .../FileSystemTreeNodeResponseFixture.cs | 4 +- .../Fixtures/TestImageFixture.cs | 4 +- .../Path/CheckPathExistsEndpointTests.cs | 126 +++ .../Path/CombinePathEndpointTests.cs | 123 +++ .../Path/GetPathParentEndpointTests.cs | 191 +++++ .../Path/GetPathRootEndpointTests.cs | 149 ++++ .../Path/GetPathSeparatorEndpointTests.cs | 105 +++ .../Path/SplitPathEndpointTests.cs | 132 ++++ .../Path/ValidatePathEndpointTests.cs | 110 +++ .../Thumbnails/GetThumbnailEndpointTests.cs | 155 ++++ .../Books/AddBookEndpointTests.cs} | 487 ++++++------ .../Books/Fixtures/AddBookRequestFixture.cs | 124 +-- .../Books/Fixtures/DomainBookFixture.cs | 2 +- .../Books/GetBooksEndpointTests.cs | 86 ++ ...a.Presentation.Api.IntegrationTests.csproj | 10 +- .../OptionalJsonConverterFactoryFixture.cs | 13 - .../OptionalJsonConverterFactoryTests.cs | 111 --- .../Converters/OptionalJsonConverterTests.cs | 136 ---- .../Common/Metadata/GenreMappingTests.cs | 78 ++ .../Common/Metadata/GenreModelMappingTests.cs | 127 +++ .../Common/Metadata/TagMappingTests.cs | 80 ++ .../Common/Metadata/TagModelMappingTests.cs | 128 +++ .../DirectoryMappingConfigTests.cs | 113 --- .../FileManagement/FileMappingConfigTests.cs | 89 --- .../FileSystemTreeMappingConfigTests.cs | 158 ---- .../ThumbnailMappingConfigTests.cs | 109 --- .../FileSystemTreeNodeResponseMappingTests.cs | 61 ++ .../Directories/DirectoryMappingTests.cs | 142 ++++ .../GetDirectoriesRequestMappingTests.cs | 43 + .../GetDirectoryTreeRequestMappingTests.cs | 44 ++ .../GetTreeDirectoriesRequestMappingTests.cs | 43 + .../FileSystem/FileSystemItemMappingTests.cs | 229 ++++++ .../Fixtures/FileSystemItemFixture.cs | 26 + .../FileSystem/UnixRootItemMappingTests.cs | 44 ++ .../FileSystem/WindowsRootItemMappingTests.cs | 65 ++ .../Files/FileMappingTests.cs | 119 +++ .../Files/GetFilesRequestMappingTests.cs | 43 + .../Files/GetTreeFilesRequestMappingTests.cs | 43 + .../Paths/CheckPathExistsQueryMappingTests.cs | 82 ++ .../Paths/CombinePathRequestMappingTests.cs | 82 ++ .../Paths/GetPathParentRequestMappingTests.cs | 79 ++ .../Paths/GetPathRootRequestMappingTests.cs | 80 ++ .../Paths/PathSegmentMappingTests.cs} | 41 +- .../Paths/SplitPathRequestMappingTests.cs | 78 ++ .../Paths/ValidatePathRequestMappingTests.cs | 80 ++ .../GetThumbnailRequestMappingTests.cs | 82 ++ .../Thumbnails/ThumbnailMappingTests.cs | 101 +++ .../Books/AddBookRequestMappingTests.cs | 166 ++++ .../BookLibrary/Books/BookMappingTests.cs | 78 ++ .../Books/BookModelMappingTests.cs | 350 +++++++++ .../Common/BookRatingMappingTests.cs | 121 +++ .../Common/BookRatingModelMappingTests.cs | 153 ++++ .../BookLibrary/Common/IsbnMappingTests.cs | 102 +++ .../Common/IsbnModelMappingTests.cs | 154 ++++ .../GetTreeDirectoriesQueryHandlerTests.cs | 168 ---- .../Directories/Fixtures/DirectoryFixture.cs | 6 +- .../Fixtures/DirectoryResponseFixture.cs | 4 +- .../Fixtures/FileSystemItemModelFixture.cs | 18 +- .../FileSystemTreeNodeResponseFixture.cs | 4 +- .../Fixtures/GetDirectoriesQueryFixture.cs | 4 +- .../GetDirectoriesQueryHandlerTests.cs | 77 +- .../GetDirectoriesQueryValidatorTests.cs | 12 +- .../Fixtures/GetDirectoryTreeQueryFixture.cs | 4 +- .../GetDirectoryTreeQueryHandlerTests.cs | 58 +- .../GetDirectoryTreeQueryValidatorTests.cs | 12 +- .../GetTreeDirectoriesQueryFixture.cs | 4 +- .../GetTreeDirectoriesQueryHandlerTests.cs | 232 ++++++ .../GetTreeDirectoriesQueryValidatorTests.cs | 12 +- .../Fixtures/GetDrivesQueryFixture.cs | 4 +- .../GetDrives/GetDrivesQueryHandlerTests.cs | 50 +- .../Fixtures/UnixRootItemFixture.cs | 16 +- .../Fixtures/WindowsRootItemFixture.cs | 35 + .../GetFileSystemQueryHandlerTests.cs | 8 +- .../Files/Fixtures/FileFixture.cs | 4 +- .../Files/Fixtures/FileResponseFixture.cs | 4 +- .../GetFiles/Fixtures/GetFilesQueryFixture.cs | 4 +- .../GetFiles/GetFilesQueryHandlerTests.cs | 82 +- .../GetFiles/GetFilesQueryValidatorTests.cs | 12 +- .../Fixtures/GetTreeFilesQueryFixture.cs | 4 +- .../GetTreeFilesQueryHandlerTests.cs | 81 +- .../GetTreeFilesQueryValidatorTests.cs | 12 +- .../Fixtures/FileSystemPathIdFixture.cs | 4 +- .../CombinePathCommandHandlerTests.cs | 24 +- .../CombinePathCommandValidatorTests.cs | 18 +- .../Fixtures/CombinePathCommandFixture.cs | 4 +- .../Fixtures/SplitPathCommandFixture.cs | 4 +- .../SplitPath/SplitPathCommandHandlerTests.cs | 59 +- .../SplitPathCommandValidatorTests.cs | 12 +- .../Pahs/Fixtures/PathSegmentFixture.cs | 4 +- .../Fixtures/PathSegmentResponseFixture.cs | 4 +- .../Fixtures/PathSeparatorResponseFixture.cs | 4 +- .../CheckPathExistsQueryHandlerTests.cs | 30 +- .../CheckPathExistsQueryValidatorTests.cs | 12 +- .../Fixtures/CheckPathExistsQueryFixture.cs | 4 +- .../Fixtures/GetPathParentQueryFixture.cs | 4 +- .../GetPathParentQueryHandlerTests.cs | 46 +- .../GetPathParentQueryValidatorTests.cs | 12 +- .../Fixtures/GetPathRootQueryFixture.cs | 4 +- .../GetPathRootQueryHandlerTests.cs | 54 +- .../GetPathRootQueryValidatorTests.cs | 12 +- .../GetPathSeparatorQueryHandlerTests.cs | 8 +- .../Fixtures/ValidatePathQueryFixure.cs | 4 +- .../ValidatePathQueryHandlerTests.cs | 18 +- .../ValidatePathQueryValidatorTests.cs | 12 +- .../Fixtures/ThumbnailResponseFixture.cs | 4 +- .../Fixtures/GetThumbnailQueryFixture.cs | 4 +- .../GetThumbnailQueryHandlerTests.cs | 40 +- .../GetThumbnailQueryValidatorTests.cs | 12 +- .../AddBook/AddBookCommandHandlerTests.cs | 107 ++- .../AddBook/AddBookCommandValidatorTests.cs | 208 ++--- .../AddBook/Fixtures/AddBookCommandFixture.cs | 92 +-- .../AddBook/Fixtures/AddBookRequestFixture.cs | 274 +++++++ .../AddBook/Fixtures/BookEntityFixture.cs | 145 ++++ .../AddBook/Fixtures/DomainBookFixture.cs | 107 +++ .../Fixtures/BookRatingEntityFixture.cs | 72 ++ .../Common/Fixtures/BookRatingFixture.cs | 85 ++ .../Common/Fixtures/IsbnEntityFixture.cs | 98 +++ .../Common/Fixtures/IsbnFixture.cs | 70 ++ .../Lumina.Application.UnitTests.csproj | 18 +- .../DataAccessLayerServicesTests.cs | 16 +- .../Repositories/Books/BookRepositoryTests.cs | 50 +- .../Books/Fixtures/BookModelFixture.cs | 48 +- .../Lumina.DataAccess.UnitTests.csproj | 20 +- .../Entities/DirectoryTests.cs | 14 +- .../Entities/FileTests.cs | 10 +- .../Entities/Fixtures/DirectoryFixture.cs | 6 +- .../Entities/Fixtures/FileFixture.cs | 4 +- .../Entities/UnixRootItemTests.cs | 10 +- .../Entities/WindowsRootItemTests.cs | 12 +- .../FileSystemItemTests.cs | 13 +- .../Fixtures/FileSystemItemFixture.cs | 6 +- .../Services/DirectoryProviderServiceTests.cs | 63 +- .../Services/DirectoryServiceTests.cs | 41 +- .../Services/DriveServiceTests.cs | 11 +- .../Services/FileProviderServiceTests.cs | 35 +- .../Services/FileServiceTests.cs | 56 +- .../Services/FileTypeServiceTests.cs | 12 +- .../Services/Fixtures/ImageTypeFixture.cs | 2 +- .../Services/PathServiceTests.cs | 44 +- .../Services/ThumbnailServiceTests.cs | 14 +- .../Environment/EnvironmentContextTests.cs | 6 +- .../Strategies/Path/UnixPathStrategyTests.cs | 22 +- .../Path/WindowsPathStrategyTests.cs | 34 +- .../INonExistentPlatformContextFixture.cs | 4 +- .../Platform/PlatformContextFactoryTests.cs | 8 +- .../Platform/PlatformContextManagerTests.cs | 4 +- .../Platform/PlatformContextTests.cs | 6 +- .../ValueObjects/FileSystemPathIdTests.cs | 12 +- .../Fixtures/FileSystemPathIdFixture.cs | 42 + .../Fixtures/PathSegmentFixture.cs | 4 +- .../Fixtures/StreamInfoFixture.cs | 4 +- .../ValueObjects/Fixtures/ThumbnailFixture.cs | 4 +- .../ValueObjects/PathSegmentTests.cs | 12 +- .../ValueObjects/StreamInfoTests.cs | 22 +- .../ValueObjects/ThumbnailTests.cs | 6 +- .../Lumina.Domain.UnitTests.csproj | 18 +- .../CommonSettingsModelValidatorTests.cs | 5 +- .../DatabaseSettingsModelValidatorTests.cs | 2 +- .../Lumina.Infrastructure.UnitTests.csproj | 18 +- .../Controllers/Common/ApiControllerTests.cs | 278 ------- .../Common/Fixtures/ApiControllerFixture.cs | 36 - .../DirectoriesControllerTests.cs | 228 ------ .../FileManagement/DrivesControllerTests.cs | 149 ---- .../FileSystemControllerTests.cs | 115 --- .../FileManagement/FilesControllerTests.cs | 165 ---- .../FileManagement/PathControllerTests.cs | 737 ------------------ .../ThumbnailsControllerTests.cs | 157 ---- .../Endpoints/Common/BaseEndpointTests.cs | 191 +++++ .../Common/Fixtures/BaseEndpointFixture.cs | 57 ++ .../GetDirectoriesEndpointTests.cs | 167 ++++ .../GetDirectoryTreeEndpointTests.cs | 170 ++++ .../GetTreeDirectoriesEndpointTests.cs | 170 ++++ .../Drives/GetDrivesEndpointTests.cs | 127 +++ .../FileSystem/GetTypeEndpointTests.cs | 115 +++ .../Files/GetFilesEndpointTests.cs | 170 ++++ .../Files/GetTreeFilesEndpointTests.cs | 171 ++++ .../Fixtures/CheckPathExistsRequestFixture.cs | 30 + .../Fixtures/CombinePathRequestFixture.cs | 30 + .../FileSystemTreeNodeResponseFixture.cs | 4 +- .../Fixtures/GetPathParentRequestFixture.cs | 28 + .../Fixtures/GetPathRootRequestFixture.cs | 28 + .../Fixtures/GetThumbnailRequestFixture.cs | 30 + .../Fixtures/PathSegmentResponseFixture.cs | 4 +- .../Fixtures/PathSeparatorResponseFixture.cs | 4 +- .../Fixtures/SplitPathRequestFixture.cs | 28 + .../Fixtures/ThumbnailResponseFixture.cs | 4 +- .../Fixtures/ValidatePathRequestFixture.cs | 28 + .../Path/CheckPathExistsEndpointTests.cs | 104 +++ .../Path/CombinePathEndpointTests.cs | 166 ++++ .../Path/GetPathParentEndpointTests.cs | 166 ++++ .../Path/GetPathRootEndpointTests.cs | 164 ++++ .../Path/GetPathSeparatorEndpointTests.cs | 98 +++ .../Path/SplitPathEndpointTests.cs | 144 ++++ .../Path/ValidatePathEndpointTests.cs | 104 +++ .../Thumbnails/GetThumbnailEndpointTests.cs | 164 ++++ .../BookLibrary/Books/AddBookEndpointTests.cs | 10 + .../Core/ModelBinders/UrlStringBinderTests.cs | 114 --- .../Lumina.Presentation.Api.UnitTests.csproj | 18 +- 519 files changed, 15329 insertions(+), 8539 deletions(-) rename docs/technical/domain/{Aggregates.FileManagement.md => Aggregates.FileSystemManagement.md} (100%) delete mode 100644 src/Lumina.Application/Common/Converters/OptionalJsonConverter.cs delete mode 100644 src/Lumina.Application/Common/Converters/OptionalJsonConverterFactory.cs create mode 100644 src/Lumina.Application/Common/Mapping/Common/Metadata/GenreMapping.cs create mode 100644 src/Lumina.Application/Common/Mapping/Common/Metadata/GenreModelMapping.cs create mode 100644 src/Lumina.Application/Common/Mapping/Common/Metadata/TagMapping.cs create mode 100644 src/Lumina.Application/Common/Mapping/Common/Metadata/TagModelMapping.cs delete mode 100644 src/Lumina.Application/Common/Mapping/FileManagement/DirectoryMappingConfig.cs delete mode 100644 src/Lumina.Application/Common/Mapping/FileManagement/FileMappingConfig.cs delete mode 100644 src/Lumina.Application/Common/Mapping/FileManagement/FileSystemTreeMappingConfig.cs delete mode 100644 src/Lumina.Application/Common/Mapping/FileManagement/PathSegmentMappingConfig.cs delete mode 100644 src/Lumina.Application/Common/Mapping/FileManagement/ThumbnailMappingConfig.cs create mode 100644 src/Lumina.Application/Common/Mapping/FileSystemManagement/Common/FileSystemTreeNodeResponseMapping.cs create mode 100644 src/Lumina.Application/Common/Mapping/FileSystemManagement/Directories/DirectoryMapping.cs create mode 100644 src/Lumina.Application/Common/Mapping/FileSystemManagement/Directories/GetDirectoriesRequestMapping.cs create mode 100644 src/Lumina.Application/Common/Mapping/FileSystemManagement/Directories/GetDirectoryTreeRequestMapping.cs create mode 100644 src/Lumina.Application/Common/Mapping/FileSystemManagement/Directories/GetTreeDirectoriesRequestMapping.cs create mode 100644 src/Lumina.Application/Common/Mapping/FileSystemManagement/FileSystem/FileSystemItemMapping.cs create mode 100644 src/Lumina.Application/Common/Mapping/FileSystemManagement/FileSystem/UnixRootItemMapping.cs create mode 100644 src/Lumina.Application/Common/Mapping/FileSystemManagement/FileSystem/WindowsRootItemMapping.cs create mode 100644 src/Lumina.Application/Common/Mapping/FileSystemManagement/Files/FileMapping.cs create mode 100644 src/Lumina.Application/Common/Mapping/FileSystemManagement/Files/GetFilesRequestMapping.cs create mode 100644 src/Lumina.Application/Common/Mapping/FileSystemManagement/Files/GetTreeFilesRequestMapping.cs create mode 100644 src/Lumina.Application/Common/Mapping/FileSystemManagement/Paths/CheckPathExistsQueryMapping.cs create mode 100644 src/Lumina.Application/Common/Mapping/FileSystemManagement/Paths/CombinePathRequestMapping.cs create mode 100644 src/Lumina.Application/Common/Mapping/FileSystemManagement/Paths/GetPathParentRequestMapping.cs create mode 100644 src/Lumina.Application/Common/Mapping/FileSystemManagement/Paths/GetPathRootRequestMapping.cs create mode 100644 src/Lumina.Application/Common/Mapping/FileSystemManagement/Paths/PathSegmentMapping.cs create mode 100644 src/Lumina.Application/Common/Mapping/FileSystemManagement/Paths/SplitPathRequestMapping.cs create mode 100644 src/Lumina.Application/Common/Mapping/FileSystemManagement/Paths/ValidatePathRequestMapping.cs create mode 100644 src/Lumina.Application/Common/Mapping/FileSystemManagement/Thumbnails/GetThumbnailRequestMapping.cs create mode 100644 src/Lumina.Application/Common/Mapping/FileSystemManagement/Thumbnails/ThumbnailMapping.cs delete mode 100644 src/Lumina.Application/Common/Mapping/WrittenContentLibrary/BookLibrary/BookMappingConfig.cs create mode 100644 src/Lumina.Application/Common/Mapping/WrittenContentLibrary/BookLibrary/Books/AddBookRequestMapping.cs create mode 100644 src/Lumina.Application/Common/Mapping/WrittenContentLibrary/BookLibrary/Books/BookMapping.cs create mode 100644 src/Lumina.Application/Common/Mapping/WrittenContentLibrary/BookLibrary/Books/BookModelMapping.cs create mode 100644 src/Lumina.Application/Common/Mapping/WrittenContentLibrary/BookLibrary/Common/BookRatingMapping.cs create mode 100644 src/Lumina.Application/Common/Mapping/WrittenContentLibrary/BookLibrary/Common/BookRatingModelMapping.cs create mode 100644 src/Lumina.Application/Common/Mapping/WrittenContentLibrary/BookLibrary/Common/IsbnMapping.cs create mode 100644 src/Lumina.Application/Common/Mapping/WrittenContentLibrary/BookLibrary/Common/IsbnModelMapping.cs delete mode 100644 src/Lumina.Application/Core/FileManagement/Directories/Queries/GetDirectories/GetDirectoriesQuery.cs delete mode 100644 src/Lumina.Application/Core/FileManagement/Directories/Queries/GetTreeDirectories/GetTreeDirectoriesQuery.cs delete mode 100644 src/Lumina.Application/Core/FileManagement/Files/Queries/GetFiles/GetFilesQuery.cs delete mode 100644 src/Lumina.Application/Core/FileManagement/Files/Queries/GetTreeFiles/GetTreeFilesQuery.cs delete mode 100644 src/Lumina.Application/Core/FileManagement/Paths/Commands/CombinePath/CombinePathCommand.cs delete mode 100644 src/Lumina.Application/Core/FileManagement/Paths/Commands/SplitPath/SplitPathCommand.cs delete mode 100644 src/Lumina.Application/Core/FileManagement/Paths/Queries/CheckPathExists/CheckPathExistsQuery.cs delete mode 100644 src/Lumina.Application/Core/FileManagement/Paths/Queries/GetPathParent/GetPathParentQuery.cs delete mode 100644 src/Lumina.Application/Core/FileManagement/Paths/Queries/GetPathRoot/GetPathRootQuery.cs delete mode 100644 src/Lumina.Application/Core/FileManagement/Paths/Queries/ValidatePath/ValidatePathQuery.cs create mode 100644 src/Lumina.Application/Core/FileSystemManagement/Directories/Queries/GetDirectories/GetDirectoriesQuery.cs rename src/Lumina.Application/Core/{FileManagement => FileSystemManagement}/Directories/Queries/GetDirectories/GetDirectoriesQueryHandler.cs (71%) rename src/Lumina.Application/Core/{FileManagement => FileSystemManagement}/Directories/Queries/GetDirectories/GetDirectoriesQueryValidator.cs (75%) rename src/Lumina.Application/Core/{FileManagement => FileSystemManagement}/Directories/Queries/GetDirectoryTree/GetDirectoryTreeQuery.cs (61%) rename src/Lumina.Application/Core/{FileManagement => FileSystemManagement}/Directories/Queries/GetDirectoryTree/GetDirectoryTreeQueryHandler.cs (91%) rename src/Lumina.Application/Core/{FileManagement => FileSystemManagement}/Directories/Queries/GetDirectoryTree/GetDirectoryTreeQueryValidator.cs (75%) create mode 100644 src/Lumina.Application/Core/FileSystemManagement/Directories/Queries/GetTreeDirectories/GetTreeDirectoriesQuery.cs rename src/Lumina.Application/Core/{FileManagement => FileSystemManagement}/Directories/Queries/GetTreeDirectories/GetTreeDirectoriesQueryHandler.cs (71%) rename src/Lumina.Application/Core/{FileManagement => FileSystemManagement}/Directories/Queries/GetTreeDirectories/GetTreeDirectoriesQueryValidator.cs (75%) rename src/Lumina.Application/Core/{FileManagement => FileSystemManagement}/Drives/Queries/GetDrives/GetDrivesQuery.cs (74%) rename src/Lumina.Application/Core/{FileManagement => FileSystemManagement}/Drives/Queries/GetDrives/GetDrivesQueryHandler.cs (71%) rename src/Lumina.Application/Core/{FileManagement => FileSystemManagement}/FileSystem/Queries/GetFileSystem/GetFileSystemQuery.cs (69%) rename src/Lumina.Application/Core/{FileManagement => FileSystemManagement}/FileSystem/Queries/GetFileSystem/GetFileSystemQueryHandler.cs (84%) create mode 100644 src/Lumina.Application/Core/FileSystemManagement/Files/Queries/GetFiles/GetFilesQuery.cs rename src/Lumina.Application/Core/{FileManagement => FileSystemManagement}/Files/Queries/GetFiles/GetFilesQueryHandler.cs (68%) rename src/Lumina.Application/Core/{FileManagement => FileSystemManagement}/Files/Queries/GetFiles/GetFilesQueryValidator.cs (75%) create mode 100644 src/Lumina.Application/Core/FileSystemManagement/Files/Queries/GetTreeFiles/GetTreeFilesQuery.cs rename src/Lumina.Application/Core/{FileManagement => FileSystemManagement}/Files/Queries/GetTreeFiles/GetTreeFilesQueryHandler.cs (68%) rename src/Lumina.Application/Core/{FileManagement => FileSystemManagement}/Files/Queries/GetTreeFiles/GetTreeFilesQueryValidator.cs (76%) create mode 100644 src/Lumina.Application/Core/FileSystemManagement/Paths/Commands/CombinePath/CombinePathCommand.cs rename src/Lumina.Application/Core/{FileManagement => FileSystemManagement}/Paths/Commands/CombinePath/CombinePathCommandHandler.cs (72%) rename src/Lumina.Application/Core/{FileManagement => FileSystemManagement}/Paths/Commands/CombinePath/CombinePathCommandValidator.cs (61%) create mode 100644 src/Lumina.Application/Core/FileSystemManagement/Paths/Commands/SplitPath/SplitPathCommand.cs rename src/Lumina.Application/Core/{FileManagement => FileSystemManagement}/Paths/Commands/SplitPath/SplitPathCommandHandler.cs (70%) rename src/Lumina.Application/Core/{FileManagement => FileSystemManagement}/Paths/Commands/SplitPath/SplitPathCommandValidator.cs (76%) create mode 100644 src/Lumina.Application/Core/FileSystemManagement/Paths/Queries/CheckPathExists/CheckPathExistsQuery.cs rename src/Lumina.Application/Core/{FileManagement => FileSystemManagement}/Paths/Queries/CheckPathExists/CheckPathExistsQueryHandler.cs (82%) rename src/Lumina.Application/Core/{FileManagement => FileSystemManagement}/Paths/Queries/CheckPathExists/CheckPathExistsQueryValidator.cs (76%) create mode 100644 src/Lumina.Application/Core/FileSystemManagement/Paths/Queries/GetPathParent/GetPathParentQuery.cs rename src/Lumina.Application/Core/{FileManagement => FileSystemManagement}/Paths/Queries/GetPathParent/GetPathParentQueryHandler.cs (70%) rename src/Lumina.Application/Core/{FileManagement => FileSystemManagement}/Paths/Queries/GetPathParent/GetPathParentQueryValidator.cs (76%) create mode 100644 src/Lumina.Application/Core/FileSystemManagement/Paths/Queries/GetPathRoot/GetPathRootQuery.cs rename src/Lumina.Application/Core/{FileManagement => FileSystemManagement}/Paths/Queries/GetPathRoot/GetPathRootQueryHandler.cs (68%) rename src/Lumina.Application/Core/{FileManagement => FileSystemManagement}/Paths/Queries/GetPathRoot/GetPathRootQueryValidator.cs (75%) rename src/Lumina.Application/Core/{FileManagement => FileSystemManagement}/Paths/Queries/GetPathSeparator/GetPathSeparatorQuery.cs (71%) rename src/Lumina.Application/Core/{FileManagement => FileSystemManagement}/Paths/Queries/GetPathSeparator/GetPathSeparatorQueryHandler.cs (85%) create mode 100644 src/Lumina.Application/Core/FileSystemManagement/Paths/Queries/ValidatePath/ValidatePathQuery.cs rename src/Lumina.Application/Core/{FileManagement => FileSystemManagement}/Paths/Queries/ValidatePath/ValidatePathQueryHandler.cs (73%) rename src/Lumina.Application/Core/{FileManagement => FileSystemManagement}/Paths/Queries/ValidatePath/ValidatePathQueryValidator.cs (76%) rename src/Lumina.Application/Core/{FileManagement => FileSystemManagement}/Thumbnails/Queries/GetThumbnail/GetThumbnailQuery.cs (61%) rename src/Lumina.Application/Core/{FileManagement => FileSystemManagement}/Thumbnails/Queries/GetThumbnail/GetThumbnailQueryHandler.cs (67%) rename src/Lumina.Application/Core/{FileManagement => FileSystemManagement}/Thumbnails/Queries/GetThumbnail/GetThumbnailQueryValidator.cs (77%) rename src/Lumina.Contracts/{Models/Common/GenreModel.cs => Entities/Common/GenreEntity.cs} (77%) rename src/Lumina.Contracts/{Models => Entities}/Common/IStorageEntity.cs (93%) rename src/Lumina.Contracts/{Models/Common/LanguageInfoModel.cs => Entities/Common/LanguageInfoEntity.cs} (78%) rename src/Lumina.Contracts/{Models/Common/RatingModel.cs => Entities/Common/RatingEntity.cs} (87%) rename src/Lumina.Contracts/{Models/Common/ReleaseInfoModel.cs => Entities/Common/ReleaseInfoEntity.cs} (87%) rename src/Lumina.Contracts/{Models/Common/TagModel.cs => Entities/Common/TagEntity.cs} (77%) rename src/Lumina.Contracts/{Models/FileManagement/FileSystemItemModel.cs => Entities/FileSystemManagement/FileSystemItemEntity.cs} (76%) create mode 100644 src/Lumina.Contracts/Entities/MediaContributors/MediaContributorEntity.cs create mode 100644 src/Lumina.Contracts/Entities/MediaContributors/MediaContributorNameEntity.cs create mode 100644 src/Lumina.Contracts/Entities/MediaContributors/MediaContributorRoleEntity.cs rename src/Lumina.Contracts/{Models/WrittenContentLibrary/BookLibrary/BookModel.cs => Entities/WrittenContentLibrary/BookLibrary/BookEntity.cs} (92%) create mode 100644 src/Lumina.Contracts/Entities/WrittenContentLibrary/BookLibrary/BookRatingEntity.cs rename src/Lumina.Contracts/{Models/WrittenContentLibrary/BookLibrary/BookSeriesModel.cs => Entities/WrittenContentLibrary/BookLibrary/BookSeriesEntity.cs} (50%) create mode 100644 src/Lumina.Contracts/Entities/WrittenContentLibrary/BookLibrary/IsbnEntity.cs create mode 100644 src/Lumina.Contracts/Entities/WrittenContentLibrary/WrittenContentMetadataEntity.cs delete mode 100644 src/Lumina.Contracts/Models/MediaContributors/MediaContributorModel.cs delete mode 100644 src/Lumina.Contracts/Models/MediaContributors/MediaContributorNameModel.cs delete mode 100644 src/Lumina.Contracts/Models/MediaContributors/MediaContributorRoleModel.cs delete mode 100644 src/Lumina.Contracts/Models/WrittenContentLibrary/BookLibrary/BookRatingModel.cs delete mode 100644 src/Lumina.Contracts/Models/WrittenContentLibrary/BookLibrary/IsbnModel.cs delete mode 100644 src/Lumina.Contracts/Models/WrittenContentLibrary/WrittenContentMetadataModel.cs create mode 100644 src/Lumina.Contracts/Requests/FileSystemManagement/Directories/GetDirectoriesRequest.cs create mode 100644 src/Lumina.Contracts/Requests/FileSystemManagement/Directories/GetDirectoryTreeRequest.cs create mode 100644 src/Lumina.Contracts/Requests/FileSystemManagement/Directories/GetTreeDirectoriesRequest.cs create mode 100644 src/Lumina.Contracts/Requests/FileSystemManagement/Files/GetFilesRequest.cs create mode 100644 src/Lumina.Contracts/Requests/FileSystemManagement/Files/GetTreeFilesRequest.cs create mode 100644 src/Lumina.Contracts/Requests/FileSystemManagement/Path/CheckPathExistsRequest.cs create mode 100644 src/Lumina.Contracts/Requests/FileSystemManagement/Path/CombinePathRequest.cs create mode 100644 src/Lumina.Contracts/Requests/FileSystemManagement/Path/GetPathParentRequest.cs create mode 100644 src/Lumina.Contracts/Requests/FileSystemManagement/Path/GetPathRootRequest.cs create mode 100644 src/Lumina.Contracts/Requests/FileSystemManagement/Path/SplitPathRequest.cs create mode 100644 src/Lumina.Contracts/Requests/FileSystemManagement/Path/ValidatePathRequest.cs create mode 100644 src/Lumina.Contracts/Requests/FileSystemManagement/Thumbnails/GetThumbnailRequest.cs rename src/Lumina.Contracts/Requests/WrittenContentLibrary/BookLibrary/{ => Books}/AddBookRequest.cs (83%) create mode 100644 src/Lumina.Contracts/Requests/WrittenContentLibrary/BookLibrary/Books/GetBookRequest.cs delete mode 100644 src/Lumina.Contracts/Responses/FileManagement/PathExistsResponse.cs delete mode 100644 src/Lumina.Contracts/Responses/FileManagement/PathSegmentResponse.cs delete mode 100644 src/Lumina.Contracts/Responses/FileManagement/PathSeparatorResponse.cs delete mode 100644 src/Lumina.Contracts/Responses/FileManagement/PathValidResponse.cs rename src/Lumina.Contracts/Responses/{FileManagement => FileSystemManagement/Common}/FileSystemTreeNodeResponse.cs (80%) rename src/Lumina.Contracts/Responses/{FileManagement => FileSystemManagement/Directories}/DirectoryResponse.cs (66%) rename src/Lumina.Contracts/Responses/{FileManagement => FileSystemManagement/FileSystem}/FileSystemTypeResponse.cs (52%) rename src/Lumina.Contracts/Responses/{FileManagement => FileSystemManagement/Files}/FileResponse.cs (66%) create mode 100644 src/Lumina.Contracts/Responses/FileSystemManagement/Path/PathExistsResponse.cs create mode 100644 src/Lumina.Contracts/Responses/FileSystemManagement/Path/PathSegmentResponse.cs create mode 100644 src/Lumina.Contracts/Responses/FileSystemManagement/Path/PathSeparatorResponse.cs create mode 100644 src/Lumina.Contracts/Responses/FileSystemManagement/Path/PathValidResponse.cs rename src/Lumina.Contracts/Responses/{FileManagement => FileSystemManagement/Thumbnails}/ThumbnailResponse.cs (80%) create mode 100644 src/Lumina.Contracts/Responses/WrittenContentLibrary/BookLibrary/Books/BookResponse.cs rename src/Lumina.Domain/Common/Errors/{Errors.FileManagement.cs => Errors.FileSystemManagement.cs} (50%) rename src/Lumina.Domain/Core/Aggregates/{FileManagement/FileManagementAggregate => FileSystemManagement/FileSystemManagementAggregate}/Entities/Directory.cs (95%) rename src/Lumina.Domain/Core/Aggregates/{FileManagement/FileManagementAggregate => FileSystemManagement/FileSystemManagementAggregate}/Entities/File.cs (94%) rename src/Lumina.Domain/Core/Aggregates/{FileManagement/FileManagementAggregate => FileSystemManagement/FileSystemManagementAggregate}/Entities/UnixRootItem.cs (82%) rename src/Lumina.Domain/Core/Aggregates/{FileManagement/FileManagementAggregate => FileSystemManagement/FileSystemManagementAggregate}/Entities/WindowsRootItem.cs (92%) rename src/Lumina.Domain/Core/Aggregates/{FileManagement/FileManagementAggregate => FileSystemManagement/FileSystemManagementAggregate}/FileSystemItem.cs (84%) rename src/Lumina.Domain/Core/Aggregates/{FileManagement/FileManagementAggregate => FileSystemManagement/FileSystemManagementAggregate}/Services/DirectoryProviderService.cs (96%) rename src/Lumina.Domain/Core/Aggregates/{FileManagement/FileManagementAggregate => FileSystemManagement/FileSystemManagementAggregate}/Services/DirectoryService.cs (96%) rename src/Lumina.Domain/Core/Aggregates/{FileManagement/FileManagementAggregate => FileSystemManagement/FileSystemManagementAggregate}/Services/DriveService.cs (88%) rename src/Lumina.Domain/Core/Aggregates/{FileManagement/FileManagementAggregate => FileSystemManagement/FileSystemManagementAggregate}/Services/FileProviderService.cs (94%) rename src/Lumina.Domain/Core/Aggregates/{FileManagement/FileManagementAggregate => FileSystemManagement/FileSystemManagementAggregate}/Services/FileService.cs (95%) rename src/Lumina.Domain/Core/Aggregates/{FileManagement/FileManagementAggregate => FileSystemManagement/FileSystemManagementAggregate}/Services/FileSystemPermissionsService.cs (89%) rename src/Lumina.Domain/Core/Aggregates/{FileManagement/FileManagementAggregate => FileSystemManagement/FileSystemManagementAggregate}/Services/FileTypeService.cs (96%) rename src/Lumina.Domain/Core/Aggregates/{FileManagement/FileManagementAggregate => FileSystemManagement/FileSystemManagementAggregate}/Services/IDirectoryProviderService.cs (93%) rename src/Lumina.Domain/Core/Aggregates/{FileManagement/FileManagementAggregate => FileSystemManagement/FileSystemManagementAggregate}/Services/IDirectoryService.cs (90%) rename src/Lumina.Domain/Core/Aggregates/{FileManagement/FileManagementAggregate => FileSystemManagement/FileSystemManagementAggregate}/Services/IDriveService.cs (53%) rename src/Lumina.Domain/Core/Aggregates/{FileManagement/FileManagementAggregate => FileSystemManagement/FileSystemManagementAggregate}/Services/IFileProviderService.cs (93%) rename src/Lumina.Domain/Core/Aggregates/{FileManagement/FileManagementAggregate => FileSystemManagement/FileSystemManagementAggregate}/Services/IFileService.cs (88%) rename src/Lumina.Domain/Core/Aggregates/{FileManagement/FileManagementAggregate => FileSystemManagement/FileSystemManagementAggregate}/Services/IFileSystemPermissionsService.cs (66%) rename src/Lumina.Domain/Core/Aggregates/{FileManagement/FileManagementAggregate => FileSystemManagement/FileSystemManagementAggregate}/Services/IFileTypeService.cs (83%) rename src/Lumina.Domain/Core/Aggregates/{FileManagement/FileManagementAggregate => FileSystemManagement/FileSystemManagementAggregate}/Services/IPathService.cs (93%) rename src/Lumina.Domain/Core/Aggregates/{FileManagement/FileManagementAggregate => FileSystemManagement/FileSystemManagementAggregate}/Services/IThumbnailService.cs (89%) rename src/Lumina.Domain/Core/Aggregates/{FileManagement/FileManagementAggregate => FileSystemManagement/FileSystemManagementAggregate}/Services/PathService.cs (93%) rename src/Lumina.Domain/Core/Aggregates/{FileManagement/FileManagementAggregate => FileSystemManagement/FileSystemManagementAggregate}/Services/ThumbnailService.cs (96%) rename src/Lumina.Domain/Core/Aggregates/{FileManagement/FileManagementAggregate => FileSystemManagement/FileSystemManagementAggregate}/Strategies/Environment/EnvironmentContext.cs (88%) rename src/Lumina.Domain/Core/Aggregates/{FileManagement/FileManagementAggregate => FileSystemManagement/FileSystemManagementAggregate}/Strategies/Environment/IEnvironmentContext.cs (64%) rename src/Lumina.Domain/Core/Aggregates/{FileManagement/FileManagementAggregate => FileSystemManagement/FileSystemManagementAggregate}/Strategies/Path/IPathStrategy.cs (93%) rename src/Lumina.Domain/Core/Aggregates/{FileManagement/FileManagementAggregate => FileSystemManagement/FileSystemManagementAggregate}/Strategies/Path/IUnixPathStrategy.cs (60%) rename src/Lumina.Domain/Core/Aggregates/{FileManagement/FileManagementAggregate => FileSystemManagement/FileSystemManagementAggregate}/Strategies/Path/IWindowsPathStrategy.cs (61%) rename src/Lumina.Domain/Core/Aggregates/{FileManagement/FileManagementAggregate => FileSystemManagement/FileSystemManagementAggregate}/Strategies/Path/UnixPathStrategy.cs (93%) rename src/Lumina.Domain/Core/Aggregates/{FileManagement/FileManagementAggregate => FileSystemManagement/FileSystemManagementAggregate}/Strategies/Path/WindowsPathStrategy.cs (89%) rename src/Lumina.Domain/Core/Aggregates/{FileManagement/FileManagementAggregate => FileSystemManagement/FileSystemManagementAggregate}/Strategies/Platform/IOperatingSystemInfo.cs (87%) rename src/Lumina.Domain/Core/Aggregates/{FileManagement/FileManagementAggregate => FileSystemManagement/FileSystemManagementAggregate}/Strategies/Platform/IPlatformContext.cs (54%) rename src/Lumina.Domain/Core/Aggregates/{FileManagement/FileManagementAggregate => FileSystemManagement/FileSystemManagementAggregate}/Strategies/Platform/IPlatformContextFactory.cs (81%) rename src/Lumina.Domain/Core/Aggregates/{FileManagement/FileManagementAggregate => FileSystemManagement/FileSystemManagementAggregate}/Strategies/Platform/IPlatformContextManager.cs (70%) rename src/Lumina.Domain/Core/Aggregates/{FileManagement/FileManagementAggregate => FileSystemManagement/FileSystemManagementAggregate}/Strategies/Platform/IUnixPlatformContext.cs (57%) rename src/Lumina.Domain/Core/Aggregates/{FileManagement/FileManagementAggregate => FileSystemManagement/FileSystemManagementAggregate}/Strategies/Platform/IWindowsPlatformContext.cs (58%) rename src/Lumina.Domain/Core/Aggregates/{FileManagement/FileManagementAggregate => FileSystemManagement/FileSystemManagementAggregate}/Strategies/Platform/OperatingSystemInfo.cs (89%) rename src/Lumina.Domain/Core/Aggregates/{FileManagement/FileManagementAggregate => FileSystemManagement/FileSystemManagementAggregate}/Strategies/Platform/PlatformContextFactory.cs (78%) rename src/Lumina.Domain/Core/Aggregates/{FileManagement/FileManagementAggregate => FileSystemManagement/FileSystemManagementAggregate}/Strategies/Platform/PlatformContextManager.cs (95%) rename src/Lumina.Domain/Core/Aggregates/{FileManagement/FileManagementAggregate => FileSystemManagement/FileSystemManagementAggregate}/Strategies/Platform/UnixPlatformContext.cs (82%) rename src/Lumina.Domain/Core/Aggregates/{FileManagement/FileManagementAggregate => FileSystemManagement/FileSystemManagementAggregate}/Strategies/Platform/WindowsPlatformContext.cs (82%) rename src/Lumina.Domain/Core/Aggregates/{FileManagement/FileManagementAggregate => FileSystemManagement/FileSystemManagementAggregate}/ValueObjects/FileSystemPathId.cs (90%) rename src/Lumina.Domain/Core/Aggregates/{FileManagement/FileManagementAggregate => FileSystemManagement/FileSystemManagementAggregate}/ValueObjects/PathSegment.cs (93%) rename src/Lumina.Domain/Core/Aggregates/{FileManagement/FileManagementAggregate => FileSystemManagement/FileSystemManagementAggregate}/ValueObjects/StreamInfo.cs (93%) rename src/Lumina.Domain/Core/Aggregates/{FileManagement/FileManagementAggregate => FileSystemManagement/FileSystemManagementAggregate}/ValueObjects/Thumbnail.cs (79%) delete mode 100644 src/Lumina.Presentation.Api/Common/Configuration/ConfigureSwaggerOptions.cs delete mode 100644 src/Lumina.Presentation.Api/Common/Errors/CustomProblemDetailsFactory.cs delete mode 100644 src/Lumina.Presentation.Api/Common/Mapping/WrittenContentLibrary/BookLibrary/BookMappingConfig.cs delete mode 100644 src/Lumina.Presentation.Api/Common/ModelBinders/UrlStringBinder.cs create mode 100644 src/Lumina.Presentation.Api/Common/Routes/FileSystemManagement/ApiRoutes.Directories.cs create mode 100644 src/Lumina.Presentation.Api/Common/Routes/FileSystemManagement/ApiRoutes.Drives.cs create mode 100644 src/Lumina.Presentation.Api/Common/Routes/FileSystemManagement/ApiRoutes.FileSystem.cs create mode 100644 src/Lumina.Presentation.Api/Common/Routes/FileSystemManagement/ApiRoutes.Files.cs create mode 100644 src/Lumina.Presentation.Api/Common/Routes/FileSystemManagement/ApiRoutes.Path.cs create mode 100644 src/Lumina.Presentation.Api/Common/Routes/FileSystemManagement/ApiRoutes.Thumbnails.cs create mode 100644 src/Lumina.Presentation.Api/Common/Routes/Maintenance/ApiRoutes.Health.cs create mode 100644 src/Lumina.Presentation.Api/Common/Routes/WrittenContentLibrary/BookLibrary/ApiRoutes.Books.cs delete mode 100644 src/Lumina.Presentation.Api/Core/Controllers/Common/ApiController.cs delete mode 100644 src/Lumina.Presentation.Api/Core/Controllers/FileManagement/DirectoriesController.cs delete mode 100644 src/Lumina.Presentation.Api/Core/Controllers/FileManagement/DrivesController.cs delete mode 100644 src/Lumina.Presentation.Api/Core/Controllers/FileManagement/FileSystemController.cs delete mode 100644 src/Lumina.Presentation.Api/Core/Controllers/FileManagement/FilesController.cs delete mode 100644 src/Lumina.Presentation.Api/Core/Controllers/FileManagement/PathController.cs delete mode 100644 src/Lumina.Presentation.Api/Core/Controllers/FileManagement/ThumbnailsController.cs delete mode 100644 src/Lumina.Presentation.Api/Core/Controllers/Maintenance/HealthController.cs delete mode 100644 src/Lumina.Presentation.Api/Core/Controllers/WrittenContentLibrary/BookLibrary/Books/BooksController.cs create mode 100644 src/Lumina.Presentation.Api/Core/Endpoints/Common/BaseEndpoint.cs create mode 100644 src/Lumina.Presentation.Api/Core/Endpoints/FileSystemManagement/Directories/GetDirectories/GetDirectoriesEndpoint.cs create mode 100644 src/Lumina.Presentation.Api/Core/Endpoints/FileSystemManagement/Directories/GetDirectories/GetDirectoriesEndpointSummary.cs create mode 100644 src/Lumina.Presentation.Api/Core/Endpoints/FileSystemManagement/Directories/GetDirectoryTree/GetDirectoryTreeEndpoint.cs create mode 100644 src/Lumina.Presentation.Api/Core/Endpoints/FileSystemManagement/Directories/GetDirectoryTree/GetDirectoryTreeEndpointSummary.cs create mode 100644 src/Lumina.Presentation.Api/Core/Endpoints/FileSystemManagement/Directories/GetTreeDirectories/GetTreeDirectoriesEndpoint.cs create mode 100644 src/Lumina.Presentation.Api/Core/Endpoints/FileSystemManagement/Directories/GetTreeDirectories/GetTreeDirectoriesEndpointSummary.cs create mode 100644 src/Lumina.Presentation.Api/Core/Endpoints/FileSystemManagement/Drives/GetDrives/GetDrivesEndpoint.cs create mode 100644 src/Lumina.Presentation.Api/Core/Endpoints/FileSystemManagement/Drives/GetDrives/GetDrivesEndpointSummary.cs create mode 100644 src/Lumina.Presentation.Api/Core/Endpoints/FileSystemManagement/FileSystem/GetType/GetTypeEndpoint.cs create mode 100644 src/Lumina.Presentation.Api/Core/Endpoints/FileSystemManagement/FileSystem/GetType/GetTypeEndpointSummary.cs create mode 100644 src/Lumina.Presentation.Api/Core/Endpoints/FileSystemManagement/Files/GetFiles/GetFilesEndpoint.cs create mode 100644 src/Lumina.Presentation.Api/Core/Endpoints/FileSystemManagement/Files/GetFiles/GetFilesEndpointSummary.cs create mode 100644 src/Lumina.Presentation.Api/Core/Endpoints/FileSystemManagement/Files/GetTreeFiles/GetTreeFilesEndpoint.cs create mode 100644 src/Lumina.Presentation.Api/Core/Endpoints/FileSystemManagement/Files/GetTreeFiles/GetTreeFilesEndpointSummary.cs create mode 100644 src/Lumina.Presentation.Api/Core/Endpoints/FileSystemManagement/Path/CheckPathExists/CheckPathExistsEndpoint.cs create mode 100644 src/Lumina.Presentation.Api/Core/Endpoints/FileSystemManagement/Path/CheckPathExists/CheckPathExistsEndpointSummary.cs create mode 100644 src/Lumina.Presentation.Api/Core/Endpoints/FileSystemManagement/Path/CombinePath/CombinePathEndpoint.cs create mode 100644 src/Lumina.Presentation.Api/Core/Endpoints/FileSystemManagement/Path/CombinePath/CombinePathEndpointSummary.cs create mode 100644 src/Lumina.Presentation.Api/Core/Endpoints/FileSystemManagement/Path/GetPathParent/GetPathParentEndpoint.cs create mode 100644 src/Lumina.Presentation.Api/Core/Endpoints/FileSystemManagement/Path/GetPathParent/GetPathParentEndpointSummary.cs create mode 100644 src/Lumina.Presentation.Api/Core/Endpoints/FileSystemManagement/Path/GetPathRoot/GetPathRootEndpoint.cs create mode 100644 src/Lumina.Presentation.Api/Core/Endpoints/FileSystemManagement/Path/GetPathRoot/GetPathRootEndpointSummary.cs create mode 100644 src/Lumina.Presentation.Api/Core/Endpoints/FileSystemManagement/Path/GetPathSeparator/GetPathSeparatorEndpoint.cs create mode 100644 src/Lumina.Presentation.Api/Core/Endpoints/FileSystemManagement/Path/GetPathSeparator/GetPathSeparatorEndpointSummary.cs create mode 100644 src/Lumina.Presentation.Api/Core/Endpoints/FileSystemManagement/Path/SplitPath/SplitPathEndpoint.cs create mode 100644 src/Lumina.Presentation.Api/Core/Endpoints/FileSystemManagement/Path/SplitPath/SplitPathEndpointSummary.cs create mode 100644 src/Lumina.Presentation.Api/Core/Endpoints/FileSystemManagement/Path/ValidatePath/ValidatePathEndpoint.cs create mode 100644 src/Lumina.Presentation.Api/Core/Endpoints/FileSystemManagement/Path/ValidatePath/ValidatePathEndpointSummary.cs create mode 100644 src/Lumina.Presentation.Api/Core/Endpoints/FileSystemManagement/Thumbnails/GetThumbnail/GetThumbnailEndpoint.cs create mode 100644 src/Lumina.Presentation.Api/Core/Endpoints/FileSystemManagement/Thumbnails/GetThumbnail/GetThumbnailEndpointSummary.cs create mode 100644 src/Lumina.Presentation.Api/Core/Endpoints/Maintenance/CheckHealthEndpoint.cs create mode 100644 src/Lumina.Presentation.Api/Core/Endpoints/WrittenContentLibrary/BookLibrary/Books/AddBook/AddBookEndpoint.cs create mode 100644 src/Lumina.Presentation.Api/Core/Endpoints/WrittenContentLibrary/BookLibrary/Books/AddBook/AddBookEndpointSummary.cs create mode 100644 src/Lumina.Presentation.Api/Core/Endpoints/WrittenContentLibrary/BookLibrary/Books/GetBooks/GetBooksEndpoint.cs create mode 100644 src/Lumina.Presentation.Api/Core/Endpoints/WrittenContentLibrary/BookLibrary/Books/GetBooks/GetBooksEndpointSummary.cs create mode 100644 src/Lumina.Presentation.Api/Core/Endpoints/WrittenContentLibrary/BookLibrary/GetBook/GetBookEndpoint.cs rename src/Lumina.Presentation.Web/Common/Models/{FileManagement => FileSystemManagement}/BlobDataModel.cs (91%) rename src/Lumina.Presentation.Web/Common/Models/{FileManagement => FileSystemManagement}/DirectoryModel.cs (89%) rename src/Lumina.Presentation.Web/Common/Models/{FileManagement => FileSystemManagement}/FileModel.cs (88%) rename src/Lumina.Presentation.Web/Common/Models/{FileManagement => FileSystemManagement}/FileSystemItemModel.cs (93%) rename src/Lumina.Presentation.Web/Common/Models/{FileManagement => FileSystemManagement}/FileSystemTreeNodeModel.cs (95%) rename src/Lumina.Presentation.Web/Common/Models/{FileManagement => FileSystemManagement}/FileSystemTypeModel.cs (88%) rename src/Lumina.Presentation.Web/Common/Models/{FileManagement => FileSystemManagement}/PathExistsModel.cs (87%) rename src/Lumina.Presentation.Web/Common/Models/{FileManagement => FileSystemManagement}/PathSegmentModel.cs (87%) rename src/Lumina.Presentation.Web/Common/Models/{FileManagement => FileSystemManagement}/PathSeparatorModel.cs (86%) rename src/Lumina.Presentation.Web/Common/Models/{FileManagement => FileSystemManagement}/PathValidModel.cs (87%) rename src/Lumina.Presentation.Web/Controllers/{FileManagement => FileSystemManagement}/DirectoriesController.cs (96%) rename src/Lumina.Presentation.Web/Controllers/{FileManagement => FileSystemManagement}/DrivesController.cs (91%) rename src/Lumina.Presentation.Web/Controllers/{FileManagement => FileSystemManagement}/FileSystemController.cs (91%) rename src/Lumina.Presentation.Web/Controllers/{FileManagement => FileSystemManagement}/FilesController.cs (95%) rename src/Lumina.Presentation.Web/Controllers/{FileManagement => FileSystemManagement}/PathController.cs (97%) delete mode 100644 tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Controllers/FileManagement/DirectoriesControllerTests.cs delete mode 100644 tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Controllers/FileManagement/FilesControllerTests.cs delete mode 100644 tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Controllers/FileManagement/PathControllerTests.cs delete mode 100644 tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Controllers/FileManagement/ThumbnailsControllerTests.cs create mode 100644 tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/FileSystemManagement/Directories/GetDirectoriesEndpointTests.cs create mode 100644 tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/FileSystemManagement/Directories/GetDirectoryTreeEndpointTests.cs create mode 100644 tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/FileSystemManagement/Directories/GetTreeDirectoriesEndpointTests.cs rename tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/{Controllers/FileManagement/DrivesControllerTests.cs => Endpoints/FileSystemManagement/Drives/GetDrivesEndpointTests.cs} (57%) rename tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/{Controllers/FileManagement/FileSystemControllerTests.cs => Endpoints/FileSystemManagement/FileSystem/GetTypeEndpointTests.cs} (72%) create mode 100644 tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/FileSystemManagement/Files/GetFilesEndpointTests.cs create mode 100644 tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/FileSystemManagement/Files/GetTreeFilesEndpointTests.cs rename tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/{Controllers/FileManagement => Endpoints/FileSystemManagement}/Fixtures/FileSystemStructureFixture.cs (82%) rename tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/{Controllers/FileManagement => Endpoints/FileSystemManagement}/Fixtures/FileSystemTreeNodeResponseFixture.cs (94%) rename tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/{Controllers/FileManagement => Endpoints/FileSystemManagement}/Fixtures/TestImageFixture.cs (86%) create mode 100644 tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/FileSystemManagement/Path/CheckPathExistsEndpointTests.cs create mode 100644 tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/FileSystemManagement/Path/CombinePathEndpointTests.cs create mode 100644 tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/FileSystemManagement/Path/GetPathParentEndpointTests.cs create mode 100644 tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/FileSystemManagement/Path/GetPathRootEndpointTests.cs create mode 100644 tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/FileSystemManagement/Path/GetPathSeparatorEndpointTests.cs create mode 100644 tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/FileSystemManagement/Path/SplitPathEndpointTests.cs create mode 100644 tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/FileSystemManagement/Path/ValidatePathEndpointTests.cs create mode 100644 tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/FileSystemManagement/Thumbnails/GetThumbnailEndpointTests.cs rename tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/{Controllers/WrittenContentLibrary/BookLibrary/Books/BooksControllerTests.cs => Endpoints/WrittenContentLibrary/BookLibrary/Books/AddBookEndpointTests.cs} (75%) rename tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/{Controllers => Endpoints}/WrittenContentLibrary/BookLibrary/Books/Fixtures/AddBookRequestFixture.cs (70%) rename tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/{Controllers => Endpoints}/WrittenContentLibrary/BookLibrary/Books/Fixtures/DomainBookFixture.cs (97%) create mode 100644 tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/WrittenContentLibrary/BookLibrary/Books/GetBooksEndpointTests.cs delete mode 100644 tests/UnitTests/Lumina.Application.UnitTests/Common/Converters/Fixtures/OptionalJsonConverterFactoryFixture.cs delete mode 100644 tests/UnitTests/Lumina.Application.UnitTests/Common/Converters/OptionalJsonConverterFactoryTests.cs delete mode 100644 tests/UnitTests/Lumina.Application.UnitTests/Common/Converters/OptionalJsonConverterTests.cs create mode 100644 tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Common/Metadata/GenreMappingTests.cs create mode 100644 tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Common/Metadata/GenreModelMappingTests.cs create mode 100644 tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Common/Metadata/TagMappingTests.cs create mode 100644 tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Common/Metadata/TagModelMappingTests.cs delete mode 100644 tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/FileManagement/DirectoryMappingConfigTests.cs delete mode 100644 tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/FileManagement/FileMappingConfigTests.cs delete mode 100644 tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/FileManagement/FileSystemTreeMappingConfigTests.cs delete mode 100644 tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/FileManagement/ThumbnailMappingConfigTests.cs create mode 100644 tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/FileSystemManagement/Common/FileSystemTreeNodeResponseMappingTests.cs create mode 100644 tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/FileSystemManagement/Directories/DirectoryMappingTests.cs create mode 100644 tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/FileSystemManagement/Directories/GetDirectoriesRequestMappingTests.cs create mode 100644 tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/FileSystemManagement/Directories/GetDirectoryTreeRequestMappingTests.cs create mode 100644 tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/FileSystemManagement/Directories/GetTreeDirectoriesRequestMappingTests.cs create mode 100644 tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/FileSystemManagement/FileSystem/FileSystemItemMappingTests.cs create mode 100644 tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/FileSystemManagement/FileSystem/Fixtures/FileSystemItemFixture.cs create mode 100644 tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/FileSystemManagement/FileSystem/UnixRootItemMappingTests.cs create mode 100644 tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/FileSystemManagement/FileSystem/WindowsRootItemMappingTests.cs create mode 100644 tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/FileSystemManagement/Files/FileMappingTests.cs create mode 100644 tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/FileSystemManagement/Files/GetFilesRequestMappingTests.cs create mode 100644 tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/FileSystemManagement/Files/GetTreeFilesRequestMappingTests.cs create mode 100644 tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/FileSystemManagement/Paths/CheckPathExistsQueryMappingTests.cs create mode 100644 tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/FileSystemManagement/Paths/CombinePathRequestMappingTests.cs create mode 100644 tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/FileSystemManagement/Paths/GetPathParentRequestMappingTests.cs create mode 100644 tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/FileSystemManagement/Paths/GetPathRootRequestMappingTests.cs rename tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/{FileManagement/PathSegmentMappingConfigTests.cs => FileSystemManagement/Paths/PathSegmentMappingTests.cs} (55%) create mode 100644 tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/FileSystemManagement/Paths/SplitPathRequestMappingTests.cs create mode 100644 tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/FileSystemManagement/Paths/ValidatePathRequestMappingTests.cs create mode 100644 tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/FileSystemManagement/Thumbnails/GetThumbnailRequestMappingTests.cs create mode 100644 tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/FileSystemManagement/Thumbnails/ThumbnailMappingTests.cs create mode 100644 tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/WrittenContentLibrary/BookLibrary/Books/AddBookRequestMappingTests.cs create mode 100644 tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/WrittenContentLibrary/BookLibrary/Books/BookMappingTests.cs create mode 100644 tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/WrittenContentLibrary/BookLibrary/Books/BookModelMappingTests.cs create mode 100644 tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/WrittenContentLibrary/BookLibrary/Common/BookRatingMappingTests.cs create mode 100644 tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/WrittenContentLibrary/BookLibrary/Common/BookRatingModelMappingTests.cs create mode 100644 tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/WrittenContentLibrary/BookLibrary/Common/IsbnMappingTests.cs create mode 100644 tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/WrittenContentLibrary/BookLibrary/Common/IsbnModelMappingTests.cs delete mode 100644 tests/UnitTests/Lumina.Application.UnitTests/Core/FileManagement/Directories/Queries/GetTreeDirectories/GetTreeDirectoriesQueryHandlerTests.cs rename tests/UnitTests/Lumina.Application.UnitTests/Core/{FileManagement => FileSystemManagement}/Directories/Fixtures/DirectoryFixture.cs (94%) rename tests/UnitTests/Lumina.Application.UnitTests/Core/{FileManagement => FileSystemManagement}/Directories/Fixtures/DirectoryResponseFixture.cs (91%) rename tests/UnitTests/Lumina.Application.UnitTests/Core/{FileManagement => FileSystemManagement}/Directories/Fixtures/FileSystemItemModelFixture.cs (61%) rename tests/UnitTests/Lumina.Application.UnitTests/Core/{FileManagement => FileSystemManagement}/Directories/Fixtures/FileSystemTreeNodeResponseFixture.cs (94%) rename tests/UnitTests/Lumina.Application.UnitTests/Core/{FileManagement => FileSystemManagement}/Directories/Queries/GetDirectories/Fixtures/GetDirectoriesQueryFixture.cs (84%) rename tests/UnitTests/Lumina.Application.UnitTests/Core/{FileManagement => FileSystemManagement}/Directories/Queries/GetDirectories/GetDirectoriesQueryHandlerTests.cs (62%) rename tests/UnitTests/Lumina.Application.UnitTests/Core/{FileManagement => FileSystemManagement}/Directories/Queries/GetDirectories/GetDirectoriesQueryValidatorTests.cs (86%) rename tests/UnitTests/Lumina.Application.UnitTests/Core/{FileManagement => FileSystemManagement}/Directories/Queries/GetDirectoryTree/Fixtures/GetDirectoryTreeQueryFixture.cs (86%) rename tests/UnitTests/Lumina.Application.UnitTests/Core/{FileManagement => FileSystemManagement}/Directories/Queries/GetDirectoryTree/GetDirectoryTreeQueryHandlerTests.cs (87%) rename tests/UnitTests/Lumina.Application.UnitTests/Core/{FileManagement => FileSystemManagement}/Directories/Queries/GetDirectoryTree/GetDirectoryTreeQueryValidatorTests.cs (88%) rename tests/UnitTests/Lumina.Application.UnitTests/Core/{FileManagement => FileSystemManagement}/Directories/Queries/GetTreeDirectories/Fixtures/GetTreeDirectoriesQueryFixture.cs (84%) create mode 100644 tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Directories/Queries/GetTreeDirectories/GetTreeDirectoriesQueryHandlerTests.cs rename tests/UnitTests/Lumina.Application.UnitTests/Core/{FileManagement => FileSystemManagement}/Directories/Queries/GetTreeDirectories/GetTreeDirectoriesQueryValidatorTests.cs (86%) rename tests/UnitTests/Lumina.Application.UnitTests/Core/{FileManagement => FileSystemManagement}/Drives/Queries/GetDrives/Fixtures/GetDrivesQueryFixture.cs (94%) rename tests/UnitTests/Lumina.Application.UnitTests/Core/{FileManagement => FileSystemManagement}/Drives/Queries/GetDrives/GetDrivesQueryHandlerTests.cs (67%) rename tests/UnitTests/{Lumina.Domain.UnitTests/Core/Aggregates/FileManagementAggregate/Entities => Lumina.Application.UnitTests/Core/FileSystemManagement/FileSystem}/Fixtures/UnixRootItemFixture.cs (65%) create mode 100644 tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/FileSystem/Fixtures/WindowsRootItemFixture.cs rename tests/UnitTests/Lumina.Application.UnitTests/Core/{FileManagement => FileSystemManagement}/FileSystem/Queries/GetFileSystem/GetFileSystemQueryHandlerTests.cs (91%) rename tests/UnitTests/Lumina.Application.UnitTests/Core/{FileManagement => FileSystemManagement}/Files/Fixtures/FileFixture.cs (93%) rename tests/UnitTests/Lumina.Application.UnitTests/Core/{FileManagement => FileSystemManagement}/Files/Fixtures/FileResponseFixture.cs (89%) rename tests/UnitTests/Lumina.Application.UnitTests/Core/{FileManagement => FileSystemManagement}/Files/Queries/GetFiles/Fixtures/GetFilesQueryFixture.cs (85%) rename tests/UnitTests/Lumina.Application.UnitTests/Core/{FileManagement => FileSystemManagement}/Files/Queries/GetFiles/GetFilesQueryHandlerTests.cs (58%) rename tests/UnitTests/Lumina.Application.UnitTests/Core/{FileManagement => FileSystemManagement}/Files/Queries/GetFiles/GetFilesQueryValidatorTests.cs (86%) rename tests/UnitTests/Lumina.Application.UnitTests/Core/{FileManagement => FileSystemManagement}/Files/Queries/GetTreeFiles/Fixtures/GetTreeFilesQueryFixture.cs (85%) rename tests/UnitTests/Lumina.Application.UnitTests/Core/{FileManagement => FileSystemManagement}/Files/Queries/GetTreeFiles/GetTreeFilesQueryHandlerTests.cs (59%) rename tests/UnitTests/Lumina.Application.UnitTests/Core/{FileManagement => FileSystemManagement}/Files/Queries/GetTreeFiles/GetTreeFilesQueryValidatorTests.cs (86%) rename tests/UnitTests/{Lumina.Domain.UnitTests/Core/Aggregates/FileManagementAggregate/ValueObjects => Lumina.Application.UnitTests/Core/FileSystemManagement}/Fixtures/FileSystemPathIdFixture.cs (87%) rename tests/UnitTests/Lumina.Application.UnitTests/Core/{FileManagement => FileSystemManagement}/Pahs/Commands/CombinePath/CombinePathCommandHandlerTests.cs (80%) rename tests/UnitTests/Lumina.Application.UnitTests/Core/{FileManagement => FileSystemManagement}/Pahs/Commands/CombinePath/CombinePathCommandValidatorTests.cs (83%) rename tests/UnitTests/Lumina.Application.UnitTests/Core/{FileManagement => FileSystemManagement}/Pahs/Commands/CombinePath/Fixtures/CombinePathCommandFixture.cs (83%) rename tests/UnitTests/Lumina.Application.UnitTests/Core/{FileManagement => FileSystemManagement}/Pahs/Commands/SplitPath/Fixtures/SplitPathCommandFixture.cs (82%) rename tests/UnitTests/Lumina.Application.UnitTests/Core/{FileManagement => FileSystemManagement}/Pahs/Commands/SplitPath/SplitPathCommandHandlerTests.cs (56%) rename tests/UnitTests/Lumina.Application.UnitTests/Core/{FileManagement => FileSystemManagement}/Pahs/Commands/SplitPath/SplitPathCommandValidatorTests.cs (82%) rename tests/UnitTests/Lumina.Application.UnitTests/Core/{FileManagement => FileSystemManagement}/Pahs/Fixtures/PathSegmentFixture.cs (90%) rename tests/UnitTests/Lumina.Application.UnitTests/Core/{FileManagement => FileSystemManagement}/Pahs/Fixtures/PathSegmentResponseFixture.cs (89%) rename tests/UnitTests/Lumina.Application.UnitTests/Core/{FileManagement => FileSystemManagement}/Pahs/Fixtures/PathSeparatorResponseFixture.cs (89%) rename tests/UnitTests/Lumina.Application.UnitTests/Core/{FileManagement => FileSystemManagement}/Pahs/Queries/CheckPathExists/CheckPathExistsQueryHandlerTests.cs (76%) rename tests/UnitTests/Lumina.Application.UnitTests/Core/{FileManagement => FileSystemManagement}/Pahs/Queries/CheckPathExists/CheckPathExistsQueryValidatorTests.cs (82%) rename tests/UnitTests/Lumina.Application.UnitTests/Core/{FileManagement => FileSystemManagement}/Pahs/Queries/CheckPathExists/Fixtures/CheckPathExistsQueryFixture.cs (85%) rename tests/UnitTests/Lumina.Application.UnitTests/Core/{FileManagement => FileSystemManagement}/Pahs/Queries/GetPathParent/Fixtures/GetPathParentQueryFixture.cs (82%) rename tests/UnitTests/Lumina.Application.UnitTests/Core/{FileManagement => FileSystemManagement}/Pahs/Queries/GetPathParent/GetPathParentQueryHandlerTests.cs (60%) rename tests/UnitTests/Lumina.Application.UnitTests/Core/{FileManagement => FileSystemManagement}/Pahs/Queries/GetPathParent/GetPathParentQueryValidatorTests.cs (82%) rename tests/UnitTests/Lumina.Application.UnitTests/Core/{FileManagement => FileSystemManagement}/Pahs/Queries/GetPathRoot/Fixtures/GetPathRootQueryFixture.cs (82%) rename tests/UnitTests/Lumina.Application.UnitTests/Core/{FileManagement => FileSystemManagement}/Pahs/Queries/GetPathRoot/GetPathRootQueryHandlerTests.cs (54%) rename tests/UnitTests/Lumina.Application.UnitTests/Core/{FileManagement => FileSystemManagement}/Pahs/Queries/GetPathRoot/GetPathRootQueryValidatorTests.cs (82%) rename tests/UnitTests/Lumina.Application.UnitTests/Core/{FileManagement => FileSystemManagement}/Pahs/Queries/GetPathSeparator/GetPathSeparatorQueryHandlerTests.cs (90%) rename tests/UnitTests/Lumina.Application.UnitTests/Core/{FileManagement => FileSystemManagement}/Pahs/Queries/ValidatePath/Fixtures/ValidatePathQueryFixure.cs (82%) rename tests/UnitTests/Lumina.Application.UnitTests/Core/{FileManagement => FileSystemManagement}/Pahs/Queries/ValidatePath/ValidatePathQueryHandlerTests.cs (79%) rename tests/UnitTests/Lumina.Application.UnitTests/Core/{FileManagement => FileSystemManagement}/Pahs/Queries/ValidatePath/ValidatePathQueryValidatorTests.cs (82%) rename tests/UnitTests/{Lumina.Presentation.Api.UnitTests/Core/Controllers/FileManagement => Lumina.Application.UnitTests/Core/FileSystemManagement/Thumbnails}/Fixtures/ThumbnailResponseFixture.cs (86%) rename tests/UnitTests/Lumina.Application.UnitTests/Core/{FileManagement => FileSystemManagement}/Thumbnails/Queries/GetThumbnail/Fixtures/GetThumbnailQueryFixture.cs (82%) rename tests/UnitTests/Lumina.Application.UnitTests/Core/{FileManagement => FileSystemManagement}/Thumbnails/Queries/GetThumbnail/GetThumbnailQueryHandlerTests.cs (62%) rename tests/UnitTests/Lumina.Application.UnitTests/Core/{FileManagement => FileSystemManagement}/Thumbnails/Queries/GetThumbnail/GetThumbnailQueryValidatorTests.cs (89%) create mode 100644 tests/UnitTests/Lumina.Application.UnitTests/Core/WrittenContentLibrary/BooksLibrary/Books/Commands/AddBook/Fixtures/AddBookRequestFixture.cs create mode 100644 tests/UnitTests/Lumina.Application.UnitTests/Core/WrittenContentLibrary/BooksLibrary/Books/Commands/AddBook/Fixtures/BookEntityFixture.cs create mode 100644 tests/UnitTests/Lumina.Application.UnitTests/Core/WrittenContentLibrary/BooksLibrary/Books/Commands/AddBook/Fixtures/DomainBookFixture.cs create mode 100644 tests/UnitTests/Lumina.Application.UnitTests/Core/WrittenContentLibrary/BooksLibrary/Common/Fixtures/BookRatingEntityFixture.cs create mode 100644 tests/UnitTests/Lumina.Application.UnitTests/Core/WrittenContentLibrary/BooksLibrary/Common/Fixtures/BookRatingFixture.cs create mode 100644 tests/UnitTests/Lumina.Application.UnitTests/Core/WrittenContentLibrary/BooksLibrary/Common/Fixtures/IsbnEntityFixture.cs create mode 100644 tests/UnitTests/Lumina.Application.UnitTests/Core/WrittenContentLibrary/BooksLibrary/Common/Fixtures/IsbnFixture.cs rename tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/{FileManagementAggregate => FileSystemManagementAggregate}/Entities/DirectoryTests.cs (89%) rename tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/{FileManagementAggregate => FileSystemManagementAggregate}/Entities/FileTests.cs (91%) rename tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/{FileManagementAggregate => FileSystemManagementAggregate}/Entities/Fixtures/DirectoryFixture.cs (94%) rename tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/{FileManagementAggregate => FileSystemManagementAggregate}/Entities/Fixtures/FileFixture.cs (93%) rename tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/{FileManagementAggregate => FileSystemManagementAggregate}/Entities/UnixRootItemTests.cs (90%) rename tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/{FileManagementAggregate => FileSystemManagementAggregate}/Entities/WindowsRootItemTests.cs (89%) rename tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/{FileManagementAggregate => FileSystemManagementAggregate}/FileSystemItemTests.cs (90%) rename tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/{FileManagementAggregate => FileSystemManagementAggregate}/Fixtures/FileSystemItemFixture.cs (77%) rename tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/{FileManagementAggregate => FileSystemManagementAggregate}/Services/DirectoryProviderServiceTests.cs (96%) rename tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/{FileManagementAggregate => FileSystemManagementAggregate}/Services/DirectoryServiceTests.cs (94%) rename tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/{FileManagementAggregate => FileSystemManagementAggregate}/Services/DriveServiceTests.cs (85%) rename tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/{FileManagementAggregate => FileSystemManagementAggregate}/Services/FileProviderServiceTests.cs (96%) rename tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/{FileManagementAggregate => FileSystemManagementAggregate}/Services/FileServiceTests.cs (96%) rename tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/{FileManagementAggregate => FileSystemManagementAggregate}/Services/FileTypeServiceTests.cs (94%) rename tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/{FileManagementAggregate => FileSystemManagementAggregate}/Services/Fixtures/ImageTypeFixture.cs (94%) rename tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/{FileManagementAggregate => FileSystemManagementAggregate}/Services/PathServiceTests.cs (90%) rename tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/{FileManagementAggregate => FileSystemManagementAggregate}/Services/ThumbnailServiceTests.cs (90%) rename tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/{FileManagementAggregate => FileSystemManagementAggregate}/Strategies/Environment/EnvironmentContextTests.cs (90%) rename tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/{FileManagementAggregate => FileSystemManagementAggregate}/Strategies/Path/UnixPathStrategyTests.cs (95%) rename tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/{FileManagementAggregate => FileSystemManagementAggregate}/Strategies/Path/WindowsPathStrategyTests.cs (94%) rename tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/{FileManagementAggregate => FileSystemManagementAggregate}/Strategies/Platform/Fixtures/INonExistentPlatformContextFixture.cs (61%) rename tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/{FileManagementAggregate => FileSystemManagementAggregate}/Strategies/Platform/PlatformContextFactoryTests.cs (84%) rename tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/{FileManagementAggregate => FileSystemManagementAggregate}/Strategies/Platform/PlatformContextManagerTests.cs (96%) rename tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/{FileManagementAggregate => FileSystemManagementAggregate}/Strategies/Platform/PlatformContextTests.cs (92%) rename tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/{FileManagementAggregate => FileSystemManagementAggregate}/ValueObjects/FileSystemPathIdTests.cs (89%) create mode 100644 tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/FileSystemManagementAggregate/ValueObjects/Fixtures/FileSystemPathIdFixture.cs rename tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/{FileManagementAggregate => FileSystemManagementAggregate}/ValueObjects/Fixtures/PathSegmentFixture.cs (89%) rename tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/{FileManagementAggregate => FileSystemManagementAggregate}/ValueObjects/Fixtures/StreamInfoFixture.cs (95%) rename tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/{FileManagementAggregate => FileSystemManagementAggregate}/ValueObjects/Fixtures/ThumbnailFixture.cs (89%) rename tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/{FileManagementAggregate => FileSystemManagementAggregate}/ValueObjects/PathSegmentTests.cs (89%) rename tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/{FileManagementAggregate => FileSystemManagementAggregate}/ValueObjects/StreamInfoTests.cs (82%) rename tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/{FileManagementAggregate => FileSystemManagementAggregate}/ValueObjects/ThumbnailTests.cs (92%) delete mode 100644 tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Controllers/Common/ApiControllerTests.cs delete mode 100644 tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Controllers/Common/Fixtures/ApiControllerFixture.cs delete mode 100644 tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Controllers/FileManagement/DirectoriesControllerTests.cs delete mode 100644 tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Controllers/FileManagement/DrivesControllerTests.cs delete mode 100644 tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Controllers/FileManagement/FileSystemControllerTests.cs delete mode 100644 tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Controllers/FileManagement/FilesControllerTests.cs delete mode 100644 tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Controllers/FileManagement/PathControllerTests.cs delete mode 100644 tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Controllers/FileManagement/ThumbnailsControllerTests.cs create mode 100644 tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Common/BaseEndpointTests.cs create mode 100644 tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Common/Fixtures/BaseEndpointFixture.cs create mode 100644 tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/FileSystemManagement/Directories/GetDirectoriesEndpointTests.cs create mode 100644 tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/FileSystemManagement/Directories/GetDirectoryTreeEndpointTests.cs create mode 100644 tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/FileSystemManagement/Directories/GetTreeDirectoriesEndpointTests.cs create mode 100644 tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/FileSystemManagement/Drives/GetDrivesEndpointTests.cs create mode 100644 tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/FileSystemManagement/FileSystem/GetTypeEndpointTests.cs create mode 100644 tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/FileSystemManagement/Files/GetFilesEndpointTests.cs create mode 100644 tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/FileSystemManagement/Files/GetTreeFilesEndpointTests.cs create mode 100644 tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/FileSystemManagement/Fixtures/CheckPathExistsRequestFixture.cs create mode 100644 tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/FileSystemManagement/Fixtures/CombinePathRequestFixture.cs rename tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/{Controllers/FileManagement => Endpoints/FileSystemManagement}/Fixtures/FileSystemTreeNodeResponseFixture.cs (94%) create mode 100644 tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/FileSystemManagement/Fixtures/GetPathParentRequestFixture.cs create mode 100644 tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/FileSystemManagement/Fixtures/GetPathRootRequestFixture.cs create mode 100644 tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/FileSystemManagement/Fixtures/GetThumbnailRequestFixture.cs rename tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/{Controllers/FileManagement => Endpoints/FileSystemManagement}/Fixtures/PathSegmentResponseFixture.cs (88%) rename tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/{Controllers/FileManagement => Endpoints/FileSystemManagement}/Fixtures/PathSeparatorResponseFixture.cs (88%) create mode 100644 tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/FileSystemManagement/Fixtures/SplitPathRequestFixture.cs rename tests/UnitTests/{Lumina.Application.UnitTests/Core/FileManagement/Thumbnails => Lumina.Presentation.Api.UnitTests/Core/Endpoints/FileSystemManagement}/Fixtures/ThumbnailResponseFixture.cs (85%) create mode 100644 tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/FileSystemManagement/Fixtures/ValidatePathRequestFixture.cs create mode 100644 tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/FileSystemManagement/Path/CheckPathExistsEndpointTests.cs create mode 100644 tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/FileSystemManagement/Path/CombinePathEndpointTests.cs create mode 100644 tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/FileSystemManagement/Path/GetPathParentEndpointTests.cs create mode 100644 tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/FileSystemManagement/Path/GetPathRootEndpointTests.cs create mode 100644 tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/FileSystemManagement/Path/GetPathSeparatorEndpointTests.cs create mode 100644 tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/FileSystemManagement/Path/SplitPathEndpointTests.cs create mode 100644 tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/FileSystemManagement/Path/ValidatePathEndpointTests.cs create mode 100644 tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/FileSystemManagement/Thumbnails/GetThumbnailEndpointTests.cs create mode 100644 tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/WrittenContentLibrary/BookLibrary/Books/AddBookEndpointTests.cs delete mode 100644 tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/ModelBinders/UrlStringBinderTests.cs diff --git a/docs/technical/domain/Aggregates.FileManagement.md b/docs/technical/domain/Aggregates.FileSystemManagement.md similarity index 100% rename from docs/technical/domain/Aggregates.FileManagement.md rename to docs/technical/domain/Aggregates.FileSystemManagement.md diff --git a/docs/technical/domain/UbiquitousLanguage.md b/docs/technical/domain/UbiquitousLanguage.md index 6d935dc8..fe42a9ac 100644 --- a/docs/technical/domain/UbiquitousLanguage.md +++ b/docs/technical/domain/UbiquitousLanguage.md @@ -121,7 +121,7 @@ - PhotoLibrary (root: PhotoLibrary, entities: Photo, PhotoAlbum, AlbumArtwork, MoviePoster) - UserProfile (root: User, entities: Playlist, Collection) - SupplementaryContentLibrary (root: SupplementaryContentLibrary, entities: SubtitleFile, Lyrics, LanguageTrack) -- FileManagement (root: File, entities: Stream) +- FileSystemManagement (root: File, entities: Stream) - WrittenContentLibrary - BookLibrary (root: BookLibrary) @@ -219,7 +219,7 @@ - Aggregates: UserProfile - Services: RecommendationEngine, ContentCurationService, UserActivityTrackingService - ContentDelivery - - Aggregates: FileManagement + - Aggregates: FileSystemManagement - Services: StreamingService, ContentSynchronizationService - MetadataManagement - Aggregates: SupplementaryContentLibrary diff --git a/src/Lumina.Application/Common/Behaviors/ValidationBehavior.cs b/src/Lumina.Application/Common/Behaviors/ValidationBehavior.cs index 05a2c53b..1c3fda2c 100644 --- a/src/Lumina.Application/Common/Behaviors/ValidationBehavior.cs +++ b/src/Lumina.Application/Common/Behaviors/ValidationBehavior.cs @@ -3,7 +3,6 @@ using ErrorOr; using FluentValidation; using Mediator; using System.Collections.Generic; -using System.ComponentModel.DataAnnotations; using System.Threading; using System.Threading.Tasks; #endregion @@ -51,4 +50,4 @@ public class ValidationBehavior : IPipelineBehavior -/// Converts an to and from JSON. -/// -/// The type of the value represented by the structure. -public class OptionalJsonConverter : JsonConverter> -{ - /// - /// Reads and converts the JSON to an instance of . - /// - /// The to read from. - /// The type to convert. - /// An object that specifies serialization options to use. - /// The converted value. - public override Optional Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) - { - if (reader.TokenType == JsonTokenType.Null) - return Optional.None(); - TValue? value = JsonSerializer.Deserialize(ref reader, options); - return Optional.Some(value!); - } - - /// - /// Writes an value as JSON. - /// - /// The to write to. - /// The value to convert to JSON. - /// An object that specifies serialization options to use. - public override void Write(Utf8JsonWriter writer, Optional value, JsonSerializerOptions options) - { - if (value.HasValue) - JsonSerializer.Serialize(writer, value.Value, options); - else - writer.WriteNullValue(); - } -} \ No newline at end of file diff --git a/src/Lumina.Application/Common/Converters/OptionalJsonConverterFactory.cs b/src/Lumina.Application/Common/Converters/OptionalJsonConverterFactory.cs deleted file mode 100644 index 3bf7d378..00000000 --- a/src/Lumina.Application/Common/Converters/OptionalJsonConverterFactory.cs +++ /dev/null @@ -1,38 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using Lumina.Domain.Common.Primitives; -using System; -using System.Text.Json; -using System.Text.Json.Serialization; -#endregion - -namespace Lumina.Application.Common.Converters; - -/// -/// A factory for creating instances. -/// -public class OptionalJsonConverterFactory : JsonConverterFactory -{ - /// - /// Determines whether the converter can convert the specified type. - /// - /// The type to check for convertibility. - /// if the type is , otherwise. - public override bool CanConvert(Type typeToConvert) - { - return typeToConvert.IsGenericType && typeToConvert.GetGenericTypeDefinition() == typeof(Optional<>); - } - - /// - /// Creates a converter for the specified type. - /// - /// The type for which to create a converter. - /// The serializer options to use. - /// A converter for . - public override JsonConverter CreateConverter(Type typeToConvert, JsonSerializerOptions options) - { - Type valueType = typeToConvert.GetGenericArguments()[0]; - JsonConverter converter = (JsonConverter)Activator.CreateInstance( - typeof(OptionalJsonConverter<>).MakeGenericType(valueType))!; - return converter; - } -} \ No newline at end of file diff --git a/src/Lumina.Application/Common/DataAccess/Repositories/Books/IBookRepository.cs b/src/Lumina.Application/Common/DataAccess/Repositories/Books/IBookRepository.cs index b925c108..ca22fcc6 100644 --- a/src/Lumina.Application/Common/DataAccess/Repositories/Books/IBookRepository.cs +++ b/src/Lumina.Application/Common/DataAccess/Repositories/Books/IBookRepository.cs @@ -1,7 +1,8 @@ #region ========================================================================= USING ===================================================================================== using Lumina.Application.Common.DataAccess.Repositories.Common.Actions; using Lumina.Application.Common.DataAccess.Repositories.Common.Base; -using Lumina.Contracts.Models.WrittenContentLibrary.BookLibrary; +using Lumina.Contracts.Entities.WrittenContentLibrary.BookLibrary; + #endregion namespace Lumina.Application.Common.DataAccess.Repositories.Books; @@ -9,8 +10,8 @@ namespace Lumina.Application.Common.DataAccess.Repositories.Books; /// /// Interface for the repository for books. /// -public interface IBookRepository : IRepository, - IInsertRepositoryAction, - IGetAllRepositoryAction +public interface IBookRepository : IRepository, + IInsertRepositoryAction, + IGetAllRepositoryAction { } \ No newline at end of file diff --git a/src/Lumina.Application/Common/DataAccess/Repositories/Common/Actions/IGetAllRepositoryAction.cs b/src/Lumina.Application/Common/DataAccess/Repositories/Common/Actions/IGetAllRepositoryAction.cs index e30bbcc5..be409ff5 100644 --- a/src/Lumina.Application/Common/DataAccess/Repositories/Common/Actions/IGetAllRepositoryAction.cs +++ b/src/Lumina.Application/Common/DataAccess/Repositories/Common/Actions/IGetAllRepositoryAction.cs @@ -1,6 +1,6 @@ #region ========================================================================= USING ===================================================================================== using ErrorOr; -using Lumina.Contracts.Models.Common; +using Lumina.Contracts.Entities.Common; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; diff --git a/src/Lumina.Application/Common/DataAccess/Repositories/Common/Actions/IGetByIdRepositoryAction.cs b/src/Lumina.Application/Common/DataAccess/Repositories/Common/Actions/IGetByIdRepositoryAction.cs index 7da7e057..fad70678 100644 --- a/src/Lumina.Application/Common/DataAccess/Repositories/Common/Actions/IGetByIdRepositoryAction.cs +++ b/src/Lumina.Application/Common/DataAccess/Repositories/Common/Actions/IGetByIdRepositoryAction.cs @@ -1,6 +1,6 @@ #region ========================================================================= USING ===================================================================================== using ErrorOr; -using Lumina.Contracts.Models.Common; +using Lumina.Contracts.Entities.Common; using System.Threading; using System.Threading.Tasks; #endregion diff --git a/src/Lumina.Application/Common/DataAccess/Repositories/Common/Actions/IInsertRepositoryAction.cs b/src/Lumina.Application/Common/DataAccess/Repositories/Common/Actions/IInsertRepositoryAction.cs index 3772cad2..78ebafbc 100644 --- a/src/Lumina.Application/Common/DataAccess/Repositories/Common/Actions/IInsertRepositoryAction.cs +++ b/src/Lumina.Application/Common/DataAccess/Repositories/Common/Actions/IInsertRepositoryAction.cs @@ -1,6 +1,6 @@ #region ========================================================================= USING ===================================================================================== using ErrorOr; -using Lumina.Contracts.Models.Common; +using Lumina.Contracts.Entities.Common; using System.Threading; using System.Threading.Tasks; #endregion diff --git a/src/Lumina.Application/Common/DataAccess/Repositories/Common/Actions/IUpdateRepositoryAction.cs b/src/Lumina.Application/Common/DataAccess/Repositories/Common/Actions/IUpdateRepositoryAction.cs index fb315a88..ea656470 100644 --- a/src/Lumina.Application/Common/DataAccess/Repositories/Common/Actions/IUpdateRepositoryAction.cs +++ b/src/Lumina.Application/Common/DataAccess/Repositories/Common/Actions/IUpdateRepositoryAction.cs @@ -1,6 +1,6 @@ #region ========================================================================= USING ===================================================================================== using ErrorOr; -using Lumina.Contracts.Models.Common; +using Lumina.Contracts.Entities.Common; using System.Threading; using System.Threading.Tasks; #endregion diff --git a/src/Lumina.Application/Common/DataAccess/Repositories/Common/Base/IRepository.cs b/src/Lumina.Application/Common/DataAccess/Repositories/Common/Base/IRepository.cs index 4049862b..0a51e417 100644 --- a/src/Lumina.Application/Common/DataAccess/Repositories/Common/Base/IRepository.cs +++ b/src/Lumina.Application/Common/DataAccess/Repositories/Common/Base/IRepository.cs @@ -1,5 +1,6 @@ #region ========================================================================= USING ===================================================================================== -using Lumina.Contracts.Models.Common; +using Lumina.Contracts.Entities.Common; + #endregion diff --git a/src/Lumina.Application/Common/DependencyInjection/ApplicationLayerServices.cs b/src/Lumina.Application/Common/DependencyInjection/ApplicationLayerServices.cs index 2c2ae7c9..b3ea67d4 100644 --- a/src/Lumina.Application/Common/DependencyInjection/ApplicationLayerServices.cs +++ b/src/Lumina.Application/Common/DependencyInjection/ApplicationLayerServices.cs @@ -1,8 +1,6 @@ #region ========================================================================= USING ===================================================================================== using FluentValidation; using Lumina.Application.Common.Behaviors; -using Mapster; -using MapsterMapper; using Mediator; using Microsoft.Extensions.DependencyInjection; #endregion @@ -33,12 +31,6 @@ public static class ApplicationLayerServices // register fluent validators services.AddValidatorsFromAssembly(typeof(ApplicationLayerServices).Assembly); - // register mapster configs in this assembly - TypeAdapterConfig mapsterConfig = TypeAdapterConfig.GlobalSettings; - mapsterConfig.Scan(typeof(ApplicationLayerServices).Assembly); - services.AddSingleton(mapsterConfig); - services.AddScoped(); - return services; } -} \ No newline at end of file +} diff --git a/src/Lumina.Application/Common/Mapping/Common/Metadata/GenreMapping.cs b/src/Lumina.Application/Common/Mapping/Common/Metadata/GenreMapping.cs new file mode 100644 index 00000000..a8b85967 --- /dev/null +++ b/src/Lumina.Application/Common/Mapping/Common/Metadata/GenreMapping.cs @@ -0,0 +1,36 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Contracts.Entities.Common; +using Lumina.Domain.Common.ValueObjects.Metadata; +using System.Collections.Generic; +using System.Linq; +#endregion + +namespace Lumina.Application.Common.Mapping.Common.Metadata; + +/// +/// Extension methods for converting . +/// +public static class GenreMapping +{ + /// + /// Converts to . + /// + /// The domain model to be converted. + /// The converted repository entity. + public static GenreEntity ToRepositoryEntity(this Genre domainModel) + { + return new GenreEntity( + domainModel.Name + ); + } + + /// + /// Converts to a collection of . + /// + /// The domain models to be converted. + /// The converted repository entities. + public static IEnumerable ToRepositoryEntities(this IEnumerable domainModels) + { + return domainModels.Select(domainModel => domainModel.ToRepositoryEntity()); + } +} diff --git a/src/Lumina.Application/Common/Mapping/Common/Metadata/GenreModelMapping.cs b/src/Lumina.Application/Common/Mapping/Common/Metadata/GenreModelMapping.cs new file mode 100644 index 00000000..d15517f9 --- /dev/null +++ b/src/Lumina.Application/Common/Mapping/Common/Metadata/GenreModelMapping.cs @@ -0,0 +1,37 @@ +#region ========================================================================= USING ===================================================================================== +using ErrorOr; +using Lumina.Contracts.Entities.Common; +using Lumina.Domain.Common.ValueObjects.Metadata; +using System.Collections.Generic; +using System.Linq; +#endregion + +namespace Lumina.Application.Common.Mapping.Common.Metadata; + +/// +/// Extension methods for converting . +/// +public static class GenreModelMapping +{ + /// + /// Converts to . + /// + /// The repository model to be converted. + /// The converted domain model. + public static ErrorOr ToDomainModel(this GenreEntity repositoryEntity) + { + return Genre.Create( + repositoryEntity.Name + ); + } + + /// + /// Converts to a collection of . + /// + /// The repository models to be converted. + /// The converted domain models. + public static IEnumerable> ToDomainModels(this IEnumerable repositoryEntities) + { + return repositoryEntities.Select(repositoryEntity => repositoryEntity.ToDomainModel()); + } +} diff --git a/src/Lumina.Application/Common/Mapping/Common/Metadata/TagMapping.cs b/src/Lumina.Application/Common/Mapping/Common/Metadata/TagMapping.cs new file mode 100644 index 00000000..9a48dc6c --- /dev/null +++ b/src/Lumina.Application/Common/Mapping/Common/Metadata/TagMapping.cs @@ -0,0 +1,36 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Contracts.Entities.Common; +using Lumina.Domain.Common.ValueObjects.Metadata; +using System.Collections.Generic; +using System.Linq; +#endregion + +namespace Lumina.Application.Common.Mapping.Common.Metadata; + +/// +/// Extension methods for converting . +/// +public static class TagMapping +{ + /// + /// Converts to . + /// + /// The domain model to be converted. + /// The converted repository entity. + public static TagEntity ToRepositoryEntity(this Tag domainModel) + { + return new TagEntity( + domainModel.Name + ); + } + + /// + /// Converts to a collection of . + /// + /// The domain model to be converted. + /// The converted repository entities. + public static IEnumerable ToRepositoryEntities(this IEnumerable domainModels) + { + return domainModels.Select(domainModel => domainModel.ToRepositoryEntity()); + } +} diff --git a/src/Lumina.Application/Common/Mapping/Common/Metadata/TagModelMapping.cs b/src/Lumina.Application/Common/Mapping/Common/Metadata/TagModelMapping.cs new file mode 100644 index 00000000..73721306 --- /dev/null +++ b/src/Lumina.Application/Common/Mapping/Common/Metadata/TagModelMapping.cs @@ -0,0 +1,37 @@ +#region ========================================================================= USING ===================================================================================== +using ErrorOr; +using Lumina.Contracts.Entities.Common; +using Lumina.Domain.Common.ValueObjects.Metadata; +using System.Collections.Generic; +using System.Linq; +#endregion + +namespace Lumina.Application.Common.Mapping.Common.Metadata; + +/// +/// Extension methods for converting . +/// +public static class TagModelMapping +{ + /// + /// Converts to . + /// + /// The repository entity to be converted. + /// The converted domain model. + public static ErrorOr ToDomainModel(this TagEntity repositoryEntity) + { + return Tag.Create( + repositoryEntity.Name + ); + } + + /// + /// Converts to a collection of . + /// + /// The repository entities to be converted. + /// The converted domain models. + public static IEnumerable> ToDomainModels(this IEnumerable repositoryEntities) + { + return repositoryEntities.Select(domainModel => domainModel.ToDomainModel()); + } +} diff --git a/src/Lumina.Application/Common/Mapping/FileManagement/DirectoryMappingConfig.cs b/src/Lumina.Application/Common/Mapping/FileManagement/DirectoryMappingConfig.cs deleted file mode 100644 index f06995e5..00000000 --- a/src/Lumina.Application/Common/Mapping/FileManagement/DirectoryMappingConfig.cs +++ /dev/null @@ -1,50 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using Lumina.Contracts.Models.FileManagement; -using Lumina.Contracts.Responses.FileManagement; -using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate; -using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.Entities; -using Mapster; -using System; -using System.Collections.Generic; -#endregion - -namespace Lumina.Application.Common.Mapping.FileManagement; - -/// -/// Mapping configuration for file system directories between the domain object and the presentation object. -/// -public class DirectoryMappingConfig : IRegister -{ - /// - /// Registers the mapping configuration. - /// - /// The type adapter configuration. - public void Register(TypeAdapterConfig config) - { - config.NewConfig() - .Map(dest => dest.Name, src => src.Name) - .Map(dest => dest.Path, src => src.Id.Path) - .Map(dest => dest.ItemType, src => src.Type) - .Map(dest => dest.IsExpanded, () => false) - .Map(dest => dest.ChildrenLoaded, () => false) - .Map(dest => dest.Children, src => src.Items.Adapt>()) - .MapToConstructor(true); - - config.NewConfig() - .MapWith(src => new DirectoryResponse( - src.Id.Path, - src.Name, - src.DateCreated.Value, - src.DateModified.Value, - src.Items.Adapt>() - )); - - config.NewConfig() - .MapWith(src => new FileSystemItemModel( - src.Id.Path, - src.Name, - DateTime.Now, - DateTime.Now - )); - } -} diff --git a/src/Lumina.Application/Common/Mapping/FileManagement/FileMappingConfig.cs b/src/Lumina.Application/Common/Mapping/FileManagement/FileMappingConfig.cs deleted file mode 100644 index 1af19c28..00000000 --- a/src/Lumina.Application/Common/Mapping/FileManagement/FileMappingConfig.cs +++ /dev/null @@ -1,37 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using Lumina.Contracts.Responses.FileManagement; -using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.Entities; -using Mapster; -#endregion - -namespace Lumina.Application.Common.Mapping.FileManagement; - -/// -/// Mapping configuration for file system files between the domain object and the presentation object. -/// -public class FileMappingConfig : IRegister -{ - /// - /// Registers the mapping configuration. - /// - /// The type adapter configuration. - public void Register(TypeAdapterConfig config) - { - config.NewConfig() - .Map(dest => dest.Name, src => src.Name) - .Map(dest => dest.Path, src => src.Id.Path) - .Map(dest => dest.ItemType, src => src.Type) - .Map(dest => dest.IsExpanded, () => false) - .Map(dest => dest.ChildrenLoaded, () => false) - .MapToConstructor(true); - - config.NewConfig() - .MapWith(src => new FileResponse( - src.Id.Path, - src.Name, - src.DateCreated.HasValue ? src.DateCreated.Value : default, - src.DateModified.HasValue ? src.DateModified.Value : default, - src.Size - )); - } -} \ No newline at end of file diff --git a/src/Lumina.Application/Common/Mapping/FileManagement/FileSystemTreeMappingConfig.cs b/src/Lumina.Application/Common/Mapping/FileManagement/FileSystemTreeMappingConfig.cs deleted file mode 100644 index bde5226f..00000000 --- a/src/Lumina.Application/Common/Mapping/FileManagement/FileSystemTreeMappingConfig.cs +++ /dev/null @@ -1,65 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using Lumina.Contracts.Enums.FileSystem; -using Lumina.Contracts.Responses.FileManagement; -using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate; -using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.Entities; -using Mapster; -using System.Collections.Generic; -using System.Linq; -#endregion - -namespace Lumina.Application.Common.Mapping.FileManagement; - -/// -/// Mapping configuration for file system trees between the domain object and the presentation object. -/// -public class FileSystemTreeMappingConfig : IRegister -{ - /// - /// Registers the mapping configuration. - /// - /// The type adapter configuration. - public void Register(TypeAdapterConfig config) - { - config.NewConfig() - .Map(dest => dest.Path, src => src.Id.Path) - .Map(dest => dest.Name, src => src.Name) - .Map(dest => dest.ItemType, src => FileSystemItemType.Root) - .Map(dest => dest.IsExpanded, () => false); - - config.NewConfig() - .MapWith(src => WindowsRootItem.Create( - src.Path, - src.Name, - FileSystemItemStatus.Accessible) - .Value); - - config.NewConfig() - .Map(dest => dest.Path, src => src.Id.Path) - .Map(dest => dest.Name, src => src.Name) - .Map(dest => dest.ItemType, src => FileSystemItemType.Root) - .Map(dest => dest.IsExpanded, () => false) - .Map(dest => dest.ChildrenLoaded, () => false) - .Map(dest => dest.Children, src => src.Items.Select(item => item.Adapt(config)).ToList()); - - config.NewConfig() - .MapWith(src => UnixRootItem.Create( - FileSystemItemStatus.Accessible) - .Value); - - config.NewConfig() - .Map(dest => dest.Name, src => src.Name) - .Map(dest => dest.Path, src => src.Id.Path) - .Map(dest => dest.ItemType, src => src.Type) - .Map(dest => dest.IsExpanded, _ => false) - .Map(dest => dest.ChildrenLoaded, _ => false) - .Map(dest => dest.ChildrenLoaded, _ => false) - .AfterMapping((src, dest) => - { - if (src is Directory dir) - dest.Children = dir.Items.Select(item => item.Adapt(config)).ToList(); - else - dest.Children = []; - }); - } -} diff --git a/src/Lumina.Application/Common/Mapping/FileManagement/PathSegmentMappingConfig.cs b/src/Lumina.Application/Common/Mapping/FileManagement/PathSegmentMappingConfig.cs deleted file mode 100644 index bdf17a9c..00000000 --- a/src/Lumina.Application/Common/Mapping/FileManagement/PathSegmentMappingConfig.cs +++ /dev/null @@ -1,24 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using Lumina.Contracts.Responses.FileManagement; -using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.ValueObjects; -using Mapster; -#endregion - -namespace Lumina.Application.Common.Mapping.FileManagement; - -/// -/// Mapping configuration for file system paths between the domain object and the presentation object. -/// -public class PathSegmentMappingConfig : IRegister -{ - /// - /// Registers the mapping configuration. - /// - /// The type adapter configuration. - public void Register(TypeAdapterConfig config) - { - config.NewConfig() - .Map(dest => dest.Path, src => src.Name) - .MapToConstructor(true); - } -} \ No newline at end of file diff --git a/src/Lumina.Application/Common/Mapping/FileManagement/ThumbnailMappingConfig.cs b/src/Lumina.Application/Common/Mapping/FileManagement/ThumbnailMappingConfig.cs deleted file mode 100644 index d51d97ed..00000000 --- a/src/Lumina.Application/Common/Mapping/FileManagement/ThumbnailMappingConfig.cs +++ /dev/null @@ -1,25 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using Lumina.Contracts.Responses.FileManagement; -using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.ValueObjects; -using Mapster; -#endregion - -namespace Lumina.Application.Common.Mapping.FileManagement; - -/// -/// Mapping configuration for file system thumbnails between the domain object and the presentation object. -/// -public class ThumbnailMappingConfig : IRegister -{ - /// - /// Registers the mapping configuration. - /// - /// The type adapter configuration. - public void Register(TypeAdapterConfig config) - { - config.NewConfig() - .Map(dest => dest.Type, src => src.Type) - .Map(dest => dest.Bytes, src => src.Bytes) - .MapToConstructor(true); - } -} diff --git a/src/Lumina.Application/Common/Mapping/FileSystemManagement/Common/FileSystemTreeNodeResponseMapping.cs b/src/Lumina.Application/Common/Mapping/FileSystemManagement/Common/FileSystemTreeNodeResponseMapping.cs new file mode 100644 index 00000000..2bca01d9 --- /dev/null +++ b/src/Lumina.Application/Common/Mapping/FileSystemManagement/Common/FileSystemTreeNodeResponseMapping.cs @@ -0,0 +1,40 @@ +#region ========================================================================= USING ===================================================================================== +using ErrorOr; +using Lumina.Contracts.Enums.FileSystem; +using Lumina.Contracts.Responses.FileSystemManagement.Common; +using Lumina.Domain.Core.Aggregates.FileSystemManagement.FileSystemManagementAggregate.Entities; +#endregion + +namespace Lumina.Application.Common.Mapping.FileSystemManagement.Common; + +/// +/// Extension methods for converting . +/// +public static class FileSystemTreeNodeResponseMapping +{ + /// + /// Converts to . + /// + /// The response to be converted. + /// The converted domain model. + public static ErrorOr ToWindowsRootItem(this FileSystemTreeNodeResponse response) + { + return WindowsRootItem.Create( + response.Path, + response.Name, + FileSystemItemStatus.Accessible + ); + } + + /// + /// Converts to . + /// + /// The response to be converted. + /// The converted domain model. + public static ErrorOr ToUnixRootItem(this FileSystemTreeNodeResponse _) + { + return UnixRootItem.Create( + FileSystemItemStatus.Accessible + ); + } +} diff --git a/src/Lumina.Application/Common/Mapping/FileSystemManagement/Directories/DirectoryMapping.cs b/src/Lumina.Application/Common/Mapping/FileSystemManagement/Directories/DirectoryMapping.cs new file mode 100644 index 00000000..11c8182a --- /dev/null +++ b/src/Lumina.Application/Common/Mapping/FileSystemManagement/Directories/DirectoryMapping.cs @@ -0,0 +1,72 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.Mapping.FileSystemManagement.FileSystem; +using Lumina.Contracts.Responses.FileSystemManagement.Common; +using Lumina.Contracts.Responses.FileSystemManagement.Directories; +using Lumina.Domain.Core.Aggregates.FileSystemManagement.FileSystemManagementAggregate.Entities; +using System.Collections.Generic; +using System.Linq; +#endregion + +namespace Lumina.Application.Common.Mapping.FileSystemManagement.Directories; + +/// +/// Extension methods for converting . +/// +public static class DirectoryMapping +{ + /// + /// Converts to . + /// + /// The domain model to be converted. + /// The converted response. + public static FileSystemTreeNodeResponse ToFileSystemTreeNodeResponse(this Directory domainModel) + { + return new FileSystemTreeNodeResponse() + { + Name = domainModel.Name, + Path = domainModel.Id.Path, + ItemType = domainModel.Type, + IsExpanded = false, + ChildrenLoaded = false, + Children = domainModel.Items.Select(item => item.ToTreeNodeResponse()) + .ToList() + }; + } + + /// + /// Converts to a collection of . + /// + /// The domain models to be converted. + /// The converted responses. + public static IEnumerable ToFileSystemTreeNodeResponses(this IEnumerable domainModels) + { + return domainModels.Select(domainModel => domainModel.ToTreeNodeResponse()); + } + + /// + /// Converts to . + /// + /// The domain model to be converted. + /// The converted response. + public static DirectoryResponse ToResponse(this Directory domainModel) + { + return new DirectoryResponse( + domainModel.Id.Path, + domainModel.Name, + domainModel.DateCreated.Value, + domainModel.DateModified.Value, + domainModel.Items.Select(fileSystemItem => fileSystemItem.ToFileSystemItemModel()) + .ToList() + ); + } + + /// + /// Converts to a collection of . + /// + /// The domain models to be converted. + /// The converted responses. + public static IEnumerable ToResponses(this IEnumerable domainModels) + { + return domainModels.Select(domainModel => domainModel.ToResponse()); + } +} diff --git a/src/Lumina.Application/Common/Mapping/FileSystemManagement/Directories/GetDirectoriesRequestMapping.cs b/src/Lumina.Application/Common/Mapping/FileSystemManagement/Directories/GetDirectoriesRequestMapping.cs new file mode 100644 index 00000000..b57de0a7 --- /dev/null +++ b/src/Lumina.Application/Common/Mapping/FileSystemManagement/Directories/GetDirectoriesRequestMapping.cs @@ -0,0 +1,22 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Core.FileSystemManagement.Directories.Queries.GetDirectories; +using Lumina.Contracts.Requests.FileSystemManagement.Directories; +#endregion + +namespace Lumina.Application.Common.Mapping.FileSystemManagement.Directories; + +/// +/// Extension methods for converting . +/// +public static class GetDirectoriesRequestMapping +{ + /// + /// Converts to . + /// + /// The request to be converted. + /// The converted query. + public static GetDirectoriesQuery ToQuery(this GetDirectoriesRequest request) + { + return new GetDirectoriesQuery(request.Path, request.IncludeHiddenElements); + } +} diff --git a/src/Lumina.Application/Common/Mapping/FileSystemManagement/Directories/GetDirectoryTreeRequestMapping.cs b/src/Lumina.Application/Common/Mapping/FileSystemManagement/Directories/GetDirectoryTreeRequestMapping.cs new file mode 100644 index 00000000..8326966b --- /dev/null +++ b/src/Lumina.Application/Common/Mapping/FileSystemManagement/Directories/GetDirectoryTreeRequestMapping.cs @@ -0,0 +1,22 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Core.FileSystemManagement.Directories.Queries.GetDirectoryTree; +using Lumina.Contracts.Requests.FileSystemManagement.Directories; +#endregion + +namespace Lumina.Application.Common.Mapping.FileSystemManagement.Directories; + +/// +/// Extension methods for converting . +/// +public static class GetDirectoryTreeRequestMapping +{ + /// + /// Converts to . + /// + /// The request to be converted. + /// The converted query. + public static GetDirectoryTreeQuery ToQuery(this GetDirectoryTreeRequest request) + { + return new GetDirectoryTreeQuery(request.Path, request.IncludeFiles, request.IncludeHiddenElements); + } +} diff --git a/src/Lumina.Application/Common/Mapping/FileSystemManagement/Directories/GetTreeDirectoriesRequestMapping.cs b/src/Lumina.Application/Common/Mapping/FileSystemManagement/Directories/GetTreeDirectoriesRequestMapping.cs new file mode 100644 index 00000000..ba826c6a --- /dev/null +++ b/src/Lumina.Application/Common/Mapping/FileSystemManagement/Directories/GetTreeDirectoriesRequestMapping.cs @@ -0,0 +1,22 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Core.FileSystemManagement.Directories.Queries.GetTreeDirectories; +using Lumina.Contracts.Requests.FileSystemManagement.Directories; +#endregion + +namespace Lumina.Application.Common.Mapping.FileSystemManagement.Directories; + +/// +/// Extension methods for converting . +/// +public static class GetTreeDirectoriesRequestMapping +{ + /// + /// Converts to . + /// + /// The request to be converted. + /// The converted query. + public static GetTreeDirectoriesQuery ToQuery(this GetTreeDirectoriesRequest request) + { + return new GetTreeDirectoriesQuery(request.Path, request.IncludeHiddenElements); + } +} diff --git a/src/Lumina.Application/Common/Mapping/FileSystemManagement/FileSystem/FileSystemItemMapping.cs b/src/Lumina.Application/Common/Mapping/FileSystemManagement/FileSystem/FileSystemItemMapping.cs new file mode 100644 index 00000000..6bf8262e --- /dev/null +++ b/src/Lumina.Application/Common/Mapping/FileSystemManagement/FileSystem/FileSystemItemMapping.cs @@ -0,0 +1,64 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.Mapping.FileSystemManagement.Directories; +using Lumina.Application.Common.Mapping.FileSystemManagement.Files; +using Lumina.Contracts.Entities.FileSystemManagement; +using Lumina.Contracts.Responses.FileSystemManagement.Common; +using Lumina.Domain.Core.Aggregates.FileSystemManagement.FileSystemManagementAggregate; +using Lumina.Domain.Core.Aggregates.FileSystemManagement.FileSystemManagementAggregate.Entities; +using System; +using System.Collections.Generic; +using System.Linq; +#endregion + +namespace Lumina.Application.Common.Mapping.FileSystemManagement.FileSystem; + +/// +/// Extension methods for converting . +/// +public static class FileSystemItemMapping +{ + /// + /// Converts to . + /// + /// The domain model to be converted. + /// The converted model. + public static FileSystemItemEntity ToFileSystemItemModel(this FileSystemItem domainModel) + { + return new FileSystemItemEntity( + domainModel.Id.Path, + domainModel.Name, + DateTime.Now, + DateTime.Now + ); + } + + /// + /// Converts to . + /// + /// The domain model to be converted. + /// The converted model. + /// Thrown when the provided parameter is not an expected descendant of . + public static FileSystemTreeNodeResponse ToTreeNodeResponse(this FileSystemItem domainModel) + { + if (domainModel is Directory directory) + return directory.ToFileSystemTreeNodeResponse(); + else if (domainModel is File file) + return file.ToFileSystemTreeNodeResponse(); + else if (domainModel is WindowsRootItem windowsRootItem) + return windowsRootItem.ToTreeNodeResponse(); + else if (domainModel is UnixRootItem unixRootItem) + return unixRootItem.ToTreeNodeResponse(); + else + throw new ArgumentException("Invalid FileSystemItem"); + } + + /// + /// Converts to . + /// + /// The domain models to be converted. + /// The converted models. + public static IEnumerable ToTreeNodeResponses(this IEnumerable domainModels) + { + return domainModels.Select(domainModel => domainModel.ToTreeNodeResponse()); + } +} diff --git a/src/Lumina.Application/Common/Mapping/FileSystemManagement/FileSystem/UnixRootItemMapping.cs b/src/Lumina.Application/Common/Mapping/FileSystemManagement/FileSystem/UnixRootItemMapping.cs new file mode 100644 index 00000000..adbea999 --- /dev/null +++ b/src/Lumina.Application/Common/Mapping/FileSystemManagement/FileSystem/UnixRootItemMapping.cs @@ -0,0 +1,33 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Contracts.Enums.FileSystem; +using Lumina.Contracts.Responses.FileSystemManagement.Common; +using Lumina.Domain.Core.Aggregates.FileSystemManagement.FileSystemManagementAggregate.Entities; +using System.Linq; +#endregion + +namespace Lumina.Application.Common.Mapping.FileSystemManagement.FileSystem; + +/// +/// Extension methods for converting . +/// +public static class UnixRootItemMapping +{ + /// + /// Converts to . + /// + /// The domain model to be converted. + /// The converted response. + public static FileSystemTreeNodeResponse ToTreeNodeResponse(this UnixRootItem domainModel) + { + return new FileSystemTreeNodeResponse() + { + Path = domainModel.Id.Path, + Name = domainModel.Name, + ItemType = FileSystemItemType.Root, + IsExpanded = false, + ChildrenLoaded = false, + Children = domainModel.Items.Select(item => item.ToTreeNodeResponse()) + .ToList() + }; + } +} diff --git a/src/Lumina.Application/Common/Mapping/FileSystemManagement/FileSystem/WindowsRootItemMapping.cs b/src/Lumina.Application/Common/Mapping/FileSystemManagement/FileSystem/WindowsRootItemMapping.cs new file mode 100644 index 00000000..12dc2ce2 --- /dev/null +++ b/src/Lumina.Application/Common/Mapping/FileSystemManagement/FileSystem/WindowsRootItemMapping.cs @@ -0,0 +1,32 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.Mapping.FileSystemManagement.Common; +using Lumina.Contracts.Enums.FileSystem; +using Lumina.Contracts.Responses.FileSystemManagement.Common; +using Lumina.Contracts.Responses.FileSystemManagement.Directories; +using Lumina.Domain.Core.Aggregates.FileSystemManagement.FileSystemManagementAggregate.Entities; +using System.Linq; +#endregion + +namespace Lumina.Application.Common.Mapping.FileSystemManagement.FileSystem; + +/// +/// Extension methods for converting . +/// +public static class WindowsRootItemMapping +{ + /// + /// Converts to . + /// + /// The domain model to be converted. + /// The converted response. + public static FileSystemTreeNodeResponse ToTreeNodeResponse(this WindowsRootItem domainModel) + { + return new FileSystemTreeNodeResponse() + { + Path = domainModel.Id.Path, + Name = domainModel.Name, + ItemType = FileSystemItemType.Root, + IsExpanded = false + }; + } +} diff --git a/src/Lumina.Application/Common/Mapping/FileSystemManagement/Files/FileMapping.cs b/src/Lumina.Application/Common/Mapping/FileSystemManagement/Files/FileMapping.cs new file mode 100644 index 00000000..07a4204d --- /dev/null +++ b/src/Lumina.Application/Common/Mapping/FileSystemManagement/Files/FileMapping.cs @@ -0,0 +1,68 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Contracts.Responses.FileSystemManagement.Common; +using Lumina.Contracts.Responses.FileSystemManagement.Files; +using Lumina.Domain.Core.Aggregates.FileSystemManagement.FileSystemManagementAggregate.Entities; +using System.Collections.Generic; +using System.Linq; +#endregion + +namespace Lumina.Application.Common.Mapping.FileSystemManagement.Files; + +/// +/// Extension methods for converting . +/// +public static class FileMapping +{ + /// + /// Converts to . + /// + /// The domain model to be converted. + /// The converted response. + public static FileSystemTreeNodeResponse ToFileSystemTreeNodeResponse(this File domainModel) + { + return new FileSystemTreeNodeResponse() + { + Name = domainModel.Name, + Path = domainModel.Id.Path, + ItemType = domainModel.Type, + IsExpanded = false, + ChildrenLoaded = false + }; + } + + /// + /// Converts to a collection of . + /// + /// The domain models to be converted. + /// The converted responses. + public static IEnumerable ToFileSystemTreeNodeResponses(this IEnumerable domainModels) + { + return domainModels.Select(domainModel => domainModel.ToFileSystemTreeNodeResponse()); + } + + /// + /// Converts to . + /// + /// The domain model to be converted. + /// The converted response. + public static FileResponse ToResponse(this File domainModel) + { + return new FileResponse( + domainModel.Id.Path, + domainModel.Name, + domainModel.DateCreated.HasValue ? domainModel.DateCreated.Value : default, + domainModel.DateModified.HasValue ? domainModel.DateModified.Value : default, + domainModel.Size + ); + } + + /// + /// Converts to a collection of . + /// + /// The domain models to be converted. + /// The converted responses. + public static IEnumerable ToResponses(this IEnumerable domainModels) + { + return domainModels.Select(domainModel => domainModel.ToResponse()); + } +} diff --git a/src/Lumina.Application/Common/Mapping/FileSystemManagement/Files/GetFilesRequestMapping.cs b/src/Lumina.Application/Common/Mapping/FileSystemManagement/Files/GetFilesRequestMapping.cs new file mode 100644 index 00000000..76bda209 --- /dev/null +++ b/src/Lumina.Application/Common/Mapping/FileSystemManagement/Files/GetFilesRequestMapping.cs @@ -0,0 +1,22 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Core.FileSystemManagement.Files.Queries.GetFiles; +using Lumina.Contracts.Requests.FileSystemManagement.Files; +#endregion + +namespace Lumina.Application.Common.Mapping.FileSystemManagement.Files; + +/// +/// Extension methods for converting . +/// +public static class GetFilesRequestMapping +{ + /// + /// Converts to . + /// + /// The request to be converted. + /// The converted query. + public static GetFilesQuery ToQuery(this GetFilesRequest request) + { + return new GetFilesQuery(request.Path, request.IncludeHiddenElements); + } +} diff --git a/src/Lumina.Application/Common/Mapping/FileSystemManagement/Files/GetTreeFilesRequestMapping.cs b/src/Lumina.Application/Common/Mapping/FileSystemManagement/Files/GetTreeFilesRequestMapping.cs new file mode 100644 index 00000000..1ab64057 --- /dev/null +++ b/src/Lumina.Application/Common/Mapping/FileSystemManagement/Files/GetTreeFilesRequestMapping.cs @@ -0,0 +1,23 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Core.FileSystemManagement.Directories.Queries.GetTreeDirectories; +using Lumina.Application.Core.FileSystemManagement.Files.Queries.GetTreeFiles; +using Lumina.Contracts.Requests.FileSystemManagement.Files; +#endregion + +namespace Lumina.Application.Common.Mapping.FileSystemManagement.Files; + +/// +/// Extension methods for converting . +/// +public static class GetTreeFilesRequestMapping +{ + /// + /// Converts to . + /// + /// The request to be converted. + /// The converted query. + public static GetTreeFilesQuery ToQuery(this GetTreeFilesRequest request) + { + return new GetTreeFilesQuery(request.Path, request.IncludeHiddenElements); + } +} diff --git a/src/Lumina.Application/Common/Mapping/FileSystemManagement/Paths/CheckPathExistsQueryMapping.cs b/src/Lumina.Application/Common/Mapping/FileSystemManagement/Paths/CheckPathExistsQueryMapping.cs new file mode 100644 index 00000000..85ab6d66 --- /dev/null +++ b/src/Lumina.Application/Common/Mapping/FileSystemManagement/Paths/CheckPathExistsQueryMapping.cs @@ -0,0 +1,25 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Core.FileSystemManagement.Paths.Queries.CheckPathExists; +using Lumina.Contracts.Requests.FileSystemManagement.Path; +#endregion + +namespace Lumina.Application.Common.Mapping.FileSystemManagement.Paths; + +/// +/// Extension methods for converting . +/// +public static class CheckPathExistsQueryMapping +{ + /// + /// Converts to . + /// + /// The request to be converted. + /// The converted query. + public static CheckPathExistsQuery ToQuery(this CheckPathExistsRequest request) + { + return new CheckPathExistsQuery( + request.Path, + request.IncludeHiddenElements + ); + } +} diff --git a/src/Lumina.Application/Common/Mapping/FileSystemManagement/Paths/CombinePathRequestMapping.cs b/src/Lumina.Application/Common/Mapping/FileSystemManagement/Paths/CombinePathRequestMapping.cs new file mode 100644 index 00000000..0078aadb --- /dev/null +++ b/src/Lumina.Application/Common/Mapping/FileSystemManagement/Paths/CombinePathRequestMapping.cs @@ -0,0 +1,25 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Core.FileSystemManagement.Paths.Commands.CombinePath; +using Lumina.Contracts.Requests.FileSystemManagement.Path; +#endregion + +namespace Lumina.Application.Common.Mapping.FileSystemManagement.Paths; + +/// +/// Extension methods for converting . +/// +public static class CombinePathRequestMapping +{ + /// + /// Converts to . + /// + /// The request to be converted. + /// The converted command. + public static CombinePathCommand ToCommand(this CombinePathRequest request) + { + return new CombinePathCommand( + request.OriginalPath, + request.NewPath + ); + } +} diff --git a/src/Lumina.Application/Common/Mapping/FileSystemManagement/Paths/GetPathParentRequestMapping.cs b/src/Lumina.Application/Common/Mapping/FileSystemManagement/Paths/GetPathParentRequestMapping.cs new file mode 100644 index 00000000..121e5dad --- /dev/null +++ b/src/Lumina.Application/Common/Mapping/FileSystemManagement/Paths/GetPathParentRequestMapping.cs @@ -0,0 +1,24 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Core.FileSystemManagement.Paths.Queries.GetPathParent; +using Lumina.Contracts.Requests.FileSystemManagement.Path; +#endregion + +namespace Lumina.Application.Common.Mapping.FileSystemManagement.Paths; + +/// +/// Extension methods for converting . +/// +public static class GetPathParentRequestMapping +{ + /// + /// Converts to . + /// + /// The request to be converted. + /// The converted query. + public static GetPathParentQuery ToQuery(this GetPathParentRequest request) + { + return new GetPathParentQuery( + request.Path + ); + } +} diff --git a/src/Lumina.Application/Common/Mapping/FileSystemManagement/Paths/GetPathRootRequestMapping.cs b/src/Lumina.Application/Common/Mapping/FileSystemManagement/Paths/GetPathRootRequestMapping.cs new file mode 100644 index 00000000..a6538eed --- /dev/null +++ b/src/Lumina.Application/Common/Mapping/FileSystemManagement/Paths/GetPathRootRequestMapping.cs @@ -0,0 +1,22 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Core.FileSystemManagement.Paths.Queries.GetPathRoot; +using Lumina.Contracts.Requests.FileSystemManagement.Path; +#endregion + +namespace Lumina.Application.Common.Mapping.FileSystemManagement.Paths; + +/// +/// Extension methods for converting . +/// +public static class GetPathRootRequestMapping +{ + /// + /// Converts to . + /// + /// The request to be converted. + /// The converted query. + public static GetPathRootQuery ToQuery(this GetPathRootRequest request) + { + return new GetPathRootQuery(request.Path); + } +} diff --git a/src/Lumina.Application/Common/Mapping/FileSystemManagement/Paths/PathSegmentMapping.cs b/src/Lumina.Application/Common/Mapping/FileSystemManagement/Paths/PathSegmentMapping.cs new file mode 100644 index 00000000..a7102995 --- /dev/null +++ b/src/Lumina.Application/Common/Mapping/FileSystemManagement/Paths/PathSegmentMapping.cs @@ -0,0 +1,36 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Contracts.Responses.FileSystemManagement.Path; +using Lumina.Domain.Core.Aggregates.FileSystemManagement.FileSystemManagementAggregate.ValueObjects; +using System.Collections.Generic; +using System.Linq; +#endregion + +namespace Lumina.Application.Common.Mapping.FileSystemManagement.Paths; + +/// +/// Extension methods for converting . +/// +public static class PathSegmentMapping +{ + /// + /// Converts to . + /// + /// The domain model to be converted. + /// The converted response. + public static PathSegmentResponse ToResponse(this PathSegment domainModel) + { + return new PathSegmentResponse( + domainModel.Name + ); + } + + /// + /// Converts to a collection of . + /// + /// The domain models to be converted. + /// The converted responses. + public static IEnumerable ToResponses(this IEnumerable domainModels) + { + return domainModels.Select(domainModel => domainModel.ToResponse()); + } +} diff --git a/src/Lumina.Application/Common/Mapping/FileSystemManagement/Paths/SplitPathRequestMapping.cs b/src/Lumina.Application/Common/Mapping/FileSystemManagement/Paths/SplitPathRequestMapping.cs new file mode 100644 index 00000000..1d44cd1d --- /dev/null +++ b/src/Lumina.Application/Common/Mapping/FileSystemManagement/Paths/SplitPathRequestMapping.cs @@ -0,0 +1,24 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Core.FileSystemManagement.Paths.Commands.SplitPath; +using Lumina.Contracts.Requests.FileSystemManagement.Path; +#endregion + +namespace Lumina.Application.Common.Mapping.FileSystemManagement.Paths; + +/// +/// Extension methods for converting . +/// +public static class SplitPathRequestMapping +{ + /// + /// Converts to . + /// + /// The request to be converted. + /// The converted command. + public static SplitPathCommand ToCommand(this SplitPathRequest request) + { + return new SplitPathCommand( + request.Path + ); + } +} diff --git a/src/Lumina.Application/Common/Mapping/FileSystemManagement/Paths/ValidatePathRequestMapping.cs b/src/Lumina.Application/Common/Mapping/FileSystemManagement/Paths/ValidatePathRequestMapping.cs new file mode 100644 index 00000000..ac918191 --- /dev/null +++ b/src/Lumina.Application/Common/Mapping/FileSystemManagement/Paths/ValidatePathRequestMapping.cs @@ -0,0 +1,24 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Core.FileSystemManagement.Paths.Queries.ValidatePath; +using Lumina.Contracts.Requests.FileSystemManagement.Path; +#endregion + +namespace Lumina.Application.Common.Mapping.FileSystemManagement.Paths; + +/// +/// Extension methods for converting . +/// +public static class ValidatePathRequestMapping +{ + /// + /// Converts to . + /// + /// The request to be converted. + /// The converted query. + public static ValidatePathQuery ToQuery(this ValidatePathRequest request) + { + return new ValidatePathQuery( + request.Path + ); + } +} diff --git a/src/Lumina.Application/Common/Mapping/FileSystemManagement/Thumbnails/GetThumbnailRequestMapping.cs b/src/Lumina.Application/Common/Mapping/FileSystemManagement/Thumbnails/GetThumbnailRequestMapping.cs new file mode 100644 index 00000000..8fa534eb --- /dev/null +++ b/src/Lumina.Application/Common/Mapping/FileSystemManagement/Thumbnails/GetThumbnailRequestMapping.cs @@ -0,0 +1,22 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Core.FileSystemManagement.Thumbnails.Queries.GetThumbnail; +using Lumina.Contracts.Requests.FileSystemManagement.Thumbnails; +#endregion + +namespace Lumina.Application.Common.Mapping.FileSystemManagement.Thumbnails; + +/// +/// Extension methods for converting . +/// +public static class GetThumbnailRequestMapping +{ + /// + /// Converts to . + /// + /// The request to be converted. + /// The converted query. + public static GetThumbnailQuery ToQuery(this GetThumbnailRequest request) + { + return new GetThumbnailQuery(request.Path, request.Quality); + } +} diff --git a/src/Lumina.Application/Common/Mapping/FileSystemManagement/Thumbnails/ThumbnailMapping.cs b/src/Lumina.Application/Common/Mapping/FileSystemManagement/Thumbnails/ThumbnailMapping.cs new file mode 100644 index 00000000..9ef20ac8 --- /dev/null +++ b/src/Lumina.Application/Common/Mapping/FileSystemManagement/Thumbnails/ThumbnailMapping.cs @@ -0,0 +1,25 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Contracts.Responses.FileSystemManagement.Thumbnails; +using Lumina.Domain.Core.Aggregates.FileSystemManagement.FileSystemManagementAggregate.ValueObjects; +#endregion + +namespace Lumina.Application.Common.Mapping.FileSystemManagement.Thumbnails; + +/// +/// Extension methods for converting . +/// +public static class ThumbnailMapping +{ + /// + /// Converts to . + /// + /// The domain model to be converted. + /// The converted response. + public static ThumbnailResponse ToResponse(this Thumbnail domainModel) + { + return new ThumbnailResponse( + domainModel.Type, + domainModel.Bytes + ); + } +} diff --git a/src/Lumina.Application/Common/Mapping/WrittenContentLibrary/BookLibrary/BookMappingConfig.cs b/src/Lumina.Application/Common/Mapping/WrittenContentLibrary/BookLibrary/BookMappingConfig.cs deleted file mode 100644 index 03dd13d7..00000000 --- a/src/Lumina.Application/Common/Mapping/WrittenContentLibrary/BookLibrary/BookMappingConfig.cs +++ /dev/null @@ -1,132 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using Lumina.Contracts.Enums.BookLibrary; -using Lumina.Contracts.Models.WrittenContentLibrary.BookLibrary; -using Lumina.Domain.Common.Primitives; -using Lumina.Domain.Common.ValueObjects.Metadata; -using Lumina.Domain.Core.Aggregates.MediaContributor.MediaContributorAggregate.ValueObjects; -using Lumina.Domain.Core.Aggregates.WrittenContentLibrary.BookLibraryAggregate; -using Lumina.Domain.Core.Aggregates.WrittenContentLibrary.BookLibraryAggregate.Entities; -using Lumina.Domain.Core.Aggregates.WrittenContentLibrary.BookLibraryAggregate.ValueObjects; -using Mapster; -using System; -using System.Collections.Generic; -using System.Linq; -#endregion - -namespace Lumina.Application.Common.Mapping.WrittenContentLibrary.BookLibrary; - -/// -/// Mapping configuration for books between the domain object and the persistence object. -/// -public class BookMappingConfig : IRegister -{ - /// - /// Registers the mapping configuration. - /// - /// The type adapter configuration. - public void Register(TypeAdapterConfig config) - { - config.NewConfig() - .Map(dest => dest.Id, src => src.Id.Value) - .Map(dest => dest.Title, src => src.Metadata.Title) - .Map(dest => dest.OriginalTitle, src => src.Metadata.OriginalTitle.HasValue ? src.Metadata.OriginalTitle.Value : default) - .Map(dest => dest.Description, src => src.Metadata.Description.HasValue ? src.Metadata.Description.Value : default) - .Map(dest => dest.OriginalReleaseDate, src => src.Metadata.ReleaseInfo.OriginalReleaseDate.HasValue ? src.Metadata.ReleaseInfo.OriginalReleaseDate.Value : default) - .Map(dest => dest.OriginalReleaseYear, src => src.Metadata.ReleaseInfo.OriginalReleaseYear.HasValue ? src.Metadata.ReleaseInfo.OriginalReleaseYear.Value : default) - .Map(dest => dest.ReReleaseDate, src => src.Metadata.ReleaseInfo.ReReleaseDate.HasValue ? src.Metadata.ReleaseInfo.ReReleaseDate.Value : default) - .Map(dest => dest.ReReleaseYear, src => src.Metadata.ReleaseInfo.ReReleaseYear.HasValue ? src.Metadata.ReleaseInfo.ReReleaseYear.Value : default) - .Map(dest => dest.ReleaseCountry, src => src.Metadata.ReleaseInfo.ReleaseCountry.HasValue ? src.Metadata.ReleaseInfo.ReleaseCountry.Value : default) - .Map(dest => dest.ReleaseVersion, src => src.Metadata.ReleaseInfo.ReleaseVersion.HasValue ? src.Metadata.ReleaseInfo.ReleaseVersion.Value : default) - .Map(dest => dest.LanguageCode, src => src.Metadata.Language.HasValue ? src.Metadata.Language.Value.LanguageCode : default) - .Map(dest => dest.LanguageName, src => src.Metadata.Language.HasValue ? src.Metadata.Language.Value.LanguageName : default) - .Map(dest => dest.LanguageNativeName, src => src.Metadata.Language.HasValue ? src.Metadata.Language.Value.NativeName : default) - .Map(dest => dest.OriginalLanguageCode, src => src.Metadata.OriginalLanguage.HasValue ? src.Metadata.OriginalLanguage.Value.LanguageCode : default) - .Map(dest => dest.OriginalLanguageName, src => src.Metadata.OriginalLanguage.HasValue ? src.Metadata.OriginalLanguage.Value.LanguageName : default) - .Map(dest => dest.OriginalLanguageNativeName, src => src.Metadata.OriginalLanguage.HasValue ? src.Metadata.OriginalLanguage.Value.NativeName : default) - .Map(dest => dest.Tags, src => src.Metadata.Tags) - .Map(dest => dest.Genres, src => src.Metadata.Genres) - .Map(dest => dest.Publisher, src => src.Metadata.Publisher.HasValue ? src.Metadata.Publisher.Value : default) - .Map(dest => dest.PageCount, src => src.Metadata.PageCount.HasValue ? src.Metadata.PageCount.Value : default) - .Map(dest => dest.Format, src => src.Format.ToString()) - .Map(dest => dest.Edition, src => src.Edition.HasValue ? src.Edition.Value : default) - .Map(dest => dest.VolumeNumber, src => src.VolumeNumber.HasValue ? src.VolumeNumber.Value : default) - .Map(dest => dest.ASIN, src => src.ASIN.HasValue ? src.ASIN.Value : default) - .Map(dest => dest.GoodreadsId, src => src.GoodreadsId.HasValue ? src.GoodreadsId.Value : default) - .Map(dest => dest.LCCN, src => src.LCCN.HasValue ? src.LCCN.Value : default) - .Map(dest => dest.OCLCNumber, src => src.OCLCNumber.HasValue ? src.OCLCNumber.Value : default) - .Map(dest => dest.OpenLibraryId, src => src.OpenLibraryId.HasValue ? src.OpenLibraryId.Value : default) - .Map(dest => dest.LibraryThingId, src => src.LibraryThingId.HasValue ? src.LibraryThingId.Value : default) - .Map(dest => dest.GoogleBooksId, src => src.GoogleBooksId.HasValue ? src.GoogleBooksId.Value : default) - .Map(dest => dest.BarnesAndNobleId, src => src.BarnesAndNobleId.HasValue ? src.BarnesAndNobleId.Value : default) - .Map(dest => dest.AppleBooksId, src => src.AppleBooksId.HasValue ? src.AppleBooksId.Value : default) - .Map(dest => dest.ISBNs, src => src.ISBNs) - .Map(dest => dest.Ratings, src => src.Ratings) - .Map(dest => dest.Created, src => src.Created) - .Map(dest => dest.Updated, src => src.Updated.HasValue ? src.Updated : null); - - config.NewConfig() - .Map(dest => dest.Value, src => src.Value) - .Map(dest => dest.MaxValue, src => src.MaxValue) - .Map(dest => dest.VoteCount, src => src.VoteCount.HasValue ? src.VoteCount.Value : default) - .Map(dest => dest.Source, src => src.Source.HasValue ? src.Source.Value : default); - - config.NewConfig, BookRatingSource?>() - .MapWith(src => src.HasValue ? src.Value : default); - - // from BookModel to Book - config.NewConfig() - .MapWith(src => Book.Create( - BookId.Create(src.Id), - WrittenContentMetadata.Create( - src.Title, - Optional.FromNullable(src.OriginalTitle), - Optional.FromNullable(src.Description), - ReleaseInfo.Create( - Optional.FromNullable(src.OriginalReleaseDate), - Optional.FromNullable(src.OriginalReleaseYear), - Optional.FromNullable(src.ReReleaseDate), - Optional.FromNullable(src.ReReleaseYear), - Optional.FromNullable(src.ReleaseCountry), - Optional.FromNullable(src.ReleaseVersion) - ).Value, - src.Genres.Select(g => Genre.Create(g.Name!).Value).ToList(), - src.Tags.Select(t => Tag.Create(t.Name!).Value).ToList(), - src.LanguageCode != null ? LanguageInfo.Create( - src.LanguageCode, - src.LanguageName!, - Optional.FromNullable(src.LanguageNativeName) - ).Value : Optional.None(), - src.OriginalLanguageCode != null ? LanguageInfo.Create( - src.OriginalLanguageCode, - src.OriginalLanguageName!, - Optional.FromNullable(src.OriginalLanguageNativeName) - ).Value : Optional.None(), - Optional.FromNullable(src.Publisher), - Optional.FromNullable(src.PageCount) - ).Value, - Optional.FromNullable(!string.IsNullOrWhiteSpace(src.Format) ? Enum.Parse(src.Format) : default), - Optional.FromNullable(src.Edition), - Optional.FromNullable(src.VolumeNumber), - Optional.None(), - Optional.FromNullable(src.ASIN), - Optional.FromNullable(src.GoodreadsId), - Optional.FromNullable(src.LCCN), - Optional.FromNullable(src.OCLCNumber), - Optional.FromNullable(src.OpenLibraryId), - Optional.FromNullable(src.LibraryThingId), - Optional.FromNullable(src.GoogleBooksId), - Optional.FromNullable(src.BarnesAndNobleId), - Optional.FromNullable(src.AppleBooksId), - src.Created, - Optional.FromNullable(src.Updated), - src.ISBNs.Select(i => Isbn.Create(i.Value!, i.Format ?? default).Value).ToList(), - new List(), - src.Ratings.Select(r => BookRating.Create( - r.Value ?? default, - r.MaxValue ?? default, - Optional.FromNullable(r.Source), - Optional.FromNullable(r.VoteCount) - ).Value).ToList() - ).Value); - } -} \ No newline at end of file diff --git a/src/Lumina.Application/Common/Mapping/WrittenContentLibrary/BookLibrary/Books/AddBookRequestMapping.cs b/src/Lumina.Application/Common/Mapping/WrittenContentLibrary/BookLibrary/Books/AddBookRequestMapping.cs new file mode 100644 index 00000000..8b740310 --- /dev/null +++ b/src/Lumina.Application/Common/Mapping/WrittenContentLibrary/BookLibrary/Books/AddBookRequestMapping.cs @@ -0,0 +1,40 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Core.WrittenContentLibrary.BooksLibrary.Books.Commands.AddBook; +using Lumina.Contracts.Requests.WrittenContentLibrary.BookLibrary.Books; +#endregion + +namespace Lumina.Application.Common.Mapping.WrittenContentLibrary.BookLibrary.Books; + +/// +/// Extension methods for converting . +/// +public static class AddBookRequestMapping +{ + /// + /// Converts to . + /// + /// The request to be converted. + /// The converted command. + public static AddBookCommand ToCommand(this AddBookRequest request) + { + return new AddBookCommand( + request.Metadata, + request.Format, + request.Edition, + request.VolumeNumber, + request.Series, + request.ASIN, + request.GoodreadsId, + request.LCCN, + request.OCLCNumber, + request.OpenLibraryId, + request.LibraryThingId, + request.GoogleBooksId, + request.BarnesAndNobleId, + request.AppleBooksId, + request.ISBNs, + request.Contributors, + request.Ratings + ); + } +} diff --git a/src/Lumina.Application/Common/Mapping/WrittenContentLibrary/BookLibrary/Books/BookMapping.cs b/src/Lumina.Application/Common/Mapping/WrittenContentLibrary/BookLibrary/Books/BookMapping.cs new file mode 100644 index 00000000..5dc00f66 --- /dev/null +++ b/src/Lumina.Application/Common/Mapping/WrittenContentLibrary/BookLibrary/Books/BookMapping.cs @@ -0,0 +1,64 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.Mapping.Common.Metadata; +using Lumina.Application.Common.Mapping.WrittenContentLibrary.BookLibrary.Common; +using Lumina.Contracts.Entities.WrittenContentLibrary.BookLibrary; +using Lumina.Contracts.Responses.WrittenContentLibrary.BookLibrary.Books; +using Lumina.Domain.Core.Aggregates.WrittenContentLibrary.BookLibraryAggregate; +using System.Linq; +#endregion + +namespace Lumina.Application.Common.Mapping.WrittenContentLibrary.BookLibrary.Books; + +/// +/// Extension methods for converting . +/// +public static class BookMapping +{ + /// + /// Converts to . + /// + /// The domain model to be converted. + /// The converted repository entity. + public static BookEntity ToRepositoryEntity(this Book domainModel) + { + return new BookEntity + { + Id = domainModel.Id.Value, + Title = domainModel.Metadata.Title, + OriginalTitle = domainModel.Metadata.OriginalTitle.HasValue ? domainModel.Metadata.OriginalTitle.Value : null, + Description = domainModel.Metadata.Description.HasValue ? domainModel.Metadata.Description.Value : null, + OriginalReleaseDate = domainModel.Metadata.ReleaseInfo.OriginalReleaseDate.HasValue ? domainModel.Metadata.ReleaseInfo.OriginalReleaseDate.Value : null, + OriginalReleaseYear = domainModel.Metadata.ReleaseInfo.OriginalReleaseYear.HasValue ? domainModel.Metadata.ReleaseInfo.OriginalReleaseYear.Value : null, + ReReleaseDate = domainModel.Metadata.ReleaseInfo.ReReleaseDate.HasValue ? domainModel.Metadata.ReleaseInfo.ReReleaseDate.Value : null, + ReReleaseYear = domainModel.Metadata.ReleaseInfo.ReReleaseYear.HasValue ? domainModel.Metadata.ReleaseInfo.ReReleaseYear.Value : null, + ReleaseCountry = domainModel.Metadata.ReleaseInfo.ReleaseCountry.HasValue ? domainModel.Metadata.ReleaseInfo.ReleaseCountry.Value : null, + ReleaseVersion = domainModel.Metadata.ReleaseInfo.ReleaseVersion.HasValue ? domainModel.Metadata.ReleaseInfo.ReleaseVersion.Value : null, + LanguageCode = domainModel.Metadata.Language.HasValue ? domainModel.Metadata.Language.Value.LanguageCode : null, + LanguageName = domainModel.Metadata.Language.HasValue ? domainModel.Metadata.Language.Value.LanguageName : null, + LanguageNativeName = domainModel.Metadata.Language.HasValue ? domainModel.Metadata.Language.Value.NativeName.Value : null, + OriginalLanguageCode = domainModel.Metadata.OriginalLanguage.HasValue ? domainModel.Metadata.OriginalLanguage.Value.LanguageCode : null, + OriginalLanguageName = domainModel.Metadata.OriginalLanguage.HasValue ? domainModel.Metadata.OriginalLanguage.Value.LanguageName : null, + OriginalLanguageNativeName = domainModel.Metadata.OriginalLanguage.HasValue ? domainModel.Metadata.OriginalLanguage.Value.NativeName.Value : null, + Tags = domainModel.Metadata.Tags.ToRepositoryEntities().ToHashSet(), + Genres = domainModel.Metadata.Genres.ToRepositoryEntities().ToHashSet(), + Publisher = domainModel.Metadata.Publisher.HasValue ? domainModel.Metadata.Publisher.Value : null, + PageCount = domainModel.Metadata.PageCount.HasValue ? domainModel.Metadata.PageCount.Value : null, + Format = domainModel.Format.ToString(), + Edition = domainModel.Edition.HasValue ? domainModel.Edition.Value : null, + VolumeNumber = domainModel.VolumeNumber.HasValue ? domainModel.VolumeNumber.Value : null, + ASIN = domainModel.ASIN.HasValue ? domainModel.ASIN.Value : null, + GoodreadsId = domainModel.GoodreadsId.HasValue ? domainModel.GoodreadsId.Value : null, + LCCN = domainModel.LCCN.HasValue ? domainModel.LCCN.Value : null, + OCLCNumber = domainModel.OCLCNumber.HasValue ? domainModel.OCLCNumber.Value : null, + OpenLibraryId = domainModel.OpenLibraryId.HasValue ? domainModel.OpenLibraryId.Value : null, + LibraryThingId = domainModel.LibraryThingId.HasValue ? domainModel.LibraryThingId.Value : null, + GoogleBooksId = domainModel.GoogleBooksId.HasValue ? domainModel.GoogleBooksId.Value : null, + BarnesAndNobleId = domainModel.BarnesAndNobleId.HasValue ? domainModel.BarnesAndNobleId.Value : null, + AppleBooksId = domainModel.AppleBooksId.HasValue ? domainModel.AppleBooksId.Value : null, + ISBNs = domainModel.ISBNs.ToRepositoryEntities().ToList(), + Ratings = domainModel.Ratings.ToRepositoryEntities().ToList(), + Created = domainModel.Created, + Updated = domainModel.Updated.HasValue ? domainModel.Updated : null + }; + } +} diff --git a/src/Lumina.Application/Common/Mapping/WrittenContentLibrary/BookLibrary/Books/BookModelMapping.cs b/src/Lumina.Application/Common/Mapping/WrittenContentLibrary/BookLibrary/Books/BookModelMapping.cs new file mode 100644 index 00000000..7ab29ec1 --- /dev/null +++ b/src/Lumina.Application/Common/Mapping/WrittenContentLibrary/BookLibrary/Books/BookModelMapping.cs @@ -0,0 +1,223 @@ +#region ========================================================================= USING ===================================================================================== +using ErrorOr; +using Lumina.Application.Common.Mapping.Common.Metadata; +using Lumina.Application.Common.Mapping.WrittenContentLibrary.BookLibrary.Common; +using Lumina.Contracts.Entities.Common; +using Lumina.Contracts.Entities.WrittenContentLibrary; +using Lumina.Contracts.Entities.WrittenContentLibrary.BookLibrary; +using Lumina.Contracts.Enums.BookLibrary; +using Lumina.Contracts.Responses.WrittenContentLibrary.BookLibrary.Books; +using Lumina.Domain.Common.Primitives; +using Lumina.Domain.Common.ValueObjects.Metadata; +using Lumina.Domain.Core.Aggregates.WrittenContentLibrary.BookLibraryAggregate; +using Lumina.Domain.Core.Aggregates.WrittenContentLibrary.BookLibraryAggregate.Entities; +using Lumina.Domain.Core.Aggregates.WrittenContentLibrary.BookLibraryAggregate.ValueObjects; +using System; +using System.Collections.Generic; +using System.Linq; +#endregion + +namespace Lumina.Application.Common.Mapping.WrittenContentLibrary.BookLibrary.Books; + +/// +/// Extension methods for converting . +/// +public static class BookModelMapping +{ + /// + /// Converts to . + /// + /// The repository model to be converted. + /// + /// An containing either a successfully converted , or an error message. + /// + public static ErrorOr ToDomainModel(this BookEntity repositoryEntity) + { + IEnumerable> tagsResult = repositoryEntity.Tags.ToDomainModels(); + foreach (ErrorOr tagResult in tagsResult) + if (tagResult.IsError) + return tagResult.Errors; + + IEnumerable> genresResult = repositoryEntity.Genres.ToDomainModels(); + foreach (ErrorOr genreResult in genresResult) + if (genreResult.IsError) + return genreResult.Errors; + + IEnumerable> isbnsResult = repositoryEntity.ISBNs.ToDomainModels(); + foreach (ErrorOr isbnResult in isbnsResult) + if (isbnResult.IsError) + return isbnResult.Errors; + + IEnumerable> bookRatingsResult = repositoryEntity.Ratings.ToDomainModels(); + foreach (ErrorOr bookRatingResult in bookRatingsResult) + if (bookRatingResult.IsError) + return bookRatingResult.Errors; + + ErrorOr releaseInfoResult = ReleaseInfo.Create( + Optional.FromNullable(repositoryEntity.OriginalReleaseDate), + Optional.FromNullable(repositoryEntity.OriginalReleaseYear), + Optional.FromNullable(repositoryEntity.ReReleaseDate), + Optional.FromNullable(repositoryEntity.ReReleaseYear), + Optional.FromNullable(repositoryEntity.ReleaseCountry), + Optional.FromNullable(repositoryEntity.ReleaseVersion) + ); + if (releaseInfoResult.IsError) + return releaseInfoResult.Errors; + + Optional languageInfo = Optional.None(); + if (repositoryEntity.LanguageCode is not null) + { + ErrorOr languageInfoResult = LanguageInfo.Create( + repositoryEntity.LanguageCode, + repositoryEntity.LanguageName, + Optional.FromNullable(repositoryEntity.LanguageNativeName) + ); + if (languageInfoResult.IsError) + return languageInfoResult.Errors; + languageInfo = languageInfoResult.Value; + } + + Optional originalLanguageCode = Optional.None(); + if (repositoryEntity.OriginalLanguageCode is not null) + { + ErrorOr originalLanguageInfoResult = LanguageInfo.Create( + repositoryEntity.OriginalLanguageCode, + repositoryEntity.OriginalLanguageName!, + Optional.FromNullable(repositoryEntity.OriginalLanguageNativeName) + ); + if (originalLanguageInfoResult.IsError) + return originalLanguageInfoResult.Errors; + originalLanguageCode = originalLanguageInfoResult.Value; + } + + ErrorOr writtenContentMetadataResult = WrittenContentMetadata.Create( + repositoryEntity.Title, + Optional.FromNullable(repositoryEntity.OriginalTitle), + Optional.FromNullable(repositoryEntity.Description), + releaseInfoResult.Value, + genresResult.Select(genre => genre.Value).ToList(), + tagsResult.Select(tag => tag.Value).ToList(), + languageInfo, + originalLanguageCode, + Optional.FromNullable(repositoryEntity.Publisher), + Optional.FromNullable(repositoryEntity.PageCount) + ); + if (writtenContentMetadataResult.IsError) + return writtenContentMetadataResult.Errors; + + Optional bookFormat = Optional.FromNullable(!string.IsNullOrWhiteSpace(repositoryEntity.Format) ? Enum.Parse(repositoryEntity.Format) : (BookFormat?)null); + + return Book.Create( + BookId.Create(repositoryEntity.Id), + writtenContentMetadataResult.Value, + bookFormat, + Optional.FromNullable(repositoryEntity.Edition), + Optional.FromNullable(repositoryEntity.VolumeNumber), + Optional.None(), + Optional.FromNullable(repositoryEntity.ASIN), + Optional.FromNullable(repositoryEntity.GoodreadsId), + Optional.FromNullable(repositoryEntity.LCCN), + Optional.FromNullable(repositoryEntity.OCLCNumber), + Optional.FromNullable(repositoryEntity.OpenLibraryId), + Optional.FromNullable(repositoryEntity.LibraryThingId), + Optional.FromNullable(repositoryEntity.GoogleBooksId), + Optional.FromNullable(repositoryEntity.BarnesAndNobleId), + Optional.FromNullable(repositoryEntity.AppleBooksId), + repositoryEntity.Created, + Optional.FromNullable(repositoryEntity.Updated), + isbnsResult.Select(isbn => isbn.Value).ToList(), + [], + bookRatingsResult.Select(bookRating => bookRating.Value).ToList()); + } + + /// + /// Converts to a collection of . + /// + /// The repository models to be converted. + /// The converted domain models. + /// + /// An colection of containing either successfully converted , or error messages. + /// + public static IEnumerable> ToDomainModels(this IEnumerable repositoryEntities) + { + return repositoryEntities.Select(repositoryEntity => repositoryEntity.ToDomainModel()); + } + + /// + /// Converts to . + /// + /// The repository model to be converted. + /// The converted response model. + public static BookResponse ToResponse(this BookEntity repositoryEntity) + { + ReleaseInfoEntity releaseInfoModel = new( + repositoryEntity.OriginalReleaseDate, + repositoryEntity.OriginalReleaseYear, + repositoryEntity.ReReleaseDate, + repositoryEntity.ReReleaseYear, + repositoryEntity.ReleaseCountry, + repositoryEntity.ReleaseVersion + ); + // language and original language make sense only if their subproperties have values + LanguageInfoEntity? languageInfoModel = (!string.IsNullOrWhiteSpace(repositoryEntity.LanguageCode) || + !string.IsNullOrWhiteSpace(repositoryEntity.LanguageName) || + !string.IsNullOrWhiteSpace(repositoryEntity.LanguageNativeName)) + ? new LanguageInfoEntity( + repositoryEntity.LanguageCode, + repositoryEntity.LanguageName, + repositoryEntity.LanguageNativeName + ) : null; + LanguageInfoEntity? originalLanguageInfoModel = (!string.IsNullOrWhiteSpace(repositoryEntity.OriginalLanguageCode) || + !string.IsNullOrWhiteSpace(repositoryEntity.OriginalLanguageName) || + !string.IsNullOrWhiteSpace(repositoryEntity.OriginalLanguageNativeName)) + ? new LanguageInfoEntity( + repositoryEntity.OriginalLanguageCode, + repositoryEntity.OriginalLanguageName, + repositoryEntity.OriginalLanguageNativeName + ) : null; + WrittenContentMetadataEntity metadata = new( + repositoryEntity.Title, + repositoryEntity.OriginalTitle, + repositoryEntity.Description, + releaseInfoModel, + [.. repositoryEntity.Genres], + [.. repositoryEntity.Tags], + languageInfoModel, + originalLanguageInfoModel, + repositoryEntity.Publisher, + repositoryEntity.PageCount + ); + return new BookResponse( + repositoryEntity.Id, + metadata, + !string.IsNullOrWhiteSpace(repositoryEntity.Format) ? Enum.Parse(repositoryEntity.Format) : null, + repositoryEntity.Edition, + repositoryEntity.VolumeNumber, + null, + repositoryEntity.ASIN, + repositoryEntity.GoodreadsId, + repositoryEntity.LCCN, + repositoryEntity.OCLCNumber, + repositoryEntity.OpenLibraryId, + repositoryEntity.LibraryThingId, + repositoryEntity.GoogleBooksId, + repositoryEntity.BarnesAndNobleId, + repositoryEntity.AppleBooksId, + repositoryEntity.ISBNs, + null, + repositoryEntity.Ratings, + repositoryEntity.Created, + repositoryEntity.Updated + ); + } + + /// + /// Converts to a collection of . + /// + /// The repository models to be converted. + /// The converted reponses. + public static IEnumerable ToResponses(this IEnumerable repositoryEntities) + { + return repositoryEntities.Select(repositoryEntity => repositoryEntity.ToResponse()); + } +} diff --git a/src/Lumina.Application/Common/Mapping/WrittenContentLibrary/BookLibrary/Common/BookRatingMapping.cs b/src/Lumina.Application/Common/Mapping/WrittenContentLibrary/BookLibrary/Common/BookRatingMapping.cs new file mode 100644 index 00000000..4b234f48 --- /dev/null +++ b/src/Lumina.Application/Common/Mapping/WrittenContentLibrary/BookLibrary/Common/BookRatingMapping.cs @@ -0,0 +1,39 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Contracts.Entities.WrittenContentLibrary.BookLibrary; +using Lumina.Domain.Core.Aggregates.WrittenContentLibrary.BookLibraryAggregate.ValueObjects; +using System.Collections.Generic; +using System.Linq; +#endregion + +namespace Lumina.Application.Common.Mapping.WrittenContentLibrary.BookLibrary.Common; + +/// +/// Extension methods for converting . +/// +public static class BookRatingMapping +{ + /// + /// Converts to . + /// + /// The domain model to be converted. + /// The converted repository entity. + public static BookRatingEntity ToRepositoryEntity(this BookRating domainModel) + { + return new BookRatingEntity( + domainModel.Value, + domainModel.MaxValue, + domainModel.Source.HasValue ? domainModel.Source.Value : null, + domainModel.VoteCount.HasValue ? domainModel.VoteCount.Value : null + ); + } + + /// + /// Converts to a collection of . + /// + /// The domain models to be converted. + /// The converted repository entities. + public static IEnumerable ToRepositoryEntities(this IEnumerable domainModels) + { + return domainModels.Select(domainModel => domainModel.ToRepositoryEntity()); + } +} diff --git a/src/Lumina.Application/Common/Mapping/WrittenContentLibrary/BookLibrary/Common/BookRatingModelMapping.cs b/src/Lumina.Application/Common/Mapping/WrittenContentLibrary/BookLibrary/Common/BookRatingModelMapping.cs new file mode 100644 index 00000000..509c5846 --- /dev/null +++ b/src/Lumina.Application/Common/Mapping/WrittenContentLibrary/BookLibrary/Common/BookRatingModelMapping.cs @@ -0,0 +1,42 @@ +#region ========================================================================= USING ===================================================================================== +using ErrorOr; +using Lumina.Contracts.Entities.WrittenContentLibrary.BookLibrary; +using Lumina.Contracts.Enums.BookLibrary; +using Lumina.Domain.Common.Primitives; +using Lumina.Domain.Core.Aggregates.WrittenContentLibrary.BookLibraryAggregate.ValueObjects; +using System.Collections.Generic; +using System.Linq; +#endregion + +namespace Lumina.Application.Common.Mapping.WrittenContentLibrary.BookLibrary.Common; + +/// +/// Extension methods for converting . +/// +public static class BookRatingModelMapping +{ + /// + /// Converts to . + /// + /// The repository model to be converted. + /// The converted domain model. + public static ErrorOr ToDomainModel(this BookRatingEntity repositoryEntity) + { + return BookRating.Create( + repositoryEntity.Value ?? default, + repositoryEntity.MaxValue ?? default, + Optional.FromNullable(repositoryEntity.Source), + Optional.FromNullable(repositoryEntity.VoteCount) + ); + } + + /// + /// Converts to a collection of . + /// + /// The repository models to be converted. + /// The converted domain models. + public static IEnumerable> ToDomainModels(this IEnumerable repositoryEntities) + { + return repositoryEntities.Select(domainModel => domainModel.ToDomainModel()); + } +} diff --git a/src/Lumina.Application/Common/Mapping/WrittenContentLibrary/BookLibrary/Common/IsbnMapping.cs b/src/Lumina.Application/Common/Mapping/WrittenContentLibrary/BookLibrary/Common/IsbnMapping.cs new file mode 100644 index 00000000..0532c660 --- /dev/null +++ b/src/Lumina.Application/Common/Mapping/WrittenContentLibrary/BookLibrary/Common/IsbnMapping.cs @@ -0,0 +1,37 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Contracts.Entities.WrittenContentLibrary.BookLibrary; +using Lumina.Domain.Core.Aggregates.WrittenContentLibrary.BookLibraryAggregate.ValueObjects; +using System.Collections.Generic; +using System.Linq; +#endregion + +namespace Lumina.Application.Common.Mapping.WrittenContentLibrary.BookLibrary.Common; + +/// +/// Extension methods for converting . +/// +public static class IsbnMapping +{ + /// + /// Converts to . + /// + /// The domain model to be converted. + /// The converted repository entity. + public static IsbnEntity ToRepositoryEntity(this Isbn domainModel) + { + return new IsbnEntity( + domainModel.Value, + domainModel.Format + ); + } + + /// + /// Converts to a collection of . + /// + /// The domain models to be converted. + /// The converted repository entities. + public static IEnumerable ToRepositoryEntities(this IEnumerable domainModels) + { + return domainModels.Select(domainModel => domainModel.ToRepositoryEntity()); + } +} diff --git a/src/Lumina.Application/Common/Mapping/WrittenContentLibrary/BookLibrary/Common/IsbnModelMapping.cs b/src/Lumina.Application/Common/Mapping/WrittenContentLibrary/BookLibrary/Common/IsbnModelMapping.cs new file mode 100644 index 00000000..bfeb7bb8 --- /dev/null +++ b/src/Lumina.Application/Common/Mapping/WrittenContentLibrary/BookLibrary/Common/IsbnModelMapping.cs @@ -0,0 +1,41 @@ +#region ========================================================================= USING ===================================================================================== +using ErrorOr; +using Lumina.Contracts.Entities.WrittenContentLibrary.BookLibrary; +using Lumina.Contracts.Enums.BookLibrary; +using Lumina.Domain.Core.Aggregates.WrittenContentLibrary.BookLibraryAggregate.ValueObjects; +using System.Collections.Generic; +using System.Linq; +#endregion + +namespace Lumina.Application.Common.Mapping.WrittenContentLibrary.BookLibrary.Common; + +/// +/// Extension methods for converting . +/// +public static class IsbnModelMapping +{ + /// + /// Converts to . + /// + /// The repository model to be converted. + /// + /// An containing either a successfully converted , or an error message. + /// + public static ErrorOr ToDomainModel(this IsbnEntity repositoryEntity) + { + return Isbn.Create( + repositoryEntity.Value, + repositoryEntity.Format ?? IsbnFormat.Isbn13 + ); + } + + /// + /// Converts to a collection of . + /// + /// The repository models to be converted. + /// The converted domain models. + public static IEnumerable> ToDomainModels(this IEnumerable repositoryEntities) + { + return repositoryEntities.Select(domainModel => domainModel.ToDomainModel()); + } +} diff --git a/src/Lumina.Application/Core/FileManagement/Directories/Queries/GetDirectories/GetDirectoriesQuery.cs b/src/Lumina.Application/Core/FileManagement/Directories/Queries/GetDirectories/GetDirectoriesQuery.cs deleted file mode 100644 index b303fec9..00000000 --- a/src/Lumina.Application/Core/FileManagement/Directories/Queries/GetDirectories/GetDirectoriesQuery.cs +++ /dev/null @@ -1,15 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using ErrorOr; -using Lumina.Contracts.Responses.FileManagement; -using Mediator; -using System.Collections.Generic; -#endregion - -namespace Lumina.Application.Core.FileManagement.Directories.Queries.GetDirectories; - -/// -/// Query for retrieving the list of directories at a path. -/// -/// The path for which to retrieve the list of directories. -/// Whether to include hidden directories or not. -public record GetDirectoriesQuery(string Path, bool IncludeHiddenElements) : IRequest>>; \ No newline at end of file diff --git a/src/Lumina.Application/Core/FileManagement/Directories/Queries/GetTreeDirectories/GetTreeDirectoriesQuery.cs b/src/Lumina.Application/Core/FileManagement/Directories/Queries/GetTreeDirectories/GetTreeDirectoriesQuery.cs deleted file mode 100644 index 5e447708..00000000 --- a/src/Lumina.Application/Core/FileManagement/Directories/Queries/GetTreeDirectories/GetTreeDirectoriesQuery.cs +++ /dev/null @@ -1,15 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using ErrorOr; -using Lumina.Contracts.Responses.FileManagement; -using Mediator; -using System.Collections.Generic; -#endregion - -namespace Lumina.Application.Core.FileManagement.Directories.Queries.GetTreeDirectories; - -/// -/// Query for retrieving the list of directories at a path. -/// -/// The path for which to retrieve the list of directories. -/// Whether to include hidden directories or not. -public record GetTreeDirectoriesQuery(string Path, bool IncludeHiddenElements) : IRequest>>; \ No newline at end of file diff --git a/src/Lumina.Application/Core/FileManagement/Files/Queries/GetFiles/GetFilesQuery.cs b/src/Lumina.Application/Core/FileManagement/Files/Queries/GetFiles/GetFilesQuery.cs deleted file mode 100644 index 8393d753..00000000 --- a/src/Lumina.Application/Core/FileManagement/Files/Queries/GetFiles/GetFilesQuery.cs +++ /dev/null @@ -1,15 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using ErrorOr; -using Lumina.Contracts.Responses.FileManagement; -using Mediator; -using System.Collections.Generic; -#endregion - -namespace Lumina.Application.Core.FileManagement.Files.Queries.GetFiles; - -/// -/// Query for retrieving the list of files at a path. -/// -/// The path for which to retrieve the list of files. -/// Whether to include hidden files and directories or not. -public record GetFilesQuery(string Path, bool IncludeHiddenElements) : IRequest>>; \ No newline at end of file diff --git a/src/Lumina.Application/Core/FileManagement/Files/Queries/GetTreeFiles/GetTreeFilesQuery.cs b/src/Lumina.Application/Core/FileManagement/Files/Queries/GetTreeFiles/GetTreeFilesQuery.cs deleted file mode 100644 index 7b9c7bc7..00000000 --- a/src/Lumina.Application/Core/FileManagement/Files/Queries/GetTreeFiles/GetTreeFilesQuery.cs +++ /dev/null @@ -1,15 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using ErrorOr; -using Lumina.Contracts.Responses.FileManagement; -using Mediator; -using System.Collections.Generic; -#endregion - -namespace Lumina.Application.Core.FileManagement.Files.Queries.GetTreeFiles; - -/// -/// Query for retrieving the list of files at a path. -/// -/// The path for which to retrieve the list of files. -/// Whether to include hidden files and directories or not. -public record GetTreeFilesQuery(string Path, bool IncludeHiddenElements) : IRequest>>; \ No newline at end of file diff --git a/src/Lumina.Application/Core/FileManagement/Paths/Commands/CombinePath/CombinePathCommand.cs b/src/Lumina.Application/Core/FileManagement/Paths/Commands/CombinePath/CombinePathCommand.cs deleted file mode 100644 index 44e08e79..00000000 --- a/src/Lumina.Application/Core/FileManagement/Paths/Commands/CombinePath/CombinePathCommand.cs +++ /dev/null @@ -1,16 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using ErrorOr; -using Lumina.Contracts.Responses.FileManagement; -using Mediator; -#endregion - -namespace Lumina.Application.Core.FileManagement.Paths.Commands.CombinePath; - -/// -/// Command for combining two file system path. -/// -/// The path to combine to. -/// The path to combine with. -public record CombinePathCommand( - string OriginalPath, string NewPath -) : IRequest>; \ No newline at end of file diff --git a/src/Lumina.Application/Core/FileManagement/Paths/Commands/SplitPath/SplitPathCommand.cs b/src/Lumina.Application/Core/FileManagement/Paths/Commands/SplitPath/SplitPathCommand.cs deleted file mode 100644 index f1b9ad02..00000000 --- a/src/Lumina.Application/Core/FileManagement/Paths/Commands/SplitPath/SplitPathCommand.cs +++ /dev/null @@ -1,16 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using ErrorOr; -using Lumina.Contracts.Responses.FileManagement; -using Mediator; -using System.Collections.Generic; -#endregion - -namespace Lumina.Application.Core.FileManagement.Paths.Commands.SplitPath; - -/// -/// Command for splitting a file system path. -/// -/// The path to split. -public record SplitPathCommand( - string Path -) : IRequest>>; \ No newline at end of file diff --git a/src/Lumina.Application/Core/FileManagement/Paths/Queries/CheckPathExists/CheckPathExistsQuery.cs b/src/Lumina.Application/Core/FileManagement/Paths/Queries/CheckPathExists/CheckPathExistsQuery.cs deleted file mode 100644 index dcba55c1..00000000 --- a/src/Lumina.Application/Core/FileManagement/Paths/Queries/CheckPathExists/CheckPathExistsQuery.cs +++ /dev/null @@ -1,13 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using Lumina.Contracts.Responses.FileManagement; -using Mediator; -#endregion - -namespace Lumina.Application.Core.FileManagement.Paths.Queries.CheckPathExists; - -/// -/// Query for retrieving the existence of a file system path. -/// -/// The path for which to check the existence. -/// Whether to include hidden file system elements or not. -public record CheckPathExistsQuery(string Path, bool IncludeHiddenElements) : IRequest; diff --git a/src/Lumina.Application/Core/FileManagement/Paths/Queries/GetPathParent/GetPathParentQuery.cs b/src/Lumina.Application/Core/FileManagement/Paths/Queries/GetPathParent/GetPathParentQuery.cs deleted file mode 100644 index f4d00063..00000000 --- a/src/Lumina.Application/Core/FileManagement/Paths/Queries/GetPathParent/GetPathParentQuery.cs +++ /dev/null @@ -1,14 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using ErrorOr; -using Lumina.Contracts.Responses.FileManagement; -using Mediator; -using System.Collections.Generic; -#endregion - -namespace Lumina.Application.Core.FileManagement.Paths.Queries.GetPathParent; - -/// -/// Query for retrieving the parent of a file system path. -/// -/// The path for which to get the parent. -public record GetPathParentQuery(string Path) : IRequest>>; \ No newline at end of file diff --git a/src/Lumina.Application/Core/FileManagement/Paths/Queries/GetPathRoot/GetPathRootQuery.cs b/src/Lumina.Application/Core/FileManagement/Paths/Queries/GetPathRoot/GetPathRootQuery.cs deleted file mode 100644 index 89df4002..00000000 --- a/src/Lumina.Application/Core/FileManagement/Paths/Queries/GetPathRoot/GetPathRootQuery.cs +++ /dev/null @@ -1,13 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using ErrorOr; -using Lumina.Contracts.Responses.FileManagement; -using Mediator; -#endregion - -namespace Lumina.Application.Core.FileManagement.Paths.Queries.GetPathRoot; - -/// -/// Query for retrieving the root of a path. -/// -/// The path for which to get the path root. -public record GetPathRootQuery(string Path) : IRequest>; \ No newline at end of file diff --git a/src/Lumina.Application/Core/FileManagement/Paths/Queries/ValidatePath/ValidatePathQuery.cs b/src/Lumina.Application/Core/FileManagement/Paths/Queries/ValidatePath/ValidatePathQuery.cs deleted file mode 100644 index 899c3a6b..00000000 --- a/src/Lumina.Application/Core/FileManagement/Paths/Queries/ValidatePath/ValidatePathQuery.cs +++ /dev/null @@ -1,12 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using Lumina.Contracts.Responses.FileManagement; -using Mediator; -#endregion - -namespace Lumina.Application.Core.FileManagement.Paths.Queries.ValidatePath; - -/// -/// Query for validating a path. -/// -/// The path to be validated. -public record ValidatePathQuery(string Path) : IRequest; \ No newline at end of file diff --git a/src/Lumina.Application/Core/FileSystemManagement/Directories/Queries/GetDirectories/GetDirectoriesQuery.cs b/src/Lumina.Application/Core/FileSystemManagement/Directories/Queries/GetDirectories/GetDirectoriesQuery.cs new file mode 100644 index 00000000..c4be3e4b --- /dev/null +++ b/src/Lumina.Application/Core/FileSystemManagement/Directories/Queries/GetDirectories/GetDirectoriesQuery.cs @@ -0,0 +1,20 @@ +#region ========================================================================= USING ===================================================================================== +using ErrorOr; +using Lumina.Contracts.Responses.FileSystemManagement.Directories; +using Mediator; +using System.Collections.Generic; +using System.Diagnostics; +#endregion + +namespace Lumina.Application.Core.FileSystemManagement.Directories.Queries.GetDirectories; + +/// +/// Query for retrieving the list of directories at a path. +/// +/// The path for which to retrieve the list of directories. +/// Whether to include hidden directories or not. +[DebuggerDisplay("Path: {Path}")] +public record GetDirectoriesQuery( + string? Path, + bool IncludeHiddenElements +) : IRequest>>; diff --git a/src/Lumina.Application/Core/FileManagement/Directories/Queries/GetDirectories/GetDirectoriesQueryHandler.cs b/src/Lumina.Application/Core/FileSystemManagement/Directories/Queries/GetDirectories/GetDirectoriesQueryHandler.cs similarity index 71% rename from src/Lumina.Application/Core/FileManagement/Directories/Queries/GetDirectories/GetDirectoriesQueryHandler.cs rename to src/Lumina.Application/Core/FileSystemManagement/Directories/Queries/GetDirectories/GetDirectoriesQueryHandler.cs index d182d486..b0aab643 100644 --- a/src/Lumina.Application/Core/FileManagement/Directories/Queries/GetDirectories/GetDirectoriesQueryHandler.cs +++ b/src/Lumina.Application/Core/FileSystemManagement/Directories/Queries/GetDirectories/GetDirectoriesQueryHandler.cs @@ -1,17 +1,16 @@ #region ========================================================================= USING ===================================================================================== using ErrorOr; -using Lumina.Contracts.Responses.FileManagement; -using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.Entities; -using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.Services; -using Mapster; -using MapsterMapper; +using Lumina.Application.Common.Mapping.FileSystemManagement.Directories; +using Lumina.Contracts.Responses.FileSystemManagement.Directories; +using Lumina.Domain.Core.Aggregates.FileSystemManagement.FileSystemManagementAggregate.Entities; +using Lumina.Domain.Core.Aggregates.FileSystemManagement.FileSystemManagementAggregate.Services; using Mediator; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; #endregion -namespace Lumina.Application.Core.FileManagement.Directories.Queries.GetDirectories; +namespace Lumina.Application.Core.FileSystemManagement.Directories.Queries.GetDirectories; /// /// Handler for the query to get all directories. @@ -19,17 +18,14 @@ namespace Lumina.Application.Core.FileManagement.Directories.Queries.GetDirector public class GetDirectoriesQueryHandler : IRequestHandler>> { private readonly IDirectoryService _directoryService; - private readonly IMapper _mapper; /// /// Initializes a new instance of the class. /// /// Injected service for handling directories. - /// Injected service for mapping objects. - public GetDirectoriesQueryHandler(IDirectoryService directoryService, IMapper mapper) + public GetDirectoriesQueryHandler(IDirectoryService directoryService) { _directoryService = directoryService; - _mapper = mapper; } /// @@ -42,7 +38,7 @@ public class GetDirectoriesQueryHandler : IRequestHandler public ValueTask>> Handle(GetDirectoriesQuery request, CancellationToken cancellationToken) { - ErrorOr> result = _directoryService.GetSubdirectories(request.Path, request.IncludeHiddenElements); - return ValueTask.FromResult(result.Match(values => ErrorOrFactory.From(_mapper.Map>(values)), errors => errors)); + ErrorOr> result = _directoryService.GetSubdirectories(request.Path!, request.IncludeHiddenElements); + return ValueTask.FromResult(result.Match(values => ErrorOrFactory.From(values.ToResponses()), errors => errors)); } } diff --git a/src/Lumina.Application/Core/FileManagement/Directories/Queries/GetDirectories/GetDirectoriesQueryValidator.cs b/src/Lumina.Application/Core/FileSystemManagement/Directories/Queries/GetDirectories/GetDirectoriesQueryValidator.cs similarity index 75% rename from src/Lumina.Application/Core/FileManagement/Directories/Queries/GetDirectories/GetDirectoriesQueryValidator.cs rename to src/Lumina.Application/Core/FileSystemManagement/Directories/Queries/GetDirectories/GetDirectoriesQueryValidator.cs index 96fe8a25..95253b8f 100644 --- a/src/Lumina.Application/Core/FileManagement/Directories/Queries/GetDirectories/GetDirectoriesQueryValidator.cs +++ b/src/Lumina.Application/Core/FileSystemManagement/Directories/Queries/GetDirectories/GetDirectoriesQueryValidator.cs @@ -3,7 +3,7 @@ using FluentValidation; using Lumina.Domain.Common.Errors; #endregion -namespace Lumina.Application.Core.FileManagement.Directories.Queries.GetDirectories; +namespace Lumina.Application.Core.FileSystemManagement.Directories.Queries.GetDirectories; /// /// Validates the needed validation rules for . @@ -15,6 +15,6 @@ public class GetDirectoriesQueryValidator : AbstractValidator public GetDirectoriesQueryValidator() { - RuleFor(x => x.Path).NotEmpty().WithMessage(Errors.FileManagement.PathCannotBeEmpty.Code); + RuleFor(x => x.Path).NotEmpty().WithMessage(Errors.FileSystemManagement.PathCannotBeEmpty.Description); } } \ No newline at end of file diff --git a/src/Lumina.Application/Core/FileManagement/Directories/Queries/GetDirectoryTree/GetDirectoryTreeQuery.cs b/src/Lumina.Application/Core/FileSystemManagement/Directories/Queries/GetDirectoryTree/GetDirectoryTreeQuery.cs similarity index 61% rename from src/Lumina.Application/Core/FileManagement/Directories/Queries/GetDirectoryTree/GetDirectoryTreeQuery.cs rename to src/Lumina.Application/Core/FileSystemManagement/Directories/Queries/GetDirectoryTree/GetDirectoryTreeQuery.cs index 2142c2d6..2692a771 100644 --- a/src/Lumina.Application/Core/FileManagement/Directories/Queries/GetDirectoryTree/GetDirectoryTreeQuery.cs +++ b/src/Lumina.Application/Core/FileSystemManagement/Directories/Queries/GetDirectoryTree/GetDirectoryTreeQuery.cs @@ -1,11 +1,12 @@ #region ========================================================================= USING ===================================================================================== using ErrorOr; -using Lumina.Contracts.Responses.FileManagement; +using Lumina.Contracts.Responses.FileSystemManagement.Common; using Mediator; using System.Collections.Generic; +using System.Diagnostics; #endregion -namespace Lumina.Application.Core.FileManagement.Directories.Queries.GetDirectoryTree; +namespace Lumina.Application.Core.FileSystemManagement.Directories.Queries.GetDirectoryTree; /// /// Query for retrieving the tree of directories of a path. @@ -13,4 +14,9 @@ namespace Lumina.Application.Core.FileManagement.Directories.Queries.GetDirector /// The path for which to retrieve the tree of directories. /// Whether to include files in the directory tree or not. /// Whether to include hidden files and directories or not. -public record GetDirectoryTreeQuery(string Path, bool IncludeFiles, bool IncludeHiddenElements) : IRequest>>; +[DebuggerDisplay("Path: {Path}")] +public record GetDirectoryTreeQuery( + string? Path, + bool IncludeFiles, + bool IncludeHiddenElements +) : IRequest>>; diff --git a/src/Lumina.Application/Core/FileManagement/Directories/Queries/GetDirectoryTree/GetDirectoryTreeQueryHandler.cs b/src/Lumina.Application/Core/FileSystemManagement/Directories/Queries/GetDirectoryTree/GetDirectoryTreeQueryHandler.cs similarity index 91% rename from src/Lumina.Application/Core/FileManagement/Directories/Queries/GetDirectoryTree/GetDirectoryTreeQueryHandler.cs rename to src/Lumina.Application/Core/FileSystemManagement/Directories/Queries/GetDirectoryTree/GetDirectoryTreeQueryHandler.cs index cda64871..0e395d7b 100644 --- a/src/Lumina.Application/Core/FileManagement/Directories/Queries/GetDirectoryTree/GetDirectoryTreeQueryHandler.cs +++ b/src/Lumina.Application/Core/FileSystemManagement/Directories/Queries/GetDirectoryTree/GetDirectoryTreeQueryHandler.cs @@ -1,12 +1,12 @@ #region ========================================================================= USING ===================================================================================== using ErrorOr; +using Lumina.Application.Common.Mapping.FileSystemManagement.FileSystem; using Lumina.Contracts.Enums.FileSystem; -using Lumina.Contracts.Responses.FileManagement; -using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate; -using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.Entities; -using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.Services; -using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.ValueObjects; -using Mapster; +using Lumina.Contracts.Responses.FileSystemManagement.Common; +using Lumina.Domain.Core.Aggregates.FileSystemManagement.FileSystemManagementAggregate; +using Lumina.Domain.Core.Aggregates.FileSystemManagement.FileSystemManagementAggregate.Entities; +using Lumina.Domain.Core.Aggregates.FileSystemManagement.FileSystemManagementAggregate.Services; +using Lumina.Domain.Core.Aggregates.FileSystemManagement.FileSystemManagementAggregate.ValueObjects; using Mediator; using System.Collections.Generic; using System.Linq; @@ -14,7 +14,7 @@ using System.Threading; using System.Threading.Tasks; #endregion -namespace Lumina.Application.Core.FileManagement.Directories.Queries.GetDirectoryTree; +namespace Lumina.Application.Core.FileSystemManagement.Directories.Queries.GetDirectoryTree; /// /// Handler for the query to get a directory tree. @@ -56,7 +56,7 @@ public class GetDirectoryTreeQueryHandler : IRequestHandler> pathPartsResults = _pathService.ParsePath(request.Path); + ErrorOr> pathPartsResults = _pathService.ParsePath(request.Path!); if (pathPartsResults.IsError) return pathPartsResults.Errors; @@ -84,7 +84,7 @@ public class GetDirectoryTreeQueryHandler : IRequestHandler> driveResult = _driveService.GetDrives(); if (driveResult.IsError) return driveResult.Errors; - return ErrorOrFactory.From(driveResult.Value.Adapt>()); + return ErrorOrFactory.From(driveResult.Value.ToTreeNodeResponses()); } /// diff --git a/src/Lumina.Application/Core/FileManagement/Directories/Queries/GetDirectoryTree/GetDirectoryTreeQueryValidator.cs b/src/Lumina.Application/Core/FileSystemManagement/Directories/Queries/GetDirectoryTree/GetDirectoryTreeQueryValidator.cs similarity index 75% rename from src/Lumina.Application/Core/FileManagement/Directories/Queries/GetDirectoryTree/GetDirectoryTreeQueryValidator.cs rename to src/Lumina.Application/Core/FileSystemManagement/Directories/Queries/GetDirectoryTree/GetDirectoryTreeQueryValidator.cs index 08f84bc3..13229211 100644 --- a/src/Lumina.Application/Core/FileManagement/Directories/Queries/GetDirectoryTree/GetDirectoryTreeQueryValidator.cs +++ b/src/Lumina.Application/Core/FileSystemManagement/Directories/Queries/GetDirectoryTree/GetDirectoryTreeQueryValidator.cs @@ -3,7 +3,7 @@ using FluentValidation; using Lumina.Domain.Common.Errors; #endregion -namespace Lumina.Application.Core.FileManagement.Directories.Queries.GetDirectoryTree; +namespace Lumina.Application.Core.FileSystemManagement.Directories.Queries.GetDirectoryTree; /// /// Validates the needed validation rules for . @@ -15,6 +15,6 @@ public class GetDirectoryTreeQueryValidator : AbstractValidator public GetDirectoryTreeQueryValidator() { - RuleFor(x => x.Path).NotEmpty().WithMessage(Errors.FileManagement.PathCannotBeEmpty.Code); + RuleFor(x => x.Path).NotEmpty().WithMessage(Errors.FileSystemManagement.PathCannotBeEmpty.Description); } } \ No newline at end of file diff --git a/src/Lumina.Application/Core/FileSystemManagement/Directories/Queries/GetTreeDirectories/GetTreeDirectoriesQuery.cs b/src/Lumina.Application/Core/FileSystemManagement/Directories/Queries/GetTreeDirectories/GetTreeDirectoriesQuery.cs new file mode 100644 index 00000000..3157cce9 --- /dev/null +++ b/src/Lumina.Application/Core/FileSystemManagement/Directories/Queries/GetTreeDirectories/GetTreeDirectoriesQuery.cs @@ -0,0 +1,20 @@ +#region ========================================================================= USING ===================================================================================== +using ErrorOr; +using Lumina.Contracts.Responses.FileSystemManagement.Common; +using Mediator; +using System.Collections.Generic; +using System.Diagnostics; +#endregion + +namespace Lumina.Application.Core.FileSystemManagement.Directories.Queries.GetTreeDirectories; + +/// +/// Query for retrieving the list of directories at a path. +/// +/// The path for which to retrieve the list of directories. +/// Whether to include hidden directories or not. +[DebuggerDisplay("Path: {Path}")] +public record GetTreeDirectoriesQuery( + string? Path, + bool IncludeHiddenElements +) : IRequest>>; diff --git a/src/Lumina.Application/Core/FileManagement/Directories/Queries/GetTreeDirectories/GetTreeDirectoriesQueryHandler.cs b/src/Lumina.Application/Core/FileSystemManagement/Directories/Queries/GetTreeDirectories/GetTreeDirectoriesQueryHandler.cs similarity index 71% rename from src/Lumina.Application/Core/FileManagement/Directories/Queries/GetTreeDirectories/GetTreeDirectoriesQueryHandler.cs rename to src/Lumina.Application/Core/FileSystemManagement/Directories/Queries/GetTreeDirectories/GetTreeDirectoriesQueryHandler.cs index 6f301850..78de32f4 100644 --- a/src/Lumina.Application/Core/FileManagement/Directories/Queries/GetTreeDirectories/GetTreeDirectoriesQueryHandler.cs +++ b/src/Lumina.Application/Core/FileSystemManagement/Directories/Queries/GetTreeDirectories/GetTreeDirectoriesQueryHandler.cs @@ -1,17 +1,16 @@ #region ========================================================================= USING ===================================================================================== using ErrorOr; -using Lumina.Contracts.Responses.FileManagement; -using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.Entities; -using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.Services; -using Mapster; -using MapsterMapper; +using Lumina.Application.Common.Mapping.FileSystemManagement.Directories; +using Lumina.Contracts.Responses.FileSystemManagement.Common; +using Lumina.Domain.Core.Aggregates.FileSystemManagement.FileSystemManagementAggregate.Entities; +using Lumina.Domain.Core.Aggregates.FileSystemManagement.FileSystemManagementAggregate.Services; using Mediator; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; #endregion -namespace Lumina.Application.Core.FileManagement.Directories.Queries.GetTreeDirectories; +namespace Lumina.Application.Core.FileSystemManagement.Directories.Queries.GetTreeDirectories; /// /// Handler for the query to get all directories. @@ -19,17 +18,14 @@ namespace Lumina.Application.Core.FileManagement.Directories.Queries.GetTreeDire public class GetTreeDirectoriesQueryHandler : IRequestHandler>> { private readonly IDirectoryService _directoryService; - private readonly IMapper _mapper; /// /// Initializes a new instance of the class. /// /// Injected service for handling directories. - /// Injected service for mapping objects. - public GetTreeDirectoriesQueryHandler(IDirectoryService directoryService, IMapper mapper) + public GetTreeDirectoriesQueryHandler(IDirectoryService directoryService) { _directoryService = directoryService; - _mapper = mapper; } /// @@ -42,7 +38,7 @@ public class GetTreeDirectoriesQueryHandler : IRequestHandler public ValueTask>> Handle(GetTreeDirectoriesQuery request, CancellationToken cancellationToken) { - ErrorOr> result = _directoryService.GetSubdirectories(request.Path, request.IncludeHiddenElements); - return ValueTask.FromResult(result.Match(values => ErrorOrFactory.From(_mapper.Map>(values)), errors => errors)); + ErrorOr> result = _directoryService.GetSubdirectories(request.Path!, request.IncludeHiddenElements); + return ValueTask.FromResult(result.Match(values => ErrorOrFactory.From(values.ToFileSystemTreeNodeResponses()), errors => errors)); } } diff --git a/src/Lumina.Application/Core/FileManagement/Directories/Queries/GetTreeDirectories/GetTreeDirectoriesQueryValidator.cs b/src/Lumina.Application/Core/FileSystemManagement/Directories/Queries/GetTreeDirectories/GetTreeDirectoriesQueryValidator.cs similarity index 75% rename from src/Lumina.Application/Core/FileManagement/Directories/Queries/GetTreeDirectories/GetTreeDirectoriesQueryValidator.cs rename to src/Lumina.Application/Core/FileSystemManagement/Directories/Queries/GetTreeDirectories/GetTreeDirectoriesQueryValidator.cs index 7d2feb18..42963faa 100644 --- a/src/Lumina.Application/Core/FileManagement/Directories/Queries/GetTreeDirectories/GetTreeDirectoriesQueryValidator.cs +++ b/src/Lumina.Application/Core/FileSystemManagement/Directories/Queries/GetTreeDirectories/GetTreeDirectoriesQueryValidator.cs @@ -3,7 +3,7 @@ using FluentValidation; using Lumina.Domain.Common.Errors; #endregion -namespace Lumina.Application.Core.FileManagement.Directories.Queries.GetTreeDirectories; +namespace Lumina.Application.Core.FileSystemManagement.Directories.Queries.GetTreeDirectories; /// /// Validates the needed validation rules for . @@ -15,6 +15,6 @@ public class GetTreeDirectoriesQueryValidator : AbstractValidator public GetTreeDirectoriesQueryValidator() { - RuleFor(x => x.Path).NotEmpty().WithMessage(Errors.FileManagement.PathCannotBeEmpty.Code); + RuleFor(x => x.Path).NotEmpty().WithMessage(Errors.FileSystemManagement.PathCannotBeEmpty.Description); } } \ No newline at end of file diff --git a/src/Lumina.Application/Core/FileManagement/Drives/Queries/GetDrives/GetDrivesQuery.cs b/src/Lumina.Application/Core/FileSystemManagement/Drives/Queries/GetDrives/GetDrivesQuery.cs similarity index 74% rename from src/Lumina.Application/Core/FileManagement/Drives/Queries/GetDrives/GetDrivesQuery.cs rename to src/Lumina.Application/Core/FileSystemManagement/Drives/Queries/GetDrives/GetDrivesQuery.cs index b1e0269e..74b2c0b0 100644 --- a/src/Lumina.Application/Core/FileManagement/Drives/Queries/GetDrives/GetDrivesQuery.cs +++ b/src/Lumina.Application/Core/FileSystemManagement/Drives/Queries/GetDrives/GetDrivesQuery.cs @@ -1,11 +1,11 @@ #region ========================================================================= USING ===================================================================================== using ErrorOr; -using Lumina.Contracts.Responses.FileManagement; +using Lumina.Contracts.Responses.FileSystemManagement.Common; using Mediator; using System.Collections.Generic; #endregion -namespace Lumina.Application.Core.FileManagement.Drives.Queries.GetDrives; +namespace Lumina.Application.Core.FileSystemManagement.Drives.Queries.GetDrives; /// /// Query for retrieving the list of drives. diff --git a/src/Lumina.Application/Core/FileManagement/Drives/Queries/GetDrives/GetDrivesQueryHandler.cs b/src/Lumina.Application/Core/FileSystemManagement/Drives/Queries/GetDrives/GetDrivesQueryHandler.cs similarity index 71% rename from src/Lumina.Application/Core/FileManagement/Drives/Queries/GetDrives/GetDrivesQueryHandler.cs rename to src/Lumina.Application/Core/FileSystemManagement/Drives/Queries/GetDrives/GetDrivesQueryHandler.cs index 5246948d..962ff9e0 100644 --- a/src/Lumina.Application/Core/FileManagement/Drives/Queries/GetDrives/GetDrivesQueryHandler.cs +++ b/src/Lumina.Application/Core/FileSystemManagement/Drives/Queries/GetDrives/GetDrivesQueryHandler.cs @@ -1,17 +1,16 @@ #region ========================================================================= USING ===================================================================================== using ErrorOr; -using Lumina.Contracts.Responses.FileManagement; -using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate; -using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.Services; -using Mapster; -using MapsterMapper; +using Lumina.Application.Common.Mapping.FileSystemManagement.FileSystem; +using Lumina.Contracts.Responses.FileSystemManagement.Common; +using Lumina.Domain.Core.Aggregates.FileSystemManagement.FileSystemManagementAggregate; +using Lumina.Domain.Core.Aggregates.FileSystemManagement.FileSystemManagementAggregate.Services; using Mediator; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; #endregion -namespace Lumina.Application.Core.FileManagement.Drives.Queries.GetDrives; +namespace Lumina.Application.Core.FileSystemManagement.Drives.Queries.GetDrives; /// /// Handler for the query to get all drives. @@ -19,17 +18,14 @@ namespace Lumina.Application.Core.FileManagement.Drives.Queries.GetDrives; public class GetDrivesQueryHandler : IRequestHandler>> { private readonly IDriveService _driveService; - private readonly IMapper _mapper; /// /// Initializes a new instance of the class. /// /// Injected service for handling file system drives. - /// Injected service for mapping objects. - public GetDrivesQueryHandler(IDriveService driveService, IMapper mapper) + public GetDrivesQueryHandler(IDriveService driveService) { _driveService = driveService; - _mapper = mapper; } /// @@ -43,6 +39,6 @@ public class GetDrivesQueryHandler : IRequestHandler>> Handle(GetDrivesQuery request, CancellationToken cancellationToken) { ErrorOr> result = _driveService.GetDrives(); - return ValueTask.FromResult(result.Match(values => ErrorOrFactory.From(_mapper.Map>(values)), errors => errors)); + return ValueTask.FromResult(result.Match(values => ErrorOrFactory.From(values.ToTreeNodeResponses()), errors => errors)); } } diff --git a/src/Lumina.Application/Core/FileManagement/FileSystem/Queries/GetFileSystem/GetFileSystemQuery.cs b/src/Lumina.Application/Core/FileSystemManagement/FileSystem/Queries/GetFileSystem/GetFileSystemQuery.cs similarity index 69% rename from src/Lumina.Application/Core/FileManagement/FileSystem/Queries/GetFileSystem/GetFileSystemQuery.cs rename to src/Lumina.Application/Core/FileSystemManagement/FileSystem/Queries/GetFileSystem/GetFileSystemQuery.cs index e4356d59..512394b6 100644 --- a/src/Lumina.Application/Core/FileManagement/FileSystem/Queries/GetFileSystem/GetFileSystemQuery.cs +++ b/src/Lumina.Application/Core/FileSystemManagement/FileSystem/Queries/GetFileSystem/GetFileSystemQuery.cs @@ -1,9 +1,9 @@ #region ========================================================================= USING ===================================================================================== -using Lumina.Contracts.Responses.FileManagement; +using Lumina.Contracts.Responses.FileSystemManagement.FileSystem; using Mediator; #endregion -namespace Lumina.Application.Core.FileManagement.FileSystem.Queries.GetFileSystem; +namespace Lumina.Application.Core.FileSystemManagement.FileSystem.Queries.GetFileSystem; /// /// Query for retrieving the file system type. diff --git a/src/Lumina.Application/Core/FileManagement/FileSystem/Queries/GetFileSystem/GetFileSystemQueryHandler.cs b/src/Lumina.Application/Core/FileSystemManagement/FileSystem/Queries/GetFileSystem/GetFileSystemQueryHandler.cs similarity index 84% rename from src/Lumina.Application/Core/FileManagement/FileSystem/Queries/GetFileSystem/GetFileSystemQueryHandler.cs rename to src/Lumina.Application/Core/FileSystemManagement/FileSystem/Queries/GetFileSystem/GetFileSystemQueryHandler.cs index bba396b2..fd903fe2 100644 --- a/src/Lumina.Application/Core/FileManagement/FileSystem/Queries/GetFileSystem/GetFileSystemQueryHandler.cs +++ b/src/Lumina.Application/Core/FileSystemManagement/FileSystem/Queries/GetFileSystem/GetFileSystemQueryHandler.cs @@ -1,12 +1,12 @@ #region ========================================================================= USING ===================================================================================== -using Lumina.Contracts.Responses.FileManagement; -using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.Strategies.Platform; +using Lumina.Contracts.Responses.FileSystemManagement.FileSystem; +using Lumina.Domain.Core.Aggregates.FileSystemManagement.FileSystemManagementAggregate.Strategies.Platform; using Mediator; using System.Threading; using System.Threading.Tasks; #endregion -namespace Lumina.Application.Core.FileManagement.FileSystem.Queries.GetFileSystem; +namespace Lumina.Application.Core.FileSystemManagement.FileSystem.Queries.GetFileSystem; /// /// Handler for the query to get the file system type. diff --git a/src/Lumina.Application/Core/FileSystemManagement/Files/Queries/GetFiles/GetFilesQuery.cs b/src/Lumina.Application/Core/FileSystemManagement/Files/Queries/GetFiles/GetFilesQuery.cs new file mode 100644 index 00000000..52fc745b --- /dev/null +++ b/src/Lumina.Application/Core/FileSystemManagement/Files/Queries/GetFiles/GetFilesQuery.cs @@ -0,0 +1,20 @@ +#region ========================================================================= USING ===================================================================================== +using ErrorOr; +using Lumina.Contracts.Responses.FileSystemManagement.Files; +using Mediator; +using System.Collections.Generic; +using System.Diagnostics; +#endregion + +namespace Lumina.Application.Core.FileSystemManagement.Files.Queries.GetFiles; + +/// +/// Query for retrieving the list of files at a path. +/// +/// The path for which to retrieve the list of files. +/// Whether to include hidden files and directories or not. +[DebuggerDisplay("Path: {Path}")] +public record GetFilesQuery( + string? Path, + bool IncludeHiddenElements +) : IRequest>>; diff --git a/src/Lumina.Application/Core/FileManagement/Files/Queries/GetFiles/GetFilesQueryHandler.cs b/src/Lumina.Application/Core/FileSystemManagement/Files/Queries/GetFiles/GetFilesQueryHandler.cs similarity index 68% rename from src/Lumina.Application/Core/FileManagement/Files/Queries/GetFiles/GetFilesQueryHandler.cs rename to src/Lumina.Application/Core/FileSystemManagement/Files/Queries/GetFiles/GetFilesQueryHandler.cs index 750e7848..db90a861 100644 --- a/src/Lumina.Application/Core/FileManagement/Files/Queries/GetFiles/GetFilesQueryHandler.cs +++ b/src/Lumina.Application/Core/FileSystemManagement/Files/Queries/GetFiles/GetFilesQueryHandler.cs @@ -1,17 +1,16 @@ #region ========================================================================= USING ===================================================================================== using ErrorOr; -using Lumina.Contracts.Responses.FileManagement; -using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.Entities; -using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.Services; -using Mapster; -using MapsterMapper; +using Lumina.Application.Common.Mapping.FileSystemManagement.Files; +using Lumina.Contracts.Responses.FileSystemManagement.Files; +using Lumina.Domain.Core.Aggregates.FileSystemManagement.FileSystemManagementAggregate.Entities; +using Lumina.Domain.Core.Aggregates.FileSystemManagement.FileSystemManagementAggregate.Services; using Mediator; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; #endregion -namespace Lumina.Application.Core.FileManagement.Files.Queries.GetFiles; +namespace Lumina.Application.Core.FileSystemManagement.Files.Queries.GetFiles; /// /// Handler for the query to get all files. @@ -19,17 +18,14 @@ namespace Lumina.Application.Core.FileManagement.Files.Queries.GetFiles; public class GetFilesQueryHandler : IRequestHandler>> { private readonly IFileService _fileService; - private readonly IMapper _mapper; /// /// Initializes a new instance of the class. /// /// Injected service for handling files. - /// Injected service for mapping objects. - public GetFilesQueryHandler(IFileService fileService, IMapper mapper) + public GetFilesQueryHandler(IFileService fileService) { _fileService = fileService; - _mapper = mapper; } /// @@ -42,7 +38,7 @@ public class GetFilesQueryHandler : IRequestHandler public ValueTask>> Handle(GetFilesQuery request, CancellationToken cancellationToken) { - ErrorOr> result = _fileService.GetFiles(request.Path, request.IncludeHiddenElements); - return ValueTask.FromResult(result.Match(values => ErrorOrFactory.From(_mapper.Map>(values)), errors => errors)); + ErrorOr> result = _fileService.GetFiles(request.Path!, request.IncludeHiddenElements); + return ValueTask.FromResult(result.Match(values => ErrorOrFactory.From(values.ToResponses()), errors => errors)); } } diff --git a/src/Lumina.Application/Core/FileManagement/Files/Queries/GetFiles/GetFilesQueryValidator.cs b/src/Lumina.Application/Core/FileSystemManagement/Files/Queries/GetFiles/GetFilesQueryValidator.cs similarity index 75% rename from src/Lumina.Application/Core/FileManagement/Files/Queries/GetFiles/GetFilesQueryValidator.cs rename to src/Lumina.Application/Core/FileSystemManagement/Files/Queries/GetFiles/GetFilesQueryValidator.cs index f832b1c3..2b15eef1 100644 --- a/src/Lumina.Application/Core/FileManagement/Files/Queries/GetFiles/GetFilesQueryValidator.cs +++ b/src/Lumina.Application/Core/FileSystemManagement/Files/Queries/GetFiles/GetFilesQueryValidator.cs @@ -3,7 +3,7 @@ using FluentValidation; using Lumina.Domain.Common.Errors; #endregion -namespace Lumina.Application.Core.FileManagement.Files.Queries.GetFiles; +namespace Lumina.Application.Core.FileSystemManagement.Files.Queries.GetFiles; /// /// Validates the needed validation rules for . @@ -15,6 +15,6 @@ public class GetFilesQueryValidator : AbstractValidator /// public GetFilesQueryValidator() { - RuleFor(x => x.Path).NotEmpty().WithMessage(Errors.FileManagement.PathCannotBeEmpty.Code); + RuleFor(x => x.Path).NotEmpty().WithMessage(Errors.FileSystemManagement.PathCannotBeEmpty.Description); } } \ No newline at end of file diff --git a/src/Lumina.Application/Core/FileSystemManagement/Files/Queries/GetTreeFiles/GetTreeFilesQuery.cs b/src/Lumina.Application/Core/FileSystemManagement/Files/Queries/GetTreeFiles/GetTreeFilesQuery.cs new file mode 100644 index 00000000..b31a5645 --- /dev/null +++ b/src/Lumina.Application/Core/FileSystemManagement/Files/Queries/GetTreeFiles/GetTreeFilesQuery.cs @@ -0,0 +1,20 @@ +#region ========================================================================= USING ===================================================================================== +using ErrorOr; +using Lumina.Contracts.Responses.FileSystemManagement.Common; +using Mediator; +using System.Collections.Generic; +using System.Diagnostics; +#endregion + +namespace Lumina.Application.Core.FileSystemManagement.Files.Queries.GetTreeFiles; + +/// +/// Query for retrieving the list of files at a path. +/// +/// The path for which to retrieve the list of files. +/// Whether to include hidden files and directories or not. +[DebuggerDisplay("Path: {Path}")] +public record GetTreeFilesQuery( + string? Path, + bool IncludeHiddenElements +) : IRequest>>; diff --git a/src/Lumina.Application/Core/FileManagement/Files/Queries/GetTreeFiles/GetTreeFilesQueryHandler.cs b/src/Lumina.Application/Core/FileSystemManagement/Files/Queries/GetTreeFiles/GetTreeFilesQueryHandler.cs similarity index 68% rename from src/Lumina.Application/Core/FileManagement/Files/Queries/GetTreeFiles/GetTreeFilesQueryHandler.cs rename to src/Lumina.Application/Core/FileSystemManagement/Files/Queries/GetTreeFiles/GetTreeFilesQueryHandler.cs index b3263ad7..aad93898 100644 --- a/src/Lumina.Application/Core/FileManagement/Files/Queries/GetTreeFiles/GetTreeFilesQueryHandler.cs +++ b/src/Lumina.Application/Core/FileSystemManagement/Files/Queries/GetTreeFiles/GetTreeFilesQueryHandler.cs @@ -1,17 +1,16 @@ #region ========================================================================= USING ===================================================================================== using ErrorOr; -using Lumina.Contracts.Responses.FileManagement; -using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.Entities; -using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.Services; -using Mapster; -using MapsterMapper; +using Lumina.Application.Common.Mapping.FileSystemManagement.Files; +using Lumina.Contracts.Responses.FileSystemManagement.Common; +using Lumina.Domain.Core.Aggregates.FileSystemManagement.FileSystemManagementAggregate.Entities; +using Lumina.Domain.Core.Aggregates.FileSystemManagement.FileSystemManagementAggregate.Services; using Mediator; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; #endregion -namespace Lumina.Application.Core.FileManagement.Files.Queries.GetTreeFiles; +namespace Lumina.Application.Core.FileSystemManagement.Files.Queries.GetTreeFiles; /// /// Handler for the query to get all files. @@ -19,17 +18,14 @@ namespace Lumina.Application.Core.FileManagement.Files.Queries.GetTreeFiles; public class GetTreeFilesQueryHandler : IRequestHandler>> { private readonly IFileService _fileService; - private readonly IMapper _mapper; /// /// Initializes a new instance of the class. /// /// Injected service for handling files. - /// Injected service for mapping objects. - public GetTreeFilesQueryHandler(IFileService fileService, IMapper mapper) + public GetTreeFilesQueryHandler(IFileService fileService) { _fileService = fileService; - _mapper = mapper; } /// @@ -42,7 +38,7 @@ public class GetTreeFilesQueryHandler : IRequestHandler public ValueTask>> Handle(GetTreeFilesQuery request, CancellationToken cancellationToken) { - ErrorOr> result = _fileService.GetFiles(request.Path, request.IncludeHiddenElements); - return ValueTask.FromResult(result.Match(values => ErrorOrFactory.From(_mapper.Map>(values)), errors => errors)); + ErrorOr> result = _fileService.GetFiles(request.Path!, request.IncludeHiddenElements); + return ValueTask.FromResult(result.Match(values => ErrorOrFactory.From(values.ToFileSystemTreeNodeResponses()), errors => errors)); } } diff --git a/src/Lumina.Application/Core/FileManagement/Files/Queries/GetTreeFiles/GetTreeFilesQueryValidator.cs b/src/Lumina.Application/Core/FileSystemManagement/Files/Queries/GetTreeFiles/GetTreeFilesQueryValidator.cs similarity index 76% rename from src/Lumina.Application/Core/FileManagement/Files/Queries/GetTreeFiles/GetTreeFilesQueryValidator.cs rename to src/Lumina.Application/Core/FileSystemManagement/Files/Queries/GetTreeFiles/GetTreeFilesQueryValidator.cs index d3d2f073..59e2480e 100644 --- a/src/Lumina.Application/Core/FileManagement/Files/Queries/GetTreeFiles/GetTreeFilesQueryValidator.cs +++ b/src/Lumina.Application/Core/FileSystemManagement/Files/Queries/GetTreeFiles/GetTreeFilesQueryValidator.cs @@ -3,7 +3,7 @@ using FluentValidation; using Lumina.Domain.Common.Errors; #endregion -namespace Lumina.Application.Core.FileManagement.Files.Queries.GetTreeFiles; +namespace Lumina.Application.Core.FileSystemManagement.Files.Queries.GetTreeFiles; /// /// Validates the needed validation rules for . @@ -15,6 +15,6 @@ public class GetTreeFilesQueryValidator : AbstractValidator /// public GetTreeFilesQueryValidator() { - RuleFor(x => x.Path).NotEmpty().WithMessage(Errors.FileManagement.PathCannotBeEmpty.Code); + RuleFor(x => x.Path).NotEmpty().WithMessage(Errors.FileSystemManagement.PathCannotBeEmpty.Description); } } \ No newline at end of file diff --git a/src/Lumina.Application/Core/FileSystemManagement/Paths/Commands/CombinePath/CombinePathCommand.cs b/src/Lumina.Application/Core/FileSystemManagement/Paths/Commands/CombinePath/CombinePathCommand.cs new file mode 100644 index 00000000..56330289 --- /dev/null +++ b/src/Lumina.Application/Core/FileSystemManagement/Paths/Commands/CombinePath/CombinePathCommand.cs @@ -0,0 +1,19 @@ +#region ========================================================================= USING ===================================================================================== +using ErrorOr; +using Lumina.Contracts.Responses.FileSystemManagement.Path; +using Mediator; +using System.Diagnostics; +#endregion + +namespace Lumina.Application.Core.FileSystemManagement.Paths.Commands.CombinePath; + +/// +/// Command for combining two file system path. +/// +/// The path to combine to. +/// The path to combine with. +[DebuggerDisplay("OriginalPath: {OriginalPath}, NewPath: {NewPath}")] +public record CombinePathCommand( + string? OriginalPath, + string? NewPath +) : IRequest>; diff --git a/src/Lumina.Application/Core/FileManagement/Paths/Commands/CombinePath/CombinePathCommandHandler.cs b/src/Lumina.Application/Core/FileSystemManagement/Paths/Commands/CombinePath/CombinePathCommandHandler.cs similarity index 72% rename from src/Lumina.Application/Core/FileManagement/Paths/Commands/CombinePath/CombinePathCommandHandler.cs rename to src/Lumina.Application/Core/FileSystemManagement/Paths/Commands/CombinePath/CombinePathCommandHandler.cs index fee6ccc1..6afac030 100644 --- a/src/Lumina.Application/Core/FileManagement/Paths/Commands/CombinePath/CombinePathCommandHandler.cs +++ b/src/Lumina.Application/Core/FileSystemManagement/Paths/Commands/CombinePath/CombinePathCommandHandler.cs @@ -1,14 +1,14 @@ -#region ========================================================================= USING ===================================================================================== +#region ========================================================================= USING ===================================================================================== using ErrorOr; -using Lumina.Application.Core.FileManagement.Paths.Commands.SplitPath; -using Lumina.Contracts.Responses.FileManagement; -using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.Services; +using Lumina.Application.Core.FileSystemManagement.Paths.Commands.SplitPath; +using Lumina.Contracts.Responses.FileSystemManagement.Path; +using Lumina.Domain.Core.Aggregates.FileSystemManagement.FileSystemManagementAggregate.Services; using Mediator; using System.Threading; using System.Threading.Tasks; #endregion -namespace Lumina.Application.Core.FileManagement.Paths.Commands.CombinePath; +namespace Lumina.Application.Core.FileSystemManagement.Paths.Commands.CombinePath; /// /// Handler for the command to split a file system path. @@ -36,7 +36,7 @@ public class CombinePathCommandHandler : IRequestHandler public ValueTask> Handle(CombinePathCommand request, CancellationToken cancellationToken) { - ErrorOr result = _pathService.CombinePath(request.OriginalPath, request.NewPath); + ErrorOr result = _pathService.CombinePath(request.OriginalPath!, request.NewPath!); return ValueTask.FromResult(result.Match(values => ErrorOrFactory.From(new PathSegmentResponse(result.Value)), errors => errors)); } -} \ No newline at end of file +} diff --git a/src/Lumina.Application/Core/FileManagement/Paths/Commands/CombinePath/CombinePathCommandValidator.cs b/src/Lumina.Application/Core/FileSystemManagement/Paths/Commands/CombinePath/CombinePathCommandValidator.cs similarity index 61% rename from src/Lumina.Application/Core/FileManagement/Paths/Commands/CombinePath/CombinePathCommandValidator.cs rename to src/Lumina.Application/Core/FileSystemManagement/Paths/Commands/CombinePath/CombinePathCommandValidator.cs index b4d14759..506ff300 100644 --- a/src/Lumina.Application/Core/FileManagement/Paths/Commands/CombinePath/CombinePathCommandValidator.cs +++ b/src/Lumina.Application/Core/FileSystemManagement/Paths/Commands/CombinePath/CombinePathCommandValidator.cs @@ -1,9 +1,9 @@ -#region ========================================================================= USING ===================================================================================== +#region ========================================================================= USING ===================================================================================== using FluentValidation; using Lumina.Domain.Common.Errors; #endregion -namespace Lumina.Application.Core.FileManagement.Paths.Commands.CombinePath; +namespace Lumina.Application.Core.FileSystemManagement.Paths.Commands.CombinePath; /// /// Validates the needed validation rules for . @@ -15,7 +15,7 @@ public class CombinePathCommandValidator : AbstractValidator /// public CombinePathCommandValidator() { - RuleFor(x => x.OriginalPath).NotEmpty().WithMessage(Errors.FileManagement.PathCannotBeEmpty.Code); - RuleFor(x => x.NewPath).NotEmpty().WithMessage(Errors.FileManagement.PathCannotBeEmpty.Code); + RuleFor(x => x.OriginalPath).NotEmpty().WithMessage(Errors.FileSystemManagement.PathCannotBeEmpty.Description); + RuleFor(x => x.NewPath).NotEmpty().WithMessage(Errors.FileSystemManagement.PathCannotBeEmpty.Description); } -} \ No newline at end of file +} diff --git a/src/Lumina.Application/Core/FileSystemManagement/Paths/Commands/SplitPath/SplitPathCommand.cs b/src/Lumina.Application/Core/FileSystemManagement/Paths/Commands/SplitPath/SplitPathCommand.cs new file mode 100644 index 00000000..bc211fe8 --- /dev/null +++ b/src/Lumina.Application/Core/FileSystemManagement/Paths/Commands/SplitPath/SplitPathCommand.cs @@ -0,0 +1,18 @@ +#region ========================================================================= USING ===================================================================================== +using ErrorOr; +using Lumina.Contracts.Responses.FileSystemManagement.Path; +using Mediator; +using System.Collections.Generic; +using System.Diagnostics; +#endregion + +namespace Lumina.Application.Core.FileSystemManagement.Paths.Commands.SplitPath; + +/// +/// Command for splitting a file system path. +/// +/// The file system path to split. +[DebuggerDisplay("Path: {Path}")] +public record SplitPathCommand( + string? Path +) : IRequest>>; diff --git a/src/Lumina.Application/Core/FileManagement/Paths/Commands/SplitPath/SplitPathCommandHandler.cs b/src/Lumina.Application/Core/FileSystemManagement/Paths/Commands/SplitPath/SplitPathCommandHandler.cs similarity index 70% rename from src/Lumina.Application/Core/FileManagement/Paths/Commands/SplitPath/SplitPathCommandHandler.cs rename to src/Lumina.Application/Core/FileSystemManagement/Paths/Commands/SplitPath/SplitPathCommandHandler.cs index 505cd30c..c617877e 100644 --- a/src/Lumina.Application/Core/FileManagement/Paths/Commands/SplitPath/SplitPathCommandHandler.cs +++ b/src/Lumina.Application/Core/FileSystemManagement/Paths/Commands/SplitPath/SplitPathCommandHandler.cs @@ -1,16 +1,16 @@ #region ========================================================================= USING ===================================================================================== using ErrorOr; -using Lumina.Contracts.Responses.FileManagement; -using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.Services; -using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.ValueObjects; -using MapsterMapper; +using Lumina.Application.Common.Mapping.FileSystemManagement.Paths; +using Lumina.Contracts.Responses.FileSystemManagement.Path; +using Lumina.Domain.Core.Aggregates.FileSystemManagement.FileSystemManagementAggregate.Services; +using Lumina.Domain.Core.Aggregates.FileSystemManagement.FileSystemManagementAggregate.ValueObjects; using Mediator; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; #endregion -namespace Lumina.Application.Core.FileManagement.Paths.Commands.SplitPath; +namespace Lumina.Application.Core.FileSystemManagement.Paths.Commands.SplitPath; /// /// Handler for the command to split a file system path. @@ -18,17 +18,14 @@ namespace Lumina.Application.Core.FileManagement.Paths.Commands.SplitPath; public class SplitPathCommandHandler : IRequestHandler>> { private readonly IPathService _pathService; - private readonly IMapper _mapper; /// /// Initializes a new instance of the class. /// /// Injected service for handling file system paths. - /// Injected service for mapping objects. - public SplitPathCommandHandler(IPathService pathService, IMapper mapper) + public SplitPathCommandHandler(IPathService pathService) { _pathService = pathService; - _mapper = mapper; } /// @@ -41,7 +38,7 @@ public class SplitPathCommandHandler : IRequestHandler public ValueTask>> Handle(SplitPathCommand request, CancellationToken cancellationToken) { - ErrorOr> result = _pathService.ParsePath(request.Path); - return ValueTask.FromResult(result.Match(values => ErrorOrFactory.From(_mapper.Map>(values)), errors => errors)); + ErrorOr> result = _pathService.ParsePath(request.Path!); + return ValueTask.FromResult(result.Match(values => ErrorOrFactory.From(values.ToResponses()), errors => errors)); } } diff --git a/src/Lumina.Application/Core/FileManagement/Paths/Commands/SplitPath/SplitPathCommandValidator.cs b/src/Lumina.Application/Core/FileSystemManagement/Paths/Commands/SplitPath/SplitPathCommandValidator.cs similarity index 76% rename from src/Lumina.Application/Core/FileManagement/Paths/Commands/SplitPath/SplitPathCommandValidator.cs rename to src/Lumina.Application/Core/FileSystemManagement/Paths/Commands/SplitPath/SplitPathCommandValidator.cs index 28755b32..803d26c9 100644 --- a/src/Lumina.Application/Core/FileManagement/Paths/Commands/SplitPath/SplitPathCommandValidator.cs +++ b/src/Lumina.Application/Core/FileSystemManagement/Paths/Commands/SplitPath/SplitPathCommandValidator.cs @@ -3,7 +3,7 @@ using FluentValidation; using Lumina.Domain.Common.Errors; #endregion -namespace Lumina.Application.Core.FileManagement.Paths.Commands.SplitPath; +namespace Lumina.Application.Core.FileSystemManagement.Paths.Commands.SplitPath; /// /// Validates the needed validation rules for . @@ -15,6 +15,6 @@ public class SplitPathCommandValidator : AbstractValidator /// public SplitPathCommandValidator() { - RuleFor(x => x.Path).NotEmpty().WithMessage(Errors.FileManagement.PathCannotBeEmpty.Code); + RuleFor(x => x.Path).NotEmpty().WithMessage(Errors.FileSystemManagement.PathCannotBeEmpty.Description); } } \ No newline at end of file diff --git a/src/Lumina.Application/Core/FileSystemManagement/Paths/Queries/CheckPathExists/CheckPathExistsQuery.cs b/src/Lumina.Application/Core/FileSystemManagement/Paths/Queries/CheckPathExists/CheckPathExistsQuery.cs new file mode 100644 index 00000000..13cbfbb5 --- /dev/null +++ b/src/Lumina.Application/Core/FileSystemManagement/Paths/Queries/CheckPathExists/CheckPathExistsQuery.cs @@ -0,0 +1,18 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Contracts.Responses.FileSystemManagement.Path; +using Mediator; +using System.Diagnostics; +#endregion + +namespace Lumina.Application.Core.FileSystemManagement.Paths.Queries.CheckPathExists; + +/// +/// Query for checking the existence of a file system path. +/// +/// The path for which to check the existence of. +/// Whether to include hidden file system elements or not. +[DebuggerDisplay("Path: {Path}, IncludeHiddenElements: {IncludeHiddenElements}")] +public record CheckPathExistsQuery( + string? Path, + bool IncludeHiddenElements +) : IRequest; diff --git a/src/Lumina.Application/Core/FileManagement/Paths/Queries/CheckPathExists/CheckPathExistsQueryHandler.cs b/src/Lumina.Application/Core/FileSystemManagement/Paths/Queries/CheckPathExists/CheckPathExistsQueryHandler.cs similarity index 82% rename from src/Lumina.Application/Core/FileManagement/Paths/Queries/CheckPathExists/CheckPathExistsQueryHandler.cs rename to src/Lumina.Application/Core/FileSystemManagement/Paths/Queries/CheckPathExists/CheckPathExistsQueryHandler.cs index 0e7c3169..9ab2b9a5 100644 --- a/src/Lumina.Application/Core/FileManagement/Paths/Queries/CheckPathExists/CheckPathExistsQueryHandler.cs +++ b/src/Lumina.Application/Core/FileSystemManagement/Paths/Queries/CheckPathExists/CheckPathExistsQueryHandler.cs @@ -1,12 +1,12 @@ #region ========================================================================= USING ===================================================================================== -using Lumina.Contracts.Responses.FileManagement; -using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.Services; +using Lumina.Contracts.Responses.FileSystemManagement.Path; +using Lumina.Domain.Core.Aggregates.FileSystemManagement.FileSystemManagementAggregate.Services; using Mediator; using System.Threading; using System.Threading.Tasks; #endregion -namespace Lumina.Application.Core.FileManagement.Paths.Queries.CheckPathExists; +namespace Lumina.Application.Core.FileSystemManagement.Paths.Queries.CheckPathExists; /// /// Handler for the query to check the existence a file system path. @@ -34,6 +34,6 @@ public class CheckPathExistsQueryHandler : IRequestHandler public ValueTask Handle(CheckPathExistsQuery request, CancellationToken cancellationToken) { - return ValueTask.FromResult(new PathExistsResponse(_pathService.Exists(request.Path, request.IncludeHiddenElements))); + return ValueTask.FromResult(new PathExistsResponse(_pathService.Exists(request.Path!, request.IncludeHiddenElements))); } } diff --git a/src/Lumina.Application/Core/FileManagement/Paths/Queries/CheckPathExists/CheckPathExistsQueryValidator.cs b/src/Lumina.Application/Core/FileSystemManagement/Paths/Queries/CheckPathExists/CheckPathExistsQueryValidator.cs similarity index 76% rename from src/Lumina.Application/Core/FileManagement/Paths/Queries/CheckPathExists/CheckPathExistsQueryValidator.cs rename to src/Lumina.Application/Core/FileSystemManagement/Paths/Queries/CheckPathExists/CheckPathExistsQueryValidator.cs index 6c634e45..4a0d92ad 100644 --- a/src/Lumina.Application/Core/FileManagement/Paths/Queries/CheckPathExists/CheckPathExistsQueryValidator.cs +++ b/src/Lumina.Application/Core/FileSystemManagement/Paths/Queries/CheckPathExists/CheckPathExistsQueryValidator.cs @@ -3,7 +3,7 @@ using FluentValidation; using Lumina.Domain.Common.Errors; #endregion -namespace Lumina.Application.Core.FileManagement.Paths.Queries.CheckPathExists; +namespace Lumina.Application.Core.FileSystemManagement.Paths.Queries.CheckPathExists; /// /// Validates the needed validation rules for . @@ -15,6 +15,6 @@ public class CheckPathExistsQueryValidator : AbstractValidator public CheckPathExistsQueryValidator() { - RuleFor(x => x.Path).NotEmpty().WithMessage(Errors.FileManagement.PathCannotBeEmpty.Code); + RuleFor(x => x.Path).NotEmpty().WithMessage(Errors.FileSystemManagement.PathCannotBeEmpty.Description); } } \ No newline at end of file diff --git a/src/Lumina.Application/Core/FileSystemManagement/Paths/Queries/GetPathParent/GetPathParentQuery.cs b/src/Lumina.Application/Core/FileSystemManagement/Paths/Queries/GetPathParent/GetPathParentQuery.cs new file mode 100644 index 00000000..6be2d6fc --- /dev/null +++ b/src/Lumina.Application/Core/FileSystemManagement/Paths/Queries/GetPathParent/GetPathParentQuery.cs @@ -0,0 +1,18 @@ +#region ========================================================================= USING ===================================================================================== +using ErrorOr; +using Lumina.Contracts.Responses.FileSystemManagement.Path; +using Mediator; +using System.Collections.Generic; +using System.Diagnostics; +#endregion + +namespace Lumina.Application.Core.FileSystemManagement.Paths.Queries.GetPathParent; + +/// +/// Query for retrieving the parent of a file system path. +/// +/// The path for which to get the parent. +[DebuggerDisplay("Path: {Path}")] +public record GetPathParentQuery( + string? Path +) : IRequest>>; diff --git a/src/Lumina.Application/Core/FileManagement/Paths/Queries/GetPathParent/GetPathParentQueryHandler.cs b/src/Lumina.Application/Core/FileSystemManagement/Paths/Queries/GetPathParent/GetPathParentQueryHandler.cs similarity index 70% rename from src/Lumina.Application/Core/FileManagement/Paths/Queries/GetPathParent/GetPathParentQueryHandler.cs rename to src/Lumina.Application/Core/FileSystemManagement/Paths/Queries/GetPathParent/GetPathParentQueryHandler.cs index 80f18f34..a1a720a8 100644 --- a/src/Lumina.Application/Core/FileManagement/Paths/Queries/GetPathParent/GetPathParentQueryHandler.cs +++ b/src/Lumina.Application/Core/FileSystemManagement/Paths/Queries/GetPathParent/GetPathParentQueryHandler.cs @@ -1,16 +1,16 @@ #region ========================================================================= USING ===================================================================================== using ErrorOr; -using Lumina.Contracts.Responses.FileManagement; -using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.Services; -using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.ValueObjects; -using MapsterMapper; +using Lumina.Application.Common.Mapping.FileSystemManagement.Paths; +using Lumina.Contracts.Responses.FileSystemManagement.Path; +using Lumina.Domain.Core.Aggregates.FileSystemManagement.FileSystemManagementAggregate.Services; +using Lumina.Domain.Core.Aggregates.FileSystemManagement.FileSystemManagementAggregate.ValueObjects; using Mediator; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; #endregion -namespace Lumina.Application.Core.FileManagement.Paths.Queries.GetPathParent; +namespace Lumina.Application.Core.FileSystemManagement.Paths.Queries.GetPathParent; /// /// Handler for the query to get the parent of a file system path. @@ -18,17 +18,14 @@ namespace Lumina.Application.Core.FileManagement.Paths.Queries.GetPathParent; public class GetPathParentQueryHandler : IRequestHandler>> { private readonly IPathService _pathService; - private readonly IMapper _mapper; /// /// Initializes a new instance of the class. /// /// Injected service for managing file system paths. - /// Injected service for mapping objects. - public GetPathParentQueryHandler(IPathService pathService, IMapper mapper) + public GetPathParentQueryHandler(IPathService pathService) { _pathService = pathService; - _mapper = mapper; } /// @@ -41,7 +38,7 @@ public class GetPathParentQueryHandler : IRequestHandler public ValueTask>> Handle(GetPathParentQuery request, CancellationToken cancellationToken) { - ErrorOr> result = _pathService.GoUpOneLevel(request.Path); - return ValueTask.FromResult(result.Match(values => ErrorOrFactory.From(_mapper.Map>(values)), errors => errors)); + ErrorOr> result = _pathService.GoUpOneLevel(request.Path!); + return ValueTask.FromResult(result.Match(values => ErrorOrFactory.From(values.ToResponses()), errors => errors)); } } diff --git a/src/Lumina.Application/Core/FileManagement/Paths/Queries/GetPathParent/GetPathParentQueryValidator.cs b/src/Lumina.Application/Core/FileSystemManagement/Paths/Queries/GetPathParent/GetPathParentQueryValidator.cs similarity index 76% rename from src/Lumina.Application/Core/FileManagement/Paths/Queries/GetPathParent/GetPathParentQueryValidator.cs rename to src/Lumina.Application/Core/FileSystemManagement/Paths/Queries/GetPathParent/GetPathParentQueryValidator.cs index 562a6ec0..1731feff 100644 --- a/src/Lumina.Application/Core/FileManagement/Paths/Queries/GetPathParent/GetPathParentQueryValidator.cs +++ b/src/Lumina.Application/Core/FileSystemManagement/Paths/Queries/GetPathParent/GetPathParentQueryValidator.cs @@ -3,7 +3,7 @@ using FluentValidation; using Lumina.Domain.Common.Errors; #endregion -namespace Lumina.Application.Core.FileManagement.Paths.Queries.GetPathParent; +namespace Lumina.Application.Core.FileSystemManagement.Paths.Queries.GetPathParent; /// /// Validates the needed validation rules for . @@ -15,6 +15,6 @@ public class GetPathParentQueryValidator : AbstractValidator /// public GetPathParentQueryValidator() { - RuleFor(x => x.Path).NotEmpty().WithMessage(Errors.FileManagement.PathCannotBeEmpty.Code); + RuleFor(x => x.Path).NotEmpty().WithMessage(Errors.FileSystemManagement.PathCannotBeEmpty.Description); } } \ No newline at end of file diff --git a/src/Lumina.Application/Core/FileSystemManagement/Paths/Queries/GetPathRoot/GetPathRootQuery.cs b/src/Lumina.Application/Core/FileSystemManagement/Paths/Queries/GetPathRoot/GetPathRootQuery.cs new file mode 100644 index 00000000..e3822cfc --- /dev/null +++ b/src/Lumina.Application/Core/FileSystemManagement/Paths/Queries/GetPathRoot/GetPathRootQuery.cs @@ -0,0 +1,17 @@ +#region ========================================================================= USING ===================================================================================== +using ErrorOr; +using Lumina.Contracts.Responses.FileSystemManagement.Path; +using Mediator; +using System.Diagnostics; +#endregion + +namespace Lumina.Application.Core.FileSystemManagement.Paths.Queries.GetPathRoot; + +/// +/// Query for retrieving the root of a path. +/// +/// The path for which to get the path root. +[DebuggerDisplay("Path: {Path}")] +public record GetPathRootQuery( + string? Path +) : IRequest>; diff --git a/src/Lumina.Application/Core/FileManagement/Paths/Queries/GetPathRoot/GetPathRootQueryHandler.cs b/src/Lumina.Application/Core/FileSystemManagement/Paths/Queries/GetPathRoot/GetPathRootQueryHandler.cs similarity index 68% rename from src/Lumina.Application/Core/FileManagement/Paths/Queries/GetPathRoot/GetPathRootQueryHandler.cs rename to src/Lumina.Application/Core/FileSystemManagement/Paths/Queries/GetPathRoot/GetPathRootQueryHandler.cs index 047a3059..9c85ec78 100644 --- a/src/Lumina.Application/Core/FileManagement/Paths/Queries/GetPathRoot/GetPathRootQueryHandler.cs +++ b/src/Lumina.Application/Core/FileSystemManagement/Paths/Queries/GetPathRoot/GetPathRootQueryHandler.cs @@ -1,15 +1,15 @@ #region ========================================================================= USING ===================================================================================== using ErrorOr; -using Lumina.Contracts.Responses.FileManagement; -using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.Services; -using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.ValueObjects; -using MapsterMapper; +using Lumina.Application.Common.Mapping.FileSystemManagement.Paths; +using Lumina.Contracts.Responses.FileSystemManagement.Path; +using Lumina.Domain.Core.Aggregates.FileSystemManagement.FileSystemManagementAggregate.Services; +using Lumina.Domain.Core.Aggregates.FileSystemManagement.FileSystemManagementAggregate.ValueObjects; using Mediator; using System.Threading; using System.Threading.Tasks; #endregion -namespace Lumina.Application.Core.FileManagement.Paths.Queries.GetPathRoot; +namespace Lumina.Application.Core.FileSystemManagement.Paths.Queries.GetPathRoot; /// /// Handler for the query to get the root of a file system path. @@ -17,17 +17,14 @@ namespace Lumina.Application.Core.FileManagement.Paths.Queries.GetPathRoot; public class GetPathRootQueryHandler : IRequestHandler> { private readonly IPathService _pathService; - private readonly IMapper _mapper; /// /// Initializes a new instance of the class. /// /// Injected service for managing file system paths. - /// Injected service for mapping objects. - public GetPathRootQueryHandler(IPathService pathService, IMapper mapper) + public GetPathRootQueryHandler(IPathService pathService) { _pathService = pathService; - _mapper = mapper; } /// @@ -38,7 +35,7 @@ public class GetPathRootQueryHandler : IRequestHandlerThe root of the specified path. public ValueTask> Handle(GetPathRootQuery request, CancellationToken cancellationToken) { - ErrorOr result = _pathService.GetPathRoot(request.Path); - return ValueTask.FromResult(result.Match(values => ErrorOrFactory.From(_mapper.Map(values)), errors => errors)); + ErrorOr result = _pathService.GetPathRoot(request.Path!); + return ValueTask.FromResult(result.Match(values => ErrorOrFactory.From(values.ToResponse()), errors => errors)); } } diff --git a/src/Lumina.Application/Core/FileManagement/Paths/Queries/GetPathRoot/GetPathRootQueryValidator.cs b/src/Lumina.Application/Core/FileSystemManagement/Paths/Queries/GetPathRoot/GetPathRootQueryValidator.cs similarity index 75% rename from src/Lumina.Application/Core/FileManagement/Paths/Queries/GetPathRoot/GetPathRootQueryValidator.cs rename to src/Lumina.Application/Core/FileSystemManagement/Paths/Queries/GetPathRoot/GetPathRootQueryValidator.cs index 6d8ed642..b8987d05 100644 --- a/src/Lumina.Application/Core/FileManagement/Paths/Queries/GetPathRoot/GetPathRootQueryValidator.cs +++ b/src/Lumina.Application/Core/FileSystemManagement/Paths/Queries/GetPathRoot/GetPathRootQueryValidator.cs @@ -3,7 +3,7 @@ using FluentValidation; using Lumina.Domain.Common.Errors; #endregion -namespace Lumina.Application.Core.FileManagement.Paths.Queries.GetPathRoot; +namespace Lumina.Application.Core.FileSystemManagement.Paths.Queries.GetPathRoot; /// /// Validates the needed validation rules for . @@ -15,6 +15,6 @@ public class GetPathRootQueryValidator : AbstractValidator /// public GetPathRootQueryValidator() { - RuleFor(x => x.Path).NotEmpty().WithMessage(Errors.FileManagement.PathCannotBeEmpty.Code); + RuleFor(x => x.Path).NotEmpty().WithMessage(Errors.FileSystemManagement.PathCannotBeEmpty.Description); } } \ No newline at end of file diff --git a/src/Lumina.Application/Core/FileManagement/Paths/Queries/GetPathSeparator/GetPathSeparatorQuery.cs b/src/Lumina.Application/Core/FileSystemManagement/Paths/Queries/GetPathSeparator/GetPathSeparatorQuery.cs similarity index 71% rename from src/Lumina.Application/Core/FileManagement/Paths/Queries/GetPathSeparator/GetPathSeparatorQuery.cs rename to src/Lumina.Application/Core/FileSystemManagement/Paths/Queries/GetPathSeparator/GetPathSeparatorQuery.cs index 650c7818..e8c318f6 100644 --- a/src/Lumina.Application/Core/FileManagement/Paths/Queries/GetPathSeparator/GetPathSeparatorQuery.cs +++ b/src/Lumina.Application/Core/FileSystemManagement/Paths/Queries/GetPathSeparator/GetPathSeparatorQuery.cs @@ -1,9 +1,9 @@ #region ========================================================================= USING ===================================================================================== -using Lumina.Contracts.Responses.FileManagement; +using Lumina.Contracts.Responses.FileSystemManagement.Path; using Mediator; #endregion -namespace Lumina.Application.Core.FileManagement.Paths.Queries.GetPathSeparator; +namespace Lumina.Application.Core.FileSystemManagement.Paths.Queries.GetPathSeparator; /// /// Query for retrieving the file system path separator. diff --git a/src/Lumina.Application/Core/FileManagement/Paths/Queries/GetPathSeparator/GetPathSeparatorQueryHandler.cs b/src/Lumina.Application/Core/FileSystemManagement/Paths/Queries/GetPathSeparator/GetPathSeparatorQueryHandler.cs similarity index 85% rename from src/Lumina.Application/Core/FileManagement/Paths/Queries/GetPathSeparator/GetPathSeparatorQueryHandler.cs rename to src/Lumina.Application/Core/FileSystemManagement/Paths/Queries/GetPathSeparator/GetPathSeparatorQueryHandler.cs index 8e4a94a1..226d7f26 100644 --- a/src/Lumina.Application/Core/FileManagement/Paths/Queries/GetPathSeparator/GetPathSeparatorQueryHandler.cs +++ b/src/Lumina.Application/Core/FileSystemManagement/Paths/Queries/GetPathSeparator/GetPathSeparatorQueryHandler.cs @@ -1,12 +1,12 @@ #region ========================================================================= USING ===================================================================================== -using Lumina.Contracts.Responses.FileManagement; -using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.Services; +using Lumina.Contracts.Responses.FileSystemManagement.Path; +using Lumina.Domain.Core.Aggregates.FileSystemManagement.FileSystemManagementAggregate.Services; using Mediator; using System.Threading; using System.Threading.Tasks; #endregion -namespace Lumina.Application.Core.FileManagement.Paths.Queries.GetPathSeparator; +namespace Lumina.Application.Core.FileSystemManagement.Paths.Queries.GetPathSeparator; /// /// Handler for the query to get the path separator character of a file system path. diff --git a/src/Lumina.Application/Core/FileSystemManagement/Paths/Queries/ValidatePath/ValidatePathQuery.cs b/src/Lumina.Application/Core/FileSystemManagement/Paths/Queries/ValidatePath/ValidatePathQuery.cs new file mode 100644 index 00000000..c1e35376 --- /dev/null +++ b/src/Lumina.Application/Core/FileSystemManagement/Paths/Queries/ValidatePath/ValidatePathQuery.cs @@ -0,0 +1,16 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Contracts.Responses.FileSystemManagement.Path; +using Mediator; +using System.Diagnostics; +#endregion + +namespace Lumina.Application.Core.FileSystemManagement.Paths.Queries.ValidatePath; + +/// +/// Query for validating a path. +/// +/// The path to be validated. +[DebuggerDisplay("Path: {Path}")] +public record ValidatePathQuery( + string? Path +) : IRequest; diff --git a/src/Lumina.Application/Core/FileManagement/Paths/Queries/ValidatePath/ValidatePathQueryHandler.cs b/src/Lumina.Application/Core/FileSystemManagement/Paths/Queries/ValidatePath/ValidatePathQueryHandler.cs similarity index 73% rename from src/Lumina.Application/Core/FileManagement/Paths/Queries/ValidatePath/ValidatePathQueryHandler.cs rename to src/Lumina.Application/Core/FileSystemManagement/Paths/Queries/ValidatePath/ValidatePathQueryHandler.cs index 1f4d9791..71d2ae07 100644 --- a/src/Lumina.Application/Core/FileManagement/Paths/Queries/ValidatePath/ValidatePathQueryHandler.cs +++ b/src/Lumina.Application/Core/FileSystemManagement/Paths/Queries/ValidatePath/ValidatePathQueryHandler.cs @@ -1,12 +1,12 @@ -#region ========================================================================= USING ===================================================================================== -using Lumina.Contracts.Responses.FileManagement; -using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.Services; +#region ========================================================================= USING ===================================================================================== +using Lumina.Contracts.Responses.FileSystemManagement.Path; +using Lumina.Domain.Core.Aggregates.FileSystemManagement.FileSystemManagementAggregate.Services; using Mediator; using System.Threading; using System.Threading.Tasks; #endregion -namespace Lumina.Application.Core.FileManagement.Paths.Queries.ValidatePath; +namespace Lumina.Application.Core.FileSystemManagement.Paths.Queries.ValidatePath; /// /// Handler for the query to validate a file system path. @@ -34,6 +34,6 @@ public class ValidatePathQueryHandler : IRequestHandler public ValueTask Handle(ValidatePathQuery request, CancellationToken cancellationToken) { - return ValueTask.FromResult(new PathValidResponse(_pathService.IsValidPath(request.Path))); + return ValueTask.FromResult(new PathValidResponse(_pathService.IsValidPath(request.Path!))); } -} \ No newline at end of file +} diff --git a/src/Lumina.Application/Core/FileManagement/Paths/Queries/ValidatePath/ValidatePathQueryValidator.cs b/src/Lumina.Application/Core/FileSystemManagement/Paths/Queries/ValidatePath/ValidatePathQueryValidator.cs similarity index 76% rename from src/Lumina.Application/Core/FileManagement/Paths/Queries/ValidatePath/ValidatePathQueryValidator.cs rename to src/Lumina.Application/Core/FileSystemManagement/Paths/Queries/ValidatePath/ValidatePathQueryValidator.cs index 6cb77fbf..3395155e 100644 --- a/src/Lumina.Application/Core/FileManagement/Paths/Queries/ValidatePath/ValidatePathQueryValidator.cs +++ b/src/Lumina.Application/Core/FileSystemManagement/Paths/Queries/ValidatePath/ValidatePathQueryValidator.cs @@ -3,7 +3,7 @@ using FluentValidation; using Lumina.Domain.Common.Errors; #endregion -namespace Lumina.Application.Core.FileManagement.Paths.Queries.ValidatePath; +namespace Lumina.Application.Core.FileSystemManagement.Paths.Queries.ValidatePath; /// /// Validates the needed validation rules for . @@ -15,6 +15,6 @@ public class ValidatePathQueryValidator : AbstractValidator /// public ValidatePathQueryValidator() { - RuleFor(x => x.Path).NotEmpty().WithMessage(Errors.FileManagement.PathCannotBeEmpty.Code); + RuleFor(x => x.Path).NotEmpty().WithMessage(Errors.FileSystemManagement.PathCannotBeEmpty.Description); } } \ No newline at end of file diff --git a/src/Lumina.Application/Core/FileManagement/Thumbnails/Queries/GetThumbnail/GetThumbnailQuery.cs b/src/Lumina.Application/Core/FileSystemManagement/Thumbnails/Queries/GetThumbnail/GetThumbnailQuery.cs similarity index 61% rename from src/Lumina.Application/Core/FileManagement/Thumbnails/Queries/GetThumbnail/GetThumbnailQuery.cs rename to src/Lumina.Application/Core/FileSystemManagement/Thumbnails/Queries/GetThumbnail/GetThumbnailQuery.cs index 16c725fc..9b658739 100644 --- a/src/Lumina.Application/Core/FileManagement/Thumbnails/Queries/GetThumbnail/GetThumbnailQuery.cs +++ b/src/Lumina.Application/Core/FileSystemManagement/Thumbnails/Queries/GetThumbnail/GetThumbnailQuery.cs @@ -1,14 +1,19 @@ #region ========================================================================= USING ===================================================================================== using ErrorOr; -using Lumina.Contracts.Responses.FileManagement; +using Lumina.Contracts.Responses.FileSystemManagement.Thumbnails; using Mediator; +using System.Diagnostics; #endregion -namespace Lumina.Application.Core.FileManagement.Thumbnails.Queries.GetThumbnail; +namespace Lumina.Application.Core.FileSystemManagement.Thumbnails.Queries.GetThumbnail; /// /// Query for retrieving the thumbnail of a file at a path. /// /// The file path of the image to generate the thumbnail from. /// The desired quality of the thumbnail image (e.g., resolution or compression level). -public record GetThumbnailQuery(string Path, int Quality) : IRequest>; +[DebuggerDisplay("Path: {Path}")] +public record GetThumbnailQuery( + string? Path, + int Quality +) : IRequest>; diff --git a/src/Lumina.Application/Core/FileManagement/Thumbnails/Queries/GetThumbnail/GetThumbnailQueryHandler.cs b/src/Lumina.Application/Core/FileSystemManagement/Thumbnails/Queries/GetThumbnail/GetThumbnailQueryHandler.cs similarity index 67% rename from src/Lumina.Application/Core/FileManagement/Thumbnails/Queries/GetThumbnail/GetThumbnailQueryHandler.cs rename to src/Lumina.Application/Core/FileSystemManagement/Thumbnails/Queries/GetThumbnail/GetThumbnailQueryHandler.cs index e4ed3df4..9e22114f 100644 --- a/src/Lumina.Application/Core/FileManagement/Thumbnails/Queries/GetThumbnail/GetThumbnailQueryHandler.cs +++ b/src/Lumina.Application/Core/FileSystemManagement/Thumbnails/Queries/GetThumbnail/GetThumbnailQueryHandler.cs @@ -1,15 +1,15 @@ #region ========================================================================= USING ===================================================================================== using ErrorOr; -using Lumina.Contracts.Responses.FileManagement; -using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.Services; -using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.ValueObjects; -using MapsterMapper; +using Lumina.Application.Common.Mapping.FileSystemManagement.Thumbnails; +using Lumina.Contracts.Responses.FileSystemManagement.Thumbnails; +using Lumina.Domain.Core.Aggregates.FileSystemManagement.FileSystemManagementAggregate.Services; +using Lumina.Domain.Core.Aggregates.FileSystemManagement.FileSystemManagementAggregate.ValueObjects; using Mediator; using System.Threading; using System.Threading.Tasks; #endregion -namespace Lumina.Application.Core.FileManagement.Thumbnails.Queries.GetThumbnail; +namespace Lumina.Application.Core.FileSystemManagement.Thumbnails.Queries.GetThumbnail; /// /// Handler for the query to get the file thumbnail. @@ -17,17 +17,14 @@ namespace Lumina.Application.Core.FileManagement.Thumbnails.Queries.GetThumbnail public class GetThumbnailQueryHandler : IRequestHandler> { private readonly IThumbnailService _thumbnailsService; - private readonly IMapper _mapper; /// /// Initializes a new instance of the class. /// /// Injected service for handling thumbnails. - /// Injected service for mapping objects. - public GetThumbnailQueryHandler(IThumbnailService thumbnailsService, IMapper mapper) + public GetThumbnailQueryHandler(IThumbnailService thumbnailsService) { _thumbnailsService = thumbnailsService; - _mapper = mapper; } /// @@ -38,7 +35,7 @@ public class GetThumbnailQueryHandler : IRequestHandlerAn containing either a thumbnail, or an error. public async ValueTask> Handle(GetThumbnailQuery request, CancellationToken cancellationToken) { - ErrorOr result = await _thumbnailsService.GetThumbnailAsync(request.Path, request.Quality, cancellationToken); - return await ValueTask.FromResult(result.Match(values => ErrorOrFactory.From(_mapper.Map(values)), errors => errors)); + ErrorOr result = await _thumbnailsService.GetThumbnailAsync(request.Path!, request.Quality, cancellationToken); + return await ValueTask.FromResult(result.Match(value => ErrorOrFactory.From(value.ToResponse()), errors => errors)); } } diff --git a/src/Lumina.Application/Core/FileManagement/Thumbnails/Queries/GetThumbnail/GetThumbnailQueryValidator.cs b/src/Lumina.Application/Core/FileSystemManagement/Thumbnails/Queries/GetThumbnail/GetThumbnailQueryValidator.cs similarity index 77% rename from src/Lumina.Application/Core/FileManagement/Thumbnails/Queries/GetThumbnail/GetThumbnailQueryValidator.cs rename to src/Lumina.Application/Core/FileSystemManagement/Thumbnails/Queries/GetThumbnail/GetThumbnailQueryValidator.cs index 5f90cde8..d62e68b5 100644 --- a/src/Lumina.Application/Core/FileManagement/Thumbnails/Queries/GetThumbnail/GetThumbnailQueryValidator.cs +++ b/src/Lumina.Application/Core/FileSystemManagement/Thumbnails/Queries/GetThumbnail/GetThumbnailQueryValidator.cs @@ -3,7 +3,7 @@ using FluentValidation; using Lumina.Domain.Common.Errors; #endregion -namespace Lumina.Application.Core.FileManagement.Thumbnails.Queries.GetThumbnail; +namespace Lumina.Application.Core.FileSystemManagement.Thumbnails.Queries.GetThumbnail; /// /// Validates the needed validation rules for . @@ -15,7 +15,7 @@ public class GetThumbnailQueryValidator : AbstractValidator /// public GetThumbnailQueryValidator() { - RuleFor(x => x.Path).NotEmpty().WithMessage(Errors.FileManagement.PathCannotBeEmpty.Code); - RuleFor(x => x.Quality).InclusiveBetween(0, 100).WithMessage(Errors.Thumbnails.ImageQaulityMustBeBetweenZeroAndOneHundred.Code); + RuleFor(x => x.Path).NotEmpty().WithMessage(Errors.FileSystemManagement.PathCannotBeEmpty.Description); + RuleFor(x => x.Quality).InclusiveBetween(0, 100).WithMessage(Errors.Thumbnails.ImageQaulityMustBeBetweenZeroAndOneHundred.Description); } } diff --git a/src/Lumina.Application/Core/WrittenContentLibrary/BooksLibrary/Books/Commands/AddBook/AddBookCommand.cs b/src/Lumina.Application/Core/WrittenContentLibrary/BooksLibrary/Books/Commands/AddBook/AddBookCommand.cs index cff7a7b3..7e4f91a1 100644 --- a/src/Lumina.Application/Core/WrittenContentLibrary/BooksLibrary/Books/Commands/AddBook/AddBookCommand.cs +++ b/src/Lumina.Application/Core/WrittenContentLibrary/BooksLibrary/Books/Commands/AddBook/AddBookCommand.cs @@ -1,12 +1,13 @@ #region ========================================================================= USING ===================================================================================== using ErrorOr; +using Lumina.Contracts.Entities.MediaContributors; +using Lumina.Contracts.Entities.WrittenContentLibrary; +using Lumina.Contracts.Entities.WrittenContentLibrary.BookLibrary; using Lumina.Contracts.Enums.BookLibrary; -using Lumina.Contracts.Models.MediaContributors; -using Lumina.Contracts.Models.WrittenContentLibrary; -using Lumina.Contracts.Models.WrittenContentLibrary.BookLibrary; -using Lumina.Domain.Core.Aggregates.WrittenContentLibrary.BookLibraryAggregate; +using Lumina.Contracts.Responses.WrittenContentLibrary.BookLibrary.Books; using Mediator; using System.Collections.Generic; +using System.Diagnostics; #endregion namespace Lumina.Application.Core.WrittenContentLibrary.BooksLibrary.Books.Commands.AddBook; @@ -31,12 +32,13 @@ namespace Lumina.Application.Core.WrittenContentLibrary.BooksLibrary.Books.Comma /// The list of ISBN (International Standard Book Number) of the book. /// The list of media contributors (actors, directors, etc) starring in this book. /// The list of ratings for this book. +[DebuggerDisplay("Title: {Title}")] public record AddBookCommand( - WrittenContentMetadataModel Metadata, + WrittenContentMetadataEntity? Metadata, BookFormat? Format, string? Edition, int? VolumeNumber, - BookSeriesModel? Series, + BookSeriesEntity? Series, string? ASIN, string? GoodreadsId, string? LCCN, @@ -46,7 +48,7 @@ public record AddBookCommand( string? GoogleBooksId, string? BarnesAndNobleId, string? AppleBooksId, - List ISBNs, - List Contributors, - List Ratings -) : IRequest>; \ No newline at end of file + List? ISBNs, + List? Contributors, + List? Ratings +) : IRequest>; diff --git a/src/Lumina.Application/Core/WrittenContentLibrary/BooksLibrary/Books/Commands/AddBook/AddBookCommandHandler.cs b/src/Lumina.Application/Core/WrittenContentLibrary/BooksLibrary/Books/Commands/AddBook/AddBookCommandHandler.cs index 6134d50e..0d2abeda 100644 --- a/src/Lumina.Application/Core/WrittenContentLibrary/BooksLibrary/Books/Commands/AddBook/AddBookCommandHandler.cs +++ b/src/Lumina.Application/Core/WrittenContentLibrary/BooksLibrary/Books/Commands/AddBook/AddBookCommandHandler.cs @@ -2,16 +2,17 @@ using ErrorOr; using Lumina.Application.Common.DataAccess.Repositories.Books; using Lumina.Application.Common.DataAccess.UoW; +using Lumina.Application.Common.Mapping.WrittenContentLibrary.BookLibrary.Books; +using Lumina.Contracts.Entities.MediaContributors; +using Lumina.Contracts.Entities.WrittenContentLibrary.BookLibrary; using Lumina.Contracts.Enums.BookLibrary; -using Lumina.Contracts.Models.MediaContributors; -using Lumina.Contracts.Models.WrittenContentLibrary.BookLibrary; +using Lumina.Contracts.Responses.WrittenContentLibrary.BookLibrary.Books; using Lumina.Domain.Common.Primitives; using Lumina.Domain.Common.ValueObjects.Metadata; using Lumina.Domain.Core.Aggregates.MediaContributor.MediaContributorAggregate.ValueObjects; using Lumina.Domain.Core.Aggregates.WrittenContentLibrary.BookLibraryAggregate; using Lumina.Domain.Core.Aggregates.WrittenContentLibrary.BookLibraryAggregate.Entities; using Lumina.Domain.Core.Aggregates.WrittenContentLibrary.BookLibraryAggregate.ValueObjects; -using MapsterMapper; using Mediator; using System; using System.Collections.Generic; @@ -25,20 +26,17 @@ namespace Lumina.Application.Core.WrittenContentLibrary.BooksLibrary.Books.Comma /// /// Handler for the command to add a book. /// -public class AddBookCommandHandler : IRequestHandler> +public class AddBookCommandHandler : IRequestHandler> { private readonly IUnitOfWork _unitOfWork; - private readonly IMapper _mapper; /// /// Initializes a new instance of the class. /// /// Injected unit of work for interacting with the data access layer repositories. - /// Injected service for mapping objects. - public AddBookCommandHandler(IUnitOfWork unitOfWork, IMapper mapper) + public AddBookCommandHandler(IUnitOfWork unitOfWork) { _unitOfWork = unitOfWork; - _mapper = mapper; } /// @@ -49,11 +47,11 @@ public class AddBookCommandHandler : IRequestHandler /// An containing either a successfully created , or an error message. /// - public async ValueTask> Handle(AddBookCommand request, CancellationToken cancellationToken) + public async ValueTask> Handle(AddBookCommand request, CancellationToken cancellationToken) { // TODO: update Api.Book.md documentation when the functionality is fully implemented List contributorIds = []; - foreach (MediaContributorModel mediaContributor in request.Contributors) + foreach (MediaContributorEntity mediaContributor in request.Contributors!) { // TODO: add logic to search the media contributors repository for existing contributors, based on the provided names } @@ -63,10 +61,10 @@ public class AddBookCommandHandler : IRequestHandler> domainRatingsResult = request.Ratings.ConvertAll(rating => BookRating.Create( + List> domainRatingsResult = request.Ratings!.ConvertAll(rating => BookRating.Create( rating.Value ?? default, rating.MaxValue ?? default, - Optional.FromNullable(rating.Source.HasValue ? (BookRatingSource)(int)rating.Source : default), + Optional.FromNullable(rating.Source.HasValue ? (BookRatingSource)(int)rating.Source : (BookRatingSource?)null), Optional.FromNullable(rating.VoteCount))); // check if any of the results contain errors List errors = domainRatingsResult.Where(ratingResult => ratingResult.IsError).SelectMany(ratingResult => ratingResult.Errors).ToList(); @@ -75,7 +73,7 @@ public class AddBookCommandHandler : IRequestHandler domainRatings = domainRatingsResult.Select(rating => rating.Value).ToList(); - List> domainGenresResult = request.Metadata.Genres!.ConvertAll(genre => Genre.Create(genre.Name!)); + List> domainGenresResult = request.Metadata!.Genres!.ConvertAll(genre => Genre.Create(genre.Name!)); errors = domainGenresResult.Where(genreResult => genreResult.IsError).SelectMany(genreResult => genreResult.Errors).ToList(); if (errors.Count != 0) return errors; @@ -87,7 +85,7 @@ public class AddBookCommandHandler : IRequestHandler domainTags = domainTagsResult.Select(tag => tag.Value).ToList(); - List> domainIsbnsResult = request.ISBNs.ConvertAll(isbn => Isbn.Create(isbn.Value!, (IsbnFormat)(int)isbn.Format!)); + List> domainIsbnsResult = request.ISBNs!.ConvertAll(isbn => Isbn.Create(isbn.Value!, (IsbnFormat)(int)isbn.Format!)); errors = domainIsbnsResult.Where(isbnResult => isbnResult.IsError).SelectMany(isbnResult => isbnResult.Errors).ToList(); if (errors.Count != 0) return errors; @@ -163,12 +161,12 @@ public class AddBookCommandHandler : IRequestHandler(); - BookModel persistenceBook = _mapper.Map(createBookResult.Value); + BookEntity persistenceBook = createBookResult.Value.ToRepositoryEntity(); ErrorOr insertBookResult = await bookRepository.InsertAsync(persistenceBook, cancellationToken).ConfigureAwait(false); if (insertBookResult.IsError) return insertBookResult.Errors; await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false); - return createBookResult.Value; + return persistenceBook.ToResponse(); } } diff --git a/src/Lumina.Application/Core/WrittenContentLibrary/BooksLibrary/Books/Commands/AddBook/AddBookCommandValidator.cs b/src/Lumina.Application/Core/WrittenContentLibrary/BooksLibrary/Books/Commands/AddBook/AddBookCommandValidator.cs index 2b554f54..efdce6b9 100644 --- a/src/Lumina.Application/Core/WrittenContentLibrary/BooksLibrary/Books/Commands/AddBook/AddBookCommandValidator.cs +++ b/src/Lumina.Application/Core/WrittenContentLibrary/BooksLibrary/Books/Commands/AddBook/AddBookCommandValidator.cs @@ -17,197 +17,230 @@ public class AddBookCommandValidator : AbstractValidator public AddBookCommandValidator() { RuleFor(x => x.Metadata) - .NotNull().WithMessage(Errors.Metadata.MetadataCannotBeNull.Code) + .NotNull().WithMessage(Errors.Metadata.MetadataCannotBeNull.Description) .ChildRules(metadata => { - metadata.RuleFor(m => m.Title) - .NotEmpty().WithMessage(Errors.Metadata.TitleCannotBeEmpty.Code) - .MaximumLength(255).WithMessage(Errors.Metadata.TitleMustBeMaximum255CharactersLong.Code); - metadata.RuleFor(m => m.OriginalTitle) - .MaximumLength(255).When(m => m.OriginalTitle is not null) - .WithMessage(Errors.Metadata.OriginalTitleMustBeMaximum255CharactersLong.Code); - metadata.RuleFor(m => m.Description) - .MaximumLength(2000).When(m => m.Description is not null) - .WithMessage(Errors.Metadata.DescriptionMustBeMaximum2000CharactersLong.Code); - metadata.RuleFor(m => m.ReleaseInfo) - .NotNull().WithMessage(Errors.Metadata.ReleaseInfoCannotBeNull.Code) + metadata.RuleFor(m => m!.Title) + .NotEmpty().WithMessage(Errors.Metadata.TitleCannotBeEmpty.Description) + .MaximumLength(255).WithMessage(Errors.Metadata.TitleMustBeMaximum255CharactersLong.Description); + metadata.RuleFor(m => m!.OriginalTitle) + .MaximumLength(255).When(m => m!.OriginalTitle is not null) + .WithMessage(Errors.Metadata.OriginalTitleMustBeMaximum255CharactersLong.Description); + metadata.RuleFor(m => m!.Description) + .MaximumLength(2000).When(m => m!.Description is not null) + .WithMessage(Errors.Metadata.DescriptionMustBeMaximum2000CharactersLong.Description); + metadata.RuleFor(m => m!.ReleaseInfo) + .NotNull().WithMessage(Errors.Metadata.ReleaseInfoCannotBeNull.Description) .ChildRules(ri => { ri.RuleFor(r => r!.OriginalReleaseYear) .InclusiveBetween(1, 9999).When(r => r!.OriginalReleaseYear.HasValue) - .WithMessage(Errors.Metadata.OriginalReleaseYearMustBeBetween1And9999.Code); + .WithMessage(Errors.Metadata.OriginalReleaseYearMustBeBetween1And9999.Description); ri.RuleFor(r => r!.ReReleaseYear) .InclusiveBetween(1, 9999).When(r => r!.ReReleaseYear.HasValue) - .WithMessage(Errors.Metadata.ReReleaseYearMustBeBetween1And9999.Code); + .WithMessage(Errors.Metadata.ReReleaseYearMustBeBetween1And9999.Description); ri.RuleFor(r => r!.ReleaseCountry) .Matches("^[A-Za-z]{2}$").When(r => r!.ReleaseCountry is not null) - .WithMessage(Errors.Metadata.CountryCodeMustBe2CharactersLong.Code); + .WithMessage(Errors.Metadata.CountryCodeMustBe2CharactersLong.Description); ri.RuleFor(r => r!.ReleaseVersion) .MaximumLength(50).When(r => r!.ReleaseVersion is not null) - .WithMessage(Errors.Metadata.ReleaseVersionMustBeMaximum50CharactersLong.Code); + .WithMessage(Errors.Metadata.ReleaseVersionMustBeMaximum50CharactersLong.Description); + ri.RuleFor(r => r!.OriginalReleaseYear) + .Must((releaseInfo, originalReleaseYear) => + !releaseInfo!.OriginalReleaseDate.HasValue || + !releaseInfo.OriginalReleaseYear.HasValue || + originalReleaseYear == releaseInfo.OriginalReleaseDate.Value.Year) + .When(r => r!.OriginalReleaseDate.HasValue && r.OriginalReleaseYear.HasValue) + .WithMessage(Errors.Metadata.OriginalReleaseDateAndYearMustMatch.Description); ri.RuleFor(r => r!.ReReleaseYear) .Must((releaseInfo, reReleaseYear) => - !releaseInfo!.ReReleaseYear.HasValue || - !releaseInfo.OriginalReleaseYear.HasValue || - reReleaseYear >= releaseInfo.OriginalReleaseYear) - .When(r => r!.ReReleaseYear.HasValue && r.OriginalReleaseYear.HasValue) - .WithMessage(Errors.Metadata.ReReleaseYearCannotBeEarlierThanOriginalReleaseYear.Code); + !releaseInfo!.ReReleaseDate.HasValue || + !releaseInfo.ReReleaseYear.HasValue || + reReleaseYear == releaseInfo.ReReleaseDate.Value.Year) + .When(r => r!.ReReleaseDate.HasValue && r.ReReleaseYear.HasValue) + .WithMessage(Errors.Metadata.ReReleaseDateAndYearMustMatch.Description); + ri.RuleFor(r => r!.ReReleaseYear) + .Must((releaseInfo, reReleaseYear) => + !releaseInfo!.ReReleaseYear.HasValue || + !releaseInfo.OriginalReleaseYear.HasValue || + reReleaseYear >= releaseInfo.OriginalReleaseYear) + .When(r => r!.ReReleaseYear.HasValue && r.OriginalReleaseYear.HasValue) + .WithMessage(Errors.Metadata.ReReleaseYearCannotBeEarlierThanOriginalReleaseYear.Description); ri.RuleFor(r => r!.ReReleaseDate) .Must((releaseInfo, reReleaseDate) => !releaseInfo!.ReReleaseDate.HasValue || !releaseInfo.OriginalReleaseDate.HasValue || reReleaseDate >= releaseInfo.OriginalReleaseDate) .When(r => r!.ReReleaseDate.HasValue && r.OriginalReleaseDate.HasValue) - .WithMessage(Errors.Metadata.ReReleaseDateCannotBeEarlierThanOriginalReleaseDate.Code); + .WithMessage(Errors.Metadata.ReReleaseDateCannotBeEarlierThanOriginalReleaseDate.Description); + ri.RuleFor(r => r!.ReReleaseYear) + .Must((releaseInfo, reReleaseYear) => + !releaseInfo!.ReReleaseDate.HasValue || + !releaseInfo.ReReleaseYear.HasValue || + reReleaseYear == releaseInfo.ReReleaseDate.Value.Year) + .When(r => r!.ReReleaseDate.HasValue && r.ReReleaseYear.HasValue) + .WithMessage(Errors.Metadata.ReReleaseDateAndYearMustMatch.Description); }); - metadata.RuleFor(m => m.Genres) - .NotNull().WithMessage(Errors.Metadata.GenresListCannotBeNull.Code); - metadata.RuleForEach(m => m.Genres) + metadata.RuleFor(m => m!.Genres) + .NotNull().WithMessage(Errors.Metadata.GenresListCannotBeNull.Description); + metadata.RuleForEach(m => m!.Genres) .ChildRules(g => g.RuleFor(genre => genre.Name) - .NotEmpty().WithMessage(Errors.Metadata.GenreNameCannotBeEmpty.Code) - .MaximumLength(50).WithMessage(Errors.Metadata.GenreNameMustBeMaximum50CharactersLong.Code)); - metadata.RuleFor(m => m.Tags) - .NotNull().WithMessage(Errors.Metadata.TagsListCannotBeNull.Code); - metadata.RuleForEach(m => m.Tags) + .NotEmpty().WithMessage(Errors.Metadata.GenreNameCannotBeEmpty.Description) + .MaximumLength(50).WithMessage(Errors.Metadata.GenreNameMustBeMaximum50CharactersLong.Description)); + metadata.RuleFor(m => m!.Tags) + .NotNull().WithMessage(Errors.Metadata.TagsListCannotBeNull.Description); + metadata.RuleForEach(m => m!.Tags) .ChildRules(t => t.RuleFor(tag => tag.Name) - .NotEmpty().WithMessage(Errors.Metadata.TagNameCannotBeEmpty.Code) - .MaximumLength(50).WithMessage(Errors.Metadata.TagNameMustBeMaximum50CharactersLong.Code)); - metadata.RuleFor(m => m.Language) - .ChildRules(l => + .NotEmpty().WithMessage(Errors.Metadata.TagNameCannotBeEmpty.Description) + .MaximumLength(50).WithMessage(Errors.Metadata.TagNameMustBeMaximum50CharactersLong.Description)); + metadata.RuleFor(m => m!.Language) + .Custom((language, context) => { - l.RuleFor(x => x!.LanguageCode) - .NotEmpty().WithMessage(Errors.Metadata.LanguageCodeCannotBeEmpty.Code) - .MaximumLength(2).WithMessage(Errors.Metadata.LanguageCodeMustBe2CharactersLong.Code); - l.RuleFor(x => x!.LanguageName) - .NotEmpty().WithMessage(Errors.Metadata.LanguageNameCannotBeEmpty.Code) - .MaximumLength(50).WithMessage(Errors.Metadata.LanguageNameMustBeMaximum50CharactersLong.Code); - l.RuleFor(x => x!.NativeName) - .MaximumLength(50).When(x => x!.NativeName is not null) - .WithMessage(Errors.Metadata.LanguageNativeNameMustBeMaximum50CharactersLong.Code); - }).When(m => m.Language is not null); - metadata.RuleFor(m => m.OriginalLanguage) - .ChildRules(l => + if (language is null) + return; + + if (string.IsNullOrEmpty(language.LanguageCode)) + context.AddFailure("Language.LanguageCode", Errors.Metadata.LanguageCodeCannotBeEmpty.Description); + else if (language.LanguageCode.Length > 2) + context.AddFailure("Language.LanguageCode", Errors.Metadata.LanguageCodeMustBe2CharactersLong.Description); + + if (string.IsNullOrEmpty(language.LanguageName)) + context.AddFailure("Language.LanguageName", Errors.Metadata.LanguageNameCannotBeEmpty.Description); + else if (language.LanguageName.Length > 50) + context.AddFailure("Language.LanguageName", Errors.Metadata.LanguageNameMustBeMaximum50CharactersLong.Description); + + if (language.NativeName != null && language.NativeName.Length > 50) + context.AddFailure("Language.NativeName", Errors.Metadata.LanguageNativeNameMustBeMaximum50CharactersLong.Description); + }); + metadata.RuleFor(m => m!.OriginalLanguage) + .Custom((language, context) => { - l.RuleFor(x => x!.LanguageCode) - .NotEmpty().WithMessage(Errors.Metadata.LanguageCodeCannotBeEmpty.Code) - .MaximumLength(2).WithMessage(Errors.Metadata.LanguageCodeMustBe2CharactersLong.Code); - l.RuleFor(x => x!.LanguageName) - .NotEmpty().WithMessage(Errors.Metadata.LanguageNameCannotBeEmpty.Code) - .MaximumLength(50).WithMessage(Errors.Metadata.LanguageNameMustBeMaximum50CharactersLong.Code); - l.RuleFor(x => x!.NativeName) - .MaximumLength(50).When(x => x!.NativeName is not null) - .WithMessage(Errors.Metadata.LanguageNativeNameMustBeMaximum50CharactersLong.Code); - }).When(m => m.OriginalLanguage is not null); - metadata.RuleFor(m => m.Publisher) - .MaximumLength(100).When(m => m.Publisher is not null) - .WithMessage(Errors.WrittenContent.PublisherMustBeMaximum100CharactersLong.Code); - metadata.RuleFor(m => m.PageCount) - .GreaterThan(0).When(m => m.PageCount.HasValue) - .WithMessage(Errors.WrittenContent.PageCountMustBeGreaterThanZero.Code); + if (language is null) + return; + + if (string.IsNullOrEmpty(language.LanguageCode)) + context.AddFailure("OriginalLanguage.LanguageCode", Errors.Metadata.LanguageCodeCannotBeEmpty.Description); + else if (language.LanguageCode.Length > 2) + context.AddFailure("OriginalLanguage.LanguageCode", Errors.Metadata.LanguageCodeMustBe2CharactersLong.Description); + + if (string.IsNullOrEmpty(language.LanguageName)) + context.AddFailure("OriginalLanguage.LanguageName", Errors.Metadata.LanguageNameCannotBeEmpty.Description); + else if (language.LanguageName.Length > 50) + context.AddFailure("OriginalLanguage.LanguageName", Errors.Metadata.LanguageNameMustBeMaximum50CharactersLong.Description); + + if (language.NativeName != null && language.NativeName.Length > 50) + context.AddFailure("OriginalLanguage.NativeName", Errors.Metadata.LanguageNativeNameMustBeMaximum50CharactersLong.Description); + }); + metadata.RuleFor(m => m!.Publisher) + .MaximumLength(100).When(m => m!.Publisher is not null) + .WithMessage(Errors.WrittenContent.PublisherMustBeMaximum100CharactersLong.Description); + metadata.RuleFor(m => m!.PageCount) + .GreaterThan(0).When(m => m!.PageCount.HasValue) + .WithMessage(Errors.WrittenContent.PageCountMustBeGreaterThanZero.Description); }); RuleFor(x => x.Format) - .IsInEnum().When(f => f.Format is not null).WithMessage(Errors.WrittenContent.UnknownBookFormat.Code); + .IsInEnum().When(f => f.Format is not null).WithMessage(Errors.WrittenContent.UnknownBookFormat.Description); RuleFor(x => x.Edition) .MaximumLength(50).When(x => x.Edition is not null) - .WithMessage(Errors.WrittenContent.EditionMustBeMaximum50CharactersLong.Code); + .WithMessage(Errors.WrittenContent.EditionMustBeMaximum50CharactersLong.Description); RuleFor(x => x.VolumeNumber) .GreaterThan(0).When(x => x.VolumeNumber.HasValue) - .WithMessage(Errors.WrittenContent.VolumeNumberMustBeGreaterThanZero.Code); + .WithMessage(Errors.WrittenContent.VolumeNumberMustBeGreaterThanZero.Description); RuleFor(x => x.Series) .ChildRules(s => s.RuleFor(series => series!.Title) - .NotEmpty().WithMessage(Errors.Metadata.TitleCannotBeEmpty.Code) - .MaximumLength(255)).WithMessage(Errors.Metadata.TitleMustBeMaximum255CharactersLong.Code) + .NotEmpty().WithMessage(Errors.Metadata.TitleCannotBeEmpty.Description) + .MaximumLength(255)).WithMessage(Errors.Metadata.TitleMustBeMaximum255CharactersLong.Description) .When(x => x.Series is not null); RuleFor(x => x.ASIN) .Length(10).When(x => x.ASIN is not null) - .WithMessage(Errors.WrittenContent.AsinMustBe10CharactersLong.Code); + .WithMessage(Errors.WrittenContent.AsinMustBe10CharactersLong.Description); RuleFor(x => x.GoodreadsId) .Matches(@"^\d+$").When(x => x.GoodreadsId is not null) - .WithMessage(Errors.WrittenContent.GoodreadsIdMustBeNumeric.Code); + .WithMessage(Errors.WrittenContent.GoodreadsIdMustBeNumeric.Description); RuleFor(x => x.LCCN) - .Matches(@"^[a-z]{0,3}\d{8,10}$").WithMessage(Errors.WrittenContent.InvalidLccnFormat.Code) + .Matches(@"^[a-z]{0,3}\d{8,10}$").WithMessage(Errors.WrittenContent.InvalidLccnFormat.Description) .When(x => x.LCCN is not null); RuleFor(x => x.OCLCNumber) .Matches(@"^(ocm\d{8}|ocn\d{9,}|on\d{10,}|\(OCoLC\)\d{8,}|\d{8,})$").When(x => x.OCLCNumber is not null) - .WithMessage(Errors.WrittenContent.InvalidOclcFormat.Code); + .WithMessage(Errors.WrittenContent.InvalidOclcFormat.Description); RuleFor(x => x.OpenLibraryId) .Matches(@"^OL[1-9]\d*[AMW]$").When(x => x.OpenLibraryId is not null) - .WithMessage(Errors.WrittenContent.InvalidOpenLibraryId.Code); + .WithMessage(Errors.WrittenContent.InvalidOpenLibraryId.Description); RuleFor(x => x.LibraryThingId) .MaximumLength(50).When(x => x.LibraryThingId is not null) - .WithMessage(Errors.WrittenContent.LibraryThingIdMustBeMaximum50CharactersLong.Code); + .WithMessage(Errors.WrittenContent.LibraryThingIdMustBeMaximum50CharactersLong.Description); RuleFor(x => x.GoogleBooksId) - .Length(12).WithMessage(Errors.WrittenContent.GoogleBooksIdMustBe12CharactersLong.Code) - .Matches(@"^[A-Za-z0-9_-]{12}$").WithMessage(Errors.WrittenContent.InvalidGoogleBooksIdFormat.Code) + .Length(12).WithMessage(Errors.WrittenContent.GoogleBooksIdMustBe12CharactersLong.Description) + .Matches(@"^[A-Za-z0-9_-]{12}$").WithMessage(Errors.WrittenContent.InvalidGoogleBooksIdFormat.Description) .When(x => x.GoogleBooksId is not null); RuleFor(x => x.BarnesAndNobleId) - .Length(10).WithMessage(Errors.WrittenContent.BarnesAndNoblesIdMustBe10CharactersLong.Code) - .Matches(@"^\d{10}$").WithMessage(Errors.WrittenContent.InvalidBarnesAndNoblesIdFormat.Code) + .Length(10).WithMessage(Errors.WrittenContent.BarnesAndNoblesIdMustBe10CharactersLong.Description) + .Matches(@"^\d{10}$").WithMessage(Errors.WrittenContent.InvalidBarnesAndNoblesIdFormat.Description) .When(x => x.BarnesAndNobleId is not null); RuleFor(x => x.AppleBooksId) .Matches(@"^id\d+$").When(x => x.AppleBooksId is not null) - .WithMessage(Errors.WrittenContent.InvalidAppleBooksIdFormat.Code); + .WithMessage(Errors.WrittenContent.InvalidAppleBooksIdFormat.Description); RuleFor(x => x.ISBNs) - .NotNull().WithMessage(Errors.WrittenContent.IsbnListCannotBeNull.Code); + .NotNull().WithMessage(Errors.WrittenContent.IsbnListCannotBeNull.Description); RuleForEach(x => x.ISBNs) .ChildRules(isbn => { isbn.RuleFor(i => i.Value) - .NotEmpty().WithMessage(Errors.WrittenContent.IsbnValueCannotBeEmpty.Code) + .NotEmpty().WithMessage(Errors.WrittenContent.IsbnValueCannotBeEmpty.Description) .Matches(i => i.Format == IsbnFormat.Isbn13 ? @"^(?:ISBN(?:-13)?:? )?(?=[0-9]{13}$|(?=(?:[0-9]+[-\ ]){4})[-\ 0-9]{17}$)97[89][-\ ]?[0-9]{1,5}[-\ ]?[0-9]+[-\ ]?[0-9]+[-\ ]?[0-9]$" : @"^(?:ISBN(?:-10)?:? )?(?=[0-9X]{10}$|(?=(?:[0-9]+[-\ ]){3})[-\ 0-9X]{13}$)[0-9]{1,5}[-\ ]?[0-9]+[-\ ]?[0-9]+[-\ ]?[0-9X]$") .WithMessage(i => i.Format == IsbnFormat.Isbn13 - ? Errors.WrittenContent.InvalidIsbn13Format.Code - : Errors.WrittenContent.InvalidIsbn10Format.Code); + ? Errors.WrittenContent.InvalidIsbn13Format.Description + : Errors.WrittenContent.InvalidIsbn10Format.Description); isbn.RuleFor(i => i.Format) - .IsInEnum().WithMessage(Errors.WrittenContent.UnknownIsbnFormat.Code); + .IsInEnum().WithMessage(Errors.WrittenContent.UnknownIsbnFormat.Description); }); RuleFor(x => x.Contributors) - .NotNull().WithMessage(Errors.MediaContributor.ContributorsListCannotBeNull.Code); + .NotNull().WithMessage(Errors.MediaContributor.ContributorsListCannotBeNull.Description); RuleForEach(x => x.Contributors) .ChildRules(contributor => { contributor.RuleFor(c => c.Name) - .NotNull().WithMessage(Errors.MediaContributor.ContributorNameCannotBeEmpty.Code) + .NotNull().WithMessage(Errors.MediaContributor.ContributorNameCannotBeEmpty.Description) .ChildRules(name => { name.RuleFor(n => n!.DisplayName) - .NotNull().WithMessage(Errors.MediaContributor.ContributorDisplayNameCannotBeEmpty.Code) - .NotEmpty().WithMessage(Errors.MediaContributor.ContributorDisplayNameCannotBeEmpty.Code) - .MaximumLength(100).WithMessage(Errors.MediaContributor.ContributorDisplayNameMustBeMaximum100CharactersLong.Code); + .NotNull().WithMessage(Errors.MediaContributor.ContributorDisplayNameCannotBeEmpty.Description) + .NotEmpty().WithMessage(Errors.MediaContributor.ContributorDisplayNameCannotBeEmpty.Description) + .MaximumLength(100).WithMessage(Errors.MediaContributor.ContributorDisplayNameMustBeMaximum100CharactersLong.Description); name.RuleFor(n => n!.LegalName) .MaximumLength(100).When(n => n!.LegalName is not null) - .WithMessage(Errors.MediaContributor.ContributorLegalNameMustBeMaximum100CharactersLong.Code); + .WithMessage(Errors.MediaContributor.ContributorLegalNameMustBeMaximum100CharactersLong.Description); }); contributor.RuleFor(c => c.Role) - .NotNull().WithMessage(Errors.MediaContributor.ContributorRoleCannotBeNull.Code) + .NotNull().WithMessage(Errors.MediaContributor.ContributorRoleCannotBeNull.Description) .ChildRules(role => { role.RuleFor(r => r!.Name) - .NotEmpty().WithMessage(Errors.MediaContributor.RoleNameCannotBeEmpty.Code) - .MaximumLength(50).WithMessage(Errors.MediaContributor.RoleNameMustBeMaximum50CharactersLong.Code); + .NotEmpty().WithMessage(Errors.MediaContributor.RoleNameCannotBeEmpty.Description) + .MaximumLength(50).WithMessage(Errors.MediaContributor.RoleNameMustBeMaximum50CharactersLong.Description); role.RuleFor(r => r!.Category) - .NotEmpty().WithMessage(Errors.MediaContributor.RoleCategoryCannotBeEmpty.Code) - .MaximumLength(50).WithMessage(Errors.MediaContributor.RoleCategoryMustBeMaximum50CharactersLong.Code); + .NotEmpty().WithMessage(Errors.MediaContributor.RoleCategoryCannotBeEmpty.Description) + .MaximumLength(50).WithMessage(Errors.MediaContributor.RoleCategoryMustBeMaximum50CharactersLong.Description); }); }); RuleFor(x => x.Ratings) - .NotNull().WithMessage(Errors.Metadata.RatingsListCannotBeNull.Code); + .NotNull().WithMessage(Errors.Metadata.RatingsListCannotBeNull.Description); RuleForEach(x => x.Ratings) .ChildRules(rating => { rating.RuleFor(r => r.Value) - .GreaterThan(0).WithMessage(Errors.Metadata.RatingValueMustBePositive.Code) - .Must((r, value) => value <= r.MaxValue).WithMessage(Errors.Metadata.RatingValueCannotBeGreaterThanMaxValue.Code); + .GreaterThan(0).WithMessage(Errors.Metadata.RatingValueMustBePositive.Description) + .Must((r, value) => value <= r.MaxValue).WithMessage(Errors.Metadata.RatingValueCannotBeGreaterThanMaxValue.Description); rating.RuleFor(r => r.MaxValue) - .GreaterThan(0).WithMessage(Errors.Metadata.RatingMaxValueMustBePositive.Code); + .GreaterThan(0).WithMessage(Errors.Metadata.RatingMaxValueMustBePositive.Description); rating.RuleFor(r => r.VoteCount) .GreaterThanOrEqualTo(0).When(r => r.VoteCount.HasValue) - .WithMessage(Errors.Metadata.RatingVoteCountMustBePositive.Code); + .WithMessage(Errors.Metadata.RatingVoteCountMustBePositive.Description); }); } -} \ No newline at end of file +} diff --git a/src/Lumina.Application/Core/WrittenContentLibrary/BooksLibrary/Books/Queries/GetBooks/GetBooksQuery.cs b/src/Lumina.Application/Core/WrittenContentLibrary/BooksLibrary/Books/Queries/GetBooks/GetBooksQuery.cs index 8532c24c..4ea58640 100644 --- a/src/Lumina.Application/Core/WrittenContentLibrary/BooksLibrary/Books/Queries/GetBooks/GetBooksQuery.cs +++ b/src/Lumina.Application/Core/WrittenContentLibrary/BooksLibrary/Books/Queries/GetBooks/GetBooksQuery.cs @@ -1,6 +1,6 @@ -#region ========================================================================= USING ===================================================================================== +#region ========================================================================= USING ===================================================================================== using ErrorOr; -using Lumina.Domain.Core.Aggregates.WrittenContentLibrary.BookLibraryAggregate; +using Lumina.Contracts.Responses.WrittenContentLibrary.BookLibrary.Books; using Mediator; using System.Collections.Generic; #endregion @@ -10,4 +10,4 @@ namespace Lumina.Application.Core.WrittenContentLibrary.BooksLibrary.Books.Queri /// /// Query for getting all books. /// -public record class GetBooksQuery() : IRequest>>; \ No newline at end of file +public record class GetBooksQuery() : IRequest>>; diff --git a/src/Lumina.Application/Core/WrittenContentLibrary/BooksLibrary/Books/Queries/GetBooks/GetBooksQueryHandler.cs b/src/Lumina.Application/Core/WrittenContentLibrary/BooksLibrary/Books/Queries/GetBooks/GetBooksQueryHandler.cs index 65d3b556..8ec1c97e 100644 --- a/src/Lumina.Application/Core/WrittenContentLibrary/BooksLibrary/Books/Queries/GetBooks/GetBooksQueryHandler.cs +++ b/src/Lumina.Application/Core/WrittenContentLibrary/BooksLibrary/Books/Queries/GetBooks/GetBooksQueryHandler.cs @@ -2,9 +2,9 @@ using ErrorOr; using Lumina.Application.Common.DataAccess.Repositories.Books; using Lumina.Application.Common.DataAccess.UoW; -using Lumina.Contracts.Models.WrittenContentLibrary.BookLibrary; -using Lumina.Domain.Core.Aggregates.WrittenContentLibrary.BookLibraryAggregate; -using Mapster; +using Lumina.Application.Common.Mapping.WrittenContentLibrary.BookLibrary.Books; +using Lumina.Contracts.Entities.WrittenContentLibrary.BookLibrary; +using Lumina.Contracts.Responses.WrittenContentLibrary.BookLibrary.Books; using Mediator; using System.Collections.Generic; using System.Threading; @@ -16,7 +16,7 @@ namespace Lumina.Application.Core.WrittenContentLibrary.BooksLibrary.Books.Queri /// /// Handler for the query to get all books. /// -public class GetBooksQueryHandler : IRequestHandler>> +public class GetBooksQueryHandler : IRequestHandler>> { private readonly IUnitOfWork _unitOfWork; @@ -35,12 +35,14 @@ public class GetBooksQueryHandler : IRequestHandlerThe request to be handled. /// Cancellation token that can be used to stop the execution. /// - /// An containing either a collection of , or an error message. + /// An containing either a collection of , or an error message. /// - public async ValueTask>> Handle(GetBooksQuery request, CancellationToken cancellationToken) + public async ValueTask>> Handle(GetBooksQuery request, CancellationToken cancellationToken) { + // get a books repository IBookRepository bookRepository = _unitOfWork.GetRepository(); - ErrorOr> getBooksResult = await bookRepository.GetAllAsync(cancellationToken).ConfigureAwait(false); - return getBooksResult.Match(values => ErrorOrFactory.From(values.Adapt>()), errors => errors); + // get all books from the book repository + ErrorOr> getBooksResult = await bookRepository.GetAllAsync(cancellationToken).ConfigureAwait(false); + return getBooksResult.Match(result => ErrorOrFactory.From(getBooksResult.Value.ToResponses()), errors => errors); } } diff --git a/src/Lumina.Application/Lumina.Application.csproj b/src/Lumina.Application/Lumina.Application.csproj index bf5c2749..0d859873 100644 --- a/src/Lumina.Application/Lumina.Application.csproj +++ b/src/Lumina.Application/Lumina.Application.csproj @@ -13,16 +13,13 @@ - - - runtime; build; native; contentfiles; analyzers; buildtransitive diff --git a/src/Lumina.Contracts/Models/Common/GenreModel.cs b/src/Lumina.Contracts/Entities/Common/GenreEntity.cs similarity index 77% rename from src/Lumina.Contracts/Models/Common/GenreModel.cs rename to src/Lumina.Contracts/Entities/Common/GenreEntity.cs index 84ca2efc..262ad857 100644 --- a/src/Lumina.Contracts/Models/Common/GenreModel.cs +++ b/src/Lumina.Contracts/Entities/Common/GenreEntity.cs @@ -2,13 +2,13 @@ using System.Diagnostics; #endregion -namespace Lumina.Contracts.Models.Common; +namespace Lumina.Contracts.Entities.Common; /// /// Represents a request to get genre information. /// /// Gets the name of the genre. -[DebuggerDisplay("{Name}")] -public record GenreModel( +[DebuggerDisplay("Name: {Name}")] +public record GenreEntity( string? Name -); \ No newline at end of file +); diff --git a/src/Lumina.Contracts/Models/Common/IStorageEntity.cs b/src/Lumina.Contracts/Entities/Common/IStorageEntity.cs similarity index 93% rename from src/Lumina.Contracts/Models/Common/IStorageEntity.cs rename to src/Lumina.Contracts/Entities/Common/IStorageEntity.cs index a35d558f..bca11242 100644 --- a/src/Lumina.Contracts/Models/Common/IStorageEntity.cs +++ b/src/Lumina.Contracts/Entities/Common/IStorageEntity.cs @@ -2,7 +2,7 @@ using System; #endregion -namespace Lumina.Contracts.Models.Common; +namespace Lumina.Contracts.Entities.Common; /// /// Interface for storage models, enforces Id. diff --git a/src/Lumina.Contracts/Models/Common/LanguageInfoModel.cs b/src/Lumina.Contracts/Entities/Common/LanguageInfoEntity.cs similarity index 78% rename from src/Lumina.Contracts/Models/Common/LanguageInfoModel.cs rename to src/Lumina.Contracts/Entities/Common/LanguageInfoEntity.cs index b3078fc5..13585d60 100644 --- a/src/Lumina.Contracts/Models/Common/LanguageInfoModel.cs +++ b/src/Lumina.Contracts/Entities/Common/LanguageInfoEntity.cs @@ -2,17 +2,17 @@ using System.Diagnostics; #endregion -namespace Lumina.Contracts.Models.Common; +namespace Lumina.Contracts.Entities.Common; /// /// Represents a request to get language information. /// /// Gets the ISO code of the language (e.g., "en" for English). /// Gets the name of the language in English. -/// Gets the native name of the language (e.g., "Español" for Spanish). -[DebuggerDisplay("{LanguageName}")] -public record LanguageInfoModel( +/// Gets the native name of the language (e.g., "Español" for Spanish). +[DebuggerDisplay("LanguageName: {LanguageName}")] +public record LanguageInfoEntity( string? LanguageCode, string? LanguageName, string? NativeName -); \ No newline at end of file +); diff --git a/src/Lumina.Contracts/Models/Common/RatingModel.cs b/src/Lumina.Contracts/Entities/Common/RatingEntity.cs similarity index 87% rename from src/Lumina.Contracts/Models/Common/RatingModel.cs rename to src/Lumina.Contracts/Entities/Common/RatingEntity.cs index 86398053..33d52a8b 100644 --- a/src/Lumina.Contracts/Models/Common/RatingModel.cs +++ b/src/Lumina.Contracts/Entities/Common/RatingEntity.cs @@ -2,7 +2,7 @@ using System.Diagnostics; #endregion -namespace Lumina.Contracts.Models.Common; +namespace Lumina.Contracts.Entities.Common; /// /// Represents a rating. @@ -11,8 +11,8 @@ namespace Lumina.Contracts.Models.Common; /// Gets the maximum possible rating value. /// Gets the number of votes that contributed to the rating. [DebuggerDisplay("{Value}/{MaxValue}")] -public abstract record RatingModel( +public abstract record RatingEntity( decimal? Value, decimal? MaxValue, int? VoteCount -); \ No newline at end of file +); diff --git a/src/Lumina.Contracts/Models/Common/ReleaseInfoModel.cs b/src/Lumina.Contracts/Entities/Common/ReleaseInfoEntity.cs similarity index 87% rename from src/Lumina.Contracts/Models/Common/ReleaseInfoModel.cs rename to src/Lumina.Contracts/Entities/Common/ReleaseInfoEntity.cs index 1c8871b2..5ef9e41c 100644 --- a/src/Lumina.Contracts/Models/Common/ReleaseInfoModel.cs +++ b/src/Lumina.Contracts/Entities/Common/ReleaseInfoEntity.cs @@ -3,7 +3,7 @@ using System; using System.Diagnostics; #endregion -namespace Lumina.Contracts.Models.Common; +namespace Lumina.Contracts.Entities.Common; /// /// Represents a request to get release information. @@ -14,12 +14,12 @@ namespace Lumina.Contracts.Models.Common; /// Gets the re-release year of the content, if applicable. /// Gets the country where the content was released. /// Gets the version or edition of the content's release. -[DebuggerDisplay("{OriginalReleaseDate}")] -public record ReleaseInfoModel( +[DebuggerDisplay("OriginalReleaseDate: {OriginalReleaseDate}")] +public record ReleaseInfoEntity( DateOnly? OriginalReleaseDate, int? OriginalReleaseYear, DateOnly? ReReleaseDate, int? ReReleaseYear, string? ReleaseCountry, string? ReleaseVersion -); \ No newline at end of file +); diff --git a/src/Lumina.Contracts/Models/Common/TagModel.cs b/src/Lumina.Contracts/Entities/Common/TagEntity.cs similarity index 77% rename from src/Lumina.Contracts/Models/Common/TagModel.cs rename to src/Lumina.Contracts/Entities/Common/TagEntity.cs index 85d90520..558dd095 100644 --- a/src/Lumina.Contracts/Models/Common/TagModel.cs +++ b/src/Lumina.Contracts/Entities/Common/TagEntity.cs @@ -2,13 +2,13 @@ using System.Diagnostics; #endregion -namespace Lumina.Contracts.Models.Common; +namespace Lumina.Contracts.Entities.Common; /// /// Represents a request to get tag information. /// /// Gets the name of the tag. -[DebuggerDisplay("{Name}")] -public record TagModel( +[DebuggerDisplay("Name: {Name}")] +public record TagEntity( string? Name -); \ No newline at end of file +); diff --git a/src/Lumina.Contracts/Models/FileManagement/FileSystemItemModel.cs b/src/Lumina.Contracts/Entities/FileSystemManagement/FileSystemItemEntity.cs similarity index 76% rename from src/Lumina.Contracts/Models/FileManagement/FileSystemItemModel.cs rename to src/Lumina.Contracts/Entities/FileSystemManagement/FileSystemItemEntity.cs index fa9ef765..714a66ce 100644 --- a/src/Lumina.Contracts/Models/FileManagement/FileSystemItemModel.cs +++ b/src/Lumina.Contracts/Entities/FileSystemManagement/FileSystemItemEntity.cs @@ -3,7 +3,7 @@ using System; using System.Diagnostics; #endregion -namespace Lumina.Contracts.Models.FileManagement; +namespace Lumina.Contracts.Entities.FileSystemManagement; /// /// Generic filesystem data transfer object. @@ -12,10 +12,10 @@ namespace Lumina.Contracts.Models.FileManagement; /// The name of the file system item. /// The creation date of the file system item. /// The modification date of the file system item. -[DebuggerDisplay("{Name}")] -public record FileSystemItemModel( - string Path, - string Name, - DateTime DateCreated, +[DebuggerDisplay("Name: {Name}")] +public record FileSystemItemEntity( + string Path, + string Name, + DateTime DateCreated, DateTime DateModified ); diff --git a/src/Lumina.Contracts/Entities/MediaContributors/MediaContributorEntity.cs b/src/Lumina.Contracts/Entities/MediaContributors/MediaContributorEntity.cs new file mode 100644 index 00000000..c2039f9a --- /dev/null +++ b/src/Lumina.Contracts/Entities/MediaContributors/MediaContributorEntity.cs @@ -0,0 +1,16 @@ +#region ========================================================================= USING ===================================================================================== +using System.Diagnostics; +#endregion + +namespace Lumina.Contracts.Entities.MediaContributors; + +/// +/// Repository entity for a media contributor. +/// +/// The name details of the media contributor, including display and legal names. +/// The role details of the media contributor, including the role name and category. +[DebuggerDisplay("Name: {Name}, Role: {Role}")] +public record MediaContributorEntity( + MediaContributorNameEntity? Name, + MediaContributorRoleEntity? Role +); diff --git a/src/Lumina.Contracts/Entities/MediaContributors/MediaContributorNameEntity.cs b/src/Lumina.Contracts/Entities/MediaContributors/MediaContributorNameEntity.cs new file mode 100644 index 00000000..fdff941b --- /dev/null +++ b/src/Lumina.Contracts/Entities/MediaContributors/MediaContributorNameEntity.cs @@ -0,0 +1,16 @@ +#region ========================================================================= USING ===================================================================================== +using System.Diagnostics; +#endregion + +namespace Lumina.Contracts.Entities.MediaContributors; + +/// +/// Repository entity for a media contributor name. +/// +/// The display name of the media contributor. +/// The legal name of the media contributor. +[DebuggerDisplay("DisplayName: {DisplayName}")] +public record MediaContributorNameEntity( + string? DisplayName, + string? LegalName +); diff --git a/src/Lumina.Contracts/Entities/MediaContributors/MediaContributorRoleEntity.cs b/src/Lumina.Contracts/Entities/MediaContributors/MediaContributorRoleEntity.cs new file mode 100644 index 00000000..71e9d226 --- /dev/null +++ b/src/Lumina.Contracts/Entities/MediaContributors/MediaContributorRoleEntity.cs @@ -0,0 +1,16 @@ +#region ========================================================================= USING ===================================================================================== +using System.Diagnostics; +#endregion + +namespace Lumina.Contracts.Entities.MediaContributors; + +/// +/// Repository entity for a media contributor role. +/// +/// The name of the role assigned to the media contributor. +/// The category of the role. +[DebuggerDisplay("Name: {Name}, Category: {Category}")] +public record MediaContributorRoleEntity( + string? Name, + string? Category +); diff --git a/src/Lumina.Contracts/Models/WrittenContentLibrary/BookLibrary/BookModel.cs b/src/Lumina.Contracts/Entities/WrittenContentLibrary/BookLibrary/BookEntity.cs similarity index 92% rename from src/Lumina.Contracts/Models/WrittenContentLibrary/BookLibrary/BookModel.cs rename to src/Lumina.Contracts/Entities/WrittenContentLibrary/BookLibrary/BookEntity.cs index 1155fdb8..a8ffd8c9 100644 --- a/src/Lumina.Contracts/Models/WrittenContentLibrary/BookLibrary/BookModel.cs +++ b/src/Lumina.Contracts/Entities/WrittenContentLibrary/BookLibrary/BookEntity.cs @@ -1,17 +1,17 @@ #region ========================================================================= USING ===================================================================================== -using Lumina.Contracts.Models.Common; +using Lumina.Contracts.Entities.Common; using System; using System.Collections.Generic; using System.Diagnostics; #endregion -namespace Lumina.Contracts.Models.WrittenContentLibrary.BookLibrary; +namespace Lumina.Contracts.Entities.WrittenContentLibrary.BookLibrary; /// -/// Represents a book. +/// Repository entity for a book. /// -[DebuggerDisplay("{Title}")] -public class BookModel : IStorageEntity +[DebuggerDisplay("Title: {Title}")] +public class BookEntity : IStorageEntity { /// /// Gets the Id of the media item. @@ -97,12 +97,12 @@ public class BookModel : IStorageEntity /// /// Gets the list of tags associated with the media item. /// - public HashSet Tags { get; set; } = []; + public HashSet Tags { get; set; } = []; /// /// Gets the list of genres associated with the media item. /// - public HashSet Genres { get; set; } = []; + public HashSet Genres { get; set; } = []; /// /// Gets the publisher of the written content. @@ -128,7 +128,7 @@ public class BookModel : IStorageEntity /// Gets the volume or book number in the series, if applicable. /// public int? VolumeNumber { get; init; } - + // TODO: uncomment when series is implemented /// /// Gets the series id, if the book is part of a series. /// @@ -182,7 +182,7 @@ public class BookModel : IStorageEntity /// /// Gets the list of ISBN (International Standard Book Number) of the book. /// - public List ISBNs { get; set; } = []; + public List ISBNs { get; set; } = []; /// /// Gets the list of media contributors (actors, directors, etc) starring in this book. @@ -192,7 +192,7 @@ public class BookModel : IStorageEntity /// /// Gets the list of ratings for this book. /// - public List Ratings { get; init; } = []; + public List Ratings { get; init; } = []; /// /// Gets the time and date when the entity was added. @@ -203,4 +203,4 @@ public class BookModel : IStorageEntity /// Gets the optional time and date when the entity was updated. /// public DateTime? Updated { get; set; } -} \ No newline at end of file +} diff --git a/src/Lumina.Contracts/Entities/WrittenContentLibrary/BookLibrary/BookRatingEntity.cs b/src/Lumina.Contracts/Entities/WrittenContentLibrary/BookLibrary/BookRatingEntity.cs new file mode 100644 index 00000000..7e0eb3f3 --- /dev/null +++ b/src/Lumina.Contracts/Entities/WrittenContentLibrary/BookLibrary/BookRatingEntity.cs @@ -0,0 +1,22 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Contracts.Entities.Common; +using Lumina.Contracts.Enums.BookLibrary; +using System.Diagnostics; +#endregion + +namespace Lumina.Contracts.Entities.WrittenContentLibrary.BookLibrary; + +/// +/// Repository entity for a book rating. +/// +/// The rating value for the book. +/// The maximum possible rating value for the book. +/// The source of the book rating (e.g., a specific website or platform). +/// The number of votes that contributed to the book rating. +[DebuggerDisplay("{Value}/{MaxValue}")] +public record BookRatingEntity( + decimal? Value, + decimal? MaxValue, + BookRatingSource? Source, + int? VoteCount +) : RatingEntity(Value, MaxValue, VoteCount); diff --git a/src/Lumina.Contracts/Models/WrittenContentLibrary/BookLibrary/BookSeriesModel.cs b/src/Lumina.Contracts/Entities/WrittenContentLibrary/BookLibrary/BookSeriesEntity.cs similarity index 50% rename from src/Lumina.Contracts/Models/WrittenContentLibrary/BookLibrary/BookSeriesModel.cs rename to src/Lumina.Contracts/Entities/WrittenContentLibrary/BookLibrary/BookSeriesEntity.cs index a8b23fe0..95ac1689 100644 --- a/src/Lumina.Contracts/Models/WrittenContentLibrary/BookLibrary/BookSeriesModel.cs +++ b/src/Lumina.Contracts/Entities/WrittenContentLibrary/BookLibrary/BookSeriesEntity.cs @@ -2,13 +2,13 @@ using System.Diagnostics; #endregion -namespace Lumina.Contracts.Models.WrittenContentLibrary.BookLibrary; +namespace Lumina.Contracts.Entities.WrittenContentLibrary.BookLibrary; /// -/// Represents a request to get book series information. +/// Repository entity for book series. /// -/// Gets the title of the book series. -[DebuggerDisplay("{Title}")] -public record BookSeriesModel( +/// The title of the book series. +[DebuggerDisplay("Title: {Title}")] +public record BookSeriesEntity( string? Title -); \ No newline at end of file +); diff --git a/src/Lumina.Contracts/Entities/WrittenContentLibrary/BookLibrary/IsbnEntity.cs b/src/Lumina.Contracts/Entities/WrittenContentLibrary/BookLibrary/IsbnEntity.cs new file mode 100644 index 00000000..2cd8ce2a --- /dev/null +++ b/src/Lumina.Contracts/Entities/WrittenContentLibrary/BookLibrary/IsbnEntity.cs @@ -0,0 +1,17 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Contracts.Enums.BookLibrary; +using System.Diagnostics; +#endregion + +namespace Lumina.Contracts.Entities.WrittenContentLibrary.BookLibrary; + +/// +/// Repository entity for ISBN information. +/// +/// The ISBN value. +/// The format of the ISBN (e.g., ISBN-10 or ISBN-13). +[DebuggerDisplay("ISBN: {Value} ({Format})")] +public record IsbnEntity( + string? Value, + IsbnFormat? Format +); diff --git a/src/Lumina.Contracts/Entities/WrittenContentLibrary/WrittenContentMetadataEntity.cs b/src/Lumina.Contracts/Entities/WrittenContentLibrary/WrittenContentMetadataEntity.cs new file mode 100644 index 00000000..e4c77375 --- /dev/null +++ b/src/Lumina.Contracts/Entities/WrittenContentLibrary/WrittenContentMetadataEntity.cs @@ -0,0 +1,34 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Contracts.Entities.Common; +using System.Collections.Generic; +using System.Diagnostics; +#endregion + +namespace Lumina.Contracts.Entities.WrittenContentLibrary; + +/// +/// Repository entity for written content metadata. +/// +/// The title of the written content. +/// The original title of the written content, if different from the current title. +/// Gets a brief description or summary of the written content. +/// The release information, including release date and other relevant details. +/// The list of genres associated with the written content. +/// The list of tags that further describe or categorize the written content. +/// The language in which the written content is written. +/// The original language of the written content, if it has been translated. +/// The name of the publisher of the written content. +/// The number of pages in the written content. +[DebuggerDisplay("Title: {Title}")] +public record WrittenContentMetadataEntity( + string? Title, + string? OriginalTitle, + string? Description, + ReleaseInfoEntity? ReleaseInfo, + List? Genres, + List? Tags, + LanguageInfoEntity? Language, + LanguageInfoEntity? OriginalLanguage, + string? Publisher, + int? PageCount +); diff --git a/src/Lumina.Contracts/Lumina.Contracts.csproj b/src/Lumina.Contracts/Lumina.Contracts.csproj index 0f38f5a4..a5763a14 100644 --- a/src/Lumina.Contracts/Lumina.Contracts.csproj +++ b/src/Lumina.Contracts/Lumina.Contracts.csproj @@ -11,8 +11,4 @@ - - - - diff --git a/src/Lumina.Contracts/Models/MediaContributors/MediaContributorModel.cs b/src/Lumina.Contracts/Models/MediaContributors/MediaContributorModel.cs deleted file mode 100644 index 3615ca58..00000000 --- a/src/Lumina.Contracts/Models/MediaContributors/MediaContributorModel.cs +++ /dev/null @@ -1,16 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using System.Diagnostics; -#endregion - -namespace Lumina.Contracts.Models.MediaContributors; - -/// -/// Represents a media contributor. -/// -/// Gets the name details of the media contributor, including display and legal names. -/// Gets the role details of the media contributor, including the role name and category. -[DebuggerDisplay("{Name} {Role}")] -public record MediaContributorModel( - MediaContributorNameModel? Name, - MediaContributorRoleModel? Role -); \ No newline at end of file diff --git a/src/Lumina.Contracts/Models/MediaContributors/MediaContributorNameModel.cs b/src/Lumina.Contracts/Models/MediaContributors/MediaContributorNameModel.cs deleted file mode 100644 index c7f77eaa..00000000 --- a/src/Lumina.Contracts/Models/MediaContributors/MediaContributorNameModel.cs +++ /dev/null @@ -1,16 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using System.Diagnostics; -#endregion - -namespace Lumina.Contracts.Models.MediaContributors; - -/// -/// Represents a media contributor name. -/// -/// Gets the display name of the media contributor. -/// Gets the legal name of the media contributor. -[DebuggerDisplay("{DisplayName}")] -public record MediaContributorNameModel( - string? DisplayName, - string? LegalName -); \ No newline at end of file diff --git a/src/Lumina.Contracts/Models/MediaContributors/MediaContributorRoleModel.cs b/src/Lumina.Contracts/Models/MediaContributors/MediaContributorRoleModel.cs deleted file mode 100644 index d8693ae1..00000000 --- a/src/Lumina.Contracts/Models/MediaContributors/MediaContributorRoleModel.cs +++ /dev/null @@ -1,16 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using System.Diagnostics; -#endregion - -namespace Lumina.Contracts.Models.MediaContributors; - -/// -/// Represents a media contributor role. -/// -/// Gets the name of the role assigned to the media contributor. -/// Gets the category of the role, which may describe the type or group of roles. -[DebuggerDisplay("{Name} {Category}")] -public record MediaContributorRoleModel( - string? Name, - string? Category -); \ No newline at end of file diff --git a/src/Lumina.Contracts/Models/WrittenContentLibrary/BookLibrary/BookRatingModel.cs b/src/Lumina.Contracts/Models/WrittenContentLibrary/BookLibrary/BookRatingModel.cs deleted file mode 100644 index 4dadacfc..00000000 --- a/src/Lumina.Contracts/Models/WrittenContentLibrary/BookLibrary/BookRatingModel.cs +++ /dev/null @@ -1,22 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using Lumina.Contracts.Enums.BookLibrary; -using Lumina.Contracts.Models.Common; -using System.Diagnostics; -#endregion - -namespace Lumina.Contracts.Models.WrittenContentLibrary.BookLibrary; - -/// -/// Represents a book rating. -/// -/// Gets the rating value for the book. -/// Gets the maximum possible rating value for the book. -/// Gets the source of the book rating (e.g., a specific website or platform). -/// Gets the number of votes that contributed to the book rating. -[DebuggerDisplay("{Value}/{MaxValue}")] -public record BookRatingModel( - decimal? Value, - decimal? MaxValue, - BookRatingSource? Source, - int? VoteCount -) : RatingModel(Value, MaxValue, VoteCount); \ No newline at end of file diff --git a/src/Lumina.Contracts/Models/WrittenContentLibrary/BookLibrary/IsbnModel.cs b/src/Lumina.Contracts/Models/WrittenContentLibrary/BookLibrary/IsbnModel.cs deleted file mode 100644 index fdb25a1e..00000000 --- a/src/Lumina.Contracts/Models/WrittenContentLibrary/BookLibrary/IsbnModel.cs +++ /dev/null @@ -1,17 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using Lumina.Contracts.Enums.BookLibrary; -using System.Diagnostics; -#endregion - -namespace Lumina.Contracts.Models.WrittenContentLibrary.BookLibrary; - -/// -/// Represents a request to get ISBN information. -/// -/// Gets the ISBN value. -/// Gets the format of the ISBN (e.g., ISBN-10 or ISBN-13). -[DebuggerDisplay("{Value} ({Format})")] -public record IsbnModel( - string? Value, - IsbnFormat? Format -); \ No newline at end of file diff --git a/src/Lumina.Contracts/Models/WrittenContentLibrary/WrittenContentMetadataModel.cs b/src/Lumina.Contracts/Models/WrittenContentLibrary/WrittenContentMetadataModel.cs deleted file mode 100644 index 5f5b4aaf..00000000 --- a/src/Lumina.Contracts/Models/WrittenContentLibrary/WrittenContentMetadataModel.cs +++ /dev/null @@ -1,34 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using Lumina.Contracts.Models.Common; -using System.Collections.Generic; -using System.Diagnostics; -#endregion - -namespace Lumina.Contracts.Models.WrittenContentLibrary; - -/// -/// Represents written content metadata. -/// -/// Gets the title of the written content. -/// Gets the original title of the written content, if different from the current title. -/// Gets a brief description or summary of the written content. -/// Gets the release information, including release date and other relevant details. -/// Gets the list of genres associated with the written content. -/// Gets the list of tags that further describe or categorize the written content. -/// Gets the language in which the written content is written. -/// Gets the original language of the written content, if it has been translated. -/// Gets the name of the publisher of the written content. -/// Gets the number of pages in the written content. -[DebuggerDisplay("{Title}")] -public record WrittenContentMetadataModel( - string? Title, - string? OriginalTitle, - string? Description, - ReleaseInfoModel? ReleaseInfo, - List? Genres, - List? Tags, - LanguageInfoModel? Language, - LanguageInfoModel? OriginalLanguage, - string? Publisher, - int? PageCount -); \ No newline at end of file diff --git a/src/Lumina.Contracts/Requests/FileSystemManagement/Directories/GetDirectoriesRequest.cs b/src/Lumina.Contracts/Requests/FileSystemManagement/Directories/GetDirectoriesRequest.cs new file mode 100644 index 00000000..e7400cce --- /dev/null +++ b/src/Lumina.Contracts/Requests/FileSystemManagement/Directories/GetDirectoriesRequest.cs @@ -0,0 +1,17 @@ +#region ========================================================================= USING ===================================================================================== +using System.Diagnostics; +using System.Text.Json.Serialization; +#endregion + +namespace Lumina.Contracts.Requests.FileSystemManagement.Directories; + +/// +/// Represents a request to get the directories of a file system path. +/// +/// The file system path for which to get the directories. +/// Whether to include hidden file system elements or not. +[DebuggerDisplay("Path: {Path}")] +public record GetDirectoriesRequest( + string? Path, + bool IncludeHiddenElements +); diff --git a/src/Lumina.Contracts/Requests/FileSystemManagement/Directories/GetDirectoryTreeRequest.cs b/src/Lumina.Contracts/Requests/FileSystemManagement/Directories/GetDirectoryTreeRequest.cs new file mode 100644 index 00000000..b88a621f --- /dev/null +++ b/src/Lumina.Contracts/Requests/FileSystemManagement/Directories/GetDirectoryTreeRequest.cs @@ -0,0 +1,19 @@ +#region ========================================================================= USING ===================================================================================== +using System.Diagnostics; +using System.Text.Json.Serialization; +#endregion + +namespace Lumina.Contracts.Requests.FileSystemManagement.Directories; + +/// +/// Represents a request to get the tree of directories that make up a file system path. +/// +/// The file system path for which to get the directory tree. +/// Whether to include files along the directories or not. +/// Whether to include hidden file system elements or not. +[DebuggerDisplay("Path: {Path}")] +public record GetDirectoryTreeRequest( + string? Path, + bool IncludeFiles, + bool IncludeHiddenElements +); diff --git a/src/Lumina.Contracts/Requests/FileSystemManagement/Directories/GetTreeDirectoriesRequest.cs b/src/Lumina.Contracts/Requests/FileSystemManagement/Directories/GetTreeDirectoriesRequest.cs new file mode 100644 index 00000000..70bff675 --- /dev/null +++ b/src/Lumina.Contracts/Requests/FileSystemManagement/Directories/GetTreeDirectoriesRequest.cs @@ -0,0 +1,17 @@ +#region ========================================================================= USING ===================================================================================== +using System.Diagnostics; +using System.Text.Json.Serialization; +#endregion + +namespace Lumina.Contracts.Requests.FileSystemManagement.Directories; + +/// +/// Represents a request to get the directories of a file system path. +/// +/// The file system path for which to get the directory tree. +/// Whether to include hidden file system elements or not. +[DebuggerDisplay("Path: {Path}")] +public record GetTreeDirectoriesRequest( + string? Path, + bool IncludeHiddenElements +); diff --git a/src/Lumina.Contracts/Requests/FileSystemManagement/Files/GetFilesRequest.cs b/src/Lumina.Contracts/Requests/FileSystemManagement/Files/GetFilesRequest.cs new file mode 100644 index 00000000..a24d1c6d --- /dev/null +++ b/src/Lumina.Contracts/Requests/FileSystemManagement/Files/GetFilesRequest.cs @@ -0,0 +1,17 @@ +#region ========================================================================= USING ===================================================================================== +using System.Diagnostics; +using System.Text.Json.Serialization; +#endregion + +namespace Lumina.Contracts.Requests.FileSystemManagement.Files; + +/// +/// Represents a request to get the files at a file system path. +/// +/// The file system path for which to get the files. +/// Whether to include hidden file system elements or not. +[DebuggerDisplay("Path: {Path}")] +public record GetFilesRequest( + string? Path, + bool IncludeHiddenElements +); diff --git a/src/Lumina.Contracts/Requests/FileSystemManagement/Files/GetTreeFilesRequest.cs b/src/Lumina.Contracts/Requests/FileSystemManagement/Files/GetTreeFilesRequest.cs new file mode 100644 index 00000000..530bd93b --- /dev/null +++ b/src/Lumina.Contracts/Requests/FileSystemManagement/Files/GetTreeFilesRequest.cs @@ -0,0 +1,17 @@ +#region ========================================================================= USING ===================================================================================== +using System.Diagnostics; +using System.Text.Json.Serialization; +#endregion + +namespace Lumina.Contracts.Requests.FileSystemManagement.Files; + +/// +/// Represents a request to get the files of a file system path. +/// +/// The file system path for which to get the tree files. +/// Whether to include hidden file system elements or not. +[DebuggerDisplay("Path: {Path}")] +public record GetTreeFilesRequest( + string? Path, + bool IncludeHiddenElements +); diff --git a/src/Lumina.Contracts/Requests/FileSystemManagement/Path/CheckPathExistsRequest.cs b/src/Lumina.Contracts/Requests/FileSystemManagement/Path/CheckPathExistsRequest.cs new file mode 100644 index 00000000..6a7ac216 --- /dev/null +++ b/src/Lumina.Contracts/Requests/FileSystemManagement/Path/CheckPathExistsRequest.cs @@ -0,0 +1,17 @@ +#region ========================================================================= USING ===================================================================================== +using System.Diagnostics; +using System.Text.Json.Serialization; +#endregion + +namespace Lumina.Contracts.Requests.FileSystemManagement.Path; + +/// +/// Represents a request to check the existence of a file system path. +/// +/// The file system path to check the exitence of. +/// Whether to include hidden elements in the search results, or not. +[DebuggerDisplay("Path: {Path}, IncludeHiddenElements: {IncludeHiddenElements}")] +public record CheckPathExistsRequest( + string? Path, + bool IncludeHiddenElements +); diff --git a/src/Lumina.Contracts/Requests/FileSystemManagement/Path/CombinePathRequest.cs b/src/Lumina.Contracts/Requests/FileSystemManagement/Path/CombinePathRequest.cs new file mode 100644 index 00000000..ccdc57fe --- /dev/null +++ b/src/Lumina.Contracts/Requests/FileSystemManagement/Path/CombinePathRequest.cs @@ -0,0 +1,17 @@ +#region ========================================================================= USING ===================================================================================== +using System.Diagnostics; +using System.Text.Json.Serialization; +#endregion + +namespace Lumina.Contracts.Requests.FileSystemManagement.Path; + +/// +/// Represents a request to get the root of a file system path. +/// +/// The file system path to combine to. +/// The file system path to combine with. +[DebuggerDisplay("OriginalPath: {OriginalPath}, NewPath: {NewPath}")] +public record CombinePathRequest( + string? OriginalPath, + string? NewPath +); diff --git a/src/Lumina.Contracts/Requests/FileSystemManagement/Path/GetPathParentRequest.cs b/src/Lumina.Contracts/Requests/FileSystemManagement/Path/GetPathParentRequest.cs new file mode 100644 index 00000000..647fa21e --- /dev/null +++ b/src/Lumina.Contracts/Requests/FileSystemManagement/Path/GetPathParentRequest.cs @@ -0,0 +1,15 @@ +#region ========================================================================= USING ===================================================================================== +using System.Diagnostics; +using System.Text.Json.Serialization; +#endregion + +namespace Lumina.Contracts.Requests.FileSystemManagement.Path; + +/// +/// Represents a request to get the root of a file system path. +/// +/// The file system path for which to get the root. +[DebuggerDisplay("Path: {Path}")] +public record GetPathParentRequest( + string? Path +); diff --git a/src/Lumina.Contracts/Requests/FileSystemManagement/Path/GetPathRootRequest.cs b/src/Lumina.Contracts/Requests/FileSystemManagement/Path/GetPathRootRequest.cs new file mode 100644 index 00000000..a0cf7eb9 --- /dev/null +++ b/src/Lumina.Contracts/Requests/FileSystemManagement/Path/GetPathRootRequest.cs @@ -0,0 +1,15 @@ +#region ========================================================================= USING ===================================================================================== +using System.Diagnostics; +using System.Text.Json.Serialization; +#endregion + +namespace Lumina.Contracts.Requests.FileSystemManagement.Path; + +/// +/// Represents a request to get the root of a file system path. +/// +/// The file system path for which to get the root. +[DebuggerDisplay("Path: {Path}")] +public record GetPathRootRequest( + string? Path +); diff --git a/src/Lumina.Contracts/Requests/FileSystemManagement/Path/SplitPathRequest.cs b/src/Lumina.Contracts/Requests/FileSystemManagement/Path/SplitPathRequest.cs new file mode 100644 index 00000000..a312bc90 --- /dev/null +++ b/src/Lumina.Contracts/Requests/FileSystemManagement/Path/SplitPathRequest.cs @@ -0,0 +1,15 @@ +#region ========================================================================= USING ===================================================================================== +using System.Diagnostics; +using System.Text.Json.Serialization; +#endregion + +namespace Lumina.Contracts.Requests.FileSystemManagement.Path; + +/// +/// Represents a request to split a file system path. +/// +/// The file system path for which to get the path segments. +[DebuggerDisplay("Path: {Path}")] +public record SplitPathRequest( + string? Path +); diff --git a/src/Lumina.Contracts/Requests/FileSystemManagement/Path/ValidatePathRequest.cs b/src/Lumina.Contracts/Requests/FileSystemManagement/Path/ValidatePathRequest.cs new file mode 100644 index 00000000..cb5e5096 --- /dev/null +++ b/src/Lumina.Contracts/Requests/FileSystemManagement/Path/ValidatePathRequest.cs @@ -0,0 +1,15 @@ +#region ========================================================================= USING ===================================================================================== +using System.Diagnostics; +using System.Text.Json.Serialization; +#endregion + +namespace Lumina.Contracts.Requests.FileSystemManagement.Path; + +/// +/// Represents a request to check the validity of a file system path. +/// +/// The file system path to validate. +[DebuggerDisplay("Path: {Path}")] +public record ValidatePathRequest( + string? Path +); diff --git a/src/Lumina.Contracts/Requests/FileSystemManagement/Thumbnails/GetThumbnailRequest.cs b/src/Lumina.Contracts/Requests/FileSystemManagement/Thumbnails/GetThumbnailRequest.cs new file mode 100644 index 00000000..46012f9b --- /dev/null +++ b/src/Lumina.Contracts/Requests/FileSystemManagement/Thumbnails/GetThumbnailRequest.cs @@ -0,0 +1,17 @@ +#region ========================================================================= USING ===================================================================================== +using System.Diagnostics; +using System.Text.Json.Serialization; +#endregion + +namespace Lumina.Contracts.Requests.FileSystemManagement.Thumbnails; + +/// +/// Represents a request to get the thumbnail of a file system file. +/// +/// The path of the file for which to get the thumbnail. +/// The quality to use for the thumbnail. +[DebuggerDisplay("Path: {Path}")] +public record GetThumbnailRequest( + string? Path, + int Quality +); diff --git a/src/Lumina.Contracts/Requests/WrittenContentLibrary/BookLibrary/AddBookRequest.cs b/src/Lumina.Contracts/Requests/WrittenContentLibrary/BookLibrary/Books/AddBookRequest.cs similarity index 83% rename from src/Lumina.Contracts/Requests/WrittenContentLibrary/BookLibrary/AddBookRequest.cs rename to src/Lumina.Contracts/Requests/WrittenContentLibrary/BookLibrary/Books/AddBookRequest.cs index 806768e3..a229184f 100644 --- a/src/Lumina.Contracts/Requests/WrittenContentLibrary/BookLibrary/AddBookRequest.cs +++ b/src/Lumina.Contracts/Requests/WrittenContentLibrary/BookLibrary/Books/AddBookRequest.cs @@ -1,12 +1,13 @@ #region ========================================================================= USING ===================================================================================== +using Lumina.Contracts.Entities.MediaContributors; +using Lumina.Contracts.Entities.WrittenContentLibrary; +using Lumina.Contracts.Entities.WrittenContentLibrary.BookLibrary; using Lumina.Contracts.Enums.BookLibrary; -using Lumina.Contracts.Models.MediaContributors; -using Lumina.Contracts.Models.WrittenContentLibrary; -using Lumina.Contracts.Models.WrittenContentLibrary.BookLibrary; using System.Collections.Generic; +using System.Diagnostics; #endregion -namespace Lumina.Contracts.Requests.WrittenContentLibrary.BookLibrary; +namespace Lumina.Contracts.Requests.WrittenContentLibrary.BookLibrary.Books; /// /// Represents a request to add a book. @@ -28,12 +29,13 @@ namespace Lumina.Contracts.Requests.WrittenContentLibrary.BookLibrary; /// The list of ISBN (International Standard Book Number) of the book. /// The list of media contributors (actors, directors, etc) starring in this book. /// The list of ratings for this book. +[DebuggerDisplay("Title: {Metadata.Title}")] public record AddBookRequest( - WrittenContentMetadataModel? Metadata, + WrittenContentMetadataEntity? Metadata, BookFormat? Format, string? Edition, int? VolumeNumber, - BookSeriesModel? Series, + BookSeriesEntity? Series, string? ASIN, string? GoodreadsId, string? LCCN, @@ -43,7 +45,7 @@ public record AddBookRequest( string? GoogleBooksId, string? BarnesAndNobleId, string? AppleBooksId, - List? ISBNs, - List? Contributors, - List? Ratings -); \ No newline at end of file + List? ISBNs, + List? Contributors, + List? Ratings +); diff --git a/src/Lumina.Contracts/Requests/WrittenContentLibrary/BookLibrary/Books/GetBookRequest.cs b/src/Lumina.Contracts/Requests/WrittenContentLibrary/BookLibrary/Books/GetBookRequest.cs new file mode 100644 index 00000000..0fbdbe55 --- /dev/null +++ b/src/Lumina.Contracts/Requests/WrittenContentLibrary/BookLibrary/Books/GetBookRequest.cs @@ -0,0 +1,15 @@ +#region ========================================================================= USING ===================================================================================== +using System.Diagnostics; +using System.Text.Json.Serialization; +#endregion + +namespace Lumina.Contracts.Requests.WrittenContentLibrary.BookLibrary.Books; + +/// +/// Represents a request to get a book by the specified Id. +/// +/// The Id of the book to retrieve. +[DebuggerDisplay("Id: {Id}")] +public record GetBookRequest( + string? Id +); diff --git a/src/Lumina.Contracts/Responses/FileManagement/PathExistsResponse.cs b/src/Lumina.Contracts/Responses/FileManagement/PathExistsResponse.cs deleted file mode 100644 index 17f2ab12..00000000 --- a/src/Lumina.Contracts/Responses/FileManagement/PathExistsResponse.cs +++ /dev/null @@ -1,14 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using System.Diagnostics; -#endregion - -namespace Lumina.Contracts.Responses.FileManagement; - -/// -/// Represents a response to the inquiry about the existence of a file system path. -/// -/// Whether a file system path exists or not. -[DebuggerDisplay("{Exists}")] -public record PathExistsResponse( - bool Exists -); \ No newline at end of file diff --git a/src/Lumina.Contracts/Responses/FileManagement/PathSegmentResponse.cs b/src/Lumina.Contracts/Responses/FileManagement/PathSegmentResponse.cs deleted file mode 100644 index 1cf90572..00000000 --- a/src/Lumina.Contracts/Responses/FileManagement/PathSegmentResponse.cs +++ /dev/null @@ -1,14 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using System.Diagnostics; -#endregion - -namespace Lumina.Contracts.Responses.FileManagement; - -/// -/// Represents a response containing a file system path. -/// -/// The returned path. -[DebuggerDisplay("{Path}")] -public record PathSegmentResponse( - string Path -); \ No newline at end of file diff --git a/src/Lumina.Contracts/Responses/FileManagement/PathSeparatorResponse.cs b/src/Lumina.Contracts/Responses/FileManagement/PathSeparatorResponse.cs deleted file mode 100644 index 663f4d49..00000000 --- a/src/Lumina.Contracts/Responses/FileManagement/PathSeparatorResponse.cs +++ /dev/null @@ -1,14 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using System.Diagnostics; -#endregion - -namespace Lumina.Contracts.Responses.FileManagement; - -/// -/// Represents a response to the inquiry about the system's path separator. -/// -/// The system's path separator. -[DebuggerDisplay("{Separator}")] -public record PathSeparatorResponse( - string Separator -); \ No newline at end of file diff --git a/src/Lumina.Contracts/Responses/FileManagement/PathValidResponse.cs b/src/Lumina.Contracts/Responses/FileManagement/PathValidResponse.cs deleted file mode 100644 index 0b72e8a5..00000000 --- a/src/Lumina.Contracts/Responses/FileManagement/PathValidResponse.cs +++ /dev/null @@ -1,14 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using System.Diagnostics; -#endregion - -namespace Lumina.Contracts.Responses.FileManagement; - -/// -/// Represents a response to the inquiry about the validity of a file system path. -/// -/// Whether a file system path is valid or not. -[DebuggerDisplay("{IsValid}")] -public record PathValidResponse( - bool IsValid -); \ No newline at end of file diff --git a/src/Lumina.Contracts/Responses/FileManagement/FileSystemTreeNodeResponse.cs b/src/Lumina.Contracts/Responses/FileSystemManagement/Common/FileSystemTreeNodeResponse.cs similarity index 80% rename from src/Lumina.Contracts/Responses/FileManagement/FileSystemTreeNodeResponse.cs rename to src/Lumina.Contracts/Responses/FileSystemManagement/Common/FileSystemTreeNodeResponse.cs index d2ac28b4..1cb890c3 100644 --- a/src/Lumina.Contracts/Responses/FileManagement/FileSystemTreeNodeResponse.cs +++ b/src/Lumina.Contracts/Responses/FileSystemManagement/Common/FileSystemTreeNodeResponse.cs @@ -1,15 +1,15 @@ -#region ========================================================================= USING ===================================================================================== +#region ========================================================================= USING ===================================================================================== using Lumina.Contracts.Enums.FileSystem; using System.Collections.Generic; using System.Diagnostics; #endregion -namespace Lumina.Contracts.Responses.FileManagement; +namespace Lumina.Contracts.Responses.FileSystemManagement.Common; /// /// Generic file system node. /// -[DebuggerDisplay("{Path}")] +[DebuggerDisplay("Path: {Path}")] public class FileSystemTreeNodeResponse { /// @@ -41,4 +41,4 @@ public class FileSystemTreeNodeResponse /// Gets or sets the list of child nodes. /// public List Children { get; set; } = []; -} \ No newline at end of file +} diff --git a/src/Lumina.Contracts/Responses/FileManagement/DirectoryResponse.cs b/src/Lumina.Contracts/Responses/FileSystemManagement/Directories/DirectoryResponse.cs similarity index 66% rename from src/Lumina.Contracts/Responses/FileManagement/DirectoryResponse.cs rename to src/Lumina.Contracts/Responses/FileSystemManagement/Directories/DirectoryResponse.cs index ef25f547..9aefe50c 100644 --- a/src/Lumina.Contracts/Responses/FileManagement/DirectoryResponse.cs +++ b/src/Lumina.Contracts/Responses/FileSystemManagement/Directories/DirectoryResponse.cs @@ -1,11 +1,11 @@ #region ========================================================================= USING ===================================================================================== -using Lumina.Contracts.Models.FileManagement; +using Lumina.Contracts.Entities.FileSystemManagement; using System; using System.Collections.Generic; using System.Diagnostics; #endregion -namespace Lumina.Contracts.Responses.FileManagement; +namespace Lumina.Contracts.Responses.FileSystemManagement.Directories; /// /// Represents a response containing a file system directory. @@ -15,11 +15,11 @@ namespace Lumina.Contracts.Responses.FileManagement; /// The creation date of the directory. /// The modification date of the directory. /// The children items of the directory. -[DebuggerDisplay("{Name} (Directory)")] +[DebuggerDisplay("Name: {Name} (Directory)")] public record DirectoryResponse( - string Path, - string Name, - DateTime DateCreated, - DateTime DateModified, - List Items -) : FileSystemItemModel(Path, Name, DateCreated, DateModified); + string Path, + string Name, + DateTime DateCreated, + DateTime DateModified, + List Items +) : FileSystemItemEntity(Path, Name, DateCreated, DateModified); diff --git a/src/Lumina.Contracts/Responses/FileManagement/FileSystemTypeResponse.cs b/src/Lumina.Contracts/Responses/FileSystemManagement/FileSystem/FileSystemTypeResponse.cs similarity index 52% rename from src/Lumina.Contracts/Responses/FileManagement/FileSystemTypeResponse.cs rename to src/Lumina.Contracts/Responses/FileSystemManagement/FileSystem/FileSystemTypeResponse.cs index 73477def..173877be 100644 --- a/src/Lumina.Contracts/Responses/FileManagement/FileSystemTypeResponse.cs +++ b/src/Lumina.Contracts/Responses/FileSystemManagement/FileSystem/FileSystemTypeResponse.cs @@ -1,15 +1,15 @@ -#region ========================================================================= USING ===================================================================================== +#region ========================================================================= USING ===================================================================================== using Lumina.Contracts.Enums.FileSystem; using System.Diagnostics; #endregion -namespace Lumina.Contracts.Responses.FileManagement; +namespace Lumina.Contracts.Responses.FileSystemManagement.FileSystem; /// /// Represents a response containing the file system platform type. /// /// The returned file system platform type. -[DebuggerDisplay("{PlatformType}")] +[DebuggerDisplay("PlatformType: {PlatformType}")] public record FileSystemTypeResponse( PlatformType PlatformType -); \ No newline at end of file +); diff --git a/src/Lumina.Contracts/Responses/FileManagement/FileResponse.cs b/src/Lumina.Contracts/Responses/FileSystemManagement/Files/FileResponse.cs similarity index 66% rename from src/Lumina.Contracts/Responses/FileManagement/FileResponse.cs rename to src/Lumina.Contracts/Responses/FileSystemManagement/Files/FileResponse.cs index 61fe82c3..8b097b60 100644 --- a/src/Lumina.Contracts/Responses/FileManagement/FileResponse.cs +++ b/src/Lumina.Contracts/Responses/FileSystemManagement/Files/FileResponse.cs @@ -1,10 +1,10 @@ #region ========================================================================= USING ===================================================================================== -using Lumina.Contracts.Models.FileManagement; +using Lumina.Contracts.Entities.FileSystemManagement; using System; using System.Diagnostics; #endregion -namespace Lumina.Contracts.Responses.FileManagement; +namespace Lumina.Contracts.Responses.FileSystemManagement.Files; /// /// Represents a response containing a file system file. @@ -14,11 +14,11 @@ namespace Lumina.Contracts.Responses.FileManagement; /// The creation date of the file. /// The modification date of the file. /// The size of the file, in bytes. -[DebuggerDisplay("{Name} (File, Size: {Size} bytes)")] +[DebuggerDisplay("Name: {Name} (File, Size: {Size} bytes)")] public record FileResponse( - string Path, - string Name, - DateTime DateCreated, - DateTime DateModified, + string Path, + string Name, + DateTime DateCreated, + DateTime DateModified, long Size -) : FileSystemItemModel(Path, Name, DateCreated, DateModified); +) : FileSystemItemEntity(Path, Name, DateCreated, DateModified); diff --git a/src/Lumina.Contracts/Responses/FileSystemManagement/Path/PathExistsResponse.cs b/src/Lumina.Contracts/Responses/FileSystemManagement/Path/PathExistsResponse.cs new file mode 100644 index 00000000..e7d16823 --- /dev/null +++ b/src/Lumina.Contracts/Responses/FileSystemManagement/Path/PathExistsResponse.cs @@ -0,0 +1,14 @@ +#region ========================================================================= USING ===================================================================================== +using System.Diagnostics; +#endregion + +namespace Lumina.Contracts.Responses.FileSystemManagement.Path; + +/// +/// Represents a response to the inquiry about the existence of a file system path. +/// +/// Whether a file system path exists or not. +[DebuggerDisplay("Exists: {Exists}")] +public record PathExistsResponse( + bool Exists +); diff --git a/src/Lumina.Contracts/Responses/FileSystemManagement/Path/PathSegmentResponse.cs b/src/Lumina.Contracts/Responses/FileSystemManagement/Path/PathSegmentResponse.cs new file mode 100644 index 00000000..12171010 --- /dev/null +++ b/src/Lumina.Contracts/Responses/FileSystemManagement/Path/PathSegmentResponse.cs @@ -0,0 +1,14 @@ +#region ========================================================================= USING ===================================================================================== +using System.Diagnostics; +#endregion + +namespace Lumina.Contracts.Responses.FileSystemManagement.Path; + +/// +/// Represents a response containing a file system path. +/// +/// The returned path. +[DebuggerDisplay("Path: {Path}")] +public record PathSegmentResponse( + string Path +); diff --git a/src/Lumina.Contracts/Responses/FileSystemManagement/Path/PathSeparatorResponse.cs b/src/Lumina.Contracts/Responses/FileSystemManagement/Path/PathSeparatorResponse.cs new file mode 100644 index 00000000..7f7b2954 --- /dev/null +++ b/src/Lumina.Contracts/Responses/FileSystemManagement/Path/PathSeparatorResponse.cs @@ -0,0 +1,14 @@ +#region ========================================================================= USING ===================================================================================== +using System.Diagnostics; +#endregion + +namespace Lumina.Contracts.Responses.FileSystemManagement.Path; + +/// +/// Represents a response to the inquiry about the system's path separator. +/// +/// The system's path separator. +[DebuggerDisplay("Separator: {Separator}")] +public record PathSeparatorResponse( + string Separator +); diff --git a/src/Lumina.Contracts/Responses/FileSystemManagement/Path/PathValidResponse.cs b/src/Lumina.Contracts/Responses/FileSystemManagement/Path/PathValidResponse.cs new file mode 100644 index 00000000..abade223 --- /dev/null +++ b/src/Lumina.Contracts/Responses/FileSystemManagement/Path/PathValidResponse.cs @@ -0,0 +1,14 @@ +#region ========================================================================= USING ===================================================================================== +using System.Diagnostics; +#endregion + +namespace Lumina.Contracts.Responses.FileSystemManagement.Path; + +/// +/// Represents a response to the inquiry about the validity of a file system path. +/// +/// Whether a file system path is valid or not. +[DebuggerDisplay("IsValid: {IsValid}")] +public record PathValidResponse( + bool IsValid +); diff --git a/src/Lumina.Contracts/Responses/FileManagement/ThumbnailResponse.cs b/src/Lumina.Contracts/Responses/FileSystemManagement/Thumbnails/ThumbnailResponse.cs similarity index 80% rename from src/Lumina.Contracts/Responses/FileManagement/ThumbnailResponse.cs rename to src/Lumina.Contracts/Responses/FileSystemManagement/Thumbnails/ThumbnailResponse.cs index e1a68ca7..f25056ca 100644 --- a/src/Lumina.Contracts/Responses/FileManagement/ThumbnailResponse.cs +++ b/src/Lumina.Contracts/Responses/FileSystemManagement/Thumbnails/ThumbnailResponse.cs @@ -3,15 +3,15 @@ using Lumina.Contracts.Enums.PhotoLibrary; using System.Diagnostics; #endregion -namespace Lumina.Contracts.Responses.FileManagement; +namespace Lumina.Contracts.Responses.FileSystemManagement.Thumbnails; /// /// Data transfer object for thumbnails. /// /// The type of the thumbnail image. /// The bytes representing the thumbail. -[DebuggerDisplay("{Type}")] +[DebuggerDisplay("Type: {Type}")] public record ThumbnailResponse( - ImageType Type, + ImageType Type, byte[] Bytes ); diff --git a/src/Lumina.Contracts/Responses/WrittenContentLibrary/BookLibrary/Books/BookResponse.cs b/src/Lumina.Contracts/Responses/WrittenContentLibrary/BookLibrary/Books/BookResponse.cs new file mode 100644 index 00000000..4ad85533 --- /dev/null +++ b/src/Lumina.Contracts/Responses/WrittenContentLibrary/BookLibrary/Books/BookResponse.cs @@ -0,0 +1,55 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Contracts.Entities.MediaContributors; +using Lumina.Contracts.Entities.WrittenContentLibrary; +using Lumina.Contracts.Entities.WrittenContentLibrary.BookLibrary; +using Lumina.Contracts.Enums.BookLibrary; +using System; +using System.Collections.Generic; +using System.Diagnostics; +#endregion + +namespace Lumina.Contracts.Responses.WrittenContentLibrary.BookLibrary.Books; + +/// +/// Represents a request to add a book. +/// +/// Written content metadata of the book. +/// The format of the book (e.g., Hardcover, Paperback), if applicable. +/// The edition of the book, if applicable. +/// The volume or book number in the series, if applicable. +/// The series name, if the book is part of a series. +/// The ASIN (Amazon Standard Identification Number) of the book, if applicable. +/// The Goodreads ID of the book, if applicable. +/// The Library of Congress Control Number (LCCN) of the book, if applicable. +/// The OCLC Number (WorldCat identifier) of the book, if applicable. +/// The Open Library ID of the book, if applicable. +/// The LibraryThing ID of the book, if applicable. +/// The Google Books ID of the book, if applicable. +/// The Barnes & Noble ID of the book, if applicable. +/// The Apple Books ID of the book, if applicable. +/// The list of ISBN (International Standard Book Number) of the book. +/// The list of media contributors (actors, directors, etc) starring in this book. +/// The list of ratings for this book. +[DebuggerDisplay("Title: {Metadata.Title}")] +public record BookResponse( + Guid Id, + WrittenContentMetadataEntity Metadata, + BookFormat? Format, + string? Edition, + int? VolumeNumber, + BookSeriesEntity? Series, + string? ASIN, + string? GoodreadsId, + string? LCCN, + string? OCLCNumber, + string? OpenLibraryId, + string? LibraryThingId, + string? GoogleBooksId, + string? BarnesAndNobleId, + string? AppleBooksId, + List? ISBNs, + List? Contributors, + List? Ratings, + DateTime Created, + DateTime? Updated +); diff --git a/src/Lumina.DataAccess/Common/Configuration/BookConfiguration.cs b/src/Lumina.DataAccess/Common/Configuration/BookConfiguration.cs index 13f380ff..6bd15975 100644 --- a/src/Lumina.DataAccess/Common/Configuration/BookConfiguration.cs +++ b/src/Lumina.DataAccess/Common/Configuration/BookConfiguration.cs @@ -1,6 +1,6 @@ #region ========================================================================= USING ===================================================================================== -using Lumina.Contracts.Models.Common; -using Lumina.Contracts.Models.WrittenContentLibrary.BookLibrary; +using Lumina.Contracts.Entities.Common; +using Lumina.Contracts.Entities.WrittenContentLibrary.BookLibrary; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Metadata.Builders; using System.Collections.Generic; @@ -9,15 +9,15 @@ using System.Collections.Generic; namespace Lumina.DataAccess.Common.Configuration; /// -/// Configures the entity mapping for the entity. +/// Configures the entity mapping for the entity. /// -public class BookConfiguration : IEntityTypeConfiguration +public class BookConfiguration : IEntityTypeConfiguration { /// - /// Configures the entity. + /// Configures the entity. /// /// The builder to be used to configure the entity. - public void Configure(EntityTypeBuilder builder) + public void Configure(EntityTypeBuilder builder) { builder.ToTable("Books"); builder.HasKey(book => book.Id); @@ -46,8 +46,8 @@ public class BookConfiguration : IEntityTypeConfiguration .WithMany() .UsingEntity>( "BookTags", - j => j.HasOne().WithMany().HasForeignKey("TagId"), - j => j.HasOne().WithMany().HasForeignKey("BookId"), + j => j.HasOne().WithMany().HasForeignKey("TagId"), + j => j.HasOne().WithMany().HasForeignKey("BookId"), j => { j.HasKey("BookId", "TagId"); @@ -58,8 +58,8 @@ public class BookConfiguration : IEntityTypeConfiguration .WithMany() .UsingEntity>( "BookGenres", - j => j.HasOne().WithMany().HasForeignKey("GenreId"), - j => j.HasOne().WithMany().HasForeignKey("BookId"), + j => j.HasOne().WithMany().HasForeignKey("GenreId"), + j => j.HasOne().WithMany().HasForeignKey("BookId"), j => { j.HasKey("BookId", "GenreId"); diff --git a/src/Lumina.DataAccess/Common/Configuration/GenreConfiguration.cs b/src/Lumina.DataAccess/Common/Configuration/GenreConfiguration.cs index 3a50847e..31f40ccb 100644 --- a/src/Lumina.DataAccess/Common/Configuration/GenreConfiguration.cs +++ b/src/Lumina.DataAccess/Common/Configuration/GenreConfiguration.cs @@ -1,5 +1,5 @@ #region ========================================================================= USING ===================================================================================== -using Lumina.Contracts.Models.Common; +using Lumina.Contracts.Entities.Common; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Metadata.Builders; #endregion @@ -7,15 +7,15 @@ using Microsoft.EntityFrameworkCore.Metadata.Builders; namespace Lumina.DataAccess.Common.Configuration; /// -/// Configures the entity mapping for the entity. +/// Configures the entity mapping for the entity. /// -public class GenreConfiguration : IEntityTypeConfiguration +public class GenreConfiguration : IEntityTypeConfiguration { /// - /// Configures the entity. + /// Configures the entity. /// /// The builder to be used to configure the entity. - public void Configure(EntityTypeBuilder builder) + public void Configure(EntityTypeBuilder builder) { builder.ToTable("Genres"); builder.HasKey(genre => genre.Name); diff --git a/src/Lumina.DataAccess/Common/Configuration/TagConfiguration.cs b/src/Lumina.DataAccess/Common/Configuration/TagConfiguration.cs index 5695a09b..66ad4929 100644 --- a/src/Lumina.DataAccess/Common/Configuration/TagConfiguration.cs +++ b/src/Lumina.DataAccess/Common/Configuration/TagConfiguration.cs @@ -1,5 +1,5 @@ #region ========================================================================= USING ===================================================================================== -using Lumina.Contracts.Models.Common; +using Lumina.Contracts.Entities.Common; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Metadata.Builders; #endregion @@ -7,15 +7,15 @@ using Microsoft.EntityFrameworkCore.Metadata.Builders; namespace Lumina.DataAccess.Common.Configuration; /// -/// Configures the entity mapping for the entity. +/// Configures the entity mapping for the entity. /// -public class TagConfiguration : IEntityTypeConfiguration +public class TagConfiguration : IEntityTypeConfiguration { /// - /// Configures the entity. + /// Configures the entity. /// /// The builder to be used to configure the entity. - public void Configure(EntityTypeBuilder builder) + public void Configure(EntityTypeBuilder builder) { builder.ToTable("Tags"); builder.HasKey(tag => tag.Name); diff --git a/src/Lumina.DataAccess/Core/Repositories/Books/BookRepository.cs b/src/Lumina.DataAccess/Core/Repositories/Books/BookRepository.cs index db3d2cac..2b07166b 100644 --- a/src/Lumina.DataAccess/Core/Repositories/Books/BookRepository.cs +++ b/src/Lumina.DataAccess/Core/Repositories/Books/BookRepository.cs @@ -1,8 +1,8 @@ #region ========================================================================= USING ===================================================================================== using ErrorOr; using Lumina.Application.Common.DataAccess.Repositories.Books; -using Lumina.Contracts.Models.Common; -using Lumina.Contracts.Models.WrittenContentLibrary.BookLibrary; +using Lumina.Contracts.Entities.Common; +using Lumina.Contracts.Entities.WrittenContentLibrary.BookLibrary; using Lumina.DataAccess.Core.UoW; using Lumina.Domain.Common.Errors; using Microsoft.EntityFrameworkCore; @@ -36,24 +36,24 @@ internal sealed class BookRepository : IBookRepository /// The book to add. /// Cancellation token that can be used to stop the execution. /// An representing either a successfull operation, or an error. - public async Task> InsertAsync(BookModel book, CancellationToken cancellationToken) + public async Task> InsertAsync(BookEntity book, CancellationToken cancellationToken) { bool jobExists = await _luminaDbContext.Books.AnyAsync(repositoryBook => repositoryBook.Id == book.Id, cancellationToken: cancellationToken).ConfigureAwait(false); if (jobExists) return Errors.WrittenContent.BookAlreadyExists; // fetch existing tags and genres - List existingTags = await _luminaDbContext.Set() + List existingTags = await _luminaDbContext.Set() .Where(t => book.Tags.Select(bt => bt.Name).Contains(t.Name)) .ToListAsync(cancellationToken).ConfigureAwait(false); - List existingGenres = await _luminaDbContext.Set() + List existingGenres = await _luminaDbContext.Set() .Where(g => book.Genres.Select(bg => bg.Name).Contains(g.Name)) .ToListAsync(cancellationToken).ConfigureAwait(false); // replace tags and genres in the book with existing ones - book.Tags = new HashSet(book.Tags.Select(tag => existingTags.FirstOrDefault(existingTag => existingTag.Name == tag.Name) ?? tag)); - book.Genres = new HashSet(book.Genres.Select(genre => existingGenres.FirstOrDefault(existingGenre => existingGenre.Name == genre.Name) ?? genre)); + book.Tags = new HashSet(book.Tags.Select(tag => existingTags.FirstOrDefault(existingTag => existingTag.Name == tag.Name) ?? tag)); + book.Genres = new HashSet(book.Genres.Select(genre => existingGenres.FirstOrDefault(existingGenre => existingGenre.Name == genre.Name) ?? genre)); _luminaDbContext.Books.Add(book); return Result.Created; @@ -63,8 +63,8 @@ internal sealed class BookRepository : IBookRepository /// Gets all books. /// /// Cancellation token that can be used to stop the execution. - /// An containing either a collection of , or an error. - public async Task>> GetAllAsync(CancellationToken cancellationToken) + /// An containing either a collection of , or an error. + public async Task>> GetAllAsync(CancellationToken cancellationToken) { return await _luminaDbContext.Books .Include(book => book.Tags) diff --git a/src/Lumina.DataAccess/Core/UoW/LuminaDbContext.cs b/src/Lumina.DataAccess/Core/UoW/LuminaDbContext.cs index 75fe68d8..dcf7147e 100644 --- a/src/Lumina.DataAccess/Core/UoW/LuminaDbContext.cs +++ b/src/Lumina.DataAccess/Core/UoW/LuminaDbContext.cs @@ -1,6 +1,6 @@ #region ========================================================================= USING ===================================================================================== -using Lumina.Contracts.Models.Common; -using Lumina.Contracts.Models.WrittenContentLibrary.BookLibrary; +using Lumina.Contracts.Entities.Common; +using Lumina.Contracts.Entities.WrittenContentLibrary.BookLibrary; using Lumina.Domain.Common.Events; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.ChangeTracking; @@ -18,7 +18,7 @@ namespace Lumina.DataAccess.Core.UoW; /// To update the database: update-database -p Lumina.DataAccess -s Lumina.Presentation.Api public class LuminaDbContext : DbContext { - public virtual DbSet Books { get; set; } = null!; + public virtual DbSet Books { get; set; } = null!; /// /// Initializes a new instance of the class. diff --git a/src/Lumina.DataAccess/Lumina.DataAccess.csproj b/src/Lumina.DataAccess/Lumina.DataAccess.csproj index e2e55232..c4c3389a 100644 --- a/src/Lumina.DataAccess/Lumina.DataAccess.csproj +++ b/src/Lumina.DataAccess/Lumina.DataAccess.csproj @@ -17,15 +17,14 @@ - - - - + + + all runtime; build; native; contentfiles; analyzers; buildtransitive - - + + all runtime; build; native; contentfiles; analyzers; buildtransitive diff --git a/src/Lumina.Domain/Common/DependencyInjection/DomainLayerServices.cs b/src/Lumina.Domain/Common/DependencyInjection/DomainLayerServices.cs index 720bf3ea..e1047e7f 100644 --- a/src/Lumina.Domain/Common/DependencyInjection/DomainLayerServices.cs +++ b/src/Lumina.Domain/Common/DependencyInjection/DomainLayerServices.cs @@ -1,8 +1,8 @@ #region ========================================================================= USING ===================================================================================== -using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.Services; -using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.Strategies.Environment; -using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.Strategies.Path; -using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.Strategies.Platform; +using Lumina.Domain.Core.Aggregates.FileSystemManagement.FileSystemManagementAggregate.Services; +using Lumina.Domain.Core.Aggregates.FileSystemManagement.FileSystemManagementAggregate.Strategies.Environment; +using Lumina.Domain.Core.Aggregates.FileSystemManagement.FileSystemManagementAggregate.Strategies.Path; +using Lumina.Domain.Core.Aggregates.FileSystemManagement.FileSystemManagementAggregate.Strategies.Platform; using Microsoft.Extensions.DependencyInjection; using System; using System.IO.Abstractions; diff --git a/src/Lumina.Domain/Common/Errors/Errors.FileManagement.cs b/src/Lumina.Domain/Common/Errors/Errors.FileSystemManagement.cs similarity index 50% rename from src/Lumina.Domain/Common/Errors/Errors.FileManagement.cs rename to src/Lumina.Domain/Common/Errors/Errors.FileSystemManagement.cs index eeef6155..c0b90c00 100644 --- a/src/Lumina.Domain/Common/Errors/Errors.FileManagement.cs +++ b/src/Lumina.Domain/Common/Errors/Errors.FileSystemManagement.cs @@ -9,24 +9,24 @@ namespace Lumina.Domain.Common.Errors; /// public static partial class Errors { - public static class FileManagement + public static class FileSystemManagement { - public static Error ParentNodeCannotBeNull => Error.Failure(nameof(ParentNodeCannotBeNull)); - public static Error FileCopyError => Error.Failure(nameof(FileCopyError)); - public static Error FileMoveError => Error.Failure(nameof(FileMoveError)); - public static Error DirectoryCopyError => Error.Failure(nameof(DirectoryCopyError)); - public static Error DirectoryMoveError => Error.Failure(nameof(DirectoryMoveError)); - public static Error FileNotFound => Error.NotFound(nameof(FileNotFound)); - public static Error InvalidPath => Error.Validation(nameof(InvalidPath)); - public static Error PathCannotBeEmpty => Error.Validation(nameof(PathCannotBeEmpty)); - public static Error ExtensionCannotBeEmpty => Error.Validation(nameof(ExtensionCannotBeEmpty)); - public static Error StreamIdCannotBeEmpty => Error.Validation(nameof(StreamIdCannotBeEmpty)); - public static Error CodecCannotBeEmpty => Error.Validation(nameof(CodecCannotBeEmpty)); - public static Error BitrateMustBeAPositiveNumber => Error.Validation(nameof(BitrateMustBeAPositiveNumber)); - public static Error CannotNavigateUp => Error.Failure(nameof(CannotNavigateUp)); - public static Error NameCannotBeEmpty => Error.Validation(nameof(NameCannotBeEmpty)); - public static Error FileAlreadyExists => Error.Conflict(nameof(FileAlreadyExists)); - public static Error DirectoryNotFound => Error.NotFound(nameof(DirectoryNotFound)); - public static Error DirectoryAlreadyExists => Error.Conflict(nameof(DirectoryAlreadyExists)); + public static Error ParentNodeCannotBeNull => Error.Failure(description: nameof(ParentNodeCannotBeNull)); + public static Error FileCopyError => Error.Failure(description: nameof(FileCopyError)); + public static Error FileMoveError => Error.Failure(description: nameof(FileMoveError)); + public static Error DirectoryCopyError => Error.Failure(description: nameof(DirectoryCopyError)); + public static Error DirectoryMoveError => Error.Failure(description: nameof(DirectoryMoveError)); + public static Error FileNotFound => Error.NotFound(description: nameof(FileNotFound)); + public static Error InvalidPath => Error.Validation(description: nameof(InvalidPath)); + public static Error PathCannotBeEmpty => Error.Validation(description: nameof(PathCannotBeEmpty)); + public static Error ExtensionCannotBeEmpty => Error.Validation(description: nameof(ExtensionCannotBeEmpty)); + public static Error StreamIdCannotBeEmpty => Error.Validation(description: nameof(StreamIdCannotBeEmpty)); + public static Error CodecCannotBeEmpty => Error.Validation(description: nameof(CodecCannotBeEmpty)); + public static Error BitrateMustBeAPositiveNumber => Error.Validation(description: nameof(BitrateMustBeAPositiveNumber)); + public static Error CannotNavigateUp => Error.Failure(description: nameof(CannotNavigateUp)); + public static Error NameCannotBeEmpty => Error.Validation(description: nameof(NameCannotBeEmpty)); + public static Error FileAlreadyExists => Error.Conflict(description: nameof(FileAlreadyExists)); + public static Error DirectoryNotFound => Error.NotFound(description: nameof(DirectoryNotFound)); + public static Error DirectoryAlreadyExists => Error.Conflict(description: nameof(DirectoryAlreadyExists)); } } diff --git a/src/Lumina.Domain/Common/Errors/Errors.MediaContributor.cs b/src/Lumina.Domain/Common/Errors/Errors.MediaContributor.cs index 9f117b48..c392e6ed 100644 --- a/src/Lumina.Domain/Common/Errors/Errors.MediaContributor.cs +++ b/src/Lumina.Domain/Common/Errors/Errors.MediaContributor.cs @@ -11,15 +11,15 @@ public static partial class Errors { public static class MediaContributor { - public static Error ContributorsListCannotBeNull => Error.Validation(nameof(ContributorsListCannotBeNull)); - public static Error ContributorNameCannotBeEmpty => Error.Validation(nameof(ContributorNameCannotBeEmpty)); - public static Error ContributorDisplayNameCannotBeEmpty => Error.Validation(nameof(ContributorDisplayNameCannotBeEmpty)); - public static Error ContributorDisplayNameMustBeMaximum100CharactersLong => Error.Validation(nameof(ContributorDisplayNameMustBeMaximum100CharactersLong)); - public static Error ContributorLegalNameMustBeMaximum100CharactersLong => Error.Validation(nameof(ContributorLegalNameMustBeMaximum100CharactersLong)); - public static Error RoleNameCannotBeEmpty => Error.Validation(nameof(RoleNameCannotBeEmpty)); - public static Error RoleNameMustBeMaximum50CharactersLong => Error.Validation(nameof(RoleNameMustBeMaximum50CharactersLong)); - public static Error RoleCategoryCannotBeEmpty => Error.Validation(nameof(RoleCategoryCannotBeEmpty)); - public static Error RoleCategoryMustBeMaximum50CharactersLong => Error.Validation(nameof(RoleCategoryMustBeMaximum50CharactersLong)); - public static Error ContributorRoleCannotBeNull => Error.Validation(nameof(ContributorRoleCannotBeNull)); + public static Error ContributorsListCannotBeNull => Error.Validation(description: nameof(ContributorsListCannotBeNull)); + public static Error ContributorNameCannotBeEmpty => Error.Validation(description: nameof(ContributorNameCannotBeEmpty)); + public static Error ContributorDisplayNameCannotBeEmpty => Error.Validation(description: nameof(ContributorDisplayNameCannotBeEmpty)); + public static Error ContributorDisplayNameMustBeMaximum100CharactersLong => Error.Validation(description: nameof(ContributorDisplayNameMustBeMaximum100CharactersLong)); + public static Error ContributorLegalNameMustBeMaximum100CharactersLong => Error.Validation(description: nameof(ContributorLegalNameMustBeMaximum100CharactersLong)); + public static Error RoleNameCannotBeEmpty => Error.Validation(description: nameof(RoleNameCannotBeEmpty)); + public static Error RoleNameMustBeMaximum50CharactersLong => Error.Validation(description: nameof(RoleNameMustBeMaximum50CharactersLong)); + public static Error RoleCategoryCannotBeEmpty => Error.Validation(description: nameof(RoleCategoryCannotBeEmpty)); + public static Error RoleCategoryMustBeMaximum50CharactersLong => Error.Validation(description: nameof(RoleCategoryMustBeMaximum50CharactersLong)); + public static Error ContributorRoleCannotBeNull => Error.Validation(description: nameof(ContributorRoleCannotBeNull)); } } diff --git a/src/Lumina.Domain/Common/Errors/Errors.Metadata.cs b/src/Lumina.Domain/Common/Errors/Errors.Metadata.cs index 8937c7fa..0802a4e9 100644 --- a/src/Lumina.Domain/Common/Errors/Errors.Metadata.cs +++ b/src/Lumina.Domain/Common/Errors/Errors.Metadata.cs @@ -11,36 +11,36 @@ public static partial class Errors { public static class Metadata { - public static Error MetadataCannotBeNull => Error.Validation(nameof(MetadataCannotBeNull)); - public static Error TitleCannotBeEmpty => Error.Validation(nameof(TitleCannotBeEmpty)); - public static Error TitleMustBeMaximum255CharactersLong => Error.Validation(nameof(TitleMustBeMaximum255CharactersLong)); - public static Error OriginalTitleMustBeMaximum255CharactersLong => Error.Validation(nameof(OriginalTitleMustBeMaximum255CharactersLong)); - public static Error DescriptionMustBeMaximum2000CharactersLong => Error.Validation(nameof(DescriptionMustBeMaximum2000CharactersLong)); - public static Error GenresListCannotBeNull => Error.Validation(nameof(GenresListCannotBeNull)); - public static Error GenreNameCannotBeEmpty => Error.Validation(nameof(GenreNameCannotBeEmpty)); - public static Error GenreNameMustBeMaximum50CharactersLong => Error.Validation(nameof(GenreNameMustBeMaximum50CharactersLong)); - public static Error TagsListCannotBeNull => Error.Validation(nameof(TagsListCannotBeNull)); - public static Error TagNameCannotBeEmpty => Error.Validation(nameof(TagNameCannotBeEmpty)); - public static Error TagNameMustBeMaximum50CharactersLong => Error.Validation(nameof(TagNameMustBeMaximum50CharactersLong)); - public static Error LanguageCodeCannotBeEmpty => Error.Validation(nameof(LanguageCodeCannotBeEmpty)); - public static Error LanguageNameCannotBeEmpty => Error.Validation(nameof(LanguageNameCannotBeEmpty)); - public static Error LanguageCodeMustBe2CharactersLong => Error.Validation(nameof(LanguageCodeMustBe2CharactersLong)); - public static Error LanguageNameMustBeMaximum50CharactersLong => Error.Validation(nameof(LanguageNameMustBeMaximum50CharactersLong)); - public static Error LanguageNativeNameMustBeMaximum50CharactersLong => Error.Validation(nameof(LanguageNativeNameMustBeMaximum50CharactersLong)); - public static Error OriginalReleaseYearMustBeBetween1And9999 => Error.Validation(nameof(OriginalReleaseYearMustBeBetween1And9999)); - public static Error ReReleaseYearMustBeBetween1And9999 => Error.Validation(nameof(ReReleaseYearMustBeBetween1And9999)); - public static Error ReReleaseYearCannotBeEarlierThanOriginalReleaseYear => Error.Validation(nameof(ReReleaseYearCannotBeEarlierThanOriginalReleaseYear)); - public static Error CountryCodeMustBe2CharactersLong => Error.Validation(nameof(CountryCodeMustBe2CharactersLong)); - public static Error ReleaseVersionMustBeMaximum50CharactersLong => Error.Validation(nameof(ReleaseVersionMustBeMaximum50CharactersLong)); - public static Error OriginalReleaseDateAndYearMustMatch => Error.Validation(nameof(OriginalReleaseDateAndYearMustMatch)); - public static Error ReReleaseDateAndYearMustMatch => Error.Validation(nameof(ReReleaseDateAndYearMustMatch)); - public static Error ReReleaseDateCannotBeEarlierThanOriginalReleaseDate => Error.Validation(nameof(ReReleaseDateCannotBeEarlierThanOriginalReleaseDate)); - public static Error ReleaseInfoCannotBeNull => Error.Validation(nameof(ReleaseInfoCannotBeNull)); - public static Error RatingValueMustBePositive => Error.Validation(nameof(RatingValueMustBePositive)); - public static Error RatingMaxValueMustBePositive => Error.Validation(nameof(RatingMaxValueMustBePositive)); - public static Error RatingValueCannotBeGreaterThanMaxValue => Error.Validation(nameof(RatingValueCannotBeGreaterThanMaxValue)); - public static Error RatingVoteCountMustBePositive => Error.Validation(nameof(RatingVoteCountMustBePositive)); - public static Error RatingsListCannotBeNull => Error.Validation(nameof(RatingsListCannotBeNull)); - public static Error InvalidIsoCode => Error.Validation(nameof(InvalidIsoCode)); + public static Error MetadataCannotBeNull => Error.Validation(description: nameof(MetadataCannotBeNull)); + public static Error TitleCannotBeEmpty => Error.Validation(description: nameof(TitleCannotBeEmpty)); + public static Error TitleMustBeMaximum255CharactersLong => Error.Validation(description: nameof(TitleMustBeMaximum255CharactersLong)); + public static Error OriginalTitleMustBeMaximum255CharactersLong => Error.Validation(description: nameof(OriginalTitleMustBeMaximum255CharactersLong)); + public static Error DescriptionMustBeMaximum2000CharactersLong => Error.Validation(description: nameof(DescriptionMustBeMaximum2000CharactersLong)); + public static Error GenresListCannotBeNull => Error.Validation(description: nameof(GenresListCannotBeNull)); + public static Error GenreNameCannotBeEmpty => Error.Validation(description: nameof(GenreNameCannotBeEmpty)); + public static Error GenreNameMustBeMaximum50CharactersLong => Error.Validation(description: nameof(GenreNameMustBeMaximum50CharactersLong)); + public static Error TagsListCannotBeNull => Error.Validation(description: nameof(TagsListCannotBeNull)); + public static Error TagNameCannotBeEmpty => Error.Validation(description: nameof(TagNameCannotBeEmpty)); + public static Error TagNameMustBeMaximum50CharactersLong => Error.Validation(description: nameof(TagNameMustBeMaximum50CharactersLong)); + public static Error LanguageCodeCannotBeEmpty => Error.Validation(description: nameof(LanguageCodeCannotBeEmpty)); + public static Error LanguageNameCannotBeEmpty => Error.Validation(description: nameof(LanguageNameCannotBeEmpty)); + public static Error LanguageCodeMustBe2CharactersLong => Error.Validation(description: nameof(LanguageCodeMustBe2CharactersLong)); + public static Error LanguageNameMustBeMaximum50CharactersLong => Error.Validation(description: nameof(LanguageNameMustBeMaximum50CharactersLong)); + public static Error LanguageNativeNameMustBeMaximum50CharactersLong => Error.Validation(description: nameof(LanguageNativeNameMustBeMaximum50CharactersLong)); + public static Error OriginalReleaseYearMustBeBetween1And9999 => Error.Validation(description: nameof(OriginalReleaseYearMustBeBetween1And9999)); + public static Error ReReleaseYearMustBeBetween1And9999 => Error.Validation(description: nameof(ReReleaseYearMustBeBetween1And9999)); + public static Error ReReleaseYearCannotBeEarlierThanOriginalReleaseYear => Error.Validation(description: nameof(ReReleaseYearCannotBeEarlierThanOriginalReleaseYear)); + public static Error CountryCodeMustBe2CharactersLong => Error.Validation(description: nameof(CountryCodeMustBe2CharactersLong)); + public static Error ReleaseVersionMustBeMaximum50CharactersLong => Error.Validation(description: nameof(ReleaseVersionMustBeMaximum50CharactersLong)); + public static Error OriginalReleaseDateAndYearMustMatch => Error.Validation(description: nameof(OriginalReleaseDateAndYearMustMatch)); + public static Error ReReleaseDateAndYearMustMatch => Error.Validation(description: nameof(ReReleaseDateAndYearMustMatch)); + public static Error ReReleaseDateCannotBeEarlierThanOriginalReleaseDate => Error.Validation(description: nameof(ReReleaseDateCannotBeEarlierThanOriginalReleaseDate)); + public static Error ReleaseInfoCannotBeNull => Error.Validation(description: nameof(ReleaseInfoCannotBeNull)); + public static Error RatingValueMustBePositive => Error.Validation(description: nameof(RatingValueMustBePositive)); + public static Error RatingMaxValueMustBePositive => Error.Validation(description: nameof(RatingMaxValueMustBePositive)); + public static Error RatingValueCannotBeGreaterThanMaxValue => Error.Validation(description: nameof(RatingValueCannotBeGreaterThanMaxValue)); + public static Error RatingVoteCountMustBePositive => Error.Validation(description: nameof(RatingVoteCountMustBePositive)); + public static Error RatingsListCannotBeNull => Error.Validation(description: nameof(RatingsListCannotBeNull)); + public static Error InvalidIsoCode => Error.Validation(description: nameof(InvalidIsoCode)); } } diff --git a/src/Lumina.Domain/Common/Errors/Errors.Permission.cs b/src/Lumina.Domain/Common/Errors/Errors.Permission.cs index 8b929a38..4bdc449b 100644 --- a/src/Lumina.Domain/Common/Errors/Errors.Permission.cs +++ b/src/Lumina.Domain/Common/Errors/Errors.Permission.cs @@ -11,6 +11,6 @@ public static partial class Errors { public static class Permission { - public static Error UnauthorizedAccess => Error.Failure(nameof(UnauthorizedAccess)); + public static Error UnauthorizedAccess => Error.Failure(description: nameof(UnauthorizedAccess)); } } diff --git a/src/Lumina.Domain/Common/Errors/Errors.Thumbnails.cs b/src/Lumina.Domain/Common/Errors/Errors.Thumbnails.cs index 235ffb31..8d9ee829 100644 --- a/src/Lumina.Domain/Common/Errors/Errors.Thumbnails.cs +++ b/src/Lumina.Domain/Common/Errors/Errors.Thumbnails.cs @@ -11,7 +11,7 @@ public static partial class Errors { public static class Thumbnails { - public static Error NoThumbnail => Error.Failure(nameof(NoThumbnail)); - public static Error ImageQaulityMustBeBetweenZeroAndOneHundred => Error.Validation(nameof(ImageQaulityMustBeBetweenZeroAndOneHundred)); + public static Error NoThumbnail => Error.Failure(description: nameof(NoThumbnail)); + public static Error ImageQaulityMustBeBetweenZeroAndOneHundred => Error.Validation(description: nameof(ImageQaulityMustBeBetweenZeroAndOneHundred)); } } diff --git a/src/Lumina.Domain/Common/Errors/Errors.WrittenContent.cs b/src/Lumina.Domain/Common/Errors/Errors.WrittenContent.cs index fc2dc493..418ddd61 100644 --- a/src/Lumina.Domain/Common/Errors/Errors.WrittenContent.cs +++ b/src/Lumina.Domain/Common/Errors/Errors.WrittenContent.cs @@ -11,29 +11,29 @@ public static partial class Errors { public static class WrittenContent { - public static Error BookAlreadyExists => Error.Conflict(nameof(BookAlreadyExists)); - public static Error IsbnValueCannotBeEmpty => Error.Validation(nameof(IsbnValueCannotBeEmpty)); - public static Error IsbnListCannotBeNull => Error.Validation(nameof(IsbnListCannotBeNull)); - public static Error InvalidIsbn10Format => Error.Validation(nameof(InvalidIsbn10Format)); - public static Error InvalidIsbn13Format => Error.Validation(nameof(InvalidIsbn13Format)); - public static Error UnknownIsbnFormat => Error.Unexpected(nameof(UnknownIsbnFormat)); - public static Error TheBookIsAlreadyInTheSeries => Error.Forbidden(nameof(TheBookIsAlreadyInTheSeries)); - public static Error TheBookIsNotInTheSeries => Error.Forbidden(nameof(TheBookIsNotInTheSeries)); - public static Error AsinMustBe10CharactersLong => Error.Validation(nameof(AsinMustBe10CharactersLong)); - public static Error GoodreadsIdMustBeNumeric => Error.Validation(nameof(GoodreadsIdMustBeNumeric)); - public static Error InvalidLccnFormat => Error.Validation(nameof(InvalidLccnFormat)); - public static Error InvalidOclcFormat => Error.Validation(nameof(InvalidOclcFormat)); - public static Error InvalidOpenLibraryId => Error.Validation(nameof(InvalidOpenLibraryId)); - public static Error LibraryThingIdMustBeMaximum50CharactersLong => Error.Validation(nameof(LibraryThingIdMustBeMaximum50CharactersLong)); - public static Error GoogleBooksIdMustBe12CharactersLong => Error.Validation(nameof(GoogleBooksIdMustBe12CharactersLong)); - public static Error InvalidGoogleBooksIdFormat => Error.Validation(nameof(InvalidGoogleBooksIdFormat)); - public static Error BarnesAndNoblesIdMustBe10CharactersLong => Error.Validation(nameof(BarnesAndNoblesIdMustBe10CharactersLong)); - public static Error InvalidBarnesAndNoblesIdFormat => Error.Validation(nameof(InvalidBarnesAndNoblesIdFormat)); - public static Error InvalidAppleBooksIdFormat => Error.Validation(nameof(InvalidAppleBooksIdFormat)); - public static Error PublisherMustBeMaximum100CharactersLong => Error.Validation(nameof(PublisherMustBeMaximum100CharactersLong)); - public static Error PageCountMustBeGreaterThanZero => Error.Validation(nameof(PageCountMustBeGreaterThanZero)); - public static Error UnknownBookFormat => Error.Validation(nameof(UnknownBookFormat)); - public static Error EditionMustBeMaximum50CharactersLong => Error.Validation(nameof(EditionMustBeMaximum50CharactersLong)); - public static Error VolumeNumberMustBeGreaterThanZero => Error.Validation(nameof(VolumeNumberMustBeGreaterThanZero)); + public static Error BookAlreadyExists => Error.Conflict(description: nameof(BookAlreadyExists)); + public static Error IsbnValueCannotBeEmpty => Error.Validation(description: nameof(IsbnValueCannotBeEmpty)); + public static Error IsbnListCannotBeNull => Error.Validation(description: nameof(IsbnListCannotBeNull)); + public static Error InvalidIsbn10Format => Error.Validation(description: nameof(InvalidIsbn10Format)); + public static Error InvalidIsbn13Format => Error.Validation(description: nameof(InvalidIsbn13Format)); + public static Error UnknownIsbnFormat => Error.Unexpected(description: nameof(UnknownIsbnFormat)); + public static Error TheBookIsAlreadyInTheSeries => Error.Forbidden(description: nameof(TheBookIsAlreadyInTheSeries)); + public static Error TheBookIsNotInTheSeries => Error.Forbidden(description: nameof(TheBookIsNotInTheSeries)); + public static Error AsinMustBe10CharactersLong => Error.Validation(description: nameof(AsinMustBe10CharactersLong)); + public static Error GoodreadsIdMustBeNumeric => Error.Validation(description: nameof(GoodreadsIdMustBeNumeric)); + public static Error InvalidLccnFormat => Error.Validation(description: nameof(InvalidLccnFormat)); + public static Error InvalidOclcFormat => Error.Validation(description: nameof(InvalidOclcFormat)); + public static Error InvalidOpenLibraryId => Error.Validation(description: nameof(InvalidOpenLibraryId)); + public static Error LibraryThingIdMustBeMaximum50CharactersLong => Error.Validation(description: nameof(LibraryThingIdMustBeMaximum50CharactersLong)); + public static Error GoogleBooksIdMustBe12CharactersLong => Error.Validation(description: nameof(GoogleBooksIdMustBe12CharactersLong)); + public static Error InvalidGoogleBooksIdFormat => Error.Validation(description: nameof(InvalidGoogleBooksIdFormat)); + public static Error BarnesAndNoblesIdMustBe10CharactersLong => Error.Validation(description: nameof(BarnesAndNoblesIdMustBe10CharactersLong)); + public static Error InvalidBarnesAndNoblesIdFormat => Error.Validation(description: nameof(InvalidBarnesAndNoblesIdFormat)); + public static Error InvalidAppleBooksIdFormat => Error.Validation(description: nameof(InvalidAppleBooksIdFormat)); + public static Error PublisherMustBeMaximum100CharactersLong => Error.Validation(description: nameof(PublisherMustBeMaximum100CharactersLong)); + public static Error PageCountMustBeGreaterThanZero => Error.Validation(description: nameof(PageCountMustBeGreaterThanZero)); + public static Error UnknownBookFormat => Error.Validation(description: nameof(UnknownBookFormat)); + public static Error EditionMustBeMaximum50CharactersLong => Error.Validation(description: nameof(EditionMustBeMaximum50CharactersLong)); + public static Error VolumeNumberMustBeGreaterThanZero => Error.Validation(description: nameof(VolumeNumberMustBeGreaterThanZero)); } } diff --git a/src/Lumina.Domain/Common/Models/Core/AggregateRoot.cs b/src/Lumina.Domain/Common/Models/Core/AggregateRoot.cs index 37ff7de2..97a54a34 100644 --- a/src/Lumina.Domain/Common/Models/Core/AggregateRoot.cs +++ b/src/Lumina.Domain/Common/Models/Core/AggregateRoot.cs @@ -1,4 +1,4 @@ -namespace Lumina.Domain.Common.Models.Core; +namespace Lumina.Domain.Common.Models.Core; /// /// Base class for all domain Aggregate Roots. @@ -15,7 +15,6 @@ public abstract class AggregateRoot : Entity where TId : notnull Id = id; } -#pragma warning disable CS8618 /// /// Initializes a new instance of the class. /// @@ -23,5 +22,4 @@ public abstract class AggregateRoot : Entity where TId : notnull { } -#pragma warning restore CS8618 -} \ No newline at end of file +} diff --git a/src/Lumina.Domain/Common/ValueObjects/Metadata/BaseMetadata.cs b/src/Lumina.Domain/Common/ValueObjects/Metadata/BaseMetadata.cs index 585f5453..bc17e1b2 100644 --- a/src/Lumina.Domain/Common/ValueObjects/Metadata/BaseMetadata.cs +++ b/src/Lumina.Domain/Common/ValueObjects/Metadata/BaseMetadata.cs @@ -23,12 +23,12 @@ public abstract class BaseMetadata : ValueObject public string Title { get; private set; } /// - /// Gets the original title of the media item. + /// Gets the original title of the media item, if applicable. /// public Optional OriginalTitle { get; private set; } /// - /// Gets the optional description of the media item. + /// Gets the optional description of the media item, if applicable. /// public Optional Description { get; private set; } @@ -38,12 +38,12 @@ public abstract class BaseMetadata : ValueObject public ReleaseInfo ReleaseInfo { get; private set; } /// - /// Gets the optional language of the media item. + /// Gets the optional language of the media item, if applicable. /// public Optional Language { get; private set; } /// - /// Gets the optional original language of the media item. + /// Gets the optional original language of the media item, if applicable. /// public Optional OriginalLanguage { get; private set; } @@ -61,13 +61,13 @@ public abstract class BaseMetadata : ValueObject /// Initializes a new instance of the class. /// /// The title of the element to which this metadata object belongs to. - /// The optional original title of the element to which this metadata object belongs to. - /// The optional description of the element to which this metadata object belongs to. + /// The optional original title of the element to which this metadata object belongs to, if applicable. + /// The optional description of the element to which this metadata object belongs to, if applicable. /// The optional release information of the media item. /// The list of genres of the element to which this metadata object belongs to. /// The list of tags of the element to which this metadata object belongs to. - /// The optional language of the element to which this metadata object belongs to. - /// The optional original language of the element to which this metadata object belongs to. + /// The optional language of the element to which this metadata object belongs to, if applicable. + /// The optional original language of the element to which this metadata object belongs to, if applicable. /// Thrown when the value is protected BaseMetadata( string title, @@ -103,4 +103,4 @@ public abstract class BaseMetadata : ValueObject yield return Language; yield return OriginalLanguage; } -} \ No newline at end of file +} diff --git a/src/Lumina.Domain/Common/ValueObjects/Metadata/Genre.cs b/src/Lumina.Domain/Common/ValueObjects/Metadata/Genre.cs index 0e093b1f..e076d9bf 100644 --- a/src/Lumina.Domain/Common/ValueObjects/Metadata/Genre.cs +++ b/src/Lumina.Domain/Common/ValueObjects/Metadata/Genre.cs @@ -34,7 +34,7 @@ public class Genre : ValueObject /// /// An containing either a successfully created , or an error message. /// - public static ErrorOr Create(string name) + public static ErrorOr Create(string? name) { if (string.IsNullOrWhiteSpace(name)) return Errors.Errors.Metadata.GenreNameCannotBeEmpty; diff --git a/src/Lumina.Domain/Common/ValueObjects/Metadata/LanguageInfo.cs b/src/Lumina.Domain/Common/ValueObjects/Metadata/LanguageInfo.cs index 05204fc0..2e7ea688 100644 --- a/src/Lumina.Domain/Common/ValueObjects/Metadata/LanguageInfo.cs +++ b/src/Lumina.Domain/Common/ValueObjects/Metadata/LanguageInfo.cs @@ -51,7 +51,7 @@ public class LanguageInfo : ValueObject /// /// An containing either a successfully created , or an error message. /// - public static ErrorOr Create(string languageCode, string languageName, Optional nativeName) + public static ErrorOr Create(string? languageCode, string? languageName, Optional nativeName) { if (string.IsNullOrWhiteSpace(languageCode)) return Errors.Errors.Metadata.LanguageCodeCannotBeEmpty; diff --git a/src/Lumina.Domain/Common/ValueObjects/Metadata/Tag.cs b/src/Lumina.Domain/Common/ValueObjects/Metadata/Tag.cs index 5af8c978..ffb3f0cb 100644 --- a/src/Lumina.Domain/Common/ValueObjects/Metadata/Tag.cs +++ b/src/Lumina.Domain/Common/ValueObjects/Metadata/Tag.cs @@ -34,7 +34,7 @@ public class Tag : ValueObject /// /// An containing either a successfully created , or an error message. /// - public static ErrorOr Create(string name) + public static ErrorOr Create(string? name) { if (string.IsNullOrWhiteSpace(name)) return Errors.Errors.Metadata.TagNameCannotBeEmpty; diff --git a/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Entities/Directory.cs b/src/Lumina.Domain/Core/Aggregates/FileSystemManagement/FileSystemManagementAggregate/Entities/Directory.cs similarity index 95% rename from src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Entities/Directory.cs rename to src/Lumina.Domain/Core/Aggregates/FileSystemManagement/FileSystemManagementAggregate/Entities/Directory.cs index 26c725e2..8f3ab9b8 100644 --- a/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Entities/Directory.cs +++ b/src/Lumina.Domain/Core/Aggregates/FileSystemManagement/FileSystemManagementAggregate/Entities/Directory.cs @@ -2,13 +2,14 @@ using ErrorOr; using Lumina.Contracts.Enums.FileSystem; using Lumina.Domain.Common.Primitives; -using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.ValueObjects; +using Lumina.Domain.Core.Aggregates.FileSystemManagement.FileSystemManagementAggregate; +using Lumina.Domain.Core.Aggregates.FileSystemManagement.FileSystemManagementAggregate.ValueObjects; using System; using System.Collections.Generic; using System.Diagnostics; #endregion -namespace Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.Entities; +namespace Lumina.Domain.Core.Aggregates.FileSystemManagement.FileSystemManagementAggregate.Entities; /// /// Entity representing a file system directory. diff --git a/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Entities/File.cs b/src/Lumina.Domain/Core/Aggregates/FileSystemManagement/FileSystemManagementAggregate/Entities/File.cs similarity index 94% rename from src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Entities/File.cs rename to src/Lumina.Domain/Core/Aggregates/FileSystemManagement/FileSystemManagementAggregate/Entities/File.cs index b2a01e1f..9daa0b0d 100644 --- a/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Entities/File.cs +++ b/src/Lumina.Domain/Core/Aggregates/FileSystemManagement/FileSystemManagementAggregate/Entities/File.cs @@ -3,12 +3,13 @@ using ErrorOr; using Lumina.Contracts.Enums.FileSystem; using Lumina.Domain.Common.Errors; using Lumina.Domain.Common.Primitives; -using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.ValueObjects; +using Lumina.Domain.Core.Aggregates.FileSystemManagement.FileSystemManagementAggregate; +using Lumina.Domain.Core.Aggregates.FileSystemManagement.FileSystemManagementAggregate.ValueObjects; using System; using System.Diagnostics; #endregion -namespace Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.Entities; +namespace Lumina.Domain.Core.Aggregates.FileSystemManagement.FileSystemManagementAggregate.Entities; /// /// Entity representing a file system file. @@ -144,7 +145,7 @@ public sealed class File : FileSystemItem public ErrorOr Rename(string newName) { if (string.IsNullOrWhiteSpace(newName)) - return Errors.FileManagement.NameCannotBeEmpty; + return Errors.FileSystemManagement.NameCannotBeEmpty; Name = newName; return Result.Updated; } diff --git a/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Entities/UnixRootItem.cs b/src/Lumina.Domain/Core/Aggregates/FileSystemManagement/FileSystemManagementAggregate/Entities/UnixRootItem.cs similarity index 82% rename from src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Entities/UnixRootItem.cs rename to src/Lumina.Domain/Core/Aggregates/FileSystemManagement/FileSystemManagementAggregate/Entities/UnixRootItem.cs index 80760fa3..36a2367a 100644 --- a/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Entities/UnixRootItem.cs +++ b/src/Lumina.Domain/Core/Aggregates/FileSystemManagement/FileSystemManagementAggregate/Entities/UnixRootItem.cs @@ -1,12 +1,12 @@ #region ========================================================================= USING ===================================================================================== using ErrorOr; using Lumina.Contracts.Enums.FileSystem; -using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.ValueObjects; +using Lumina.Domain.Core.Aggregates.FileSystemManagement.FileSystemManagementAggregate.ValueObjects; using System.Collections.Generic; using System.Diagnostics; #endregion -namespace Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.Entities; +namespace Lumina.Domain.Core.Aggregates.FileSystemManagement.FileSystemManagementAggregate.Entities; /// /// Entity representing a file system root item on Unix platforms. @@ -38,15 +38,12 @@ public sealed class UnixRootItem : FileSystemItem /// /// An containing either a successfully created , or an error message. /// - public static ErrorOr Create( - FileSystemItemStatus status = FileSystemItemStatus.Accessible) + public static ErrorOr Create(FileSystemItemStatus status = FileSystemItemStatus.Accessible) { ErrorOr createPathResult = FileSystemPathId.Create(PATH); if (createPathResult.IsError) return createPathResult.Errors; - UnixRootItem newRoot = new( - createPathResult.Value, - PATH); + UnixRootItem newRoot = new(createPathResult.Value, PATH); ErrorOr setStatusResult = newRoot.SetStatus(status); if (setStatusResult.IsError) return setStatusResult.Errors; diff --git a/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Entities/WindowsRootItem.cs b/src/Lumina.Domain/Core/Aggregates/FileSystemManagement/FileSystemManagementAggregate/Entities/WindowsRootItem.cs similarity index 92% rename from src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Entities/WindowsRootItem.cs rename to src/Lumina.Domain/Core/Aggregates/FileSystemManagement/FileSystemManagementAggregate/Entities/WindowsRootItem.cs index ac825e1b..0f3d5773 100644 --- a/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Entities/WindowsRootItem.cs +++ b/src/Lumina.Domain/Core/Aggregates/FileSystemManagement/FileSystemManagementAggregate/Entities/WindowsRootItem.cs @@ -1,12 +1,13 @@ #region ========================================================================= USING ===================================================================================== using ErrorOr; using Lumina.Contracts.Enums.FileSystem; -using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.ValueObjects; +using Lumina.Domain.Core.Aggregates.FileSystemManagement.FileSystemManagementAggregate; +using Lumina.Domain.Core.Aggregates.FileSystemManagement.FileSystemManagementAggregate.ValueObjects; using System.Collections.Generic; using System.Diagnostics; #endregion -namespace Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.Entities; +namespace Lumina.Domain.Core.Aggregates.FileSystemManagement.FileSystemManagementAggregate.Entities; /// /// Entity representing a file system root item on Windows platforms. diff --git a/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/FileSystemItem.cs b/src/Lumina.Domain/Core/Aggregates/FileSystemManagement/FileSystemManagementAggregate/FileSystemItem.cs similarity index 84% rename from src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/FileSystemItem.cs rename to src/Lumina.Domain/Core/Aggregates/FileSystemManagement/FileSystemManagementAggregate/FileSystemItem.cs index 3602546a..ccc44123 100644 --- a/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/FileSystemItem.cs +++ b/src/Lumina.Domain/Core/Aggregates/FileSystemManagement/FileSystemManagementAggregate/FileSystemItem.cs @@ -1,14 +1,14 @@ -#region ========================================================================= USING ===================================================================================== +#region ========================================================================= USING ===================================================================================== using ErrorOr; using Lumina.Contracts.Enums.FileSystem; using Lumina.Domain.Common.Errors; using Lumina.Domain.Common.Models.Core; using Lumina.Domain.Common.Primitives; -using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.ValueObjects; +using Lumina.Domain.Core.Aggregates.FileSystemManagement.FileSystemManagementAggregate.ValueObjects; using System.Diagnostics; #endregion -namespace Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate; +namespace Lumina.Domain.Core.Aggregates.FileSystemManagement.FileSystemManagementAggregate; /// /// Entity representing a generic file system element. @@ -69,7 +69,7 @@ public abstract class FileSystemItem : AggregateRoot if (parent is not null) Parent = parent; else - return Errors.FileManagement.ParentNodeCannotBeNull; + return Errors.FileSystemManagement.ParentNodeCannotBeNull; return Result.Updated; } -} \ No newline at end of file +} diff --git a/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Services/DirectoryProviderService.cs b/src/Lumina.Domain/Core/Aggregates/FileSystemManagement/FileSystemManagementAggregate/Services/DirectoryProviderService.cs similarity index 96% rename from src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Services/DirectoryProviderService.cs rename to src/Lumina.Domain/Core/Aggregates/FileSystemManagement/FileSystemManagementAggregate/Services/DirectoryProviderService.cs index ae6580b2..413e74c6 100644 --- a/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Services/DirectoryProviderService.cs +++ b/src/Lumina.Domain/Core/Aggregates/FileSystemManagement/FileSystemManagementAggregate/Services/DirectoryProviderService.cs @@ -3,7 +3,7 @@ using ErrorOr; using Lumina.Contracts.Enums.FileSystem; using Lumina.Domain.Common.Errors; using Lumina.Domain.Common.Primitives; -using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.ValueObjects; +using Lumina.Domain.Core.Aggregates.FileSystemManagement.FileSystemManagementAggregate.ValueObjects; using System; using System.Collections.Generic; using System.IO; @@ -11,7 +11,7 @@ using System.IO.Abstractions; using System.Linq; #endregion -namespace Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.Services; +namespace Lumina.Domain.Core.Aggregates.FileSystemManagement.FileSystemManagementAggregate.Services; /// /// Directory provider for local file systems. @@ -146,7 +146,7 @@ internal class DirectoryProviderService : IDirectoryProviderService { // check if the source directory exists if (!_fileSystem.Directory.Exists(sourcePath.Path)) - return Errors.FileManagement.DirectoryNotFound; + return Errors.FileSystemManagement.DirectoryNotFound; string destPath = CreateUniqueDirectoryPath(destinationPath.Path); try { @@ -179,7 +179,7 @@ internal class DirectoryProviderService : IDirectoryProviderService } catch { - return Errors.FileManagement.DirectoryCopyError; + return Errors.FileSystemManagement.DirectoryCopyError; } } @@ -209,7 +209,7 @@ internal class DirectoryProviderService : IDirectoryProviderService { // check if the source directory exists if (!_fileSystem.Directory.Exists(sourcePath.Path)) - return Errors.FileManagement.DirectoryNotFound; + return Errors.FileSystemManagement.DirectoryNotFound; try { // if the destination directory does not exist, perform a simple move @@ -221,7 +221,7 @@ internal class DirectoryProviderService : IDirectoryProviderService } catch { - return Errors.FileManagement.DirectoryMoveError; + return Errors.FileSystemManagement.DirectoryMoveError; } } @@ -247,7 +247,6 @@ internal class DirectoryProviderService : IDirectoryProviderService _fileSystem.File.Delete(destFilePath); _fileSystem.File.Move(sourceFilePath, destFilePath); } - // otherwise, skip the file } else _fileSystem.File.Move(sourceFilePath, destFilePath); // move the file if it does not exist in the destination directory @@ -298,10 +297,10 @@ internal class DirectoryProviderService : IDirectoryProviderService return newDirectoryPathResult.Value; } else - return Errors.FileManagement.InvalidPath; + return Errors.FileSystemManagement.InvalidPath; } else - return Errors.FileManagement.InvalidPath; + return Errors.FileSystemManagement.InvalidPath; } /// diff --git a/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Services/DirectoryService.cs b/src/Lumina.Domain/Core/Aggregates/FileSystemManagement/FileSystemManagementAggregate/Services/DirectoryService.cs similarity index 96% rename from src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Services/DirectoryService.cs rename to src/Lumina.Domain/Core/Aggregates/FileSystemManagement/FileSystemManagementAggregate/Services/DirectoryService.cs index 4069d457..10852ed4 100644 --- a/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Services/DirectoryService.cs +++ b/src/Lumina.Domain/Core/Aggregates/FileSystemManagement/FileSystemManagementAggregate/Services/DirectoryService.cs @@ -3,15 +3,15 @@ using ErrorOr; using Lumina.Contracts.Enums.FileSystem; using Lumina.Domain.Common.Errors; using Lumina.Domain.Common.Primitives; -using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.Entities; -using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.Strategies.Environment; -using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.Strategies.Platform; -using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.ValueObjects; +using Lumina.Domain.Core.Aggregates.FileSystemManagement.FileSystemManagementAggregate.Entities; +using Lumina.Domain.Core.Aggregates.FileSystemManagement.FileSystemManagementAggregate.Strategies.Environment; +using Lumina.Domain.Core.Aggregates.FileSystemManagement.FileSystemManagementAggregate.Strategies.Platform; +using Lumina.Domain.Core.Aggregates.FileSystemManagement.FileSystemManagementAggregate.ValueObjects; using System; using System.Collections.Generic; #endregion -namespace Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.Services; +namespace Lumina.Domain.Core.Aggregates.FileSystemManagement.FileSystemManagementAggregate.Services; /// /// Service for handling directories. @@ -131,7 +131,7 @@ public class DirectoryService : IDirectoryService if (directoryExists.IsError) return directoryExists.Errors; else if (directoryExists.Value == true) - return Errors.FileManagement.DirectoryAlreadyExists; + return Errors.FileSystemManagement.DirectoryAlreadyExists; else { // create the new directory @@ -195,7 +195,7 @@ public class DirectoryService : IDirectoryService if (directoryExists.IsError) return directoryExists.Errors; else if (directoryExists.Value == false) - return Errors.FileManagement.DirectoryNotFound; + return Errors.FileSystemManagement.DirectoryNotFound; else { // copy the directory @@ -241,7 +241,7 @@ public class DirectoryService : IDirectoryService if (directoryExists.IsError) return directoryExists.Errors; else if (directoryExists.Value == false) - return Errors.FileManagement.DirectoryNotFound; + return Errors.FileSystemManagement.DirectoryNotFound; else { // move the directory @@ -281,7 +281,7 @@ public class DirectoryService : IDirectoryService if (directoryExists.IsError) return directoryExists.Errors; else if (directoryExists.Value == true) - return Errors.FileManagement.DirectoryAlreadyExists; + return Errors.FileSystemManagement.DirectoryAlreadyExists; else { // rename the directory diff --git a/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Services/DriveService.cs b/src/Lumina.Domain/Core/Aggregates/FileSystemManagement/FileSystemManagementAggregate/Services/DriveService.cs similarity index 88% rename from src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Services/DriveService.cs rename to src/Lumina.Domain/Core/Aggregates/FileSystemManagement/FileSystemManagementAggregate/Services/DriveService.cs index 07fcfa43..ec5c9fe1 100644 --- a/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Services/DriveService.cs +++ b/src/Lumina.Domain/Core/Aggregates/FileSystemManagement/FileSystemManagementAggregate/Services/DriveService.cs @@ -1,14 +1,15 @@ #region ========================================================================= USING ===================================================================================== using ErrorOr; using Lumina.Contracts.Enums.FileSystem; -using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.Entities; -using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.Strategies.Platform; +using Lumina.Domain.Core.Aggregates.FileSystemManagement.FileSystemManagementAggregate; +using Lumina.Domain.Core.Aggregates.FileSystemManagement.FileSystemManagementAggregate.Entities; +using Lumina.Domain.Core.Aggregates.FileSystemManagement.FileSystemManagementAggregate.Strategies.Platform; using System.Collections.Generic; using System.IO.Abstractions; using System.Linq; #endregion -namespace Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.Services; +namespace Lumina.Domain.Core.Aggregates.FileSystemManagement.FileSystemManagementAggregate.Services; /// /// Service for handling drives. diff --git a/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Services/FileProviderService.cs b/src/Lumina.Domain/Core/Aggregates/FileSystemManagement/FileSystemManagementAggregate/Services/FileProviderService.cs similarity index 94% rename from src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Services/FileProviderService.cs rename to src/Lumina.Domain/Core/Aggregates/FileSystemManagement/FileSystemManagementAggregate/Services/FileProviderService.cs index 82746207..876699d8 100644 --- a/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Services/FileProviderService.cs +++ b/src/Lumina.Domain/Core/Aggregates/FileSystemManagement/FileSystemManagementAggregate/Services/FileProviderService.cs @@ -3,7 +3,7 @@ using ErrorOr; using Lumina.Contracts.Enums.FileSystem; using Lumina.Domain.Common.Errors; using Lumina.Domain.Common.Primitives; -using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.ValueObjects; +using Lumina.Domain.Core.Aggregates.FileSystemManagement.FileSystemManagementAggregate.ValueObjects; using System; using System.Collections.Generic; using System.IO; @@ -11,7 +11,7 @@ using System.IO.Abstractions; using System.Linq; #endregion -namespace Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.Services; +namespace Lumina.Domain.Core.Aggregates.FileSystemManagement.FileSystemManagementAggregate.Services; /// /// File provider for local file systems. @@ -153,19 +153,17 @@ internal class FileProviderService : IFileProviderService { // check if the source file exists if (!_fileSystem.File.Exists(sourceFilePath.Path)) - return Errors.FileManagement.FileNotFound; + return Errors.FileSystemManagement.FileNotFound; string fileName = _fileSystem.Path.GetFileName(sourceFilePath.Path); string destinationFilePath = _fileSystem.Path.Combine(destinationDirectoryPath.Path, fileName); // when copying a file to the same location, just copy it with a new name if (_fileSystem.Path.GetDirectoryName(sourceFilePath.Path) == destinationDirectoryPath.Path) destinationFilePath = CreateUniqueFilePath(destinationFilePath); else - { // check if there is already a file with the same name as the copied file, in the destination directory if (_fileSystem.File.Exists(destinationFilePath)) - if (!overrideExisting) - return Errors.FileManagement.FileAlreadyExists; - } + if (!overrideExisting) + return Errors.FileSystemManagement.FileAlreadyExists; try { _fileSystem.File.Copy(sourceFilePath.Path, destinationFilePath, overrideExisting); // copy the file @@ -174,7 +172,7 @@ internal class FileProviderService : IFileProviderService } catch { - return Errors.FileManagement.FileCopyError; + return Errors.FileSystemManagement.FileCopyError; } } @@ -208,7 +206,7 @@ internal class FileProviderService : IFileProviderService { // check if the source file exists if (!_fileSystem.File.Exists(sourceFilePath.Path)) - return Errors.FileManagement.FileNotFound; + return Errors.FileSystemManagement.FileNotFound; try { string fileName = _fileSystem.Path.GetFileName(sourceFilePath.Path); @@ -217,17 +215,15 @@ internal class FileProviderService : IFileProviderService if (!_fileSystem.File.Exists(destinationFilePath)) _fileSystem.File.Move(sourceFilePath.Path, destinationFilePath); else - { if (overrideExisting) - _fileSystem.File.Move(sourceFilePath.Path, destinationFilePath, overrideExisting); - else - return Errors.FileManagement.FileAlreadyExists; - } + _fileSystem.File.Move(sourceFilePath.Path, destinationFilePath, overrideExisting); + else + return Errors.FileSystemManagement.FileAlreadyExists; return FileSystemPathId.Create(destinationFilePath); } catch { - return Errors.FileManagement.FileMoveError; + return Errors.FileSystemManagement.FileMoveError; } } @@ -260,10 +256,10 @@ internal class FileProviderService : IFileProviderService return newFilePathResult; } else - return Errors.FileManagement.InvalidPath; + return Errors.FileSystemManagement.InvalidPath; } else - return Errors.FileManagement.CannotNavigateUp; + return Errors.FileSystemManagement.CannotNavigateUp; } /// diff --git a/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Services/FileService.cs b/src/Lumina.Domain/Core/Aggregates/FileSystemManagement/FileSystemManagementAggregate/Services/FileService.cs similarity index 95% rename from src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Services/FileService.cs rename to src/Lumina.Domain/Core/Aggregates/FileSystemManagement/FileSystemManagementAggregate/Services/FileService.cs index 444f5dd5..8640251b 100644 --- a/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Services/FileService.cs +++ b/src/Lumina.Domain/Core/Aggregates/FileSystemManagement/FileSystemManagementAggregate/Services/FileService.cs @@ -3,15 +3,15 @@ using ErrorOr; using Lumina.Contracts.Enums.FileSystem; using Lumina.Domain.Common.Errors; using Lumina.Domain.Common.Primitives; -using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.Entities; -using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.Strategies.Environment; -using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.Strategies.Platform; -using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.ValueObjects; +using Lumina.Domain.Core.Aggregates.FileSystemManagement.FileSystemManagementAggregate.Entities; +using Lumina.Domain.Core.Aggregates.FileSystemManagement.FileSystemManagementAggregate.Strategies.Environment; +using Lumina.Domain.Core.Aggregates.FileSystemManagement.FileSystemManagementAggregate.Strategies.Platform; +using Lumina.Domain.Core.Aggregates.FileSystemManagement.FileSystemManagementAggregate.ValueObjects; using System; using System.Collections.Generic; #endregion -namespace Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.Services; +namespace Lumina.Domain.Core.Aggregates.FileSystemManagement.FileSystemManagementAggregate.Services; /// /// Service for handling file system files. @@ -113,7 +113,7 @@ public class FileService : IFileService public ErrorOr CopyFile(string sourceFilePath, string destinationDirectoryPath, bool? overrideExisting) { if (string.IsNullOrWhiteSpace(destinationDirectoryPath)) - return Errors.FileManagement.InvalidPath; + return Errors.FileSystemManagement.InvalidPath; // make sure the paths are in the expected format if (!destinationDirectoryPath.EndsWith(_platformContext.PathStrategy.PathSeparator)) destinationDirectoryPath += _platformContext.PathStrategy.PathSeparator; @@ -139,7 +139,7 @@ public class FileService : IFileService if (fileExists.IsError) return fileExists.Errors; else if (fileExists.Value == false) - return Errors.FileManagement.FileNotFound; + return Errors.FileSystemManagement.FileNotFound; else { // copy the file @@ -179,7 +179,7 @@ public class FileService : IFileService public ErrorOr MoveFile(string sourceFilePath, string destinationDirectoryPath, bool? overrideExisting) { if (string.IsNullOrWhiteSpace(destinationDirectoryPath)) - return Errors.FileManagement.InvalidPath; + return Errors.FileSystemManagement.InvalidPath; // make sure the paths are in the expected format if (!destinationDirectoryPath.EndsWith(_platformContext.PathStrategy.PathSeparator)) destinationDirectoryPath += _platformContext.PathStrategy.PathSeparator; @@ -205,7 +205,7 @@ public class FileService : IFileService if (fileExists.IsError) return fileExists.Errors; else if (fileExists.Value == false) - return Errors.FileManagement.FileNotFound; + return Errors.FileSystemManagement.FileNotFound; else { // move the file @@ -265,7 +265,7 @@ public class FileService : IFileService if (fileExists.IsError) return fileExists.Errors; else if (fileExists.Value == true) - return Errors.FileManagement.FileAlreadyExists; + return Errors.FileSystemManagement.FileAlreadyExists; else { // rename the file diff --git a/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Services/FileSystemPermissionsService.cs b/src/Lumina.Domain/Core/Aggregates/FileSystemManagement/FileSystemManagementAggregate/Services/FileSystemPermissionsService.cs similarity index 89% rename from src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Services/FileSystemPermissionsService.cs rename to src/Lumina.Domain/Core/Aggregates/FileSystemManagement/FileSystemManagementAggregate/Services/FileSystemPermissionsService.cs index 0a24ba0f..18a07bad 100644 --- a/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Services/FileSystemPermissionsService.cs +++ b/src/Lumina.Domain/Core/Aggregates/FileSystemManagement/FileSystemManagementAggregate/Services/FileSystemPermissionsService.cs @@ -1,7 +1,7 @@ #region ========================================================================= USING ===================================================================================== using Lumina.Contracts.Enums.FileSystem; -using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.Strategies.Platform; -using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.ValueObjects; +using Lumina.Domain.Core.Aggregates.FileSystemManagement.FileSystemManagementAggregate.Strategies.Platform; +using Lumina.Domain.Core.Aggregates.FileSystemManagement.FileSystemManagementAggregate.ValueObjects; using Mono.Unix; using Mono.Unix.Native; using System; @@ -11,7 +11,7 @@ using System.Security.AccessControl; using System.Security.Principal; #endregion -namespace Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.Services; +namespace Lumina.Domain.Core.Aggregates.FileSystemManagement.FileSystemManagementAggregate.Services; /// /// Service for file system permissions. @@ -129,31 +129,27 @@ internal class FileSystemPermissionsService : IFileSystemPermissionsService // T return HasAccess(FileSystemRights.Modify, parentDirectory, false); } else - { if (HasAccess(rights, path, isFile)) + try { - try + switch (accessMode) { - switch (accessMode) - { - case FileAccessMode.ReadProperties: - // just accessing file info for properties, without opening it - FileSystemInfo fileSystemInfo = isFile ? new FileInfo(path) : new DirectoryInfo(path); - _ = fileSystemInfo.CreationTime; // trigger potential access denial - break; - case FileAccessMode.ReadContents: - using (FileStream stream = new(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite)) - stream.Close(); - break; - } - return true; - } - catch - { - return false; + case FileAccessMode.ReadProperties: + // just accessing file info for properties, without opening it + FileSystemInfo fileSystemInfo = isFile ? new FileInfo(path) : new DirectoryInfo(path); + _ = fileSystemInfo.CreationTime; // trigger potential access denial + break; + case FileAccessMode.ReadContents: + using (FileStream stream = new(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite)) + stream.Close(); + break; } + return true; + } + catch + { + return false; } - } return false; } @@ -186,16 +182,12 @@ internal class FileSystemPermissionsService : IFileSystemPermissionsService // T acl = directoryInfo.GetAccessControl().GetAccessRules(true, true, typeof(SecurityIdentifier)); } foreach (FileSystemAccessRule accessRule in acl) - { // Check if the current rule applies to the current user or the groups they belong to if (identity?.User?.Equals(accessRule.IdentityReference) == true || principal.IsInRole((SecurityIdentifier)accessRule.IdentityReference)) - { if (accessRule.AccessControlType.Equals(AccessControlType.Deny) && (accessRule.FileSystemRights & rights) == rights) return false; // if there's a deny rule that matches the specified rights, return false immediately else if (accessRule.AccessControlType.Equals(AccessControlType.Allow) && (accessRule.FileSystemRights & rights) == rights) allowAccess = true; - } - } } catch diff --git a/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Services/FileTypeService.cs b/src/Lumina.Domain/Core/Aggregates/FileSystemManagement/FileSystemManagementAggregate/Services/FileTypeService.cs similarity index 96% rename from src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Services/FileTypeService.cs rename to src/Lumina.Domain/Core/Aggregates/FileSystemManagement/FileSystemManagementAggregate/Services/FileTypeService.cs index c942ddf9..53ea48b7 100644 --- a/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Services/FileTypeService.cs +++ b/src/Lumina.Domain/Core/Aggregates/FileSystemManagement/FileSystemManagementAggregate/Services/FileTypeService.cs @@ -3,8 +3,8 @@ using ErrorOr; using Lumina.Contracts.Enums.FileSystem; using Lumina.Contracts.Enums.PhotoLibrary; using Lumina.Domain.Common.Errors; -using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.Entities; -using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.ValueObjects; +using Lumina.Domain.Core.Aggregates.FileSystemManagement.FileSystemManagementAggregate.Entities; +using Lumina.Domain.Core.Aggregates.FileSystemManagement.FileSystemManagementAggregate.ValueObjects; using System; using System.IO.Abstractions; using System.Linq; @@ -13,7 +13,7 @@ using System.Threading; using System.Threading.Tasks; #endregion -namespace Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.Services; +namespace Lumina.Domain.Core.Aggregates.FileSystemManagement.FileSystemManagementAggregate.Services; /// /// Class defining methods for handling file-related operations. diff --git a/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Services/IDirectoryProviderService.cs b/src/Lumina.Domain/Core/Aggregates/FileSystemManagement/FileSystemManagementAggregate/Services/IDirectoryProviderService.cs similarity index 93% rename from src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Services/IDirectoryProviderService.cs rename to src/Lumina.Domain/Core/Aggregates/FileSystemManagement/FileSystemManagementAggregate/Services/IDirectoryProviderService.cs index 3e176716..a7476bcc 100644 --- a/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Services/IDirectoryProviderService.cs +++ b/src/Lumina.Domain/Core/Aggregates/FileSystemManagement/FileSystemManagementAggregate/Services/IDirectoryProviderService.cs @@ -1,12 +1,12 @@ -#region ========================================================================= USING ===================================================================================== +#region ========================================================================= USING ===================================================================================== using ErrorOr; using Lumina.Domain.Common.Primitives; -using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.ValueObjects; +using Lumina.Domain.Core.Aggregates.FileSystemManagement.FileSystemManagementAggregate.ValueObjects; using System; using System.Collections.Generic; #endregion -namespace Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.Services; +namespace Lumina.Domain.Core.Aggregates.FileSystemManagement.FileSystemManagementAggregate.Services; /// /// Interface defining the directory provider service. diff --git a/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Services/IDirectoryService.cs b/src/Lumina.Domain/Core/Aggregates/FileSystemManagement/FileSystemManagementAggregate/Services/IDirectoryService.cs similarity index 90% rename from src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Services/IDirectoryService.cs rename to src/Lumina.Domain/Core/Aggregates/FileSystemManagement/FileSystemManagementAggregate/Services/IDirectoryService.cs index b2c84dc6..64f6a1e5 100644 --- a/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Services/IDirectoryService.cs +++ b/src/Lumina.Domain/Core/Aggregates/FileSystemManagement/FileSystemManagementAggregate/Services/IDirectoryService.cs @@ -1,11 +1,11 @@ -#region ========================================================================= USING ===================================================================================== +#region ========================================================================= USING ===================================================================================== using ErrorOr; -using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.Entities; -using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.ValueObjects; +using Lumina.Domain.Core.Aggregates.FileSystemManagement.FileSystemManagementAggregate.Entities; +using Lumina.Domain.Core.Aggregates.FileSystemManagement.FileSystemManagementAggregate.ValueObjects; using System.Collections.Generic; #endregion -namespace Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.Services; +namespace Lumina.Domain.Core.Aggregates.FileSystemManagement.FileSystemManagementAggregate.Services; /// /// Interface for the service for handling directories. diff --git a/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Services/IDriveService.cs b/src/Lumina.Domain/Core/Aggregates/FileSystemManagement/FileSystemManagementAggregate/Services/IDriveService.cs similarity index 53% rename from src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Services/IDriveService.cs rename to src/Lumina.Domain/Core/Aggregates/FileSystemManagement/FileSystemManagementAggregate/Services/IDriveService.cs index 240a5860..3a77b1c0 100644 --- a/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Services/IDriveService.cs +++ b/src/Lumina.Domain/Core/Aggregates/FileSystemManagement/FileSystemManagementAggregate/Services/IDriveService.cs @@ -1,9 +1,10 @@ -#region ========================================================================= USING ===================================================================================== +#region ========================================================================= USING ===================================================================================== using ErrorOr; +using Lumina.Domain.Core.Aggregates.FileSystemManagement.FileSystemManagementAggregate; using System.Collections.Generic; #endregion -namespace Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.Services; +namespace Lumina.Domain.Core.Aggregates.FileSystemManagement.FileSystemManagementAggregate.Services; /// /// Interface for the service for handling drives. @@ -15,4 +16,4 @@ public interface IDriveService /// /// An containing either a collection of drives or an error. ErrorOr> GetDrives(); -} \ No newline at end of file +} diff --git a/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Services/IFileProviderService.cs b/src/Lumina.Domain/Core/Aggregates/FileSystemManagement/FileSystemManagementAggregate/Services/IFileProviderService.cs similarity index 93% rename from src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Services/IFileProviderService.cs rename to src/Lumina.Domain/Core/Aggregates/FileSystemManagement/FileSystemManagementAggregate/Services/IFileProviderService.cs index 6dce33bd..c1449643 100644 --- a/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Services/IFileProviderService.cs +++ b/src/Lumina.Domain/Core/Aggregates/FileSystemManagement/FileSystemManagementAggregate/Services/IFileProviderService.cs @@ -1,12 +1,12 @@ -#region ========================================================================= USING ===================================================================================== +#region ========================================================================= USING ===================================================================================== using ErrorOr; using Lumina.Domain.Common.Primitives; -using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.ValueObjects; +using Lumina.Domain.Core.Aggregates.FileSystemManagement.FileSystemManagementAggregate.ValueObjects; using System; using System.Collections.Generic; #endregion -namespace Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.Services; +namespace Lumina.Domain.Core.Aggregates.FileSystemManagement.FileSystemManagementAggregate.Services; /// /// Interface defining the file provider service. @@ -95,4 +95,4 @@ public interface IFileProviderService /// The path of the file to be deleted. /// An containing either the result of deleting a file, or an error. ErrorOr DeleteFile(FileSystemPathId path); -} \ No newline at end of file +} diff --git a/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Services/IFileService.cs b/src/Lumina.Domain/Core/Aggregates/FileSystemManagement/FileSystemManagementAggregate/Services/IFileService.cs similarity index 88% rename from src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Services/IFileService.cs rename to src/Lumina.Domain/Core/Aggregates/FileSystemManagement/FileSystemManagementAggregate/Services/IFileService.cs index 3d72da06..07a87f0d 100644 --- a/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Services/IFileService.cs +++ b/src/Lumina.Domain/Core/Aggregates/FileSystemManagement/FileSystemManagementAggregate/Services/IFileService.cs @@ -1,11 +1,11 @@ -#region ========================================================================= USING ===================================================================================== +#region ========================================================================= USING ===================================================================================== using ErrorOr; -using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.Entities; -using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.ValueObjects; +using Lumina.Domain.Core.Aggregates.FileSystemManagement.FileSystemManagementAggregate.Entities; +using Lumina.Domain.Core.Aggregates.FileSystemManagement.FileSystemManagementAggregate.ValueObjects; using System.Collections.Generic; #endregion -namespace Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.Services; +namespace Lumina.Domain.Core.Aggregates.FileSystemManagement.FileSystemManagementAggregate.Services; /// /// Interface for the service for handling file system files. @@ -68,4 +68,4 @@ public interface IFileService /// String representation of the file path. /// An containing either the result of deleting a file, or an error. ErrorOr DeleteFile(string path); -} \ No newline at end of file +} diff --git a/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Services/IFileSystemPermissionsService.cs b/src/Lumina.Domain/Core/Aggregates/FileSystemManagement/FileSystemManagementAggregate/Services/IFileSystemPermissionsService.cs similarity index 66% rename from src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Services/IFileSystemPermissionsService.cs rename to src/Lumina.Domain/Core/Aggregates/FileSystemManagement/FileSystemManagementAggregate/Services/IFileSystemPermissionsService.cs index 1eb76f9c..26530f5b 100644 --- a/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Services/IFileSystemPermissionsService.cs +++ b/src/Lumina.Domain/Core/Aggregates/FileSystemManagement/FileSystemManagementAggregate/Services/IFileSystemPermissionsService.cs @@ -1,9 +1,9 @@ -#region ========================================================================= USING ===================================================================================== +#region ========================================================================= USING ===================================================================================== using Lumina.Contracts.Enums.FileSystem; -using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.ValueObjects; +using Lumina.Domain.Core.Aggregates.FileSystemManagement.FileSystemManagementAggregate.ValueObjects; #endregion -namespace Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.Services; +namespace Lumina.Domain.Core.Aggregates.FileSystemManagement.FileSystemManagementAggregate.Services; /// /// Interface for file system permission service. @@ -18,4 +18,4 @@ public interface IFileSystemPermissionsService /// Indicates whether the path represents a file or directory. /// , if can be accessed, otherwise. bool CanAccessPath(FileSystemPathId path, FileAccessMode accessMode, bool isFile = true); -} \ No newline at end of file +} diff --git a/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Services/IFileTypeService.cs b/src/Lumina.Domain/Core/Aggregates/FileSystemManagement/FileSystemManagementAggregate/Services/IFileTypeService.cs similarity index 83% rename from src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Services/IFileTypeService.cs rename to src/Lumina.Domain/Core/Aggregates/FileSystemManagement/FileSystemManagementAggregate/Services/IFileTypeService.cs index 19285cff..e84854b7 100644 --- a/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Services/IFileTypeService.cs +++ b/src/Lumina.Domain/Core/Aggregates/FileSystemManagement/FileSystemManagementAggregate/Services/IFileTypeService.cs @@ -1,13 +1,13 @@ #region ========================================================================= USING ===================================================================================== using ErrorOr; using Lumina.Contracts.Enums.PhotoLibrary; -using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.Entities; -using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.ValueObjects; +using Lumina.Domain.Core.Aggregates.FileSystemManagement.FileSystemManagementAggregate.Entities; +using Lumina.Domain.Core.Aggregates.FileSystemManagement.FileSystemManagementAggregate.ValueObjects; using System.Threading; using System.Threading.Tasks; #endregion -namespace Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.Services; +namespace Lumina.Domain.Core.Aggregates.FileSystemManagement.FileSystemManagementAggregate.Services; /// /// Interface defining methods for handling file-related operations based on different sources. diff --git a/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Services/IPathService.cs b/src/Lumina.Domain/Core/Aggregates/FileSystemManagement/FileSystemManagementAggregate/Services/IPathService.cs similarity index 93% rename from src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Services/IPathService.cs rename to src/Lumina.Domain/Core/Aggregates/FileSystemManagement/FileSystemManagementAggregate/Services/IPathService.cs index ddfaa94f..5dfa2634 100644 --- a/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Services/IPathService.cs +++ b/src/Lumina.Domain/Core/Aggregates/FileSystemManagement/FileSystemManagementAggregate/Services/IPathService.cs @@ -1,10 +1,10 @@ #region ========================================================================= USING ===================================================================================== using ErrorOr; -using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.ValueObjects; +using Lumina.Domain.Core.Aggregates.FileSystemManagement.FileSystemManagementAggregate.ValueObjects; using System.Collections.Generic; #endregion -namespace Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.Services; +namespace Lumina.Domain.Core.Aggregates.FileSystemManagement.FileSystemManagementAggregate.Services; /// /// Interface for the service for handling file system paths. diff --git a/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Services/IThumbnailService.cs b/src/Lumina.Domain/Core/Aggregates/FileSystemManagement/FileSystemManagementAggregate/Services/IThumbnailService.cs similarity index 89% rename from src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Services/IThumbnailService.cs rename to src/Lumina.Domain/Core/Aggregates/FileSystemManagement/FileSystemManagementAggregate/Services/IThumbnailService.cs index c48225d8..146679df 100644 --- a/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Services/IThumbnailService.cs +++ b/src/Lumina.Domain/Core/Aggregates/FileSystemManagement/FileSystemManagementAggregate/Services/IThumbnailService.cs @@ -1,11 +1,11 @@ #region ========================================================================= USING ===================================================================================== using ErrorOr; -using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.ValueObjects; +using Lumina.Domain.Core.Aggregates.FileSystemManagement.FileSystemManagementAggregate.ValueObjects; using System.Threading; using System.Threading.Tasks; #endregion -namespace Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.Services; +namespace Lumina.Domain.Core.Aggregates.FileSystemManagement.FileSystemManagementAggregate.Services; /// /// Interface for the service for handling thumbnails. diff --git a/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Services/PathService.cs b/src/Lumina.Domain/Core/Aggregates/FileSystemManagement/FileSystemManagementAggregate/Services/PathService.cs similarity index 93% rename from src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Services/PathService.cs rename to src/Lumina.Domain/Core/Aggregates/FileSystemManagement/FileSystemManagementAggregate/Services/PathService.cs index 5ba130dd..c414f624 100644 --- a/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Services/PathService.cs +++ b/src/Lumina.Domain/Core/Aggregates/FileSystemManagement/FileSystemManagementAggregate/Services/PathService.cs @@ -1,12 +1,12 @@ #region ========================================================================= USING ===================================================================================== using ErrorOr; using Lumina.Domain.Common.Errors; -using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.Strategies.Platform; -using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.ValueObjects; +using Lumina.Domain.Core.Aggregates.FileSystemManagement.FileSystemManagementAggregate.Strategies.Platform; +using Lumina.Domain.Core.Aggregates.FileSystemManagement.FileSystemManagementAggregate.ValueObjects; using System.Collections.Generic; #endregion -namespace Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.Services; +namespace Lumina.Domain.Core.Aggregates.FileSystemManagement.FileSystemManagementAggregate.Services; /// /// Service defining methods for handling path-related operations. @@ -65,7 +65,7 @@ public class PathService : IPathService public ErrorOr CombinePath(string path, string name) { if (string.IsNullOrWhiteSpace(path) || string.IsNullOrWhiteSpace(name)) - return Errors.FileManagement.InvalidPath; + return Errors.FileSystemManagement.InvalidPath; ErrorOr newPathResult = FileSystemPathId.Create(path); if (newPathResult.IsError) return newPathResult.Errors; diff --git a/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Services/ThumbnailService.cs b/src/Lumina.Domain/Core/Aggregates/FileSystemManagement/FileSystemManagementAggregate/Services/ThumbnailService.cs similarity index 96% rename from src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Services/ThumbnailService.cs rename to src/Lumina.Domain/Core/Aggregates/FileSystemManagement/FileSystemManagementAggregate/Services/ThumbnailService.cs index 5e3bcee3..3c1e0513 100644 --- a/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Services/ThumbnailService.cs +++ b/src/Lumina.Domain/Core/Aggregates/FileSystemManagement/FileSystemManagementAggregate/Services/ThumbnailService.cs @@ -2,8 +2,8 @@ using ErrorOr; using Lumina.Contracts.Enums.PhotoLibrary; using Lumina.Domain.Common.Errors; -using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.Strategies.Environment; -using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.ValueObjects; +using Lumina.Domain.Core.Aggregates.FileSystemManagement.FileSystemManagementAggregate.Strategies.Environment; +using Lumina.Domain.Core.Aggregates.FileSystemManagement.FileSystemManagementAggregate.ValueObjects; using SixLabors.ImageSharp; using SixLabors.ImageSharp.Formats.Jpeg; using SixLabors.ImageSharp.Formats.Png; @@ -14,7 +14,7 @@ using System.Threading; using System.Threading.Tasks; #endregion -namespace Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.Services; +namespace Lumina.Domain.Core.Aggregates.FileSystemManagement.FileSystemManagementAggregate.Services; /// /// Service for handling thumbnails. diff --git a/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Strategies/Environment/EnvironmentContext.cs b/src/Lumina.Domain/Core/Aggregates/FileSystemManagement/FileSystemManagementAggregate/Strategies/Environment/EnvironmentContext.cs similarity index 88% rename from src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Strategies/Environment/EnvironmentContext.cs rename to src/Lumina.Domain/Core/Aggregates/FileSystemManagement/FileSystemManagementAggregate/Strategies/Environment/EnvironmentContext.cs index 850fc5be..bed48210 100644 --- a/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Strategies/Environment/EnvironmentContext.cs +++ b/src/Lumina.Domain/Core/Aggregates/FileSystemManagement/FileSystemManagementAggregate/Strategies/Environment/EnvironmentContext.cs @@ -1,8 +1,8 @@ #region ========================================================================= USING ===================================================================================== -using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.Services; +using Lumina.Domain.Core.Aggregates.FileSystemManagement.FileSystemManagementAggregate.Services; #endregion -namespace Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.Strategies.Environment; +namespace Lumina.Domain.Core.Aggregates.FileSystemManagement.FileSystemManagementAggregate.Strategies.Environment; /// /// Represents the context for environment-specific operations and services. diff --git a/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Strategies/Environment/IEnvironmentContext.cs b/src/Lumina.Domain/Core/Aggregates/FileSystemManagement/FileSystemManagementAggregate/Strategies/Environment/IEnvironmentContext.cs similarity index 64% rename from src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Strategies/Environment/IEnvironmentContext.cs rename to src/Lumina.Domain/Core/Aggregates/FileSystemManagement/FileSystemManagementAggregate/Strategies/Environment/IEnvironmentContext.cs index 4abd5b78..d25b1328 100644 --- a/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Strategies/Environment/IEnvironmentContext.cs +++ b/src/Lumina.Domain/Core/Aggregates/FileSystemManagement/FileSystemManagementAggregate/Strategies/Environment/IEnvironmentContext.cs @@ -1,8 +1,8 @@ -#region ========================================================================= USING ===================================================================================== -using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.Services; +#region ========================================================================= USING ===================================================================================== +using Lumina.Domain.Core.Aggregates.FileSystemManagement.FileSystemManagementAggregate.Services; #endregion -namespace Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.Strategies.Environment; +namespace Lumina.Domain.Core.Aggregates.FileSystemManagement.FileSystemManagementAggregate.Strategies.Environment; /// /// Interface for defining the contract of an environment-specific context, encapsulating all platform-specific services and strategies. @@ -23,4 +23,4 @@ public interface IEnvironmentContext /// Gets the service for providing file system directories. /// IDirectoryProviderService DirectoryProviderService { get; } -} \ No newline at end of file +} diff --git a/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Strategies/Path/IPathStrategy.cs b/src/Lumina.Domain/Core/Aggregates/FileSystemManagement/FileSystemManagementAggregate/Strategies/Path/IPathStrategy.cs similarity index 93% rename from src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Strategies/Path/IPathStrategy.cs rename to src/Lumina.Domain/Core/Aggregates/FileSystemManagement/FileSystemManagementAggregate/Strategies/Path/IPathStrategy.cs index fd41d7d9..bc0d03a8 100644 --- a/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Strategies/Path/IPathStrategy.cs +++ b/src/Lumina.Domain/Core/Aggregates/FileSystemManagement/FileSystemManagementAggregate/Strategies/Path/IPathStrategy.cs @@ -1,10 +1,10 @@ #region ========================================================================= USING ===================================================================================== using ErrorOr; -using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.ValueObjects; +using Lumina.Domain.Core.Aggregates.FileSystemManagement.FileSystemManagementAggregate.ValueObjects; using System.Collections.Generic; #endregion -namespace Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.Strategies.Path; +namespace Lumina.Domain.Core.Aggregates.FileSystemManagement.FileSystemManagementAggregate.Strategies.Path; /// /// Interface defining methods for handling path-related operations based on different platforms. diff --git a/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Strategies/Path/IUnixPathStrategy.cs b/src/Lumina.Domain/Core/Aggregates/FileSystemManagement/FileSystemManagementAggregate/Strategies/Path/IUnixPathStrategy.cs similarity index 60% rename from src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Strategies/Path/IUnixPathStrategy.cs rename to src/Lumina.Domain/Core/Aggregates/FileSystemManagement/FileSystemManagementAggregate/Strategies/Path/IUnixPathStrategy.cs index 74feabe5..cd926f8f 100644 --- a/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Strategies/Path/IUnixPathStrategy.cs +++ b/src/Lumina.Domain/Core/Aggregates/FileSystemManagement/FileSystemManagementAggregate/Strategies/Path/IUnixPathStrategy.cs @@ -1,8 +1,8 @@ -namespace Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.Strategies.Path; +namespace Lumina.Domain.Core.Aggregates.FileSystemManagement.FileSystemManagementAggregate.Strategies.Path; /// /// Interface defining methods for handling path-related operations on UNIX platforms. /// public interface IUnixPathStrategy : IPathStrategy { -} \ No newline at end of file +} diff --git a/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Strategies/Path/IWindowsPathStrategy.cs b/src/Lumina.Domain/Core/Aggregates/FileSystemManagement/FileSystemManagementAggregate/Strategies/Path/IWindowsPathStrategy.cs similarity index 61% rename from src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Strategies/Path/IWindowsPathStrategy.cs rename to src/Lumina.Domain/Core/Aggregates/FileSystemManagement/FileSystemManagementAggregate/Strategies/Path/IWindowsPathStrategy.cs index 47599331..569ea3e6 100644 --- a/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Strategies/Path/IWindowsPathStrategy.cs +++ b/src/Lumina.Domain/Core/Aggregates/FileSystemManagement/FileSystemManagementAggregate/Strategies/Path/IWindowsPathStrategy.cs @@ -1,8 +1,8 @@ -namespace Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.Strategies.Path; +namespace Lumina.Domain.Core.Aggregates.FileSystemManagement.FileSystemManagementAggregate.Strategies.Path; /// /// Interface defining methods for handling path-related operations on Windows platforms. /// public interface IWindowsPathStrategy : IPathStrategy { -} \ No newline at end of file +} diff --git a/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Strategies/Path/UnixPathStrategy.cs b/src/Lumina.Domain/Core/Aggregates/FileSystemManagement/FileSystemManagementAggregate/Strategies/Path/UnixPathStrategy.cs similarity index 93% rename from src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Strategies/Path/UnixPathStrategy.cs rename to src/Lumina.Domain/Core/Aggregates/FileSystemManagement/FileSystemManagementAggregate/Strategies/Path/UnixPathStrategy.cs index cc858a6c..16a1752b 100644 --- a/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Strategies/Path/UnixPathStrategy.cs +++ b/src/Lumina.Domain/Core/Aggregates/FileSystemManagement/FileSystemManagementAggregate/Strategies/Path/UnixPathStrategy.cs @@ -1,7 +1,7 @@ #region ========================================================================= USING ===================================================================================== using ErrorOr; using Lumina.Domain.Common.Errors; -using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.ValueObjects; +using Lumina.Domain.Core.Aggregates.FileSystemManagement.FileSystemManagementAggregate.ValueObjects; using System; using System.Collections.Generic; using System.IO; @@ -10,7 +10,7 @@ using System.Linq; using System.Text.RegularExpressions; #endregion -namespace Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.Strategies.Path; +namespace Lumina.Domain.Core.Aggregates.FileSystemManagement.FileSystemManagementAggregate.Strategies.Path; /// /// Service defining methods for handling path-related operations on UNIX platforms. @@ -83,7 +83,7 @@ public class UnixPathStrategy : IUnixPathStrategy public ErrorOr CombinePath(FileSystemPathId path, string name) { if (string.IsNullOrWhiteSpace(name)) - return Errors.FileManagement.NameCannotBeEmpty; + return Errors.FileSystemManagement.NameCannotBeEmpty; // trim any directory separator characters from the end of the path string subpath = path.Path.TrimEnd(PathSeparator); // if the name begins with a directory separator, remove it @@ -101,7 +101,7 @@ public class UnixPathStrategy : IUnixPathStrategy { // if path starts with anything other than '/', it's considered relative and invalid for this parser if (!path.Path.StartsWith(PathSeparator)) - return Errors.FileManagement.InvalidPath; + return Errors.FileSystemManagement.InvalidPath; // get the path segments List splitSegments = [.. path.Path.Split(new[] { PathSeparator }, StringSplitOptions.RemoveEmptyEntries)]; IEnumerable> segmentsResults = splitSegments.Select((segment, index) => @@ -128,7 +128,7 @@ public class UnixPathStrategy : IUnixPathStrategy { // validation: ensure the path is not null or empty if (!IsValidPath(path)) - return Errors.FileManagement.InvalidPath; + return Errors.FileSystemManagement.InvalidPath; // trim trailing slash for consistent processing string tempPath = path.Path; if (tempPath.EndsWith('/')) @@ -137,7 +137,7 @@ public class UnixPathStrategy : IUnixPathStrategy int lastIndex = tempPath.LastIndexOf(PathSeparator); // if there's no slash found (shouldn't happen due to previous steps), or if we are at the root level after trimming, return error if (lastIndex < 0) - return Errors.FileManagement.CannotNavigateUp; + return Errors.FileSystemManagement.CannotNavigateUp; // return the path up to the last slash, or, if there's only the root slash, return that one instead ErrorOr newPathResult = FileSystemPathId.Create(lastIndex > 0 ? tempPath[..lastIndex] : tempPath[..1]); if (newPathResult.IsError) @@ -162,11 +162,11 @@ public class UnixPathStrategy : IUnixPathStrategy public ErrorOr GetPathRoot(FileSystemPathId path) { if (!IsValidPath(path)) - return Errors.FileManagement.InvalidPath; + return Errors.FileSystemManagement.InvalidPath; // On Unix-like systems, the root is always "/" if (path.Path.StartsWith(PathSeparator)) return PathSegment.Create(PathSeparator.ToString(), isDirectory: false, isDrive: true); - return Errors.FileManagement.InvalidPath; + return Errors.FileSystemManagement.InvalidPath; } } diff --git a/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Strategies/Path/WindowsPathStrategy.cs b/src/Lumina.Domain/Core/Aggregates/FileSystemManagement/FileSystemManagementAggregate/Strategies/Path/WindowsPathStrategy.cs similarity index 89% rename from src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Strategies/Path/WindowsPathStrategy.cs rename to src/Lumina.Domain/Core/Aggregates/FileSystemManagement/FileSystemManagementAggregate/Strategies/Path/WindowsPathStrategy.cs index 8ab9d278..e153552d 100644 --- a/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Strategies/Path/WindowsPathStrategy.cs +++ b/src/Lumina.Domain/Core/Aggregates/FileSystemManagement/FileSystemManagementAggregate/Strategies/Path/WindowsPathStrategy.cs @@ -1,7 +1,7 @@ #region ========================================================================= USING ===================================================================================== using ErrorOr; using Lumina.Domain.Common.Errors; -using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.ValueObjects; +using Lumina.Domain.Core.Aggregates.FileSystemManagement.FileSystemManagementAggregate.ValueObjects; using System; using System.Collections.Generic; using System.IO; @@ -10,7 +10,7 @@ using System.Linq; using System.Text.RegularExpressions; #endregion -namespace Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.Strategies.Path; +namespace Lumina.Domain.Core.Aggregates.FileSystemManagement.FileSystemManagementAggregate.Strategies.Path; /// /// Service defining methods for handling path-related operations on Windows platforms. @@ -82,7 +82,7 @@ public class WindowsPathStrategy : IWindowsPathStrategy public ErrorOr CombinePath(FileSystemPathId path, string name) { if (name == null) - return Errors.FileManagement.NameCannotBeEmpty; + return Errors.FileSystemManagement.NameCannotBeEmpty; // trim any directory separator characters from the end of the path string subpath = path.Path.TrimEnd(PathSeparator); // if the name begins with a directory separator, remove it @@ -100,7 +100,7 @@ public class WindowsPathStrategy : IWindowsPathStrategy { // Windows paths usually start with a drive letter and colon, e.g., "C:", or "\\" (UNC paths) if (!(path.Path.StartsWith(@"\\") || (path.Path.Length >= 3 && char.IsLetter(path.Path[0]) && path.Path[1] == ':' && path.Path[2] == PathSeparator))) - return Errors.FileManagement.InvalidPath; + return Errors.FileSystemManagement.InvalidPath; IEnumerable> getPathSegmentsResults = GetPathSegments(); foreach (ErrorOr getPathSegmentsResult in getPathSegmentsResults) if (getPathSegmentsResult.IsError) @@ -153,7 +153,7 @@ public class WindowsPathStrategy : IWindowsPathStrategy { // validation: ensure the path is not null or empty if (!IsValidPath(path)) - return Errors.FileManagement.InvalidPath; + return Errors.FileSystemManagement.InvalidPath; // trim trailing backslash for consistent processing string tempPath = path.Path.TrimEnd(PathSeparator); // check for UNC path @@ -161,13 +161,13 @@ public class WindowsPathStrategy : IWindowsPathStrategy { string[] parts = tempPath.Split(PathSeparator, StringSplitOptions.RemoveEmptyEntries); if (parts.Length <= 2) - return Errors.FileManagement.CannotNavigateUp; + return Errors.FileSystemManagement.CannotNavigateUp; // if it's a single-level UNC path, return the UNC root if (parts.Length == 3) return ParsePath(FileSystemPathId.Create($@"\\{parts[0]}\{parts[1]}").Value); } // check for drive root (both with and without trailing backslash) else if ((tempPath.Length == 2 && tempPath[1] == ':') || (tempPath.Length == 3 && tempPath[1] == ':' && tempPath[2] == PathSeparator)) - return Errors.FileManagement.CannotNavigateUp; + return Errors.FileSystemManagement.CannotNavigateUp; // find the last occurrence of a backslash int lastIndex = tempPath.LastIndexOf(PathSeparator); // if there's no backslash found or it's at the root level, return the root @@ -198,14 +198,14 @@ public class WindowsPathStrategy : IWindowsPathStrategy public ErrorOr GetPathRoot(FileSystemPathId path) { if (!IsValidPath(path)) - return Errors.FileManagement.InvalidPath; + return Errors.FileSystemManagement.InvalidPath; // handle UNC paths (e.g., \\server\share\folder) if (path.Path.StartsWith(@"\\")) { // find the position of the second backslash (after \\server) int secondBackslash = path.Path.IndexOf('\\', 2); if (secondBackslash == -1) - return Errors.FileManagement.InvalidPath; // invalid UNC path, missing server name + return Errors.FileSystemManagement.InvalidPath; // invalid UNC path, missing server name // find the position of the third backslash (after \\server\share) int thirdBackslash = path.Path.IndexOf('\\', secondBackslash + 1); if (thirdBackslash == -1) @@ -214,15 +214,13 @@ public class WindowsPathStrategy : IWindowsPathStrategy return PathSegment.Create(path.Path[..thirdBackslash] + "\\", isDirectory: true, isDrive: false); } else // handle drive letter paths (e.g., C:\folder) - { - // check if the path starts with a drive letter followed by a colon (e.g., C:) - // path.Path.Length >= 2: Ensure the path is at least 2 characters long - // char.IsLetter(path.Path[0]): First character should be a letter - // path.Path[1] == ':': Second character should be a colon - if (path.Path.Length >= 2 && char.IsLetter(path.Path[0]) && path.Path[1] == ':') - return PathSegment.Create(path.Path[..2] + "\\", isDirectory: true, isDrive: true); // return the drive root (e.g., C:\) - } + // check if the path starts with a drive letter followed by a colon (e.g., C:) + // path.Path.Length >= 2: Ensure the path is at least 2 characters long + // char.IsLetter(path.Path[0]): First character should be a letter + // path.Path[1] == ':': Second character should be a colon + if (path.Path.Length >= 2 && char.IsLetter(path.Path[0]) && path.Path[1] == ':') + return PathSegment.Create(path.Path[..2] + "\\", isDirectory: true, isDrive: true); // return the drive root (e.g., C:\) // if we reach here, the path is neither a valid UNC path nor a valid drive path - return Errors.FileManagement.InvalidPath; + return Errors.FileSystemManagement.InvalidPath; } } diff --git a/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Strategies/Platform/IOperatingSystemInfo.cs b/src/Lumina.Domain/Core/Aggregates/FileSystemManagement/FileSystemManagementAggregate/Strategies/Platform/IOperatingSystemInfo.cs similarity index 87% rename from src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Strategies/Platform/IOperatingSystemInfo.cs rename to src/Lumina.Domain/Core/Aggregates/FileSystemManagement/FileSystemManagementAggregate/Strategies/Platform/IOperatingSystemInfo.cs index 4fe05f69..a095bcc8 100644 --- a/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Strategies/Platform/IOperatingSystemInfo.cs +++ b/src/Lumina.Domain/Core/Aggregates/FileSystemManagement/FileSystemManagementAggregate/Strategies/Platform/IOperatingSystemInfo.cs @@ -2,7 +2,7 @@ using System.Runtime.InteropServices; #endregion -namespace Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.Strategies.Platform; +namespace Lumina.Domain.Core.Aggregates.FileSystemManagement.FileSystemManagementAggregate.Strategies.Platform; /// /// Interface for checking the type of the current Operating System platform. diff --git a/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Strategies/Platform/IPlatformContext.cs b/src/Lumina.Domain/Core/Aggregates/FileSystemManagement/FileSystemManagementAggregate/Strategies/Platform/IPlatformContext.cs similarity index 54% rename from src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Strategies/Platform/IPlatformContext.cs rename to src/Lumina.Domain/Core/Aggregates/FileSystemManagement/FileSystemManagementAggregate/Strategies/Platform/IPlatformContext.cs index b285d2aa..494275e1 100644 --- a/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Strategies/Platform/IPlatformContext.cs +++ b/src/Lumina.Domain/Core/Aggregates/FileSystemManagement/FileSystemManagementAggregate/Strategies/Platform/IPlatformContext.cs @@ -1,9 +1,9 @@ -#region ========================================================================= USING ===================================================================================== +#region ========================================================================= USING ===================================================================================== using Lumina.Contracts.Enums.FileSystem; -using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.Strategies.Path; +using Lumina.Domain.Core.Aggregates.FileSystemManagement.FileSystemManagementAggregate.Strategies.Path; #endregion -namespace Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.Strategies.Platform; +namespace Lumina.Domain.Core.Aggregates.FileSystemManagement.FileSystemManagementAggregate.Strategies.Platform; /// /// Interface for defining the contract of a platform-specific context. @@ -19,4 +19,4 @@ public interface IPlatformContext /// Gets the path strategy for the current platform context. /// IPathStrategy PathStrategy { get; } -} \ No newline at end of file +} diff --git a/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Strategies/Platform/IPlatformContextFactory.cs b/src/Lumina.Domain/Core/Aggregates/FileSystemManagement/FileSystemManagementAggregate/Strategies/Platform/IPlatformContextFactory.cs similarity index 81% rename from src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Strategies/Platform/IPlatformContextFactory.cs rename to src/Lumina.Domain/Core/Aggregates/FileSystemManagement/FileSystemManagementAggregate/Strategies/Platform/IPlatformContextFactory.cs index 8ce72412..78fd59d1 100644 --- a/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Strategies/Platform/IPlatformContextFactory.cs +++ b/src/Lumina.Domain/Core/Aggregates/FileSystemManagement/FileSystemManagementAggregate/Strategies/Platform/IPlatformContextFactory.cs @@ -1,4 +1,4 @@ -namespace Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.Strategies.Platform; +namespace Lumina.Domain.Core.Aggregates.FileSystemManagement.FileSystemManagementAggregate.Strategies.Platform; /// /// Interface defining an factory for creating platform contexts. @@ -11,4 +11,4 @@ public interface IPlatformContextFactory /// The type of platform context to create. /// The created platform context. TIPlatformContext CreateStrategy() where TIPlatformContext : IPlatformContext; -} \ No newline at end of file +} diff --git a/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Strategies/Platform/IPlatformContextManager.cs b/src/Lumina.Domain/Core/Aggregates/FileSystemManagement/FileSystemManagementAggregate/Strategies/Platform/IPlatformContextManager.cs similarity index 70% rename from src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Strategies/Platform/IPlatformContextManager.cs rename to src/Lumina.Domain/Core/Aggregates/FileSystemManagement/FileSystemManagementAggregate/Strategies/Platform/IPlatformContextManager.cs index d29df76a..24d2480b 100644 --- a/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Strategies/Platform/IPlatformContextManager.cs +++ b/src/Lumina.Domain/Core/Aggregates/FileSystemManagement/FileSystemManagementAggregate/Strategies/Platform/IPlatformContextManager.cs @@ -1,9 +1,9 @@ -#region ========================================================================= USING ===================================================================================== +#region ========================================================================= USING ===================================================================================== using Lumina.Contracts.Enums.FileSystem; using System; #endregion -namespace Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.Strategies.Platform; +namespace Lumina.Domain.Core.Aggregates.FileSystemManagement.FileSystemManagementAggregate.Strategies.Platform; /// /// Interface for managing the platform context. @@ -22,4 +22,4 @@ public interface IPlatformContextManager /// The platform to be set. /// Thrown when an unsupported platform type is provided. void SetCurrentPlatform(PlatformType platformType); -} \ No newline at end of file +} diff --git a/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Strategies/Platform/IUnixPlatformContext.cs b/src/Lumina.Domain/Core/Aggregates/FileSystemManagement/FileSystemManagementAggregate/Strategies/Platform/IUnixPlatformContext.cs similarity index 57% rename from src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Strategies/Platform/IUnixPlatformContext.cs rename to src/Lumina.Domain/Core/Aggregates/FileSystemManagement/FileSystemManagementAggregate/Strategies/Platform/IUnixPlatformContext.cs index 3331f7e6..17f4eb04 100644 --- a/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Strategies/Platform/IUnixPlatformContext.cs +++ b/src/Lumina.Domain/Core/Aggregates/FileSystemManagement/FileSystemManagementAggregate/Strategies/Platform/IUnixPlatformContext.cs @@ -1,8 +1,8 @@ -namespace Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.Strategies.Platform; +namespace Lumina.Domain.Core.Aggregates.FileSystemManagement.FileSystemManagementAggregate.Strategies.Platform; /// /// Interface defining the platform context for UNIX platforms. /// public interface IUnixPlatformContext : IPlatformContext { -} \ No newline at end of file +} diff --git a/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Strategies/Platform/IWindowsPlatformContext.cs b/src/Lumina.Domain/Core/Aggregates/FileSystemManagement/FileSystemManagementAggregate/Strategies/Platform/IWindowsPlatformContext.cs similarity index 58% rename from src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Strategies/Platform/IWindowsPlatformContext.cs rename to src/Lumina.Domain/Core/Aggregates/FileSystemManagement/FileSystemManagementAggregate/Strategies/Platform/IWindowsPlatformContext.cs index de3e7239..f6ac7a9c 100644 --- a/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Strategies/Platform/IWindowsPlatformContext.cs +++ b/src/Lumina.Domain/Core/Aggregates/FileSystemManagement/FileSystemManagementAggregate/Strategies/Platform/IWindowsPlatformContext.cs @@ -1,8 +1,8 @@ -namespace Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.Strategies.Platform; +namespace Lumina.Domain.Core.Aggregates.FileSystemManagement.FileSystemManagementAggregate.Strategies.Platform; /// /// Interface defining the platform context for Windows platforms. /// internal interface IWindowsPlatformContext : IPlatformContext { -} \ No newline at end of file +} diff --git a/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Strategies/Platform/OperatingSystemInfo.cs b/src/Lumina.Domain/Core/Aggregates/FileSystemManagement/FileSystemManagementAggregate/Strategies/Platform/OperatingSystemInfo.cs similarity index 89% rename from src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Strategies/Platform/OperatingSystemInfo.cs rename to src/Lumina.Domain/Core/Aggregates/FileSystemManagement/FileSystemManagementAggregate/Strategies/Platform/OperatingSystemInfo.cs index 250af820..0d01186c 100644 --- a/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Strategies/Platform/OperatingSystemInfo.cs +++ b/src/Lumina.Domain/Core/Aggregates/FileSystemManagement/FileSystemManagementAggregate/Strategies/Platform/OperatingSystemInfo.cs @@ -3,7 +3,7 @@ using System.Diagnostics.CodeAnalysis; using System.Runtime.InteropServices; #endregion -namespace Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.Strategies.Platform; +namespace Lumina.Domain.Core.Aggregates.FileSystemManagement.FileSystemManagementAggregate.Strategies.Platform; /// /// Class for checking the type of the current Operating System platform. diff --git a/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Strategies/Platform/PlatformContextFactory.cs b/src/Lumina.Domain/Core/Aggregates/FileSystemManagement/FileSystemManagementAggregate/Strategies/Platform/PlatformContextFactory.cs similarity index 78% rename from src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Strategies/Platform/PlatformContextFactory.cs rename to src/Lumina.Domain/Core/Aggregates/FileSystemManagement/FileSystemManagementAggregate/Strategies/Platform/PlatformContextFactory.cs index 38620e2c..34137d85 100644 --- a/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Strategies/Platform/PlatformContextFactory.cs +++ b/src/Lumina.Domain/Core/Aggregates/FileSystemManagement/FileSystemManagementAggregate/Strategies/Platform/PlatformContextFactory.cs @@ -1,9 +1,9 @@ -#region ========================================================================= USING ===================================================================================== +#region ========================================================================= USING ===================================================================================== using Microsoft.Extensions.DependencyInjection; using System; #endregion -namespace Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.Strategies.Platform; +namespace Lumina.Domain.Core.Aggregates.FileSystemManagement.FileSystemManagementAggregate.Strategies.Platform; /// /// Defines a factory for creating platform contexts. @@ -30,4 +30,4 @@ public class PlatformContextFactory : IPlatformContextFactory { return _serviceProvider.GetRequiredService() ?? throw new ArgumentException(); } -} \ No newline at end of file +} diff --git a/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Strategies/Platform/PlatformContextManager.cs b/src/Lumina.Domain/Core/Aggregates/FileSystemManagement/FileSystemManagementAggregate/Strategies/Platform/PlatformContextManager.cs similarity index 95% rename from src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Strategies/Platform/PlatformContextManager.cs rename to src/Lumina.Domain/Core/Aggregates/FileSystemManagement/FileSystemManagementAggregate/Strategies/Platform/PlatformContextManager.cs index e029129f..b58b48b4 100644 --- a/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Strategies/Platform/PlatformContextManager.cs +++ b/src/Lumina.Domain/Core/Aggregates/FileSystemManagement/FileSystemManagementAggregate/Strategies/Platform/PlatformContextManager.cs @@ -4,7 +4,7 @@ using System; using System.Runtime.InteropServices; #endregion -namespace Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.Strategies.Platform; +namespace Lumina.Domain.Core.Aggregates.FileSystemManagement.FileSystemManagementAggregate.Strategies.Platform; /// /// Service for managing the platform context. @@ -34,12 +34,10 @@ public class PlatformContextManager : IPlatformContextManager { // set a default context if none is set if (_currentPlatformContext is null) - { if (_operatingSystemInfo.IsOSPlatform(OSPlatform.Linux)) SetCurrentPlatform(PlatformType.Unix); else SetCurrentPlatform(PlatformType.Windows); - } return _currentPlatformContext!; } diff --git a/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Strategies/Platform/UnixPlatformContext.cs b/src/Lumina.Domain/Core/Aggregates/FileSystemManagement/FileSystemManagementAggregate/Strategies/Platform/UnixPlatformContext.cs similarity index 82% rename from src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Strategies/Platform/UnixPlatformContext.cs rename to src/Lumina.Domain/Core/Aggregates/FileSystemManagement/FileSystemManagementAggregate/Strategies/Platform/UnixPlatformContext.cs index c7579366..4be8f7d6 100644 --- a/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Strategies/Platform/UnixPlatformContext.cs +++ b/src/Lumina.Domain/Core/Aggregates/FileSystemManagement/FileSystemManagementAggregate/Strategies/Platform/UnixPlatformContext.cs @@ -1,9 +1,9 @@ #region ========================================================================= USING ===================================================================================== using Lumina.Contracts.Enums.FileSystem; -using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.Strategies.Path; +using Lumina.Domain.Core.Aggregates.FileSystemManagement.FileSystemManagementAggregate.Strategies.Path; #endregion -namespace Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.Strategies.Platform; +namespace Lumina.Domain.Core.Aggregates.FileSystemManagement.FileSystemManagementAggregate.Strategies.Platform; /// /// Platform context for UNIX platforms. diff --git a/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Strategies/Platform/WindowsPlatformContext.cs b/src/Lumina.Domain/Core/Aggregates/FileSystemManagement/FileSystemManagementAggregate/Strategies/Platform/WindowsPlatformContext.cs similarity index 82% rename from src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Strategies/Platform/WindowsPlatformContext.cs rename to src/Lumina.Domain/Core/Aggregates/FileSystemManagement/FileSystemManagementAggregate/Strategies/Platform/WindowsPlatformContext.cs index 837cbea5..bae3d394 100644 --- a/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Strategies/Platform/WindowsPlatformContext.cs +++ b/src/Lumina.Domain/Core/Aggregates/FileSystemManagement/FileSystemManagementAggregate/Strategies/Platform/WindowsPlatformContext.cs @@ -1,9 +1,10 @@ #region ========================================================================= USING ===================================================================================== using Lumina.Contracts.Enums.FileSystem; -using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.Strategies.Path; +using Lumina.Domain.Core.Aggregates.FileSystemManagement.FileSystemManagementAggregate.Strategies.Path; + #endregion -namespace Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.Strategies.Platform; +namespace Lumina.Domain.Core.Aggregates.FileSystemManagement.FileSystemManagementAggregate.Strategies.Platform; /// /// Platform context for Windows platforms. diff --git a/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/ValueObjects/FileSystemPathId.cs b/src/Lumina.Domain/Core/Aggregates/FileSystemManagement/FileSystemManagementAggregate/ValueObjects/FileSystemPathId.cs similarity index 90% rename from src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/ValueObjects/FileSystemPathId.cs rename to src/Lumina.Domain/Core/Aggregates/FileSystemManagement/FileSystemManagementAggregate/ValueObjects/FileSystemPathId.cs index 8921ce95..dec61173 100644 --- a/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/ValueObjects/FileSystemPathId.cs +++ b/src/Lumina.Domain/Core/Aggregates/FileSystemManagement/FileSystemManagementAggregate/ValueObjects/FileSystemPathId.cs @@ -6,7 +6,7 @@ using System.Collections.Generic; using System.Diagnostics; #endregion -namespace Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.ValueObjects; +namespace Lumina.Domain.Core.Aggregates.FileSystemManagement.FileSystemManagementAggregate.ValueObjects; /// /// Value Object uniquely identifying file system items. @@ -44,7 +44,7 @@ public sealed class FileSystemPathId : ValueObject public static ErrorOr Create(string path) { if (string.IsNullOrWhiteSpace(path)) - return Errors.FileManagement.InvalidPath; + return Errors.FileSystemManagement.InvalidPath; return new FileSystemPathId(path); } } diff --git a/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/ValueObjects/PathSegment.cs b/src/Lumina.Domain/Core/Aggregates/FileSystemManagement/FileSystemManagementAggregate/ValueObjects/PathSegment.cs similarity index 93% rename from src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/ValueObjects/PathSegment.cs rename to src/Lumina.Domain/Core/Aggregates/FileSystemManagement/FileSystemManagementAggregate/ValueObjects/PathSegment.cs index 1a05af70..26836db2 100644 --- a/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/ValueObjects/PathSegment.cs +++ b/src/Lumina.Domain/Core/Aggregates/FileSystemManagement/FileSystemManagementAggregate/ValueObjects/PathSegment.cs @@ -6,7 +6,7 @@ using System.Collections.Generic; using System.Diagnostics; #endregion -namespace Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.ValueObjects; +namespace Lumina.Domain.Core.Aggregates.FileSystemManagement.FileSystemManagementAggregate.ValueObjects; /// /// Value object uniquely identifying path segments. @@ -54,7 +54,7 @@ public class PathSegment : ValueObject public static ErrorOr Create(string name, bool isDirectory, bool isDrive) { if (string.IsNullOrWhiteSpace(name)) - return Errors.FileManagement.NameCannotBeEmpty; + return Errors.FileSystemManagement.NameCannotBeEmpty; return new PathSegment(name, isDirectory, isDrive); } diff --git a/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/ValueObjects/StreamInfo.cs b/src/Lumina.Domain/Core/Aggregates/FileSystemManagement/FileSystemManagementAggregate/ValueObjects/StreamInfo.cs similarity index 93% rename from src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/ValueObjects/StreamInfo.cs rename to src/Lumina.Domain/Core/Aggregates/FileSystemManagement/FileSystemManagementAggregate/ValueObjects/StreamInfo.cs index 1d0ddd38..7a49e718 100644 --- a/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/ValueObjects/StreamInfo.cs +++ b/src/Lumina.Domain/Core/Aggregates/FileSystemManagement/FileSystemManagementAggregate/ValueObjects/StreamInfo.cs @@ -7,7 +7,7 @@ using System.Collections.Generic; using System.Diagnostics; #endregion -namespace Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.ValueObjects; +namespace Lumina.Domain.Core.Aggregates.FileSystemManagement.FileSystemManagementAggregate.ValueObjects; /// /// Value Object for the information about a media stream. @@ -111,11 +111,11 @@ public class StreamInfo : ValueObject Optional channels) { if (streamId is null) - return Errors.FileManagement.StreamIdCannotBeEmpty; + return Errors.FileSystemManagement.StreamIdCannotBeEmpty; if (codec is null) - return Errors.FileManagement.CodecCannotBeEmpty; + return Errors.FileSystemManagement.CodecCannotBeEmpty; if (bitrate <= 0) - return Errors.FileManagement.BitrateMustBeAPositiveNumber; + return Errors.FileSystemManagement.BitrateMustBeAPositiveNumber; return new StreamInfo(streamId, mimeType, bitrate, codec, resolution, frameRate, sampleRate, channels); } diff --git a/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/ValueObjects/Thumbnail.cs b/src/Lumina.Domain/Core/Aggregates/FileSystemManagement/FileSystemManagementAggregate/ValueObjects/Thumbnail.cs similarity index 79% rename from src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/ValueObjects/Thumbnail.cs rename to src/Lumina.Domain/Core/Aggregates/FileSystemManagement/FileSystemManagementAggregate/ValueObjects/Thumbnail.cs index 581362d3..12826072 100644 --- a/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/ValueObjects/Thumbnail.cs +++ b/src/Lumina.Domain/Core/Aggregates/FileSystemManagement/FileSystemManagementAggregate/ValueObjects/Thumbnail.cs @@ -1,11 +1,11 @@ -#region ========================================================================= USING ===================================================================================== +#region ========================================================================= USING ===================================================================================== using Lumina.Contracts.Enums.PhotoLibrary; using Lumina.Domain.Common.Models.Core; using System.Collections.Generic; using System.Diagnostics; #endregion -namespace Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.ValueObjects; +namespace Lumina.Domain.Core.Aggregates.FileSystemManagement.FileSystemManagementAggregate.ValueObjects; /// /// Value object for file system thumbnails. @@ -40,4 +40,4 @@ public class Thumbnail : ValueObject yield return Type; yield return Bytes; } -} \ No newline at end of file +} diff --git a/src/Lumina.Domain/Core/Aggregates/WrittenContentLibrary/BookLibraryAggregate/ValueObjects/Isbn.cs b/src/Lumina.Domain/Core/Aggregates/WrittenContentLibrary/BookLibraryAggregate/ValueObjects/Isbn.cs index aa6dfa1b..a8d4ef65 100644 --- a/src/Lumina.Domain/Core/Aggregates/WrittenContentLibrary/BookLibraryAggregate/ValueObjects/Isbn.cs +++ b/src/Lumina.Domain/Core/Aggregates/WrittenContentLibrary/BookLibraryAggregate/ValueObjects/Isbn.cs @@ -46,7 +46,7 @@ public sealed class Isbn : ValueObject /// The value representing this object. /// The format of the ISBN representing this object. /// The created instance. - public static ErrorOr Create(string value, IsbnFormat format) + public static ErrorOr Create(string? value, IsbnFormat format) { // enforce invariants if (string.IsNullOrWhiteSpace(value)) diff --git a/src/Lumina.Domain/Core/Aggregates/WrittenContentLibrary/BookLibraryAggregate/ValueObjects/WrittenContentMetadata.cs b/src/Lumina.Domain/Core/Aggregates/WrittenContentLibrary/BookLibraryAggregate/ValueObjects/WrittenContentMetadata.cs index 19383cd1..4a2a4bb2 100644 --- a/src/Lumina.Domain/Core/Aggregates/WrittenContentLibrary/BookLibraryAggregate/ValueObjects/WrittenContentMetadata.cs +++ b/src/Lumina.Domain/Core/Aggregates/WrittenContentLibrary/BookLibraryAggregate/ValueObjects/WrittenContentMetadata.cs @@ -16,12 +16,12 @@ namespace Lumina.Domain.Core.Aggregates.WrittenContentLibrary.BookLibraryAggrega public class WrittenContentMetadata : BaseMetadata { /// - /// Gets the publisher of the written content. + /// Gets the publisher of the written content, if applicable. /// public Optional Publisher { get; } /// - /// Gets the number of pages in the written content. + /// Gets the number of pages in the written content, if applicable. /// public Optional PageCount { get; } @@ -29,15 +29,15 @@ public class WrittenContentMetadata : BaseMetadata /// Initializes a new instance of the class. /// /// The title of the written content. - /// The optional original title of the video. - /// The description of the written content. + /// The optional original title of the written content, if applicable. + /// The description of the written content, if applicable. /// The release information of the written content. /// The genres of the written content. /// The tags associated with the written content. - /// The language of the written content. - /// The optional original language of the video. - /// The publisher of the written content. - /// The number of pages in the written content. + /// The language of the written content, if applicable. + /// The optional original language of the written content, if applicable. + /// The publisher of the written content, if applicable. + /// The number of pages in the written content, if applicable. private WrittenContentMetadata( string title, Optional originalTitle, @@ -59,15 +59,15 @@ public class WrittenContentMetadata : BaseMetadata /// Creates a new instance of the class. /// /// The title of the written content. - /// The optional original title of the video. - /// The description of the written content. + /// The optional original title of the written content, if applicable. + /// The description of the written content, if applicable. /// The release information of the written content. /// The genres of the written content. /// The tags associated with the written content. /// The language of the written content. - /// The optional original language of the video. - /// The publisher of the written content. - /// The number of pages in the written content. + /// The optional original language of the written content, if applicable. + /// The publisher of the written content, if applicable. + /// The number of pages in the written content, if applicable. /// /// An containing either a successfully created , or an error message. /// diff --git a/src/Lumina.Infrastructure/Common/Errors/Errors.Configuration.cs b/src/Lumina.Infrastructure/Common/Errors/Errors.Configuration.cs index ff34f4b3..7c961eb6 100644 --- a/src/Lumina.Infrastructure/Common/Errors/Errors.Configuration.cs +++ b/src/Lumina.Infrastructure/Common/Errors/Errors.Configuration.cs @@ -11,7 +11,7 @@ public static partial class Errors { public static class Configuration { - public static Error ApplicationThemeCannotBeEmpty => Error.Validation(nameof(ApplicationThemeCannotBeEmpty)); - public static Error DatabaseConnectionStringCannotBeEmpty => Error.Validation(nameof(DatabaseConnectionStringCannotBeEmpty)); + public static Error ApplicationThemeCannotBeEmpty => Error.Validation(description: nameof(ApplicationThemeCannotBeEmpty)); + public static Error DatabaseConnectionStringCannotBeEmpty => Error.Validation(description: nameof(DatabaseConnectionStringCannotBeEmpty)); } } diff --git a/src/Lumina.Infrastructure/Common/Validators/CommonSettingsModelValidator.cs b/src/Lumina.Infrastructure/Common/Validators/CommonSettingsModelValidator.cs index c2fb7edc..34f38741 100644 --- a/src/Lumina.Infrastructure/Common/Validators/CommonSettingsModelValidator.cs +++ b/src/Lumina.Infrastructure/Common/Validators/CommonSettingsModelValidator.cs @@ -15,6 +15,6 @@ public class CommonSettingsModelValidator : AbstractValidator public CommonSettingsModelValidator() { - RuleFor(x => x.Theme).NotEmpty().WithMessage(Errors.Errors.Configuration.ApplicationThemeCannotBeEmpty.Code); + RuleFor(x => x.Theme).NotEmpty().WithMessage(Errors.Errors.Configuration.ApplicationThemeCannotBeEmpty.Description); } } \ No newline at end of file diff --git a/src/Lumina.Infrastructure/Common/Validators/DatabaseSettingsModelValidator.cs b/src/Lumina.Infrastructure/Common/Validators/DatabaseSettingsModelValidator.cs index e9140082..dee45da9 100644 --- a/src/Lumina.Infrastructure/Common/Validators/DatabaseSettingsModelValidator.cs +++ b/src/Lumina.Infrastructure/Common/Validators/DatabaseSettingsModelValidator.cs @@ -15,6 +15,6 @@ public class DatabaseSettingsModelValidator : AbstractValidator public DatabaseSettingsModelValidator() { - RuleFor(x => x.DefaultConnection).NotEmpty().WithMessage(Errors.Errors.Configuration.DatabaseConnectionStringCannotBeEmpty.Code); + RuleFor(x => x.DefaultConnection).NotEmpty().WithMessage(Errors.Errors.Configuration.DatabaseConnectionStringCannotBeEmpty.Description); } } \ No newline at end of file diff --git a/src/Lumina.Infrastructure/Lumina.Infrastructure.csproj b/src/Lumina.Infrastructure/Lumina.Infrastructure.csproj index 036bb96b..49dd0235 100644 --- a/src/Lumina.Infrastructure/Lumina.Infrastructure.csproj +++ b/src/Lumina.Infrastructure/Lumina.Infrastructure.csproj @@ -13,12 +13,12 @@ - + - - + + diff --git a/src/Lumina.Presentation.Api/Common/Configuration/ConfigureSwaggerOptions.cs b/src/Lumina.Presentation.Api/Common/Configuration/ConfigureSwaggerOptions.cs deleted file mode 100644 index e15a35f1..00000000 --- a/src/Lumina.Presentation.Api/Common/Configuration/ConfigureSwaggerOptions.cs +++ /dev/null @@ -1,64 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using Microsoft.AspNetCore.Mvc.ApiExplorer; -using Microsoft.Extensions.DependencyInjection; -using Microsoft.Extensions.Options; -using Microsoft.OpenApi.Models; -using Swashbuckle.AspNetCore.SwaggerGen; -#endregion - -namespace Lumina.Presentation.Api.Common.Configuration; - -/// -/// Configures the Swagger options. -/// -public class ConfigureSwaggerOptions : IConfigureNamedOptions -{ - private readonly IApiVersionDescriptionProvider _provider; - - /// - /// Initializes a new instance of the class. - /// - /// Provider for API version descriptions. - public ConfigureSwaggerOptions(IApiVersionDescriptionProvider provider) - { - _provider = provider; - } - - /// - /// Configures the Swagger options. - /// - /// The options instance to configure. - public void Configure(SwaggerGenOptions options) - { - // add swagger document for every API version discovered - foreach (ApiVersionDescription description in _provider.ApiVersionDescriptions) - options.SwaggerDoc(description.GroupName, CreateVersionInfo(description)); - } - - /// - /// Configures the Swagger options. - /// - /// The name of the options instance being configured. - /// The options instance to configure. - public void Configure(string? name, SwaggerGenOptions options) - { - Configure(options); - } - - /// - /// Creates the version information for the Swagger document. - /// - /// The API version description. - /// The created instance. - private OpenApiInfo CreateVersionInfo(ApiVersionDescription description) - { - OpenApiInfo info = new() - { - Title = "Lumina API", - Version = description.ApiVersion.ToString() - }; - if (description.IsDeprecated) - info.Description += " This API version has been deprecated."; - return info; - } -} \ No newline at end of file diff --git a/src/Lumina.Presentation.Api/Common/DependencyInjection/PresentationApiLayerServices.cs b/src/Lumina.Presentation.Api/Common/DependencyInjection/PresentationApiLayerServices.cs index a358bfb6..6fa53934 100644 --- a/src/Lumina.Presentation.Api/Common/DependencyInjection/PresentationApiLayerServices.cs +++ b/src/Lumina.Presentation.Api/Common/DependencyInjection/PresentationApiLayerServices.cs @@ -1,11 +1,7 @@ #region ========================================================================= USING ===================================================================================== -using Lumina.Application.Common.Converters; -using Lumina.Presentation.Api.Common.Configuration; -using Lumina.Presentation.Api.Common.Errors; -using Mapster; -using MapsterMapper; -using Microsoft.AspNetCore.Mvc; -using Microsoft.AspNetCore.Mvc.Infrastructure; +using FastEndpoints; +using FastEndpoints.Swagger; +using Microsoft.AspNetCore.Http.Json; using Microsoft.Extensions.DependencyInjection; using System.Text.Json.Serialization; #endregion @@ -24,6 +20,40 @@ public static class PresentationApiLayerServices /// The updated . public static IServiceCollection AddPresentationApiLayerServices(this IServiceCollection services) { + + services.Configure(jsonOptions => + { + jsonOptions.SerializerOptions.Converters.Add(new JsonStringEnumConverter()); + jsonOptions.SerializerOptions.MaxDepth = 256; + jsonOptions.SerializerOptions.ReferenceHandler = ReferenceHandler.IgnoreCycles; // needed because file system API responses can have very nested structures + }); + + services.AddAuthorization(); + + services.AddFastEndpoints( + o => o.Assemblies = + [ + typeof(Program).Assembly + ]); + services.SwaggerDocument(documentOptions => + { + documentOptions.SerializerSettings = s => + { + s.PropertyNamingPolicy = null; + s.DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull; + }; + documentOptions.MaxEndpointVersion = 1; + documentOptions.MinEndpointVersion = 1; + documentOptions.DocumentSettings = s => + { + s.DocumentName = "Release 1.0"; + s.Title = "Lumina API"; + s.Version = "v1.0"; + }; + documentOptions.RemoveEmptyRequestSchema = true; + documentOptions.ShortSchemaNames = true; + }); + services.AddCors(options => { options.AddPolicy("AllowAll", @@ -33,41 +63,6 @@ public static class PresentationApiLayerServices .AllowAnyHeader()); }); - // add services to the container - services.AddControllers().AddJsonOptions(options => - { - options.JsonSerializerOptions.MaxDepth = 256; - options.JsonSerializerOptions.ReferenceHandler = ReferenceHandler.IgnoreCycles; // needed because file system API responses can have very nested structures - options.JsonSerializerOptions.Converters.Add(new JsonStringEnumConverter()); - options.JsonSerializerOptions.Converters.Add(new OptionalJsonConverterFactory()); - }); - - // add services to the container. - services.AddEndpointsApiExplorer(); - services.AddSwaggerGen(); - services.ConfigureOptions(); - - services.AddApiVersioning(options => - { - options.DefaultApiVersion = new ApiVersion(1, 0); - options.AssumeDefaultVersionWhenUnspecified = true; - options.ReportApiVersions = true; - }); - - services.AddVersionedApiExplorer(options => - { - options.GroupNameFormat = "'v'VVV"; - options.SubstituteApiVersionInUrl = true; - }); - - services.AddSingleton(); - - // register mapster configs - TypeAdapterConfig mapsterConfig = TypeAdapterConfig.GlobalSettings; - mapsterConfig.Scan(typeof(PresentationApiLayerServices).Assembly); - services.AddSingleton(mapsterConfig); - services.AddScoped(); - return services; } } diff --git a/src/Lumina.Presentation.Api/Common/Errors/CustomProblemDetailsFactory.cs b/src/Lumina.Presentation.Api/Common/Errors/CustomProblemDetailsFactory.cs deleted file mode 100644 index 3ce6dcb2..00000000 --- a/src/Lumina.Presentation.Api/Common/Errors/CustomProblemDetailsFactory.cs +++ /dev/null @@ -1,118 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using ErrorOr; -using Lumina.Presentation.Api.Common.Http; -using Microsoft.AspNetCore.Http; -using Microsoft.AspNetCore.Mvc; -using Microsoft.AspNetCore.Mvc.Infrastructure; -using Microsoft.AspNetCore.Mvc.ModelBinding; -using Microsoft.Extensions.Options; -using System; -using System.Collections.Generic; -using System.Diagnostics; -using System.Linq; -#endregion - -namespace Lumina.Presentation.Api.Common.Errors; - -/// -/// Problem details factory which adds custom properties to the default implementation provided by Microsoft. -/// -public class CustomProblemDetailsFactory : ProblemDetailsFactory -{ - private readonly ApiBehaviorOptions _options; - private readonly Action? _configure; - - /// - /// Initializes a new instance of the class. - /// - /// Injected service for retrieving . - /// Injected service for retrieving . - /// Thrown when the value of options (if any) is . - public CustomProblemDetailsFactory(IOptions apiBehaviorOptions, IOptions? problemDetailsOptions = null) - { - _options = apiBehaviorOptions?.Value ?? throw new ArgumentNullException(nameof(apiBehaviorOptions)); - _configure = problemDetailsOptions?.Value?.CustomizeProblemDetails; - } - - /// - /// Creates a instance that configures defaults based on values specified in . - /// - /// The . - /// The value for . - /// The value for . - /// The value for . - /// The value for . - /// The value for . - /// The instance. - public override ProblemDetails CreateProblemDetails(HttpContext httpContext, int? statusCode = null, string? title = null, string? type = null, - string? detail = null, string? instance = null) - { - statusCode ??= 500; - ProblemDetails problemDetails = new() - { - Status = statusCode, - Title = title, - Type = type, - Detail = detail, - Instance = instance, - }; - ApplyProblemDetailsDefaults(httpContext, problemDetails, statusCode.Value); - return problemDetails; - } - - /// - /// Creates a instance that configures defaults based on values specified in . - /// - /// The . - /// The . - /// The value for . - /// The value for . - /// The value for . - /// The value for . - /// The value for . - /// The instance. - public override ValidationProblemDetails CreateValidationProblemDetails(HttpContext httpContext, ModelStateDictionary modelStateDictionary, int? statusCode = null, - string? title = null, string? type = null, string? detail = null, string? instance = null) - { - ArgumentNullException.ThrowIfNull(modelStateDictionary); - statusCode ??= 400; - ValidationProblemDetails problemDetails = new(modelStateDictionary) - { - Status = statusCode, - Type = type, - Detail = detail, - Instance = instance, - }; - if (title != null) - problemDetails.Title = title; // for validation problem details, don't overwrite the default title with null - ApplyProblemDetailsDefaults(httpContext, problemDetails, statusCode.Value); - return problemDetails; - } - - /// - /// Creates a instance that configures defaults based on values specified in . - /// - /// The . - /// The value for . - /// The value for . - /// The instance. - private void ApplyProblemDetailsDefaults(HttpContext httpContext, ProblemDetails problemDetails, int statusCode) - { - problemDetails.Status ??= statusCode; - if (_options.ClientErrorMapping.TryGetValue(statusCode, out ClientErrorData? clientErrorData)) - { - problemDetails.Title ??= clientErrorData.Title; - problemDetails.Type ??= clientErrorData.Link; - } - string? traceId = Activity.Current?.Id ?? httpContext?.TraceIdentifier; - if (traceId != null) - problemDetails.Extensions["traceId"] = traceId; - // get any errors that might be sent by ApiController base class' Problem() method - List? errors = httpContext?.Items[HttpContextItemKeys.ERRORS] as List; - // add any extra custom properties - if (errors is not null) - problemDetails.Extensions.Add("errors", errors.Select(error => error.Code)); - //problemDetails.Extensions.Add("errorCodes", errors.Select(e => e.Type.ToString())); - _configure?.Invoke(new() { HttpContext = httpContext!, ProblemDetails = problemDetails }); - } -} diff --git a/src/Lumina.Presentation.Api/Common/Mapping/WrittenContentLibrary/BookLibrary/BookMappingConfig.cs b/src/Lumina.Presentation.Api/Common/Mapping/WrittenContentLibrary/BookLibrary/BookMappingConfig.cs deleted file mode 100644 index e7cd9b7b..00000000 --- a/src/Lumina.Presentation.Api/Common/Mapping/WrittenContentLibrary/BookLibrary/BookMappingConfig.cs +++ /dev/null @@ -1,27 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using Lumina.Application.Core.WrittenContentLibrary.BooksLibrary.Books.Commands.AddBook; -using Lumina.Contracts.Requests.WrittenContentLibrary.BookLibrary; -using Mapster; -#endregion - -namespace Lumina.Presentation.Api.Common.Mapping.WrittenContentLibrary.BookLibrary; - -/// -/// Mapping configuration for books between the API request object and the command object. -/// -public class BookMappingConfig : IRegister -{ - /// - /// Registers the mapping configuration. - /// - /// The type adapter configuration. - public void Register(TypeAdapterConfig config) - { - config.NewConfig() - .Map(dest => dest.ASIN, src => src.ASIN) - .Map(dest => dest.ISBNs, src => src.ISBNs) - .Map(dest => dest.LCCN, src => src.LCCN) - .Map(dest => dest.OCLCNumber, src => src.OCLCNumber) - .MapToConstructor(true); - } -} \ No newline at end of file diff --git a/src/Lumina.Presentation.Api/Common/ModelBinders/UrlStringBinder.cs b/src/Lumina.Presentation.Api/Common/ModelBinders/UrlStringBinder.cs deleted file mode 100644 index 37120985..00000000 --- a/src/Lumina.Presentation.Api/Common/ModelBinders/UrlStringBinder.cs +++ /dev/null @@ -1,38 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using Microsoft.AspNetCore.Mvc.ModelBinding; -using System; -using System.Threading.Tasks; -#endregion - -namespace Lumina.Presentation.Api.Common.ModelBinders; - -/// -/// Custom model binder for URL parameters. For some reason, the default binder converts "%20" to "+", instead of " ". -/// -public class UrlStringBinder : IModelBinder -{ - /// - /// Binds a model to a value by using the specified controller context and binding context. - /// - /// The context within which to bind the model. - /// A task representing the bind operation. - public Task BindModelAsync(ModelBindingContext bindingContext) - { - ArgumentNullException.ThrowIfNull(bindingContext); - string modelName = bindingContext.ModelName; - // try to fetch the value of the argument by name - ValueProviderResult valueProviderResult = bindingContext.ValueProvider.GetValue(modelName); - if (valueProviderResult == ValueProviderResult.None) - return Task.CompletedTask; - string? value = valueProviderResult.FirstValue; - if (value is null) - { - bindingContext.Result = ModelBindingResult.Failed(); - return Task.CompletedTask; - } - // do the custom decoding here - value = Uri.UnescapeDataString(value); - bindingContext.Result = ModelBindingResult.Success(value); - return Task.CompletedTask; - } -} diff --git a/src/Lumina.Presentation.Api/Common/Routes/FileSystemManagement/ApiRoutes.Directories.cs b/src/Lumina.Presentation.Api/Common/Routes/FileSystemManagement/ApiRoutes.Directories.cs new file mode 100644 index 00000000..827b8f62 --- /dev/null +++ b/src/Lumina.Presentation.Api/Common/Routes/FileSystemManagement/ApiRoutes.Directories.cs @@ -0,0 +1,17 @@ +namespace Lumina.Presentation.Api.Common.Routes.FileSystemManagement; + +/// +/// Class for the collection of routes defined in this API. +/// +public static partial class ApiRoutes +{ + /// + /// Routes for the Directories route. + /// + public static class Directories + { + public const string GET_DIRECTORY_TREE = "/directories/get-directory-tree"; + public const string GET_TREE_DIRECTORIES = "/directories/get-tree-directories"; + public const string GET_DIRECTORIES = "/directories/get-directories"; + } +} diff --git a/src/Lumina.Presentation.Api/Common/Routes/FileSystemManagement/ApiRoutes.Drives.cs b/src/Lumina.Presentation.Api/Common/Routes/FileSystemManagement/ApiRoutes.Drives.cs new file mode 100644 index 00000000..d61baeee --- /dev/null +++ b/src/Lumina.Presentation.Api/Common/Routes/FileSystemManagement/ApiRoutes.Drives.cs @@ -0,0 +1,15 @@ +namespace Lumina.Presentation.Api.Common.Routes.FileSystemManagement; + +/// +/// Class for the collection of routes defined in this API. +/// +public static partial class ApiRoutes +{ + /// + /// Routes for the Drives route. + /// + public static class Drives + { + public const string GET_DRIVES = "/drives/get-drives"; + } +} diff --git a/src/Lumina.Presentation.Api/Common/Routes/FileSystemManagement/ApiRoutes.FileSystem.cs b/src/Lumina.Presentation.Api/Common/Routes/FileSystemManagement/ApiRoutes.FileSystem.cs new file mode 100644 index 00000000..c1d62bb7 --- /dev/null +++ b/src/Lumina.Presentation.Api/Common/Routes/FileSystemManagement/ApiRoutes.FileSystem.cs @@ -0,0 +1,15 @@ +namespace Lumina.Presentation.Api.Common.Routes.FileSystemManagement; + +/// +/// Class for the collection of routes defined in this API. +/// +public static partial class ApiRoutes +{ + /// + /// Routes for the FileSystem route. + /// + public static class FileSystem + { + public const string GET_TYPES = "/file-system/get-type"; + } +} diff --git a/src/Lumina.Presentation.Api/Common/Routes/FileSystemManagement/ApiRoutes.Files.cs b/src/Lumina.Presentation.Api/Common/Routes/FileSystemManagement/ApiRoutes.Files.cs new file mode 100644 index 00000000..8450b778 --- /dev/null +++ b/src/Lumina.Presentation.Api/Common/Routes/FileSystemManagement/ApiRoutes.Files.cs @@ -0,0 +1,16 @@ +namespace Lumina.Presentation.Api.Common.Routes.FileSystemManagement; + +/// +/// Class for the collection of routes defined in this API. +/// +public static partial class ApiRoutes +{ + /// + /// Routes for the Files route. + /// + public static class Files + { + public const string GET_TREE_FILES = "/files/get-tree-files"; + public const string GET_FILES = "/files/get-files"; + } +} diff --git a/src/Lumina.Presentation.Api/Common/Routes/FileSystemManagement/ApiRoutes.Path.cs b/src/Lumina.Presentation.Api/Common/Routes/FileSystemManagement/ApiRoutes.Path.cs new file mode 100644 index 00000000..e30d3c1d --- /dev/null +++ b/src/Lumina.Presentation.Api/Common/Routes/FileSystemManagement/ApiRoutes.Path.cs @@ -0,0 +1,21 @@ +namespace Lumina.Presentation.Api.Common.Routes.FileSystemManagement; + +/// +/// Class for the collection of routes defined in this API. +/// +public static partial class ApiRoutes +{ + /// + /// Routes for the Path route. + /// + public static class Path + { + public const string GET_PATH_ROOT = "/path/get-path-root"; + public const string GET_PATH_SEPARATOR = "/path/get-path-separator"; + public const string GET_PATH_PARENT = "/path/get-path-parent"; + public const string COMBINE = "/path/combine"; + public const string SPLIT = "/path/split"; + public const string VALIDATE = "/path/validate"; + public const string CHECK_PATH_EXISTS = "/path/check-path-exists"; + } +} diff --git a/src/Lumina.Presentation.Api/Common/Routes/FileSystemManagement/ApiRoutes.Thumbnails.cs b/src/Lumina.Presentation.Api/Common/Routes/FileSystemManagement/ApiRoutes.Thumbnails.cs new file mode 100644 index 00000000..fff0fffe --- /dev/null +++ b/src/Lumina.Presentation.Api/Common/Routes/FileSystemManagement/ApiRoutes.Thumbnails.cs @@ -0,0 +1,15 @@ +namespace Lumina.Presentation.Api.Common.Routes.FileSystemManagement; + +/// +/// Class for the collection of routes defined in this API. +/// +public static partial class ApiRoutes +{ + /// + /// Routes for the Thumbnails route. + /// + public static class Thumbnails + { + public const string GET_THUMBNAIL = "/thumbnails/get-thumbnail"; + } +} diff --git a/src/Lumina.Presentation.Api/Common/Routes/Maintenance/ApiRoutes.Health.cs b/src/Lumina.Presentation.Api/Common/Routes/Maintenance/ApiRoutes.Health.cs new file mode 100644 index 00000000..42b3a4b5 --- /dev/null +++ b/src/Lumina.Presentation.Api/Common/Routes/Maintenance/ApiRoutes.Health.cs @@ -0,0 +1,15 @@ +namespace Lumina.Presentation.Api.Common.Routes.FileSystemManagement; + +/// +/// Class for the collection of routes defined in this API. +/// +public static partial class ApiRoutes +{ + /// + /// Routes for the Health route. + /// + public static class Health + { + public const string CHECK_HEALTH = "/check-health"; + } +} diff --git a/src/Lumina.Presentation.Api/Common/Routes/WrittenContentLibrary/BookLibrary/ApiRoutes.Books.cs b/src/Lumina.Presentation.Api/Common/Routes/WrittenContentLibrary/BookLibrary/ApiRoutes.Books.cs new file mode 100644 index 00000000..276a0d38 --- /dev/null +++ b/src/Lumina.Presentation.Api/Common/Routes/WrittenContentLibrary/BookLibrary/ApiRoutes.Books.cs @@ -0,0 +1,17 @@ +namespace Lumina.Presentation.Api.Common.Routes.WrittenContentLibrary.BookLibrary; + +/// +/// Class for the collection of routes defined in this API. +/// +public static partial class ApiRoutes +{ + /// + /// Routes for the Books route. + /// + public static class Books + { + public const string GET_BOOK_BY_ID = "/books/{id}"; + public const string GET_BOOKS = "/books"; + public const string ADD_BOOK = "/books"; + } +} diff --git a/src/Lumina.Presentation.Api/Core/Controllers/Common/ApiController.cs b/src/Lumina.Presentation.Api/Core/Controllers/Common/ApiController.cs deleted file mode 100644 index dd16019a..00000000 --- a/src/Lumina.Presentation.Api/Core/Controllers/Common/ApiController.cs +++ /dev/null @@ -1,69 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using ErrorOr; -using Lumina.Presentation.Api.Common.Http; -using Microsoft.AspNetCore.Http; -using Microsoft.AspNetCore.Mvc; -using Microsoft.AspNetCore.Mvc.ModelBinding; -using System.Collections.Generic; -using System.Linq; -#endregion - -namespace Lumina.Presentation.Api.Core.Controllers.Common; - -/// -/// Base class for API controllers. -/// -[ApiController] -[ApiVersion("1.0")] -public abstract class ApiController : ControllerBase -{ - /// - /// Handles controllers errors. - /// - /// The error to handle. - protected internal IActionResult Problem(List errors) - { - if (errors.Count is 0) // if there are no custom errors given, return a generic problem - return Problem(); - // try to make the problem type more specific - if (errors.All(error => error.Type == ErrorType.Validation)) - return ValidationProblem(errors); - // here we could handle custom error types, for instance: if (errors.All(error => error.NumericType == 23)), where 23 could be "domain errors" - - // share the list of errors within the scope of this HTTP request - HttpContext.Items[HttpContextItemKeys.ERRORS] = errors; - // get a HTTP error status code for the selected domain error type - return Problem(errors.First()); - } - - /// - /// Converts an to a standard problem response. - /// - /// The error to convert. - protected internal IActionResult Problem(Error error) - { - int statusCode = error.Type switch - { - ErrorType.Conflict => StatusCodes.Status409Conflict, - ErrorType.NotFound => StatusCodes.Status404NotFound, - ErrorType.Validation => StatusCodes.Status400BadRequest, - ErrorType.Failure => StatusCodes.Status403Forbidden, - _ => StatusCodes.Status500InternalServerError, - - }; - // return the HTTP error status and the domain error message - return Problem(statusCode: statusCode, title: error.Type.ToString(), detail: error.Description); - } - - /// - /// Converts a list of into a standard validation problem response. - /// - /// The list of errors to convert. - protected internal IActionResult ValidationProblem(List errors) - { - ModelStateDictionary modelStateDictionary = new(); - foreach (Error error in errors) - modelStateDictionary.AddModelError(error.Code, error.Description); - return ValidationProblem(modelStateDictionary: modelStateDictionary, title: "One or more validation errors occurred."); - } -} \ No newline at end of file diff --git a/src/Lumina.Presentation.Api/Core/Controllers/FileManagement/DirectoriesController.cs b/src/Lumina.Presentation.Api/Core/Controllers/FileManagement/DirectoriesController.cs deleted file mode 100644 index 134e5428..00000000 --- a/src/Lumina.Presentation.Api/Core/Controllers/FileManagement/DirectoriesController.cs +++ /dev/null @@ -1,101 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using ErrorOr; -using Lumina.Application.Core.FileManagement.Directories.Queries.GetDirectories; -using Lumina.Application.Core.FileManagement.Directories.Queries.GetDirectoryTree; -using Lumina.Application.Core.FileManagement.Directories.Queries.GetTreeDirectories; -using Lumina.Contracts.Responses.FileManagement; -using Lumina.Presentation.Api.Common.ModelBinders; -using Lumina.Presentation.Api.Core.Controllers.Common; -using Mediator; -using Microsoft.AspNetCore.Mvc; -using System.Collections.Generic; -using System.Runtime.CompilerServices; -using System.Threading; -#endregion - -namespace Lumina.Presentation.Api.Core.Controllers.FileManagement; - -/// -/// Controller for managing file system directories. -/// -[ApiVersion("1.0")] -[Route("api/v{version:apiVersion}/[controller]")] -public class DirectoriesController : ApiController -{ - private readonly ISender _mediator; - - /// - /// Initializes a new instance of the class. - /// - /// Injected service for mediating commands and queries. - public DirectoriesController(ISender mediator) - { - _mediator = mediator; - } - - /// - /// Gets the tree of expanded directories leading up to , with the additional list of drives, and children of the last child directory. - /// - /// The path for which to get the directory tree. - /// Whether to include hidden file system elements or not. - /// Cancellation token that can be used to stop the execution. - [HttpGet("get-directory-tree")] - public async IAsyncEnumerable GetDirectoryTree([FromQuery, ModelBinder(typeof(UrlStringBinder))] string path, - [FromQuery] bool includeFiles, [FromQuery] bool includeHiddenElements, [EnumeratorCancellation] CancellationToken cancellationToken) - { - ErrorOr> result = await _mediator.Send(new GetDirectoryTreeQuery(path, includeFiles, includeHiddenElements), cancellationToken).ConfigureAwait(false); - if (!result.IsError) - { - foreach (FileSystemTreeNodeResponse treeNode in result.Value) - { - if (cancellationToken.IsCancellationRequested) - yield break; - yield return treeNode; - } - } - } - - /// - /// Gets the directories of . - /// - /// The path for which to get the directories. - /// Whether to include hidden file system elements or not. - /// Cancellation token that can be used to stop the execution. - [HttpGet("get-tree-directories")] - public async IAsyncEnumerable GetTreeDirectories([FromQuery, ModelBinder(typeof(UrlStringBinder))] string path, - [FromQuery] bool includeHiddenElements, [EnumeratorCancellation] CancellationToken cancellationToken) - { - ErrorOr> result = await _mediator.Send(new GetTreeDirectoriesQuery(path,includeHiddenElements), cancellationToken).ConfigureAwait(false); - if (!result.IsError) - { - foreach (FileSystemTreeNodeResponse directory in result.Value) - { - if (cancellationToken.IsCancellationRequested) - yield break; - yield return directory; - } - } - } - - /// - /// Gets the directories of . - /// - /// The path for which to get the directories. - /// Whether to include hidden file system elements or not. - /// Cancellation token that can be used to stop the execution. - [HttpGet("get-directories")] - public async IAsyncEnumerable GetDirectories([FromQuery, ModelBinder(typeof(UrlStringBinder))] string path, - [FromQuery] bool includeHiddenElements, [EnumeratorCancellation] CancellationToken cancellationToken) - { - ErrorOr> result = await _mediator.Send(new GetDirectoriesQuery(path, includeHiddenElements), cancellationToken).ConfigureAwait(false); - if (!result.IsError) - { - foreach (DirectoryResponse directory in result.Value) - { - if (cancellationToken.IsCancellationRequested) - yield break; - yield return directory; - } - } - } -} diff --git a/src/Lumina.Presentation.Api/Core/Controllers/FileManagement/DrivesController.cs b/src/Lumina.Presentation.Api/Core/Controllers/FileManagement/DrivesController.cs deleted file mode 100644 index 17393b70..00000000 --- a/src/Lumina.Presentation.Api/Core/Controllers/FileManagement/DrivesController.cs +++ /dev/null @@ -1,43 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using ErrorOr; -using Lumina.Application.Core.FileManagement.Drives.Queries.GetDrives; -using Lumina.Contracts.Responses.FileManagement; -using Lumina.Presentation.Api.Core.Controllers.Common; -using Mediator; -using Microsoft.AspNetCore.Mvc; -using System.Collections.Generic; -using System.Threading; -using System.Threading.Tasks; -#endregion - -namespace Lumina.Presentation.Api.Core.Controllers.FileManagement; - -/// -/// Controller for managing file system drives. -/// -[ApiVersion("1.0")] -[Route("api/v{version:apiVersion}/[controller]")] -public class DrivesController : ApiController -{ - private readonly ISender _mediator; - - /// - /// Initializes a new instance of the class. - /// - /// Injected service for mediating commands and queries. - public DrivesController(ISender mediator) - { - _mediator = mediator; - } - - /// - /// Controller action for getting the list of all file system drives. - /// - /// Cancellation token that can be used to stop the execution. - [HttpGet("get-drives")] - public async Task GetDrives(CancellationToken cancellationToken) - { - ErrorOr> result = await _mediator.Send(new GetDrivesQuery(), cancellationToken).ConfigureAwait(false); - return result.Match(result => Ok(result), errors => Problem(errors)); - } -} diff --git a/src/Lumina.Presentation.Api/Core/Controllers/FileManagement/FileSystemController.cs b/src/Lumina.Presentation.Api/Core/Controllers/FileManagement/FileSystemController.cs deleted file mode 100644 index 200f0774..00000000 --- a/src/Lumina.Presentation.Api/Core/Controllers/FileManagement/FileSystemController.cs +++ /dev/null @@ -1,41 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using Lumina.Application.Core.FileManagement.FileSystem.Queries.GetFileSystem; -using Lumina.Contracts.Responses.FileManagement; -using Lumina.Presentation.Api.Core.Controllers.Common; -using Mediator; -using Microsoft.AspNetCore.Mvc; -using System.Threading; -using System.Threading.Tasks; -#endregion - -namespace Lumina.Presentation.Api.Core.Controllers.FileManagement; - -/// -/// Controller for managing file systems. -/// -[ApiVersion("1.0")] -[Route("api/v{version:apiVersion}/file-system")] -public class FileSystemController : ApiController -{ - private readonly ISender _mediator; - - /// - /// Initializes a new instance of the class. - /// - /// Injected service for mediating commands and queries. - public FileSystemController(ISender mediator) - { - _mediator = mediator; - } - - /// - /// Gets the type of the file system. - /// - /// Cancellation token that can be used to stop the execution. - [HttpGet("get-type")] - public async Task GetType(CancellationToken cancellationToken) - { - FileSystemTypeResponse platformType = await _mediator.Send(new GetFileSystemQuery(), cancellationToken).ConfigureAwait(false); - return Ok(platformType); - } -} diff --git a/src/Lumina.Presentation.Api/Core/Controllers/FileManagement/FilesController.cs b/src/Lumina.Presentation.Api/Core/Controllers/FileManagement/FilesController.cs deleted file mode 100644 index 5a7d7c04..00000000 --- a/src/Lumina.Presentation.Api/Core/Controllers/FileManagement/FilesController.cs +++ /dev/null @@ -1,78 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using ErrorOr; -using Lumina.Application.Core.FileManagement.Files.Queries.GetFiles; -using Lumina.Application.Core.FileManagement.Files.Queries.GetTreeFiles; -using Lumina.Contracts.Responses.FileManagement; -using Lumina.Presentation.Api.Common.ModelBinders; -using Lumina.Presentation.Api.Core.Controllers.Common; -using Mediator; -using Microsoft.AspNetCore.Mvc; -using System.Collections.Generic; -using System.Runtime.CompilerServices; -using System.Threading; -#endregion - -namespace Lumina.Presentation.Api.Core.Controllers.FileManagement; - -/// -/// Controller for managing file system files. -/// -[ApiVersion("1.0")] -[Route("api/v{version:apiVersion}/[controller]")] -public class FilesController : ApiController -{ - private readonly ISender _mediator; - - /// - /// Initializes a new instance of the class. - /// - /// Injected service for mediating commands and queries. - public FilesController(ISender mediator) - { - _mediator = mediator; - } - - /// - /// Gets the files of . - /// - /// The path for which to get the files. - /// Whether to include hidden file system elements or not. - /// Cancellation token that can be used to stop the execution. - [HttpGet("get-tree-files")] - public async IAsyncEnumerable GetTreeFiles([FromQuery, ModelBinder(typeof(UrlStringBinder))] string path, - [FromQuery] bool includeHiddenElements, [EnumeratorCancellation] CancellationToken cancellationToken) - { - ErrorOr> result = await _mediator.Send(new GetTreeFilesQuery(path, includeHiddenElements), cancellationToken).ConfigureAwait(false); - if (!result.IsError) - { - foreach (FileSystemTreeNodeResponse file in result.Value) - { - if (cancellationToken.IsCancellationRequested) - yield break; - yield return file; - } - } - } - - /// - /// Gets the files of . - /// - /// The path for which to get the files. - /// Whether to include hidden file system elements or not. - /// Cancellation token that can be used to stop the execution. - [HttpGet("get-files")] - public async IAsyncEnumerable GetFiles([FromQuery, ModelBinder(typeof(UrlStringBinder))] string path, - [FromQuery] bool includeHiddenElements, [EnumeratorCancellation] CancellationToken cancellationToken) - { - ErrorOr> result = await _mediator.Send(new GetFilesQuery(path, includeHiddenElements), cancellationToken).ConfigureAwait(false); - if (!result.IsError) - { - foreach (FileResponse file in result.Value) - { - if (cancellationToken.IsCancellationRequested) - yield break; - yield return file; - } - } - } -} diff --git a/src/Lumina.Presentation.Api/Core/Controllers/FileManagement/PathController.cs b/src/Lumina.Presentation.Api/Core/Controllers/FileManagement/PathController.cs deleted file mode 100644 index 0292e3fa..00000000 --- a/src/Lumina.Presentation.Api/Core/Controllers/FileManagement/PathController.cs +++ /dev/null @@ -1,124 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using ErrorOr; -using Lumina.Application.Core.FileManagement.Paths.Commands.CombinePath; -using Lumina.Application.Core.FileManagement.Paths.Commands.SplitPath; -using Lumina.Application.Core.FileManagement.Paths.Queries.CheckPathExists; -using Lumina.Application.Core.FileManagement.Paths.Queries.GetPathParent; -using Lumina.Application.Core.FileManagement.Paths.Queries.GetPathRoot; -using Lumina.Application.Core.FileManagement.Paths.Queries.GetPathSeparator; -using Lumina.Application.Core.FileManagement.Paths.Queries.ValidatePath; -using Lumina.Contracts.Responses.FileManagement; -using Lumina.Presentation.Api.Common.ModelBinders; -using Lumina.Presentation.Api.Core.Controllers.Common; -using Mediator; -using Microsoft.AspNetCore.Mvc; -using System.Collections.Generic; -using System.Threading; -using System.Threading.Tasks; -#endregion - -namespace Lumina.Presentation.Api.Core.Controllers.FileManagement; - -/// -/// Controller for managing file system paths. -/// -[ApiVersion("1.0")] -[Route("api/v{version:apiVersion}/[controller]")] -public class PathController : ApiController -{ - private readonly ISender _mediator; - - /// - /// Initializes a new instance of the class. - /// - /// Injected service for mediating commands and queries. - public PathController(ISender mediator) - { - _mediator = mediator; - } - - /// - /// Gets the root of . - /// - /// The path for which to get the root. - /// Cancellation token that can be used to stop the execution. - [HttpGet("get-path-root")] - public async Task GetPathRoot([FromQuery, ModelBinder(typeof(UrlStringBinder))] string path, CancellationToken cancellationToken) - { - ErrorOr result = await _mediator.Send(new GetPathRootQuery(path), cancellationToken).ConfigureAwait(false); - return result.Match(result => Ok(result), errors => Problem(errors)); - } - - /// - /// Gets the path separator character of the file system. - /// - /// Cancellation token that can be used to stop the execution. - [HttpGet("get-path-separator")] - public async Task GetPathSeparator(CancellationToken cancellationToken) - { - PathSeparatorResponse result = await _mediator.Send(new GetPathSeparatorQuery(), cancellationToken).ConfigureAwait(false); - return Ok(result); - } - - /// - /// Gets the path separator character of the file system. - /// - /// The path for which to get the parent path. - /// Cancellation token that can be used to stop the execution. - [HttpGet("get-path-parent")] - public async Task GetPathParent([FromQuery, ModelBinder(typeof(UrlStringBinder))] string path, CancellationToken cancellationToken) - { - ErrorOr> result = await _mediator.Send(new GetPathParentQuery(path), cancellationToken).ConfigureAwait(false); - return result.Match(result => Ok(result), errors => Problem(errors)); - } - - /// - /// Combines with . - /// - /// The path to combine to. - /// The path to combine with. - /// Cancellation token that can be used to stop the execution. - [HttpGet("combine")] - public async Task CombinePath([FromQuery, ModelBinder(typeof(UrlStringBinder))] string originalPath, [FromQuery, ModelBinder(typeof(UrlStringBinder))] string newPath, CancellationToken cancellationToken) - { - ErrorOr result = await _mediator.Send(new CombinePathCommand(originalPath, newPath), cancellationToken).ConfigureAwait(false); - return result.Match(result => Ok(result), errors => Problem(errors)); - } - - /// - /// Gets the path components of . - /// - /// The path for which to get the path segments. - /// Cancellation token that can be used to stop the execution. - [HttpGet("split")] - public async Task SplitPath([FromQuery, ModelBinder(typeof(UrlStringBinder))] string path, CancellationToken cancellationToken) - { - ErrorOr> result = await _mediator.Send(new SplitPathCommand(path), cancellationToken).ConfigureAwait(false); - return result.Match(result => Ok(result), errors => Problem(errors)); - } - - /// - /// Validates the validity of . - /// - /// The path to be validated. - /// Cancellation token that can be used to stop the execution. - [HttpGet("validate")] - public async Task ValidatePath([FromQuery, ModelBinder(typeof(UrlStringBinder))] string path, CancellationToken cancellationToken) - { - PathValidResponse result = await _mediator.Send(new ValidatePathQuery(path), cancellationToken).ConfigureAwait(false); - return Ok(result); - } - - /// - /// Checks whether exists or not. - /// - /// The path to be checked. - /// Whether to include hidden file system elements or not. - /// Cancellation token that can be used to stop the execution. - [HttpGet("check-path-exists")] - public async Task CheckPathExists([FromQuery, ModelBinder(typeof(UrlStringBinder))] string path, [FromQuery] bool includeHiddenElements, CancellationToken cancellationToken) - { - PathExistsResponse result = await _mediator.Send(new CheckPathExistsQuery(path, includeHiddenElements), cancellationToken).ConfigureAwait(false); - return Ok(result); - } -} diff --git a/src/Lumina.Presentation.Api/Core/Controllers/FileManagement/ThumbnailsController.cs b/src/Lumina.Presentation.Api/Core/Controllers/FileManagement/ThumbnailsController.cs deleted file mode 100644 index 72f3ede9..00000000 --- a/src/Lumina.Presentation.Api/Core/Controllers/FileManagement/ThumbnailsController.cs +++ /dev/null @@ -1,46 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using ErrorOr; -using Lumina.Application.Core.FileManagement.Thumbnails.Queries.GetThumbnail; -using Lumina.Contracts.Responses.FileManagement; -using Lumina.Presentation.Api.Common.ModelBinders; -using Lumina.Presentation.Api.Common.Utilities; -using Lumina.Presentation.Api.Core.Controllers.Common; -using Mediator; -using Microsoft.AspNetCore.Mvc; -using System.Threading; -using System.Threading.Tasks; -#endregion - -namespace Lumina.Presentation.Api.Core.Controllers.FileManagement; - -/// -/// Controller for managing file system items thumbnails. -/// -[ApiVersion("1.0")] -[Route("api/v{version:apiVersion}/[controller]")] -public class ThumbnailsController : ApiController -{ - private readonly ISender _mediator; - - /// - /// Initializes a new instance of the class. - /// - /// Injected service for mediating commands and queries. - public ThumbnailsController(ISender mediator) - { - _mediator = mediator; - } - - /// - /// Gets the thumbnail of a file identified by of . - /// - /// The path of the file for which to get the thumbnail. - /// The quality to use for the thumbnail. - /// Cancellation token that can be used to stop the execution. - [HttpGet("get-thumbnail")] - public async Task GetThumbnail([FromQuery, ModelBinder(typeof(UrlStringBinder))] string path, [FromQuery] int quality, CancellationToken cancellationToken) - { - ErrorOr getResult = await _mediator.Send(new GetThumbnailQuery(path, quality), cancellationToken); - return getResult.Match(result => File(result.Bytes, MimeTypes.GetMimeType(result.Type)), errors => Problem(errors)); - } -} diff --git a/src/Lumina.Presentation.Api/Core/Controllers/Maintenance/HealthController.cs b/src/Lumina.Presentation.Api/Core/Controllers/Maintenance/HealthController.cs deleted file mode 100644 index d66c202e..00000000 --- a/src/Lumina.Presentation.Api/Core/Controllers/Maintenance/HealthController.cs +++ /dev/null @@ -1,24 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using Lumina.Presentation.Api.Core.Controllers.Common; -using Microsoft.AspNetCore.Mvc; -using System.Threading.Tasks; -#endregion - -namespace Lumina.Presentation.Api.Core.Controllers.Maintenance; - -/// -/// Controller for health checks. -/// -[Route("[controller]")] -public class HealthController : ApiController -{ - /// - /// Checks if the application is healthy. - /// - [HttpGet("check-health")] - public async Task CheckHealth() - { - // TODO: to be implemented - return await Task.FromResult(Ok()); - } -} diff --git a/src/Lumina.Presentation.Api/Core/Controllers/WrittenContentLibrary/BookLibrary/Books/BooksController.cs b/src/Lumina.Presentation.Api/Core/Controllers/WrittenContentLibrary/BookLibrary/Books/BooksController.cs deleted file mode 100644 index 7f20ffb1..00000000 --- a/src/Lumina.Presentation.Api/Core/Controllers/WrittenContentLibrary/BookLibrary/Books/BooksController.cs +++ /dev/null @@ -1,55 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using Lumina.Application.Core.WrittenContentLibrary.BooksLibrary.Books.Commands.AddBook; -using Lumina.Application.Core.WrittenContentLibrary.BooksLibrary.Books.Queries.GetBooks; -using Lumina.Contracts.Requests.WrittenContentLibrary.BookLibrary; -using Lumina.Presentation.Api.Core.Controllers.Common; -using MapsterMapper; -using Mediator; -using Microsoft.AspNetCore.Mvc; -using System.Threading.Tasks; -#endregion - -namespace Lumina.Presentation.Api.Core.Controllers.WrittenContentLibrary.BookLibrary.Books; - -/// -/// Controller for managing books. -/// -[ApiVersion("1.0")] -[Route("api/v{version:apiVersion}/[controller]")] -public class BooksController : ApiController -{ - private readonly ISender _mediator; - private readonly IMapper _mapper; - - /// - /// Initializes a new instance of the class. - /// - /// Injected service for mediating commands and queries. - /// Injected service for mapping objects. - public BooksController(ISender mediator, IMapper mapper) - { - _mediator = mediator; - _mapper = mapper; - } - - /// - /// Controller action for getting the list of all books. - /// - [HttpGet()] - public async Task GetBooks() - { - ErrorOr.ErrorOr> result = await _mediator.Send(new GetBooksQuery()).ConfigureAwait(false); - return result.Match(result => Ok(result), errors => Problem(errors)); - } - - /// - /// Controller action for adding a book. - /// - /// The command to add a book. - [HttpPost()] - public async Task AddBook(AddBookRequest request) - { - ErrorOr.ErrorOr result = await _mediator.Send(_mapper.Map(request)).ConfigureAwait(false); - return result.Match(result => Created($"/api/v1/books/{result.Id}", result), Problem); - } -} diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Common/BaseEndpoint.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Common/BaseEndpoint.cs new file mode 100644 index 00000000..89fc9675 --- /dev/null +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Common/BaseEndpoint.cs @@ -0,0 +1,102 @@ +#region ========================================================================= USING ===================================================================================== +using ErrorOr; +using FastEndpoints; +using Lumina.Presentation.Api.Common.Http; +using Microsoft.AspNetCore.Http; +using System.Collections.Generic; +using System.Diagnostics; +using System.Linq; +#endregion + +namespace Lumina.Presentation.Api.Core.Endpoints.Common; + +/// +/// Base class for API endpoints. +/// +/// The type of the request object. +/// The type of the response object. +public abstract class BaseEndpoint : Endpoint where TRequest : notnull + where TResponse : notnull +{ + /// + /// Handles controllers errors. + /// + /// The error to handle. + protected IResult Problem(List errors) + { + if (errors.Count is 0) // if there are no custom errors given, return a generic problem + return Results.Problem(); + // try to make the problem type more specific + if (errors.All(error => error.Type == ErrorType.Validation)) + return ValidationProblem(errors); + // here we could handle custom error types, for instance: if (errors.All(error => error.NumericType == 23)), where 23 could be "domain errors" + + // share the list of errors within the scope of this HTTP request + HttpContext.Items[HttpContextItemKeys.ERRORS] = errors; + // get a HTTP error status code for the selected domain error type + return Problem(errors.First()); + } + + /// + /// Converts an to a standard problem response. + /// + /// The error to convert. + protected IResult Problem(Error error) + { + Dictionary extensionsDictionary = []; + int statusCode = error.Type switch + { + ErrorType.Conflict => StatusCodes.Status409Conflict, + ErrorType.NotFound => StatusCodes.Status404NotFound, + ErrorType.Validation => StatusCodes.Status400BadRequest, + ErrorType.Failure => StatusCodes.Status403Forbidden, + _ => StatusCodes.Status500InternalServerError, + }; + + extensionsDictionary["traceId"] = Activity.Current?.Id ?? HttpContext.TraceIdentifier; + + // return the HTTP error status and the domain error message + return Results.Problem( + detail: error.Description, + instance: HttpContext.Request.Path, + statusCode: statusCode, + title: error.Code, + extensions: extensionsDictionary + ); + } + + /// + /// Converts a list of into a standard validation problem response. + /// + /// The list of errors to convert. + protected IResult ValidationProblem(List errors) + { + Dictionary errorsDictionary = []; + Dictionary extensionsDictionary = []; + + // populate the errors dictionary with error codes and their descriptions + foreach (Error error in errors) + { + if (!errorsDictionary.TryGetValue(error.Code, out string[]? value)) + errorsDictionary.Add(error.Code, [error.Description]); + else + { + if (!errorsDictionary[error.Code].Contains(error.Description)) + errorsDictionary[error.Code] = [.. value, error.Description]; + } + } + + // add trace identifier to the extensions dictionary for tracing purposes + extensionsDictionary["traceId"] = Activity.Current?.Id ?? HttpContext.TraceIdentifier; + + // return a validation problem result with the constructed error details + return Results.ValidationProblem( + errorsDictionary, + detail: "One or more validation errors occurred.", + instance: HttpContext.Request.Path, + statusCode: 422, + title: "Validation Error", + extensions: extensionsDictionary + ); + } +} diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/FileSystemManagement/Directories/GetDirectories/GetDirectoriesEndpoint.cs b/src/Lumina.Presentation.Api/Core/Endpoints/FileSystemManagement/Directories/GetDirectories/GetDirectoriesEndpoint.cs new file mode 100644 index 00000000..f10bc0c6 --- /dev/null +++ b/src/Lumina.Presentation.Api/Core/Endpoints/FileSystemManagement/Directories/GetDirectories/GetDirectoriesEndpoint.cs @@ -0,0 +1,57 @@ +#region ========================================================================= USING ===================================================================================== +using ErrorOr; +using FastEndpoints; +using Lumina.Application.Common.Mapping.FileSystemManagement.Paths; +using Lumina.Contracts.Requests.FileSystemManagement.Directories; +using Lumina.Application.Common.Mapping.FileSystemManagement.Directories; +using Lumina.Presentation.Api.Common.Routes.FileSystemManagement; +using Lumina.Presentation.Api.Core.Endpoints.Common; +using Mediator; +using Microsoft.AspNetCore.Http; +using System.Threading; +using System.Threading.Tasks; +using System.Collections.Generic; +using Lumina.Contracts.Responses.FileSystemManagement.Directories; +#endregion + +namespace Lumina.Presentation.Api.Core.Endpoints.FileSystemManagement.Directories.GetDirectories; + +/// +/// API endpoint for the /directories/get-directories route. +/// +public class GetDirectoriesEndpoint : BaseEndpoint +{ + private readonly ISender _sender; + + /// + /// Initializes a new instance of the class. + /// + /// Injected service for mediating commands and queries. + public GetDirectoriesEndpoint(ISender sender) + { + _sender = sender; + } + + /// + /// Configures the API endpoint. + /// + public override void Configure() + { + Verbs(Http.GET); + Routes(ApiRoutes.Directories.GET_DIRECTORIES); + Version(1); + AllowAnonymous(); + DontCatchExceptions(); + } + + /// + /// Gets the directories of the path stored in . + /// + /// The request containing the file system path for which to get the directories. + /// Cancellation token that can be used to stop the execution. + public override async Task ExecuteAsync(GetDirectoriesRequest request, CancellationToken cancellationToken) + { + ErrorOr> result = await _sender.Send(request.ToQuery(), cancellationToken).ConfigureAwait(false); + return result.Match(success => TypedResults.Ok(success), Problem); + } +} diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/FileSystemManagement/Directories/GetDirectories/GetDirectoriesEndpointSummary.cs b/src/Lumina.Presentation.Api/Core/Endpoints/FileSystemManagement/Directories/GetDirectories/GetDirectoriesEndpointSummary.cs new file mode 100644 index 00000000..254e1cb1 --- /dev/null +++ b/src/Lumina.Presentation.Api/Core/Endpoints/FileSystemManagement/Directories/GetDirectories/GetDirectoriesEndpointSummary.cs @@ -0,0 +1,29 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Contracts.Requests.FileSystemManagement.Directories; +using Lumina.Contracts.Responses.FileSystemManagement.Directories; +using System.Collections.Generic; +#endregion + +namespace Lumina.Presentation.Api.Core.Endpoints.FileSystemManagement.Directories.GetDirectories; + +/// +/// Class used for providing a textual description for the API endpoint, for Swagger. +/// +public class GetDirectoriesEndpointSummary : Summary +{ + /// + /// Initializes a new instance of the class. + /// + public GetDirectoriesEndpointSummary() + { + Summary = "Retrieves the list of directories for a specified file system path."; + Description = "Returns the directories within the specified path, with an option to include hidden file system elements."; + + RequestParam(r => r.Path, "The file system path for which to get the directories."); + RequestParam(r => r.IncludeHiddenElements, "Whether to include hidden file system elements or not."); + + Response>(200, "The list of directories for the specified path is returned."); + Response(422, "The request did not pass validation checks.", "application/problem+json"); + } +} diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/FileSystemManagement/Directories/GetDirectoryTree/GetDirectoryTreeEndpoint.cs b/src/Lumina.Presentation.Api/Core/Endpoints/FileSystemManagement/Directories/GetDirectoryTree/GetDirectoryTreeEndpoint.cs new file mode 100644 index 00000000..4b6b7703 --- /dev/null +++ b/src/Lumina.Presentation.Api/Core/Endpoints/FileSystemManagement/Directories/GetDirectoryTree/GetDirectoryTreeEndpoint.cs @@ -0,0 +1,57 @@ +#region ========================================================================= USING ===================================================================================== +using ErrorOr; +using FastEndpoints; +using Lumina.Application.Common.Mapping.FileSystemManagement.Directories; +using Lumina.Contracts.Requests.FileSystemManagement.Directories; +using Lumina.Contracts.Requests.FileSystemManagement.Path; +using Lumina.Contracts.Responses.FileSystemManagement.Common; +using Lumina.Presentation.Api.Common.Routes.FileSystemManagement; +using Lumina.Presentation.Api.Core.Endpoints.Common; +using Mediator; +using Microsoft.AspNetCore.Http; +using System.Collections.Generic; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Api.Core.Endpoints.FileSystemManagement.Directories.GetDirectoryTree; + +/// +/// API endpoint for the /directories/get-directory-tree route. +/// +public class GetDirectoryTreeEndpoint : BaseEndpoint +{ + private readonly ISender _sender; + + /// + /// Initializes a new instance of the class. + /// + /// Injected service for mediating commands and queries. + public GetDirectoryTreeEndpoint(ISender sender) + { + _sender = sender; + } + + /// + /// Configures the API endpoint. + /// + public override void Configure() + { + Verbs(Http.GET); + Routes(ApiRoutes.Directories.GET_DIRECTORY_TREE); + Version(1); + AllowAnonymous(); + DontCatchExceptions(); + } + + /// + /// Gets the tree of expanded directories leading up to the path stored in , with the additional list of drives, and children of the last child directory. + /// + /// The request containing the file system path for for which to get the directory tree. + /// Cancellation token that can be used to stop the execution. + public override async Task ExecuteAsync(GetDirectoryTreeRequest request, CancellationToken cancellationToken) + { + ErrorOr> result = await _sender.Send(request.ToQuery(), cancellationToken).ConfigureAwait(false); + return result.Match(success => TypedResults.Ok(success), Problem); + } +} diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/FileSystemManagement/Directories/GetDirectoryTree/GetDirectoryTreeEndpointSummary.cs b/src/Lumina.Presentation.Api/Core/Endpoints/FileSystemManagement/Directories/GetDirectoryTree/GetDirectoryTreeEndpointSummary.cs new file mode 100644 index 00000000..d8954ec5 --- /dev/null +++ b/src/Lumina.Presentation.Api/Core/Endpoints/FileSystemManagement/Directories/GetDirectoryTree/GetDirectoryTreeEndpointSummary.cs @@ -0,0 +1,30 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Contracts.Requests.FileSystemManagement.Directories; +using Lumina.Contracts.Responses.FileSystemManagement.Common; +using System.Collections.Generic; +#endregion + +namespace Lumina.Presentation.Api.Core.Endpoints.FileSystemManagement.Directories.GetDirectoryTree; + +/// +/// Class used for providing a textual description for the API endpoint, for Swagger. +/// +public class GetDirectoryTreeEndpointSummary : Summary +{ + /// + /// Initializes a new instance of the class. + /// + public GetDirectoryTreeEndpointSummary() + { + Summary = "Retrieves the directory tree structure for a specified file system path."; + Description = "Returns a hierarchical view of the directory tree, with options to include files and hidden elements."; + + RequestParam(r => r.Path, "The file system path for which to get the directory tree."); + RequestParam(r => r.IncludeFiles, "Whether to include files along the directories or not."); + RequestParam(r => r.IncludeHiddenElements, "Whether to include hidden file system elements or not."); + + Response>(200, "The directory tree structure for the specified path."); + Response(422, "The request did not pass validation checks.", "application/problem+json"); + } +} diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/FileSystemManagement/Directories/GetTreeDirectories/GetTreeDirectoriesEndpoint.cs b/src/Lumina.Presentation.Api/Core/Endpoints/FileSystemManagement/Directories/GetTreeDirectories/GetTreeDirectoriesEndpoint.cs new file mode 100644 index 00000000..fb24cd65 --- /dev/null +++ b/src/Lumina.Presentation.Api/Core/Endpoints/FileSystemManagement/Directories/GetTreeDirectories/GetTreeDirectoriesEndpoint.cs @@ -0,0 +1,56 @@ +#region ========================================================================= USING ===================================================================================== +using ErrorOr; +using FastEndpoints; +using Lumina.Application.Common.Mapping.FileSystemManagement.Directories; +using Lumina.Contracts.Requests.FileSystemManagement.Directories; +using Lumina.Contracts.Responses.FileSystemManagement.Common; +using Lumina.Presentation.Api.Common.Routes.FileSystemManagement; +using Lumina.Presentation.Api.Core.Endpoints.Common; +using Mediator; +using Microsoft.AspNetCore.Http; +using System.Collections.Generic; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Api.Core.Endpoints.FileSystemManagement.Directories.GetTreeDirectories; + +/// +/// API endpoint for the /directories/get-tree-directories route. +/// +public class GetTreeDirectoriesEndpoint : BaseEndpoint +{ + private readonly ISender _sender; + + /// + /// Initializes a new instance of the class. + /// + /// Injected service for mediating commands and queries. + public GetTreeDirectoriesEndpoint(ISender sender) + { + _sender = sender; + } + + /// + /// Configures the API endpoint. + /// + public override void Configure() + { + Verbs(Http.GET); + Routes(ApiRoutes.Directories.GET_TREE_DIRECTORIES); + Version(1); + AllowAnonymous(); + DontCatchExceptions(); + } + + /// + /// Gets the directories of the path stored in . + /// + /// The request containing the file system path for which to get the directories. + /// Cancellation token that can be used to stop the execution. + public override async Task ExecuteAsync(GetTreeDirectoriesRequest request, CancellationToken cancellationToken) + { + ErrorOr> result = await _sender.Send(request.ToQuery(), cancellationToken).ConfigureAwait(false); + return result.Match(success => TypedResults.Ok(success), Problem); + } +} diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/FileSystemManagement/Directories/GetTreeDirectories/GetTreeDirectoriesEndpointSummary.cs b/src/Lumina.Presentation.Api/Core/Endpoints/FileSystemManagement/Directories/GetTreeDirectories/GetTreeDirectoriesEndpointSummary.cs new file mode 100644 index 00000000..107a5e3f --- /dev/null +++ b/src/Lumina.Presentation.Api/Core/Endpoints/FileSystemManagement/Directories/GetTreeDirectories/GetTreeDirectoriesEndpointSummary.cs @@ -0,0 +1,29 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Contracts.Requests.FileSystemManagement.Directories; +using Lumina.Contracts.Responses.FileSystemManagement.Common; +using System.Collections.Generic; +#endregion + +namespace Lumina.Presentation.Api.Core.Endpoints.FileSystemManagement.Directories.GetTreeDirectories; + +/// +/// Class used for providing a textual description for the API endpoint, for Swagger. +/// +public class GetTreeDirectoriesEndpointSummary : Summary +{ + /// + /// Initializes a new instance of the class. + /// + public GetTreeDirectoriesEndpointSummary() + { + Summary = "Retrieves the directory tree structure for the specified file system path."; + Description = "Returns the directory tree structure, with an option to include hidden file system elements."; + + RequestParam(r => r.Path, "The file system path for which to get the directory tree."); + RequestParam(r => r.IncludeHiddenElements, "Whether to include hidden file system elements or not."); + + Response>(200, "The directory tree structure is returned."); + Response(422, "The request did not pass validation checks.", "application/problem+json"); + } +} diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/FileSystemManagement/Drives/GetDrives/GetDrivesEndpoint.cs b/src/Lumina.Presentation.Api/Core/Endpoints/FileSystemManagement/Drives/GetDrives/GetDrivesEndpoint.cs new file mode 100644 index 00000000..af4de3d6 --- /dev/null +++ b/src/Lumina.Presentation.Api/Core/Endpoints/FileSystemManagement/Drives/GetDrives/GetDrivesEndpoint.cs @@ -0,0 +1,54 @@ +#region ========================================================================= USING ===================================================================================== +using ErrorOr; +using FastEndpoints; +using Lumina.Application.Core.FileSystemManagement.Drives.Queries.GetDrives; +using Lumina.Contracts.Responses.FileSystemManagement.Common; +using Lumina.Presentation.Api.Common.Routes.FileSystemManagement; +using Lumina.Presentation.Api.Core.Endpoints.Common; +using Mediator; +using Microsoft.AspNetCore.Http; +using System.Collections.Generic; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Api.Core.Endpoints.FileSystemManagement.Drives.GetDrives; + +/// +/// API endpoint for the /drives/get-drives route. +/// +public class GetDrivesEndpoint : BaseEndpoint +{ + private readonly ISender _sender; + + /// + /// Initializes a new instance of the class. + /// + /// Injected service for mediating commands and queries. + public GetDrivesEndpoint(ISender sender) + { + _sender = sender; + } + + /// + /// Configures the API endpoint. + /// + public override void Configure() + { + Verbs(Http.GET); + Routes(ApiRoutes.Drives.GET_DRIVES); + Version(1); + AllowAnonymous(); + DontCatchExceptions(); + } + + /// + /// Gets the list of file system drives. + /// + /// Cancellation token that can be used to stop the execution. + public override async Task ExecuteAsync(EmptyRequest _, CancellationToken cancellationToken) + { + ErrorOr> result = await _sender.Send(new GetDrivesQuery(), cancellationToken).ConfigureAwait(false); + return result.Match(success => TypedResults.Ok(success), Problem); + } +} diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/FileSystemManagement/Drives/GetDrives/GetDrivesEndpointSummary.cs b/src/Lumina.Presentation.Api/Core/Endpoints/FileSystemManagement/Drives/GetDrives/GetDrivesEndpointSummary.cs new file mode 100644 index 00000000..7c4a876d --- /dev/null +++ b/src/Lumina.Presentation.Api/Core/Endpoints/FileSystemManagement/Drives/GetDrives/GetDrivesEndpointSummary.cs @@ -0,0 +1,24 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Contracts.Responses.FileSystemManagement.Common; +using System.Collections.Generic; +#endregion + +namespace Lumina.Presentation.Api.Core.Endpoints.FileSystemManagement.Drives.GetDrives; + +/// +/// Class used for providing a textual description for the API endpoint, for Swagger. +/// +public class GetDrivesEndpointSummary : Summary +{ + /// + /// Initializes a new instance of the class. + /// + public GetDrivesEndpointSummary() + { + Summary = "Retrieves the list of file system drives."; + Description = "Returns all available drives in the file system, on Windows, or the root path, on UNIX."; + + Response>(200, "The list of file system drives is returned."); + } +} diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/FileSystemManagement/FileSystem/GetType/GetTypeEndpoint.cs b/src/Lumina.Presentation.Api/Core/Endpoints/FileSystemManagement/FileSystem/GetType/GetTypeEndpoint.cs new file mode 100644 index 00000000..249320e9 --- /dev/null +++ b/src/Lumina.Presentation.Api/Core/Endpoints/FileSystemManagement/FileSystem/GetType/GetTypeEndpoint.cs @@ -0,0 +1,56 @@ +#region ========================================================================= USING ===================================================================================== +using ErrorOr; +using FastEndpoints; +using Lumina.Application.Common.Mapping.FileSystemManagement.Files; +using Lumina.Application.Core.FileSystemManagement.FileSystem.Queries.GetFileSystem; +using Lumina.Contracts.Requests.FileSystemManagement.Files; +using Lumina.Contracts.Responses.FileSystemManagement.FileSystem; +using Lumina.Presentation.Api.Common.Routes.FileSystemManagement; +using Lumina.Presentation.Api.Core.Endpoints.Common; +using Mediator; +using Microsoft.AspNetCore.Http; +using System.Collections.Generic; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Api.Core.Endpoints.FileSystemManagement.FileSystem.GetType; + +/// +/// API endpoint for the /file-system/get-type route. +/// +public class GetTypeEndpoint : BaseEndpoint +{ + private readonly ISender _sender; + + /// + /// Initializes a new instance of the class. + /// + /// Injected service for mediating commands and queries. + public GetTypeEndpoint(ISender sender) + { + _sender = sender; + } + + /// + /// Configures the API endpoint. + /// + public override void Configure() + { + Verbs(Http.GET); + Routes(ApiRoutes.FileSystem.GET_TYPES); + Version(1); + AllowAnonymous(); + DontCatchExceptions(); + } + + /// + /// Gets the type of the file system. + /// + /// Cancellation token that can be used to stop the execution. + public override async Task ExecuteAsync(EmptyRequest _, CancellationToken cancellationToken) + { + FileSystemTypeResponse platformType = await _sender.Send(new GetFileSystemQuery(), cancellationToken).ConfigureAwait(false); + return TypedResults.Ok(platformType); + } +} diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/FileSystemManagement/FileSystem/GetType/GetTypeEndpointSummary.cs b/src/Lumina.Presentation.Api/Core/Endpoints/FileSystemManagement/FileSystem/GetType/GetTypeEndpointSummary.cs new file mode 100644 index 00000000..be0c69d3 --- /dev/null +++ b/src/Lumina.Presentation.Api/Core/Endpoints/FileSystemManagement/FileSystem/GetType/GetTypeEndpointSummary.cs @@ -0,0 +1,23 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Contracts.Responses.FileSystemManagement.FileSystem; +#endregion + +namespace Lumina.Presentation.Api.Core.Endpoints.FileSystemManagement.FileSystem.GetType; + +/// +/// Class used for providing a textual description for the API endpoint, for Swagger. +/// +public class GetTypeEndpointSummary : Summary +{ + /// + /// Initializes a new instance of the class. + /// + public GetTypeEndpointSummary() + { + Summary = "Gets the type of the file system."; + Description = "Returns the type of the file system."; + + Response(200, "The file system type is returned."); + } +} diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/FileSystemManagement/Files/GetFiles/GetFilesEndpoint.cs b/src/Lumina.Presentation.Api/Core/Endpoints/FileSystemManagement/Files/GetFiles/GetFilesEndpoint.cs new file mode 100644 index 00000000..48abc6da --- /dev/null +++ b/src/Lumina.Presentation.Api/Core/Endpoints/FileSystemManagement/Files/GetFiles/GetFilesEndpoint.cs @@ -0,0 +1,56 @@ +#region ========================================================================= USING ===================================================================================== +using ErrorOr; +using FastEndpoints; +using Lumina.Application.Common.Mapping.FileSystemManagement.Files; +using Lumina.Contracts.Requests.FileSystemManagement.Files; +using Lumina.Contracts.Responses.FileSystemManagement.Files; +using Lumina.Presentation.Api.Common.Routes.FileSystemManagement; +using Lumina.Presentation.Api.Core.Endpoints.Common; +using Mediator; +using Microsoft.AspNetCore.Http; +using System.Collections.Generic; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Api.Core.Endpoints.FileSystemManagement.Files.GetFiles; + +/// +/// API endpoint for the /files/get-files route. +/// +public class GetFilesEndpoint : BaseEndpoint +{ + private readonly ISender _sender; + + /// + /// Initializes a new instance of the class. + /// + /// Injected service for mediating commands and queries. + public GetFilesEndpoint(ISender sender) + { + _sender = sender; + } + + /// + /// Configures the API endpoint. + /// + public override void Configure() + { + Verbs(Http.GET); + Routes(ApiRoutes.Files.GET_FILES); + Version(1); + AllowAnonymous(); + DontCatchExceptions(); + } + + /// + /// Gets the files of the path stored in . + /// + /// The request containing the file system path for which to get the files. + /// Cancellation token that can be used to stop the execution. + public override async Task ExecuteAsync(GetFilesRequest request, CancellationToken cancellationToken) + { + ErrorOr> result = await _sender.Send(request.ToQuery(), cancellationToken).ConfigureAwait(false); + return result.Match(success => TypedResults.Ok(success), Problem); + } +} diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/FileSystemManagement/Files/GetFiles/GetFilesEndpointSummary.cs b/src/Lumina.Presentation.Api/Core/Endpoints/FileSystemManagement/Files/GetFiles/GetFilesEndpointSummary.cs new file mode 100644 index 00000000..c247e725 --- /dev/null +++ b/src/Lumina.Presentation.Api/Core/Endpoints/FileSystemManagement/Files/GetFiles/GetFilesEndpointSummary.cs @@ -0,0 +1,29 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Contracts.Requests.FileSystemManagement.Files; +using Lumina.Contracts.Responses.FileSystemManagement.Common; +using System.Collections.Generic; +#endregion + +namespace Lumina.Presentation.Api.Core.Endpoints.FileSystemManagement.Files.GetFiles; + +/// +/// Class used for providing a textual description for the API endpoint, for Swagger. +/// +public class GetFilesEndpointSummary : Summary +{ + /// + /// Initializes a new instance of the class. + /// + public GetFilesEndpointSummary() + { + Summary = "Retrieves the list of files for a specified file system path."; + Description = "Returns the files within the specified path, with an option to include hidden file system elements."; + + RequestParam(r => r.Path, "The file system path for which to get the files."); + RequestParam(r => r.IncludeHiddenElements, "Whether to include hidden file system elements or not."); + + Response>(200, "The list of files is returned."); + Response(422, "The request did not pass validation checks.", "application/problem+json"); + } +} diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/FileSystemManagement/Files/GetTreeFiles/GetTreeFilesEndpoint.cs b/src/Lumina.Presentation.Api/Core/Endpoints/FileSystemManagement/Files/GetTreeFiles/GetTreeFilesEndpoint.cs new file mode 100644 index 00000000..4894a63a --- /dev/null +++ b/src/Lumina.Presentation.Api/Core/Endpoints/FileSystemManagement/Files/GetTreeFiles/GetTreeFilesEndpoint.cs @@ -0,0 +1,56 @@ +#region ========================================================================= USING ===================================================================================== +using ErrorOr; +using FastEndpoints; +using Lumina.Application.Common.Mapping.FileSystemManagement.Files; +using Lumina.Contracts.Requests.FileSystemManagement.Files; +using Lumina.Contracts.Responses.FileSystemManagement.Common; +using Lumina.Presentation.Api.Common.Routes.FileSystemManagement; +using Lumina.Presentation.Api.Core.Endpoints.Common; +using Mediator; +using Microsoft.AspNetCore.Http; +using System.Collections.Generic; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Api.Core.Endpoints.FileSystemManagement.Files.GetTreeFiles; + +/// +/// API endpoint for the /files/get-tree-files route. +/// +public class GetTreeFilesEndpoint : BaseEndpoint +{ + private readonly ISender _sender; + + /// + /// Initializes a new instance of the class. + /// + /// Injected service for mediating commands and queries. + public GetTreeFilesEndpoint(ISender sender) + { + _sender = sender; + } + + /// + /// Configures the API endpoint. + /// + public override void Configure() + { + Verbs(Http.GET); + Routes(ApiRoutes.Files.GET_TREE_FILES); + Version(1); + AllowAnonymous(); + DontCatchExceptions(); + } + + /// + /// Gets the files of the path stored in . + /// + /// The request containing the file system path for which to get the files. + /// Cancellation token that can be used to stop the execution. + public override async Task ExecuteAsync(GetTreeFilesRequest request, CancellationToken cancellationToken) + { + ErrorOr> result = await _sender.Send(request.ToQuery(), cancellationToken).ConfigureAwait(false); + return result.Match(success => TypedResults.Ok(success), Problem); + } +} diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/FileSystemManagement/Files/GetTreeFiles/GetTreeFilesEndpointSummary.cs b/src/Lumina.Presentation.Api/Core/Endpoints/FileSystemManagement/Files/GetTreeFiles/GetTreeFilesEndpointSummary.cs new file mode 100644 index 00000000..1a227c34 --- /dev/null +++ b/src/Lumina.Presentation.Api/Core/Endpoints/FileSystemManagement/Files/GetTreeFiles/GetTreeFilesEndpointSummary.cs @@ -0,0 +1,29 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Contracts.Requests.FileSystemManagement.Files; +using Lumina.Contracts.Responses.FileSystemManagement.Common; +using System.Collections.Generic; +#endregion + +namespace Lumina.Presentation.Api.Core.Endpoints.FileSystemManagement.Files.GetTreeFiles; + +/// +/// Class used for providing a textual description for the API endpoint, for Swagger. +/// +public class GetTreeFilesEndpointSummary : Summary +{ + /// + /// Initializes a new instance of the class. + /// + public GetTreeFilesEndpointSummary() + { + Summary = "Retrieves the tree structure of files for a specified file system path."; + Description = "Returns the files within the specified path in a hierarchical tree structure, with an option to include hidden file system elements."; + + RequestParam(r => r.Path, "The file system path for which to get the tree files."); + RequestParam(r => r.IncludeHiddenElements, "Whether to include hidden file system elements or not."); + + Response>(200, "The tree structure of files is returned."); + Response(422, "The request did not pass validation checks.", "application/problem+json"); + } +} diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/FileSystemManagement/Path/CheckPathExists/CheckPathExistsEndpoint.cs b/src/Lumina.Presentation.Api/Core/Endpoints/FileSystemManagement/Path/CheckPathExists/CheckPathExistsEndpoint.cs new file mode 100644 index 00000000..685481eb --- /dev/null +++ b/src/Lumina.Presentation.Api/Core/Endpoints/FileSystemManagement/Path/CheckPathExists/CheckPathExistsEndpoint.cs @@ -0,0 +1,54 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Application.Common.Mapping.FileSystemManagement.Paths; +using Lumina.Contracts.Requests.FileSystemManagement.Path; +using Lumina.Contracts.Responses.FileSystemManagement.Path; +using Lumina.Presentation.Api.Common.Routes.FileSystemManagement; +using Lumina.Presentation.Api.Core.Endpoints.Common; +using Mediator; +using Microsoft.AspNetCore.Http; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Api.Core.Endpoints.FileSystemManagement.Path.CheckPathExists; + +/// +/// API endpoint for the /path/check-path-exists route. +/// +public class CheckPathExistsEndpoint : BaseEndpoint +{ + private readonly ISender _sender; + + /// + /// Initializes a new instance of the class. + /// + /// Injected service for mediating commands and queries. + public CheckPathExistsEndpoint(ISender sender) + { + _sender = sender; + } + + /// + /// Configures the API endpoint. + /// + public override void Configure() + { + Verbs(Http.GET); + Routes(ApiRoutes.Path.CHECK_PATH_EXISTS); + Version(1); + AllowAnonymous(); + DontCatchExceptions(); + } + + /// + /// Checks the existence of the file system path stored in . + /// + /// The request containing the file system path whose existence is checked. + /// Cancellation token that can be used to stop the execution. + public override async Task ExecuteAsync(CheckPathExistsRequest request, CancellationToken cancellationToken) + { + PathExistsResponse result = await _sender.Send(request.ToQuery(), cancellationToken).ConfigureAwait(false); + return TypedResults.Ok(result); + } +} diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/FileSystemManagement/Path/CheckPathExists/CheckPathExistsEndpointSummary.cs b/src/Lumina.Presentation.Api/Core/Endpoints/FileSystemManagement/Path/CheckPathExists/CheckPathExistsEndpointSummary.cs new file mode 100644 index 00000000..f75d6371 --- /dev/null +++ b/src/Lumina.Presentation.Api/Core/Endpoints/FileSystemManagement/Path/CheckPathExists/CheckPathExistsEndpointSummary.cs @@ -0,0 +1,29 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using FastEndpoints.Swagger; +using Lumina.Contracts.Requests.FileSystemManagement.Path; +using Lumina.Contracts.Responses.FileSystemManagement.Path; +#endregion + +namespace Lumina.Presentation.Api.Core.Endpoints.FileSystemManagement.Path.CheckPathExists; + +/// +/// Class used for providing a textual description for the API endpoint, for Swagger. +/// +public class CheckPathExistsEndpointSummary : Summary +{ + /// + /// Initializes a new instance of the class. + /// + public CheckPathExistsEndpointSummary() + { + Summary = "Checks the existence of a file system path."; + Description = "Verifies if the specified file system path exists, with an option to include hidden elements in the search."; + + RequestParam(r => r.Path, "The file system path to check the exitence of."); + RequestParam(r => r.IncludeHiddenElements, "Whether to include hidden elements in the search results, or not."); + + Response(200, "Indicates whether the file system path exists."); + Response(422, "The request did not pass validation checks.", "application/problem+json"); + } +} diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/FileSystemManagement/Path/CombinePath/CombinePathEndpoint.cs b/src/Lumina.Presentation.Api/Core/Endpoints/FileSystemManagement/Path/CombinePath/CombinePathEndpoint.cs new file mode 100644 index 00000000..31d1f71b --- /dev/null +++ b/src/Lumina.Presentation.Api/Core/Endpoints/FileSystemManagement/Path/CombinePath/CombinePathEndpoint.cs @@ -0,0 +1,55 @@ +#region ========================================================================= USING ===================================================================================== +using ErrorOr; +using FastEndpoints; +using Lumina.Application.Common.Mapping.FileSystemManagement.Paths; +using Lumina.Contracts.Requests.FileSystemManagement.Path; +using Lumina.Contracts.Responses.FileSystemManagement.Path; +using Lumina.Presentation.Api.Common.Routes.FileSystemManagement; +using Lumina.Presentation.Api.Core.Endpoints.Common; +using Mediator; +using Microsoft.AspNetCore.Http; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Api.Core.Endpoints.FileSystemManagement.Path.CombinePath; + +/// +/// API endpoint for the /path/combine route. +/// +public class CombinePathEndpoint : BaseEndpoint +{ + private readonly ISender _sender; + + /// + /// Initializes a new instance of the class. + /// + /// Injected service for mediating commands and queries. + public CombinePathEndpoint(ISender sender) + { + _sender = sender; + } + + /// + /// Configures the API endpoint. + /// + public override void Configure() + { + Verbs(Http.GET); + Routes(ApiRoutes.Path.COMBINE); + Version(1); + AllowAnonymous(); + DontCatchExceptions(); + } + + /// + /// Combines the paths stored in . + /// + /// The request containing the paths to be combined. + /// Cancellation token that can be used to stop the execution. + public override async Task ExecuteAsync(CombinePathRequest request, CancellationToken cancellationToken) + { + ErrorOr result = await _sender.Send(request.ToCommand(), cancellationToken).ConfigureAwait(false); + return result.Match(success => TypedResults.Ok(success), Problem); + } +} diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/FileSystemManagement/Path/CombinePath/CombinePathEndpointSummary.cs b/src/Lumina.Presentation.Api/Core/Endpoints/FileSystemManagement/Path/CombinePath/CombinePathEndpointSummary.cs new file mode 100644 index 00000000..a027c023 --- /dev/null +++ b/src/Lumina.Presentation.Api/Core/Endpoints/FileSystemManagement/Path/CombinePath/CombinePathEndpointSummary.cs @@ -0,0 +1,28 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Contracts.Requests.FileSystemManagement.Path; +using Lumina.Contracts.Responses.FileSystemManagement.Path; +#endregion + +namespace Lumina.Presentation.Api.Core.Endpoints.FileSystemManagement.Path.CombinePath; + +/// +/// Class used for providing a textual description for the API endpoint, for Swagger. +/// +public class CombinePathEndpointSummary : Summary +{ + /// + /// Initializes a new instance of the class. + /// + public CombinePathEndpointSummary() + { + Summary = "Combines two file system paths."; + Description = "Combines the specified original path with a new path to form a single file system path."; + + RequestParam(r => r.OriginalPath, "The file system path to combine to."); + RequestParam(r => r.NewPath, "The file system path to combine with."); + + Response(200, "Successfully combined the paths."); + Response(422, "The request did not pass validation checks.", "application/problem+json"); + } +} diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/FileSystemManagement/Path/GetPathParent/GetPathParentEndpoint.cs b/src/Lumina.Presentation.Api/Core/Endpoints/FileSystemManagement/Path/GetPathParent/GetPathParentEndpoint.cs new file mode 100644 index 00000000..aa5ce86c --- /dev/null +++ b/src/Lumina.Presentation.Api/Core/Endpoints/FileSystemManagement/Path/GetPathParent/GetPathParentEndpoint.cs @@ -0,0 +1,56 @@ +#region ========================================================================= USING ===================================================================================== +using ErrorOr; +using FastEndpoints; +using Lumina.Application.Common.Mapping.FileSystemManagement.Paths; +using Lumina.Contracts.Requests.FileSystemManagement.Path; +using Lumina.Contracts.Responses.FileSystemManagement.Path; +using Lumina.Presentation.Api.Common.Routes.FileSystemManagement; +using Lumina.Presentation.Api.Core.Endpoints.Common; +using Mediator; +using Microsoft.AspNetCore.Http; +using System.Collections.Generic; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Api.Core.Endpoints.FileSystemManagement.Path.GetPathParent; + +/// +/// API endpoint for the /path/get-path-parent route. +/// +public class GetPathParentEndpoint : BaseEndpoint +{ + private readonly ISender _sender; + + /// + /// Initializes a new instance of the class. + /// + /// Injected service for mediating commands and queries. + public GetPathParentEndpoint(ISender sender) + { + _sender = sender; + } + + /// + /// Configures the API endpoint. + /// + public override void Configure() + { + Verbs(Http.GET); + Routes(ApiRoutes.Path.GET_PATH_PARENT); + Version(1); + AllowAnonymous(); + DontCatchExceptions(); + } + + /// + /// Gets the parent directory of the file system path stored in . + /// + /// The request containing the file system path for which to get the parent directory. + /// Cancellation token that can be used to stop the execution. + public override async Task ExecuteAsync(GetPathParentRequest request, CancellationToken cancellationToken) + { + ErrorOr> result = await _sender.Send(request.ToQuery(), cancellationToken).ConfigureAwait(false); + return result.Match(success => TypedResults.Ok(success), Problem); + } +} diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/FileSystemManagement/Path/GetPathParent/GetPathParentEndpointSummary.cs b/src/Lumina.Presentation.Api/Core/Endpoints/FileSystemManagement/Path/GetPathParent/GetPathParentEndpointSummary.cs new file mode 100644 index 00000000..67611bf2 --- /dev/null +++ b/src/Lumina.Presentation.Api/Core/Endpoints/FileSystemManagement/Path/GetPathParent/GetPathParentEndpointSummary.cs @@ -0,0 +1,28 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Contracts.Requests.FileSystemManagement.Path; +using Lumina.Contracts.Responses.FileSystemManagement.Path; +using System.Collections.Generic; +#endregion + +namespace Lumina.Presentation.Api.Core.Endpoints.FileSystemManagement.Path.GetPathParent; + +/// +/// Class used for providing a textual description for the API endpoint, for Swagger. +/// +public class GetPathParentEndpointSummary : Summary +{ + /// + /// Initializes a new instance of the class. + /// + public GetPathParentEndpointSummary() + { + Summary = "Retrieves the parent directory of the requested file system path."; + Description = "Fetches the parent directory of a specified file system path, if available."; + + RequestParam(r => r.Path, "The path for which to get the parent directory."); + + Response>(200, "The parent directory of the requested path is returned."); + Response(422, "The request did not pass validation checks.", "application/problem+json"); + } +} diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/FileSystemManagement/Path/GetPathRoot/GetPathRootEndpoint.cs b/src/Lumina.Presentation.Api/Core/Endpoints/FileSystemManagement/Path/GetPathRoot/GetPathRootEndpoint.cs new file mode 100644 index 00000000..2b39ad17 --- /dev/null +++ b/src/Lumina.Presentation.Api/Core/Endpoints/FileSystemManagement/Path/GetPathRoot/GetPathRootEndpoint.cs @@ -0,0 +1,55 @@ +#region ========================================================================= USING ===================================================================================== +using ErrorOr; +using FastEndpoints; +using Lumina.Application.Common.Mapping.FileSystemManagement.Paths; +using Lumina.Contracts.Requests.FileSystemManagement.Path; +using Lumina.Contracts.Responses.FileSystemManagement.Path; +using Lumina.Presentation.Api.Common.Routes.FileSystemManagement; +using Lumina.Presentation.Api.Core.Endpoints.Common; +using Mediator; +using Microsoft.AspNetCore.Http; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Api.Core.Endpoints.FileSystemManagement.Path.GetPathRoot; + +/// +/// API endpoint for the /path/get-path-root route. +/// +public class GetPathRootEndpoint : BaseEndpoint +{ + private readonly ISender _sender; + + /// + /// Initializes a new instance of the class. + /// + /// Injected service for mediating commands and queries. + public GetPathRootEndpoint(ISender sender) + { + _sender = sender; + } + + /// + /// Configures the API endpoint. + /// + public override void Configure() + { + Verbs(Http.GET); + Routes(ApiRoutes.Path.GET_PATH_ROOT); + Version(1); + AllowAnonymous(); + DontCatchExceptions(); + } + + /// + /// Gets the root of the file system path stored in . + /// + /// The request containing the file system path for which to get the root. + /// Cancellation token that can be used to stop the execution. + public override async Task ExecuteAsync(GetPathRootRequest request, CancellationToken cancellationToken) + { + ErrorOr result = await _sender.Send(request.ToQuery(), cancellationToken).ConfigureAwait(false); + return result.Match(success => TypedResults.Ok(success), Problem); + } +} diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/FileSystemManagement/Path/GetPathRoot/GetPathRootEndpointSummary.cs b/src/Lumina.Presentation.Api/Core/Endpoints/FileSystemManagement/Path/GetPathRoot/GetPathRootEndpointSummary.cs new file mode 100644 index 00000000..03c63e27 --- /dev/null +++ b/src/Lumina.Presentation.Api/Core/Endpoints/FileSystemManagement/Path/GetPathRoot/GetPathRootEndpointSummary.cs @@ -0,0 +1,27 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Contracts.Requests.FileSystemManagement.Path; +using Lumina.Contracts.Responses.FileSystemManagement.Path; +#endregion + +namespace Lumina.Presentation.Api.Core.Endpoints.FileSystemManagement.Path.GetPathRoot; + +/// +/// Class used for providing a textual description for the API endpoint, for Swagger. +/// +public class GetPathRootEndpointSummary : Summary +{ + /// + /// Initializes a new instance of the class. + /// + public GetPathRootEndpointSummary() + { + Summary = "Retrieves a file system path root segment."; + Description = "Fetches the root segment of a specified file system path, using the provided path parameter."; + + RequestParam(r => r.Path, "The file system path for which to get the root."); + + Response(200, "The root of the requested path is returned."); + Response(422, "The request did not pass validation checks.", "application/problem+json"); + } +} diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/FileSystemManagement/Path/GetPathSeparator/GetPathSeparatorEndpoint.cs b/src/Lumina.Presentation.Api/Core/Endpoints/FileSystemManagement/Path/GetPathSeparator/GetPathSeparatorEndpoint.cs new file mode 100644 index 00000000..1126fc6d --- /dev/null +++ b/src/Lumina.Presentation.Api/Core/Endpoints/FileSystemManagement/Path/GetPathSeparator/GetPathSeparatorEndpoint.cs @@ -0,0 +1,51 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Application.Core.FileSystemManagement.Paths.Queries.GetPathSeparator; +using Lumina.Contracts.Responses.FileSystemManagement.Path; +using Lumina.Presentation.Api.Common.Routes.FileSystemManagement; +using Mediator; +using Microsoft.AspNetCore.Http; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Api.Core.Endpoints.FileSystemManagement.Path.GetPathSeparator; + +/// +/// API endpoint for the /path/get-path-separator route. +/// +public class GetPathSeparatorEndpoint : EndpointWithoutRequest +{ + private readonly ISender _sender; + + /// + /// Initializes a new instance of the class. + /// + /// Injected service for mediating commands and queries. + public GetPathSeparatorEndpoint(ISender sender) + { + _sender = sender; + } + + /// + /// Configures the API endpoint. + /// + public override void Configure() + { + Verbs(Http.GET); + Routes(ApiRoutes.Path.GET_PATH_SEPARATOR); + Version(1); + AllowAnonymous(); + DontCatchExceptions(); + } + + /// + /// Gets the file system path separator character of the file system. + /// + /// Cancellation token that can be used to stop the execution. + public override async Task ExecuteAsync(CancellationToken cancellationToken) + { + PathSeparatorResponse result = await _sender.Send(new GetPathSeparatorQuery(), cancellationToken).ConfigureAwait(false); + return TypedResults.Ok(result); + } +} diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/FileSystemManagement/Path/GetPathSeparator/GetPathSeparatorEndpointSummary.cs b/src/Lumina.Presentation.Api/Core/Endpoints/FileSystemManagement/Path/GetPathSeparator/GetPathSeparatorEndpointSummary.cs new file mode 100644 index 00000000..845c462f --- /dev/null +++ b/src/Lumina.Presentation.Api/Core/Endpoints/FileSystemManagement/Path/GetPathSeparator/GetPathSeparatorEndpointSummary.cs @@ -0,0 +1,23 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Contracts.Responses.FileSystemManagement.Path; +#endregion + +namespace Lumina.Presentation.Api.Core.Endpoints.FileSystemManagement.Path.GetPathSeparator; + +/// +/// Class used for providing a textual description for the API endpoint, for Swagger. +/// +public class GetPathSeparatorEndpointSummary : Summary +{ + /// + /// Initializes a new instance of the class. + /// + public GetPathSeparatorEndpointSummary() + { + Summary = "Retrieves the file system path separator character."; + Description = "Fetches the path separator character for the current file system that the API is running on."; + + Response(200, "The path separator character is returned."); + } +} diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/FileSystemManagement/Path/SplitPath/SplitPathEndpoint.cs b/src/Lumina.Presentation.Api/Core/Endpoints/FileSystemManagement/Path/SplitPath/SplitPathEndpoint.cs new file mode 100644 index 00000000..f826749b --- /dev/null +++ b/src/Lumina.Presentation.Api/Core/Endpoints/FileSystemManagement/Path/SplitPath/SplitPathEndpoint.cs @@ -0,0 +1,56 @@ +#region ========================================================================= USING ===================================================================================== +using ErrorOr; +using FastEndpoints; +using Lumina.Application.Common.Mapping.FileSystemManagement.Paths; +using Lumina.Contracts.Requests.FileSystemManagement.Path; +using Lumina.Contracts.Responses.FileSystemManagement.Path; +using Lumina.Presentation.Api.Common.Routes.FileSystemManagement; +using Lumina.Presentation.Api.Core.Endpoints.Common; +using Mediator; +using Microsoft.AspNetCore.Http; +using System.Collections.Generic; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Api.Core.Endpoints.FileSystemManagement.Path.SplitPath; + +/// +/// API endpoint for the /path/split route. +/// +public class SplitPathEndpoint : BaseEndpoint +{ + private readonly ISender _sender; + + /// + /// Initializes a new instance of the class. + /// + /// Injected service for mediating commands and queries. + public SplitPathEndpoint(ISender sender) + { + _sender = sender; + } + + /// + /// Configures the API endpoint. + /// + public override void Configure() + { + Verbs(Http.GET); + Routes(ApiRoutes.Path.SPLIT); + Version(1); + AllowAnonymous(); + DontCatchExceptions(); + } + + /// + /// Gets the path components of a file system path stored in . + /// + /// The request containing the file system path for which to get the root. + /// Cancellation token that can be used to stop the execution. + public override async Task ExecuteAsync(SplitPathRequest request, CancellationToken cancellationToken) + { + ErrorOr> result = await _sender.Send(request.ToCommand(), cancellationToken).ConfigureAwait(false); + return result.Match(success => TypedResults.Ok(success), Problem); + } +} diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/FileSystemManagement/Path/SplitPath/SplitPathEndpointSummary.cs b/src/Lumina.Presentation.Api/Core/Endpoints/FileSystemManagement/Path/SplitPath/SplitPathEndpointSummary.cs new file mode 100644 index 00000000..4344a365 --- /dev/null +++ b/src/Lumina.Presentation.Api/Core/Endpoints/FileSystemManagement/Path/SplitPath/SplitPathEndpointSummary.cs @@ -0,0 +1,28 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Contracts.Requests.FileSystemManagement.Path; +using Lumina.Contracts.Responses.FileSystemManagement.Path; +using System.Collections.Generic; +#endregion + +namespace Lumina.Presentation.Api.Core.Endpoints.FileSystemManagement.Path.SplitPath; + +/// +/// Class used for providing a textual description for the API endpoint, for Swagger. +/// +public class SplitPathEndpointSummary : Summary +{ + /// + /// Initializes a new instance of the class. + /// + public SplitPathEndpointSummary() + { + Summary = "Splits a file system path."; + Description = "Splits a file system path into its constituent segments."; + + RequestParam(r => r.Path, "The file system path for which to get the path segments."); + + Response>(200, "Successfully split the path into segments."); + Response(422, "The request did not pass validation checks.", "application/problem+json"); + } +} diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/FileSystemManagement/Path/ValidatePath/ValidatePathEndpoint.cs b/src/Lumina.Presentation.Api/Core/Endpoints/FileSystemManagement/Path/ValidatePath/ValidatePathEndpoint.cs new file mode 100644 index 00000000..459d6b51 --- /dev/null +++ b/src/Lumina.Presentation.Api/Core/Endpoints/FileSystemManagement/Path/ValidatePath/ValidatePathEndpoint.cs @@ -0,0 +1,54 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Application.Common.Mapping.FileSystemManagement.Paths; +using Lumina.Contracts.Requests.FileSystemManagement.Path; +using Lumina.Contracts.Responses.FileSystemManagement.Path; +using Lumina.Presentation.Api.Common.Routes.FileSystemManagement; +using Lumina.Presentation.Api.Core.Endpoints.Common; +using Mediator; +using Microsoft.AspNetCore.Http; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Api.Core.Endpoints.FileSystemManagement.Path.ValidatePath; + +/// +/// API endpoint for the /path/validate route. +/// +public class ValidatePathEndpoint : BaseEndpoint +{ + private readonly ISender _sender; + + /// + /// Initializes a new instance of the class. + /// + /// Injected service for mediating commands and queries. + public ValidatePathEndpoint(ISender sender) + { + _sender = sender; + } + + /// + /// Configures the API endpoint. + /// + public override void Configure() + { + Verbs(Http.GET); + Routes(ApiRoutes.Path.VALIDATE); + Version(1); + AllowAnonymous(); + DontCatchExceptions(); + } + + /// + /// Validates the validity of the file system path stored in . + /// + /// The request containing the file system path to validate. + /// Cancellation token that can be used to stop the execution. + public override async Task ExecuteAsync(ValidatePathRequest request, CancellationToken cancellationToken) + { + PathValidResponse result = await _sender.Send(request.ToQuery(), cancellationToken).ConfigureAwait(false); + return TypedResults.Ok(result); + } +} diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/FileSystemManagement/Path/ValidatePath/ValidatePathEndpointSummary.cs b/src/Lumina.Presentation.Api/Core/Endpoints/FileSystemManagement/Path/ValidatePath/ValidatePathEndpointSummary.cs new file mode 100644 index 00000000..1a19a34f --- /dev/null +++ b/src/Lumina.Presentation.Api/Core/Endpoints/FileSystemManagement/Path/ValidatePath/ValidatePathEndpointSummary.cs @@ -0,0 +1,27 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Contracts.Requests.FileSystemManagement.Path; +using Lumina.Contracts.Responses.FileSystemManagement.Path; +#endregion + +namespace Lumina.Presentation.Api.Core.Endpoints.FileSystemManagement.Path.ValidatePath; + +/// +/// Class used for providing a textual description for the API endpoint, for Swagger. +/// +public class ValidatePathEndpointSummary : Summary +{ + /// + /// Initializes a new instance of the class. + /// + public ValidatePathEndpointSummary() + { + Summary = "Validates a file system path."; + Description = "Checks if the specified file system path is valid according to predefined criteria."; + + RequestParam(r => r.Path, "The file system path to validate."); + + Response(200, "The requested path is validated."); + Response(422, "The request did not pass validation checks.", "application/problem+json"); + } +} diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/FileSystemManagement/Thumbnails/GetThumbnail/GetThumbnailEndpoint.cs b/src/Lumina.Presentation.Api/Core/Endpoints/FileSystemManagement/Thumbnails/GetThumbnail/GetThumbnailEndpoint.cs new file mode 100644 index 00000000..0c3d8bd1 --- /dev/null +++ b/src/Lumina.Presentation.Api/Core/Endpoints/FileSystemManagement/Thumbnails/GetThumbnail/GetThumbnailEndpoint.cs @@ -0,0 +1,57 @@ +#region ========================================================================= USING ===================================================================================== +using ErrorOr; +using FastEndpoints; +using Lumina.Application.Common.Mapping.FileSystemManagement.Files; +using Lumina.Application.Common.Mapping.FileSystemManagement.Thumbnails; +using Lumina.Contracts.Requests.FileSystemManagement.Thumbnails; +using Lumina.Contracts.Responses.FileSystemManagement.Thumbnails; +using Lumina.Presentation.Api.Common.Routes.FileSystemManagement; +using Lumina.Presentation.Api.Common.Utilities; +using Lumina.Presentation.Api.Core.Endpoints.Common; +using Mediator; +using Microsoft.AspNetCore.Http; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Api.Core.Endpoints.FileSystemManagement.Thumbnails.GetThumbnail; + +/// +/// API endpoint for the /thumbnails/get-thumbnail route. +/// +public class GetThumbnailEndpoint : BaseEndpoint +{ + private readonly ISender _sender; + + /// + /// Initializes a new instance of the class. + /// + /// Injected service for mediating commands and queries. + public GetThumbnailEndpoint(ISender sender) + { + _sender = sender; + } + + /// + /// Configures the API endpoint. + /// + public override void Configure() + { + Verbs(Http.GET); + Routes(ApiRoutes.Thumbnails.GET_THUMBNAIL); + Version(1); + AllowAnonymous(); + DontCatchExceptions(); + } + + /// + /// Gets the thumbnail of the file located at the path stored in . + /// + /// The request containing the file system path of the file for which to get the thumbnail. + /// Cancellation token that can be used to stop the execution. + public override async Task ExecuteAsync(GetThumbnailRequest request, CancellationToken cancellationToken) + { + ErrorOr result = await _sender.Send(request.ToQuery(), cancellationToken).ConfigureAwait(false); + return result.Match(success => TypedResults.File(success.Bytes, MimeTypes.GetMimeType(success.Type)), Problem); + } +} diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/FileSystemManagement/Thumbnails/GetThumbnail/GetThumbnailEndpointSummary.cs b/src/Lumina.Presentation.Api/Core/Endpoints/FileSystemManagement/Thumbnails/GetThumbnail/GetThumbnailEndpointSummary.cs new file mode 100644 index 00000000..9de7f5a8 --- /dev/null +++ b/src/Lumina.Presentation.Api/Core/Endpoints/FileSystemManagement/Thumbnails/GetThumbnail/GetThumbnailEndpointSummary.cs @@ -0,0 +1,27 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Contracts.Requests.FileSystemManagement.Thumbnails; +#endregion + +namespace Lumina.Presentation.Api.Core.Endpoints.FileSystemManagement.Thumbnails.GetThumbnail; + +/// +/// Class used for providing a textual description for the API endpoint, for Swagger. +/// +public class GetThumbnailEndpointSummary : Summary +{ + /// + /// Initializes a new instance of the class. + /// + public GetThumbnailEndpointSummary() + { + Summary = "Retrieves a thumbnail for a specified file."; + Description = "Returns a thumbnail image for the specified file, with the option to specify the quality."; + + RequestParam(r => r.Path, "The path of the file for which to get the thumbnail."); + RequestParam(r => r.Quality, "The quality to use for the thumbnail."); + + Response(200, "The thumbnail image for the specified file is returned."); + Response(422, "The request did not pass validation checks.", "application/problem+json"); + } +} diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Maintenance/CheckHealthEndpoint.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Maintenance/CheckHealthEndpoint.cs new file mode 100644 index 00000000..78a7d211 --- /dev/null +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Maintenance/CheckHealthEndpoint.cs @@ -0,0 +1,56 @@ +#region ========================================================================= USING ===================================================================================== +using ErrorOr; +using FastEndpoints; +using Lumina.Application.Common.Mapping.FileSystemManagement.Paths; +using Lumina.Contracts.Requests.FileSystemManagement.Directories; +using Lumina.Application.Common.Mapping.FileSystemManagement.Directories; +using Lumina.Contracts.Responses.FileSystemManagement; +using Lumina.Presentation.Api.Common.Routes.FileSystemManagement; +using Lumina.Presentation.Api.Core.Endpoints.Common; +using Mediator; +using Microsoft.AspNetCore.Http; +using System.Threading; +using System.Threading.Tasks; +using System.Collections.Generic; +#endregion + +namespace Lumina.Presentation.Api.Core.Endpoints.Maintenance; + +/// +/// API endpoint for the /directories/get-directories route. +/// +public class CheckHealthEndpoint : BaseEndpoint +{ + private readonly ISender _sender; + + /// + /// Initializes a new instance of the class. + /// + /// Injected service for mediating commands and queries. + public CheckHealthEndpoint(ISender sender) + { + _sender = sender; + } + + /// + /// Configures the API endpoint. + /// + public override void Configure() + { + Verbs(Http.GET); + Routes(ApiRoutes.Health.CHECK_HEALTH); + Version(1); + AllowAnonymous(); + DontCatchExceptions(); + } + + /// + /// Gwts the health status of the backend system. + /// + /// Cancellation token that can be used to stop the execution. + public override async Task ExecuteAsync(EmptyRequest _, CancellationToken cancellationToken) + { + // TODO: to be implemented + return await Task.FromResult(TypedResults.Ok()); + } +} diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/WrittenContentLibrary/BookLibrary/Books/AddBook/AddBookEndpoint.cs b/src/Lumina.Presentation.Api/Core/Endpoints/WrittenContentLibrary/BookLibrary/Books/AddBook/AddBookEndpoint.cs new file mode 100644 index 00000000..4cd3a076 --- /dev/null +++ b/src/Lumina.Presentation.Api/Core/Endpoints/WrittenContentLibrary/BookLibrary/Books/AddBook/AddBookEndpoint.cs @@ -0,0 +1,55 @@ +#region ========================================================================= USING ===================================================================================== +using ErrorOr; +using FastEndpoints; +using Lumina.Application.Common.Mapping.WrittenContentLibrary.BookLibrary.Books; +using Lumina.Contracts.Requests.WrittenContentLibrary.BookLibrary.Books; +using Lumina.Contracts.Responses.WrittenContentLibrary.BookLibrary.Books; +using Lumina.Presentation.Api.Common.Routes.WrittenContentLibrary.BookLibrary; +using Lumina.Presentation.Api.Core.Endpoints.Common; +using Mediator; +using Microsoft.AspNetCore.Http; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Api.Core.Endpoints.WrittenContentLibrary.BookLibrary.Books.AddBook; + +/// +/// API endpoint for the /books route. +/// +public class AddBookEndpoint : BaseEndpoint +{ + private readonly ISender _sender; + + /// + /// Initializes a new instance of the class. + /// + /// Injected service for mediating commands and queries. + public AddBookEndpoint(ISender sender) + { + _sender = sender; + } + + /// + /// Configures the API endpoint. + /// + public override void Configure() + { + Verbs(Http.POST); + Routes(ApiRoutes.Books.ADD_BOOK); + Version(1); + AllowAnonymous(); + DontCatchExceptions(); + } + + /// + /// Adds a book stored in . + /// + /// The request containing the book to be added. + /// Cancellation token that can be used to stop the execution. + public override async Task ExecuteAsync(AddBookRequest request, CancellationToken cancellationToken) + { + ErrorOr result = await _sender.Send(request.ToCommand(), cancellationToken).ConfigureAwait(false); + return result.Match(success => TypedResults.Created($"{BaseURL}api/v1{ApiRoutes.Books.ADD_BOOK}/{result.Value.Id}", result.Value), Problem); + } +} diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/WrittenContentLibrary/BookLibrary/Books/AddBook/AddBookEndpointSummary.cs b/src/Lumina.Presentation.Api/Core/Endpoints/WrittenContentLibrary/BookLibrary/Books/AddBook/AddBookEndpointSummary.cs new file mode 100644 index 00000000..1af43423 --- /dev/null +++ b/src/Lumina.Presentation.Api/Core/Endpoints/WrittenContentLibrary/BookLibrary/Books/AddBook/AddBookEndpointSummary.cs @@ -0,0 +1,50 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Contracts.Requests.WrittenContentLibrary.BookLibrary.Books; +using Lumina.Contracts.Responses.WrittenContentLibrary.BookLibrary.Books; +#endregion + +namespace Lumina.Presentation.Api.Core.Endpoints.WrittenContentLibrary.BookLibrary.Books.AddBook; + +/// +/// Class used for providing a textual description for the API endpoint, for Swagger. +/// +public class AddBookEndpointSummary : Summary +{ + /// + /// Initializes a new instance of the class. + /// + public AddBookEndpointSummary() + { + Summary = "Adds a new book."; + Description = "Creates a new book and returns its details, including the location of the newly created resource."; + + RequestParam(r => r.Metadata, "Written content metadata of the book."); + RequestParam(r => r.Metadata!.Title, "The title of the written content."); + RequestParam(r => r.Format, "The format of the book (e.g., Hardcover, Paperback), if applicable."); + RequestParam(r => r.Edition, "The edition of the book, if applicable."); + RequestParam(r => r.VolumeNumber, "The volume or book number in the series, if applicable."); + RequestParam(r => r.Series, "The series name, if the book is part of a series."); + RequestParam(r => r.ASIN, "The ASIN (Amazon Standard Identification Number) of the book, if applicable."); + RequestParam(r => r.GoodreadsId, "The Goodreads ID of the book, if applicable."); + RequestParam(r => r.LCCN, "The Library of Congress Control Number (LCCN) of the book, if applicable."); + RequestParam(r => r.OCLCNumber, "The OCLC Number (WorldCat identifier) of the book, if applicable."); + RequestParam(r => r.OpenLibraryId, "The Open Library ID of the book, if applicable."); + RequestParam(r => r.LibraryThingId, "The LibraryThing ID of the book, if applicable."); + RequestParam(r => r.GoogleBooksId, "The Google Books ID of the book, if applicable."); + RequestParam(r => r.BarnesAndNobleId, "The Barnes & Noble ID of the book, if applicable."); + RequestParam(r => r.AppleBooksId, "The Apple Books ID of the book, if applicable."); + RequestParam(r => r.ISBNs, "The list of ISBN (International Standard Book Number) of the book."); + RequestParam(r => r.Contributors, "The list of media contributors (actors, directors, etc) starring in this book."); + RequestParam(r => r.Ratings, "The list of ratings for this book."); + + ResponseParam(r => r.Id, "The unique identifier of the entity."); + ResponseParam(r => r.Created, "The date and time when the entity was created."); + ResponseParam(r => r.Updated, "The date and time when the entity was last updated."); + ResponseParam(r => r.Metadata, "The written content metadata of the book."); + ResponseParam(r => r.Metadata.Title, "The title of the media item."); + ResponseParam(r => r.Metadata.OriginalTitle, "The original title of the media item."); + Response(201, "The book was successfully created.", "The location of the created resource is provided in the Location header."); + Response(422, "The request did not pass validation checks.", "application/problem+json"); + } +} diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/WrittenContentLibrary/BookLibrary/Books/GetBooks/GetBooksEndpoint.cs b/src/Lumina.Presentation.Api/Core/Endpoints/WrittenContentLibrary/BookLibrary/Books/GetBooks/GetBooksEndpoint.cs new file mode 100644 index 00000000..96a1b08d --- /dev/null +++ b/src/Lumina.Presentation.Api/Core/Endpoints/WrittenContentLibrary/BookLibrary/Books/GetBooks/GetBooksEndpoint.cs @@ -0,0 +1,54 @@ +#region ========================================================================= USING ===================================================================================== +using ErrorOr; +using FastEndpoints; +using Lumina.Application.Core.WrittenContentLibrary.BooksLibrary.Books.Queries.GetBooks; +using Lumina.Contracts.Responses.WrittenContentLibrary.BookLibrary.Books; +using Lumina.Presentation.Api.Common.Routes.WrittenContentLibrary.BookLibrary; +using Lumina.Presentation.Api.Core.Endpoints.Common; +using Mediator; +using Microsoft.AspNetCore.Http; +using System.Collections.Generic; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Api.Core.Endpoints.WrittenContentLibrary.BookLibrary.Books.GetBooks; + +/// +/// API endpoint for the /books route. +/// +public class GetBooksEndpoint : BaseEndpoint +{ + private readonly ISender _sender; + + /// + /// Initializes a new instance of the class. + /// + /// Injected service for mediating commands and queries. + public GetBooksEndpoint(ISender sender) + { + _sender = sender; + } + + /// + /// Configures the API endpoint. + /// + public override void Configure() + { + Verbs(Http.GET); + Routes(ApiRoutes.Books.GET_BOOKS); + Version(1); + AllowAnonymous(); + DontCatchExceptions(); + } + + /// + /// Gets the list of all books. + /// + /// Cancellation token that can be used to stop the execution. + public override async Task ExecuteAsync(EmptyRequest _, CancellationToken cancellationToken) + { + ErrorOr> result = await _sender.Send(new GetBooksQuery(), cancellationToken).ConfigureAwait(false); + return result.Match(success => TypedResults.Ok(success), Problem); + } +} diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/WrittenContentLibrary/BookLibrary/Books/GetBooks/GetBooksEndpointSummary.cs b/src/Lumina.Presentation.Api/Core/Endpoints/WrittenContentLibrary/BookLibrary/Books/GetBooks/GetBooksEndpointSummary.cs new file mode 100644 index 00000000..9e3e3d77 --- /dev/null +++ b/src/Lumina.Presentation.Api/Core/Endpoints/WrittenContentLibrary/BookLibrary/Books/GetBooks/GetBooksEndpointSummary.cs @@ -0,0 +1,24 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Contracts.Responses.WrittenContentLibrary.BookLibrary.Books; +using System.Collections.Generic; +#endregion + +namespace Lumina.Presentation.Api.Core.Endpoints.WrittenContentLibrary.BookLibrary.Books.GetBooks; + +/// +/// Class used for providing a textual description for the API endpoint, for Swagger. +/// +public class GetBooksEndpointSummary : Summary +{ + /// + /// Initializes a new instance of the class. + /// + public GetBooksEndpointSummary() + { + Summary = "Retrieves the list of books."; + Description = "Returns the entire list of books."; + + Response>(200, "The list of books is returned."); + } +} diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/WrittenContentLibrary/BookLibrary/GetBook/GetBookEndpoint.cs b/src/Lumina.Presentation.Api/Core/Endpoints/WrittenContentLibrary/BookLibrary/GetBook/GetBookEndpoint.cs new file mode 100644 index 00000000..cbb69e31 --- /dev/null +++ b/src/Lumina.Presentation.Api/Core/Endpoints/WrittenContentLibrary/BookLibrary/GetBook/GetBookEndpoint.cs @@ -0,0 +1,56 @@ +#region ========================================================================= USING ===================================================================================== +using ErrorOr; +using FastEndpoints; +using Lumina.Application.Common.Mapping.WrittenContentLibrary.BookLibrary.Books; +using Lumina.Contracts.Requests.WrittenContentLibrary.BookLibrary.Books; +using Lumina.Domain.Core.Aggregates.WrittenContentLibrary.BookLibraryAggregate; +using Lumina.Presentation.Api.Common.Routes.WrittenContentLibrary.BookLibrary; +using Lumina.Presentation.Api.Core.Endpoints.Common; +using Mediator; +using Microsoft.AspNetCore.Http; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Api.Core.Endpoints.WrittenContentLibrary.BookLibrary.GetBook; + +/// +/// API endpoint for the /books route. +/// +public class GetBookEndpoint : BaseEndpoint +{ + private readonly ISender _sender; + + /// + /// Initializes a new instance of the class. + /// + /// Injected service for mediating commands and queries. + public GetBookEndpoint(ISender sender) + { + _sender = sender; + } + + /// + /// Configures the API endpoint. + /// + public override void Configure() + { + Verbs(Http.GET); + Routes(ApiRoutes.Books.GET_BOOK_BY_ID); + Version(1); + AllowAnonymous(); + DontCatchExceptions(); + } + + /// + /// Adds a book stored in . + /// + /// The request containing the book to be added. + /// Cancellation token that can be used to stop the execution. + public override async Task ExecuteAsync(GetBookRequest request, CancellationToken cancellationToken) + { + //ErrorOr result = await _sender.Send(request.ToCommand(), cancellationToken).ConfigureAwait(false); + //return result.Match(success => TypedResults.CreatedAtRoute($"/api/v1/books/{success.Id}", success), Problem); + return await Task.FromResult(TypedResults.Ok()); + } +} diff --git a/src/Lumina.Presentation.Api/Lumina.Presentation.Api.csproj b/src/Lumina.Presentation.Api/Lumina.Presentation.Api.csproj index 53d55cb7..e6066854 100644 --- a/src/Lumina.Presentation.Api/Lumina.Presentation.Api.csproj +++ b/src/Lumina.Presentation.Api/Lumina.Presentation.Api.csproj @@ -18,18 +18,14 @@ - - + + runtime; build; native; contentfiles; analyzers; buildtransitive all - - - - all runtime; build; native; contentfiles; analyzers; buildtransitive diff --git a/src/Lumina.Presentation.Api/Program.cs b/src/Lumina.Presentation.Api/Program.cs index e70d334d..9eaec7c6 100644 --- a/src/Lumina.Presentation.Api/Program.cs +++ b/src/Lumina.Presentation.Api/Program.cs @@ -1,11 +1,12 @@ #region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using FastEndpoints.Swagger; using Lumina.Application.Common.DependencyInjection; using Lumina.DataAccess.Common.DependencyInjection; using Lumina.Domain.Common.DependencyInjection; using Lumina.Infrastructure.Common.DependencyInjection; using Lumina.Presentation.Api.Common.DependencyInjection; using Microsoft.AspNetCore.Builder; -using Microsoft.Extensions.Hosting; using System.Threading.Tasks; #endregion @@ -37,18 +38,21 @@ public class Program app.UseCors("AllowAll"); - app.UseExceptionHandler("/error"); // uses a middleware which reexecutes the request to the error path - - // configure the HTTP request pipeline. - if (app.Environment.IsDevelopment()) - { - app.UseSwagger(); - app.UseSwaggerUI(); - } + //app.UseExceptionHandler("/error"); // uses a middleware which re-executes the request to the error path //app.UseHttpsRedirection(); - app.MapControllers(); + app.UseAuthorization(); + + app.UseFastEndpoints(config => + { + config.Endpoints.RoutePrefix = "api"; + config.Versioning.Prefix = "v"; + config.Versioning.DefaultVersion = 1; + config.Versioning.PrependToRoute = true; + config.Endpoints.ShortNames = true; + }); + app.UseSwaggerGen(); await app.RunAsync().ConfigureAwait(false); } diff --git a/src/Lumina.Presentation.Web/Common/Api/ApiHttpClient.cs b/src/Lumina.Presentation.Web/Common/Api/ApiHttpClient.cs index 2db649d7..1ca1551c 100644 --- a/src/Lumina.Presentation.Web/Common/Api/ApiHttpClient.cs +++ b/src/Lumina.Presentation.Web/Common/Api/ApiHttpClient.cs @@ -2,7 +2,7 @@ using Lumina.Presentation.Web.Common.Exceptions; using Lumina.Presentation.Web.Common.Models.Common; using Lumina.Presentation.Web.Common.Models.Configuration; -using Lumina.Presentation.Web.Common.Models.FileManagement; +using Lumina.Presentation.Web.Common.Models.FileSystemManagement; using Microsoft.Extensions.Options; using System; using System.Collections.Generic; diff --git a/src/Lumina.Presentation.Web/Common/Api/IApiHttpClient.cs b/src/Lumina.Presentation.Web/Common/Api/IApiHttpClient.cs index 7304556f..4ac6642f 100644 --- a/src/Lumina.Presentation.Web/Common/Api/IApiHttpClient.cs +++ b/src/Lumina.Presentation.Web/Common/Api/IApiHttpClient.cs @@ -1,5 +1,5 @@ #region ========================================================================= USING ===================================================================================== -using Lumina.Presentation.Web.Common.Models.FileManagement; +using Lumina.Presentation.Web.Common.Models.FileSystemManagement; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; diff --git a/src/Lumina.Presentation.Web/Common/Models/FileManagement/BlobDataModel.cs b/src/Lumina.Presentation.Web/Common/Models/FileSystemManagement/BlobDataModel.cs similarity index 91% rename from src/Lumina.Presentation.Web/Common/Models/FileManagement/BlobDataModel.cs rename to src/Lumina.Presentation.Web/Common/Models/FileSystemManagement/BlobDataModel.cs index 16d29359..2811b0b4 100644 --- a/src/Lumina.Presentation.Web/Common/Models/FileManagement/BlobDataModel.cs +++ b/src/Lumina.Presentation.Web/Common/Models/FileSystemManagement/BlobDataModel.cs @@ -2,7 +2,7 @@ using System.Diagnostics; #endregion -namespace Lumina.Presentation.Web.Common.Models.FileManagement; +namespace Lumina.Presentation.Web.Common.Models.FileSystemManagement; /// /// Represents a model for storing binary data (blob). diff --git a/src/Lumina.Presentation.Web/Common/Models/FileManagement/DirectoryModel.cs b/src/Lumina.Presentation.Web/Common/Models/FileSystemManagement/DirectoryModel.cs similarity index 89% rename from src/Lumina.Presentation.Web/Common/Models/FileManagement/DirectoryModel.cs rename to src/Lumina.Presentation.Web/Common/Models/FileSystemManagement/DirectoryModel.cs index 0f8d3186..a5cacc18 100644 --- a/src/Lumina.Presentation.Web/Common/Models/FileManagement/DirectoryModel.cs +++ b/src/Lumina.Presentation.Web/Common/Models/FileSystemManagement/DirectoryModel.cs @@ -3,7 +3,7 @@ using System.Collections.Generic; using System.Diagnostics; #endregion -namespace Lumina.Presentation.Web.Common.Models.FileManagement; +namespace Lumina.Presentation.Web.Common.Models.FileSystemManagement; /// /// Model for directories displayed in custom directory/file browser dialogs. diff --git a/src/Lumina.Presentation.Web/Common/Models/FileManagement/FileModel.cs b/src/Lumina.Presentation.Web/Common/Models/FileSystemManagement/FileModel.cs similarity index 88% rename from src/Lumina.Presentation.Web/Common/Models/FileManagement/FileModel.cs rename to src/Lumina.Presentation.Web/Common/Models/FileSystemManagement/FileModel.cs index 23aec27b..ff4fa39f 100644 --- a/src/Lumina.Presentation.Web/Common/Models/FileManagement/FileModel.cs +++ b/src/Lumina.Presentation.Web/Common/Models/FileSystemManagement/FileModel.cs @@ -2,7 +2,7 @@ using System.Diagnostics; #endregion -namespace Lumina.Presentation.Web.Common.Models.FileManagement; +namespace Lumina.Presentation.Web.Common.Models.FileSystemManagement; /// /// Model for files displayed in custom directory/file browser dialogs. diff --git a/src/Lumina.Presentation.Web/Common/Models/FileManagement/FileSystemItemModel.cs b/src/Lumina.Presentation.Web/Common/Models/FileSystemManagement/FileSystemItemModel.cs similarity index 93% rename from src/Lumina.Presentation.Web/Common/Models/FileManagement/FileSystemItemModel.cs rename to src/Lumina.Presentation.Web/Common/Models/FileSystemManagement/FileSystemItemModel.cs index 887cd2fa..4b2d334f 100644 --- a/src/Lumina.Presentation.Web/Common/Models/FileManagement/FileSystemItemModel.cs +++ b/src/Lumina.Presentation.Web/Common/Models/FileSystemManagement/FileSystemItemModel.cs @@ -3,7 +3,7 @@ using System; using System.Diagnostics; #endregion -namespace Lumina.Presentation.Web.Common.Models.FileManagement; +namespace Lumina.Presentation.Web.Common.Models.FileSystemManagement; /// /// Base model for files and directories displayed in custom directory/file browser dialogs. diff --git a/src/Lumina.Presentation.Web/Common/Models/FileManagement/FileSystemTreeNodeModel.cs b/src/Lumina.Presentation.Web/Common/Models/FileSystemManagement/FileSystemTreeNodeModel.cs similarity index 95% rename from src/Lumina.Presentation.Web/Common/Models/FileManagement/FileSystemTreeNodeModel.cs rename to src/Lumina.Presentation.Web/Common/Models/FileSystemManagement/FileSystemTreeNodeModel.cs index d256b376..fec72137 100644 --- a/src/Lumina.Presentation.Web/Common/Models/FileManagement/FileSystemTreeNodeModel.cs +++ b/src/Lumina.Presentation.Web/Common/Models/FileSystemManagement/FileSystemTreeNodeModel.cs @@ -4,7 +4,7 @@ using System.Collections.Generic; using System.Diagnostics; #endregion -namespace Lumina.Presentation.Web.Common.Models.FileManagement; +namespace Lumina.Presentation.Web.Common.Models.FileSystemManagement; /// /// Generic file system node. diff --git a/src/Lumina.Presentation.Web/Common/Models/FileManagement/FileSystemTypeModel.cs b/src/Lumina.Presentation.Web/Common/Models/FileSystemManagement/FileSystemTypeModel.cs similarity index 88% rename from src/Lumina.Presentation.Web/Common/Models/FileManagement/FileSystemTypeModel.cs rename to src/Lumina.Presentation.Web/Common/Models/FileSystemManagement/FileSystemTypeModel.cs index b1da75e2..21794b67 100644 --- a/src/Lumina.Presentation.Web/Common/Models/FileManagement/FileSystemTypeModel.cs +++ b/src/Lumina.Presentation.Web/Common/Models/FileSystemManagement/FileSystemTypeModel.cs @@ -3,7 +3,7 @@ using Lumina.Presentation.Web.Common.Enums.FileSystem; using System.Diagnostics; #endregion -namespace Lumina.Presentation.Web.Common.Models.FileManagement; +namespace Lumina.Presentation.Web.Common.Models.FileSystemManagement; /// /// Model containing the file system platform type. diff --git a/src/Lumina.Presentation.Web/Common/Models/FileManagement/PathExistsModel.cs b/src/Lumina.Presentation.Web/Common/Models/FileSystemManagement/PathExistsModel.cs similarity index 87% rename from src/Lumina.Presentation.Web/Common/Models/FileManagement/PathExistsModel.cs rename to src/Lumina.Presentation.Web/Common/Models/FileSystemManagement/PathExistsModel.cs index 894f6c03..5eb3caee 100644 --- a/src/Lumina.Presentation.Web/Common/Models/FileManagement/PathExistsModel.cs +++ b/src/Lumina.Presentation.Web/Common/Models/FileSystemManagement/PathExistsModel.cs @@ -2,7 +2,7 @@ using System.Diagnostics; #endregion -namespace Lumina.Presentation.Web.Common.Models.FileManagement; +namespace Lumina.Presentation.Web.Common.Models.FileSystemManagement; /// /// Represents a response to the inquiry about the existence of a file system path. diff --git a/src/Lumina.Presentation.Web/Common/Models/FileManagement/PathSegmentModel.cs b/src/Lumina.Presentation.Web/Common/Models/FileSystemManagement/PathSegmentModel.cs similarity index 87% rename from src/Lumina.Presentation.Web/Common/Models/FileManagement/PathSegmentModel.cs rename to src/Lumina.Presentation.Web/Common/Models/FileSystemManagement/PathSegmentModel.cs index 1a7d5710..82da26d3 100644 --- a/src/Lumina.Presentation.Web/Common/Models/FileManagement/PathSegmentModel.cs +++ b/src/Lumina.Presentation.Web/Common/Models/FileSystemManagement/PathSegmentModel.cs @@ -2,7 +2,7 @@ using System.Diagnostics; #endregion -namespace Lumina.Presentation.Web.Common.Models.FileManagement; +namespace Lumina.Presentation.Web.Common.Models.FileSystemManagement; /// /// Represents a response containing a file system path. diff --git a/src/Lumina.Presentation.Web/Common/Models/FileManagement/PathSeparatorModel.cs b/src/Lumina.Presentation.Web/Common/Models/FileSystemManagement/PathSeparatorModel.cs similarity index 86% rename from src/Lumina.Presentation.Web/Common/Models/FileManagement/PathSeparatorModel.cs rename to src/Lumina.Presentation.Web/Common/Models/FileSystemManagement/PathSeparatorModel.cs index d3f4d071..d778bea0 100644 --- a/src/Lumina.Presentation.Web/Common/Models/FileManagement/PathSeparatorModel.cs +++ b/src/Lumina.Presentation.Web/Common/Models/FileSystemManagement/PathSeparatorModel.cs @@ -2,7 +2,7 @@ using System.Diagnostics; #endregion -namespace Lumina.Presentation.Web.Common.Models.FileManagement; +namespace Lumina.Presentation.Web.Common.Models.FileSystemManagement; /// /// A model representing a file system path separator. diff --git a/src/Lumina.Presentation.Web/Common/Models/FileManagement/PathValidModel.cs b/src/Lumina.Presentation.Web/Common/Models/FileSystemManagement/PathValidModel.cs similarity index 87% rename from src/Lumina.Presentation.Web/Common/Models/FileManagement/PathValidModel.cs rename to src/Lumina.Presentation.Web/Common/Models/FileSystemManagement/PathValidModel.cs index 6cae38df..1954f357 100644 --- a/src/Lumina.Presentation.Web/Common/Models/FileManagement/PathValidModel.cs +++ b/src/Lumina.Presentation.Web/Common/Models/FileSystemManagement/PathValidModel.cs @@ -2,7 +2,7 @@ using System.Diagnostics; #endregion -namespace Lumina.Presentation.Web.Common.Models.FileManagement; +namespace Lumina.Presentation.Web.Common.Models.FileSystemManagement; /// /// Represents a response to the inquiry about the validity of a file system path. diff --git a/src/Lumina.Presentation.Web/Controllers/FileManagement/DirectoriesController.cs b/src/Lumina.Presentation.Web/Controllers/FileSystemManagement/DirectoriesController.cs similarity index 96% rename from src/Lumina.Presentation.Web/Controllers/FileManagement/DirectoriesController.cs rename to src/Lumina.Presentation.Web/Controllers/FileSystemManagement/DirectoriesController.cs index 8dbb6fc7..73b248bb 100644 --- a/src/Lumina.Presentation.Web/Controllers/FileManagement/DirectoriesController.cs +++ b/src/Lumina.Presentation.Web/Controllers/FileSystemManagement/DirectoriesController.cs @@ -1,6 +1,6 @@ #region ========================================================================= USING ===================================================================================== using Lumina.Presentation.Web.Common.Api; -using Lumina.Presentation.Web.Common.Models.FileManagement; +using Lumina.Presentation.Web.Common.Models.FileSystemManagement; using Microsoft.AspNetCore.Mvc; using System; using System.Collections.Generic; @@ -9,7 +9,7 @@ using System.Threading; using System.Threading.Tasks; #endregion -namespace Lumina.Presentation.Web.Controllers.FileManagement; +namespace Lumina.Presentation.Web.Controllers.FileSystemManagement; /// /// Controller for managing file system directories. diff --git a/src/Lumina.Presentation.Web/Controllers/FileManagement/DrivesController.cs b/src/Lumina.Presentation.Web/Controllers/FileSystemManagement/DrivesController.cs similarity index 91% rename from src/Lumina.Presentation.Web/Controllers/FileManagement/DrivesController.cs rename to src/Lumina.Presentation.Web/Controllers/FileSystemManagement/DrivesController.cs index 66e913d4..452af89c 100644 --- a/src/Lumina.Presentation.Web/Controllers/FileManagement/DrivesController.cs +++ b/src/Lumina.Presentation.Web/Controllers/FileSystemManagement/DrivesController.cs @@ -1,12 +1,12 @@ #region ========================================================================= USING ===================================================================================== using Lumina.Presentation.Web.Common.Api; -using Lumina.Presentation.Web.Common.Models.FileManagement; +using Lumina.Presentation.Web.Common.Models.FileSystemManagement; using Microsoft.AspNetCore.Mvc; using System.Threading; using System.Threading.Tasks; #endregion -namespace Lumina.Presentation.Web.Controllers.FileManagement; +namespace Lumina.Presentation.Web.Controllers.FileSystemManagement; /// /// Controller for managing file system drives. diff --git a/src/Lumina.Presentation.Web/Controllers/FileManagement/FileSystemController.cs b/src/Lumina.Presentation.Web/Controllers/FileSystemManagement/FileSystemController.cs similarity index 91% rename from src/Lumina.Presentation.Web/Controllers/FileManagement/FileSystemController.cs rename to src/Lumina.Presentation.Web/Controllers/FileSystemManagement/FileSystemController.cs index 4488a63f..a579147f 100644 --- a/src/Lumina.Presentation.Web/Controllers/FileManagement/FileSystemController.cs +++ b/src/Lumina.Presentation.Web/Controllers/FileSystemManagement/FileSystemController.cs @@ -1,12 +1,12 @@ #region ========================================================================= USING ===================================================================================== using Lumina.Presentation.Web.Common.Api; -using Lumina.Presentation.Web.Common.Models.FileManagement; +using Lumina.Presentation.Web.Common.Models.FileSystemManagement; using Microsoft.AspNetCore.Mvc; using System.Threading; using System.Threading.Tasks; #endregion -namespace Lumina.Presentation.Web.Controllers.FileManagement; +namespace Lumina.Presentation.Web.Controllers.FileSystemManagement; /// /// Controller for managing file systems. diff --git a/src/Lumina.Presentation.Web/Controllers/FileManagement/FilesController.cs b/src/Lumina.Presentation.Web/Controllers/FileSystemManagement/FilesController.cs similarity index 95% rename from src/Lumina.Presentation.Web/Controllers/FileManagement/FilesController.cs rename to src/Lumina.Presentation.Web/Controllers/FileSystemManagement/FilesController.cs index ed263306..373d2168 100644 --- a/src/Lumina.Presentation.Web/Controllers/FileManagement/FilesController.cs +++ b/src/Lumina.Presentation.Web/Controllers/FileSystemManagement/FilesController.cs @@ -1,6 +1,6 @@ #region ========================================================================= USING ===================================================================================== using Lumina.Presentation.Web.Common.Api; -using Lumina.Presentation.Web.Common.Models.FileManagement; +using Lumina.Presentation.Web.Common.Models.FileSystemManagement; using Microsoft.AspNetCore.Mvc; using System; using System.Collections.Generic; @@ -8,7 +8,7 @@ using System.Runtime.CompilerServices; using System.Threading; #endregion -namespace Lumina.Presentation.Web.Controllers.FileManagement; +namespace Lumina.Presentation.Web.Controllers.FileSystemManagement; /// /// Controller for managing file system files. diff --git a/src/Lumina.Presentation.Web/Controllers/FileManagement/PathController.cs b/src/Lumina.Presentation.Web/Controllers/FileSystemManagement/PathController.cs similarity index 97% rename from src/Lumina.Presentation.Web/Controllers/FileManagement/PathController.cs rename to src/Lumina.Presentation.Web/Controllers/FileSystemManagement/PathController.cs index 1d7b2299..11cf8b9c 100644 --- a/src/Lumina.Presentation.Web/Controllers/FileManagement/PathController.cs +++ b/src/Lumina.Presentation.Web/Controllers/FileSystemManagement/PathController.cs @@ -1,13 +1,13 @@ #region ========================================================================= USING ===================================================================================== using Lumina.Presentation.Web.Common.Api; -using Lumina.Presentation.Web.Common.Models.FileManagement; +using Lumina.Presentation.Web.Common.Models.FileSystemManagement; using Microsoft.AspNetCore.Mvc; using System; using System.Threading; using System.Threading.Tasks; #endregion -namespace Lumina.Presentation.Web.Controllers.FileManagement; +namespace Lumina.Presentation.Web.Controllers.FileSystemManagement; /// /// Controller for managing file system paths. diff --git a/src/Lumina.Presentation.Web/Views/Shared/Components/FileSystemBrowser/Default.cshtml b/src/Lumina.Presentation.Web/Views/Shared/Components/FileSystemBrowser/Default.cshtml index 0db4147c..45a66abd 100644 --- a/src/Lumina.Presentation.Web/Views/Shared/Components/FileSystemBrowser/Default.cshtml +++ b/src/Lumina.Presentation.Web/Views/Shared/Components/FileSystemBrowser/Default.cshtml @@ -3,7 +3,7 @@ @using Lumina.Presentation.Web.Common.Enums.FileSystem @using Lumina.Presentation.Web.Common.Enums.Notifications @using Lumina.Presentation.Web.Common.Exceptions -@using Lumina.Presentation.Web.Common.Models.FileManagement +@using Lumina.Presentation.Web.Common.Models.FileSystemManagement @using Lumina.Presentation.Web.Common.Models.UI @using Lumina.Presentation.Web.Common.Services @using Microsoft.AspNetCore.Components diff --git a/src/Lumina.sln b/src/Lumina.sln index fc1f2199..66b4106b 100644 --- a/src/Lumina.sln +++ b/src/Lumina.sln @@ -47,8 +47,8 @@ Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "api", "api", "{B045C2EC-3AC EndProject Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "domain", "domain", "{4F8D14A3-A465-4EC2-B175-A188B113AB99}" ProjectSection(SolutionItems) = preProject - ..\docs\technical\domain\Aggregates.FileManagement.md = ..\docs\technical\domain\Aggregates.FileManagement.md ..\docs\technical\domain\Aggregates.VideoLibrary.md = ..\docs\technical\domain\Aggregates.VideoLibrary.md + ..\docs\technical\domain\Aggregates.FileSystemManagement.md = ..\docs\technical\domain\Aggregates.FileSystemManagement.md ..\docs\technical\domain\Aggregates.WrittenContentLibrary.md = ..\docs\technical\domain\Aggregates.WrittenContentLibrary.md ..\docs\technical\domain\Common.Metadata.md = ..\docs\technical\domain\Common.Metadata.md ..\docs\technical\domain\UbiquitousLanguage.md = ..\docs\technical\domain\UbiquitousLanguage.md diff --git a/tests/IntegrationTests/Lumina.DataAccess.IntegrationTests/Lumina.DataAccess.IntegrationTests.csproj b/tests/IntegrationTests/Lumina.DataAccess.IntegrationTests/Lumina.DataAccess.IntegrationTests.csproj index 92668374..99d79575 100644 --- a/tests/IntegrationTests/Lumina.DataAccess.IntegrationTests/Lumina.DataAccess.IntegrationTests.csproj +++ b/tests/IntegrationTests/Lumina.DataAccess.IntegrationTests/Lumina.DataAccess.IntegrationTests.csproj @@ -16,11 +16,11 @@ all runtime; build; native; contentfiles; analyzers; buildtransitive - - - + + + - + all runtime; build; native; contentfiles; analyzers; buildtransitive diff --git a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Common/Converters/BookJsonConverter.cs b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Common/Converters/BookJsonConverter.cs index 6dc309fc..6d95bec0 100644 --- a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Common/Converters/BookJsonConverter.cs +++ b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Common/Converters/BookJsonConverter.cs @@ -35,7 +35,7 @@ public class BookJsonConverter : JsonConverter { JsonElement root = doc.RootElement; - Guid id = root.GetProperty("id").GetProperty("value").GetGuid(); + Guid id = root.GetProperty("id").GetGuid(); DateTime created = root.GetProperty("created").GetDateTime(); WrittenContentMetadata metadata = DeserializeMetadata(root.GetProperty("metadata")); BookFormat? format = null; @@ -108,7 +108,7 @@ public class BookJsonConverter : JsonConverter /// /// The JSON element containing the metadata. /// The deserialized . - private WrittenContentMetadata DeserializeMetadata(JsonElement element) + private static WrittenContentMetadata DeserializeMetadata(JsonElement element) { string? title = element.GetProperty("title").GetString(); string? originalTitle = element.GetProperty("originalTitle").GetString(); @@ -146,9 +146,9 @@ public class BookJsonConverter : JsonConverter /// /// The JSON element containing the release info. /// The deserialized . - private ReleaseInfo DeserializeReleaseInfo(JsonElement element) + private static ReleaseInfo DeserializeReleaseInfo(JsonElement element) { - DateOnly? originalReleaseDate = element.TryGetProperty("originalReleaseDate", out JsonElement ordElement) ? + DateOnly? originalReleaseDate = element.TryGetProperty("originalReleaseDate", out JsonElement ordElement) && ordElement.ValueKind != JsonValueKind.Null ? DateOnly.Parse(ordElement.GetString()!) : (DateOnly?)null; int? originalReleaseYear = element.TryGetProperty("originalReleaseYear", out JsonElement oryElement) && oryElement.ValueKind == JsonValueKind.Number ? oryElement.GetInt32() : (int?)null; @@ -180,7 +180,7 @@ public class BookJsonConverter : JsonConverter /// /// The JSON element containing the genres. /// The deserialized list of . - private List DeserializeGenres(JsonElement element) + private static List DeserializeGenres(JsonElement element) { return element.EnumerateArray() .Select(g => Genre.Create(g.GetProperty("name").GetString()!).Value) @@ -192,7 +192,7 @@ public class BookJsonConverter : JsonConverter /// /// The JSON element containing the tags. /// The deserialized list of . - private List DeserializeTags(JsonElement element) + private static List DeserializeTags(JsonElement element) { return element.EnumerateArray() .Select(t => Tag.Create(t.GetProperty("name").GetString()!).Value) @@ -204,7 +204,7 @@ public class BookJsonConverter : JsonConverter /// /// The JSON element containing the language info. /// The deserialized . - private LanguageInfo? DeserializeLanguageInfo(JsonElement element) + private static LanguageInfo? DeserializeLanguageInfo(JsonElement element) { if (element.ValueKind != JsonValueKind.Null) { @@ -231,7 +231,7 @@ public class BookJsonConverter : JsonConverter /// /// The JSON element containing the book series. /// The deserialized . - private BookSeries DeserializeBookSeries(JsonElement element) + private static BookSeries DeserializeBookSeries(JsonElement element) { // TODO: implement when book series are implemented return null!; @@ -242,7 +242,7 @@ public class BookJsonConverter : JsonConverter /// /// The JSON element containing the ISBNs. /// The deserialized list of . - private List DeserializeIsbns(JsonElement element) + private static List DeserializeIsbns(JsonElement element) { return element.EnumerateArray() .Select(i => Isbn.Create(i.GetProperty("value").GetString()!, @@ -255,7 +255,7 @@ public class BookJsonConverter : JsonConverter /// /// The JSON element containing the contributor IDs. /// The deserialized list of . - private List DeserializeContributorIds(JsonElement element) + private static List DeserializeContributorIds(JsonElement element) { // TODO: implement when contributors are implemented return []; @@ -266,7 +266,7 @@ public class BookJsonConverter : JsonConverter /// /// The JSON element containing the ratings. /// The deserialized list of . - private List DeserializeRatings(JsonElement element) + private static List DeserializeRatings(JsonElement element) { return element.EnumerateArray() .Select(r => BookRating.Create( diff --git a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Common/Setup/LuminaApiFactory.cs b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Common/Setup/LuminaApiFactory.cs index 7f7d0368..fe1e67c0 100644 --- a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Common/Setup/LuminaApiFactory.cs +++ b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Common/Setup/LuminaApiFactory.cs @@ -8,8 +8,6 @@ using Microsoft.Extensions.DependencyInjection; using System; using System.Diagnostics.CodeAnalysis; using System.Linq; -using System.Text.Json; -using System.Text.Json.Serialization; #endregion namespace Lumina.Presentation.Api.IntegrationTests.Common.Setup; diff --git a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Controllers/FileManagement/DirectoriesControllerTests.cs b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Controllers/FileManagement/DirectoriesControllerTests.cs deleted file mode 100644 index d271f74c..00000000 --- a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Controllers/FileManagement/DirectoriesControllerTests.cs +++ /dev/null @@ -1,639 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using FluentAssertions; -using Lumina.Contracts.Enums.FileSystem; -using Lumina.Contracts.Responses.FileManagement; -using Lumina.Presentation.Api.IntegrationTests.Common.Setup; -using Lumina.Presentation.Api.IntegrationTests.Core.Controllers.FileManagement.Fixtures; -using System; -using System.Collections.Generic; -using System.Diagnostics.CodeAnalysis; -using System.IO; -using System.Linq; -using System.Net; -using System.Net.Http; -using System.Runtime.InteropServices; -using System.Text.Json; -using System.Text.Json.Serialization; -using System.Threading; -using System.Threading.Tasks; -#endregion - -namespace Lumina.Presentation.Api.IntegrationTests.Core.Controllers.FileManagement; - -/// -/// Contains integration tests for the class. -/// -[ExcludeFromCodeCoverage] -public class DirectoriesControllerTests : IClassFixture -{ - private readonly HttpClient _client; - private readonly JsonSerializerOptions _jsonOptions = new() - { - ReferenceHandler = ReferenceHandler.Preserve, - PropertyNameCaseInsensitive = true, - Converters = { new JsonStringEnumConverter(JsonNamingPolicy.CamelCase) } - }; - private static readonly bool s_isLinux = RuntimeInformation.IsOSPlatform(OSPlatform.Linux); - - /// - /// Initializes a new instance of the class. - /// - /// Injected in-memory API factory. - public DirectoriesControllerTests(LuminaApiFactory apiFactory) - { - _client = apiFactory.CreateClient(); - } - - [Fact] - public async Task GetDirectoryTree_WhenCalledWithValidPathAndIncludeFilesAndNotIncludeHiddenElements_ShouldReturnDirectoryTreeWithFilesAndNotHiddenElements() - { - // Arrange - FileSystemStructureFixture fileSystemFixture = new(); - string testPath = fileSystemFixture.CreateFileSystemStructure(); - - bool includeFiles = true; - bool includeHiddenElements = false; - try - { - // Act - HttpResponseMessage response = await _client.GetAsync($"/api/v1/directories/get-directory-tree?path={Uri.EscapeDataString(testPath)}&includeFiles={includeFiles}&includeHiddenElements={includeHiddenElements}"); - - // Assert - response.EnsureSuccessStatusCode(); - response.StatusCode.Should().Be(HttpStatusCode.OK); - - List treeNodes = []; - - using (Stream stream = await response.Content.ReadAsStreamAsync()) - { - using (JsonDocument jsonDoc = await JsonDocument.ParseAsync(stream)) - { - foreach (JsonElement element in jsonDoc.RootElement.EnumerateArray()) - { - FileSystemTreeNodeResponse? node = JsonSerializer.Deserialize(element.GetRawText(), _jsonOptions); - if (node is not null) - treeNodes.Add(node); - } - } - } - treeNodes.Should().NotBeNull(); - treeNodes!.Should().NotBeEmpty(); - - string[] pathSegments = testPath.Split(Path.DirectorySeparatorChar, StringSplitOptions.RemoveEmptyEntries); - if (s_isLinux) // on UNIX, the leading slash is considered "the drive", the root location - add it! - pathSegments = new string[] { "/" }.Concat(pathSegments).ToArray(); - // recursively validate the tree structure - void ValidateNode(FileSystemTreeNodeResponse node, int depth) - { - // ensure the current node's name and path match the expected segment - string expectedSegment = pathSegments[depth]; - - if (depth == 0 && node.ItemType == FileSystemItemType.Root && expectedSegment.Length == 2 && char.IsLetter(expectedSegment[0]) && expectedSegment[1] == ':' - && !expectedSegment.EndsWith(Path.DirectorySeparatorChar)) - expectedSegment += Path.DirectorySeparatorChar; - - node.Name.Should().Be(expectedSegment); - - string expectedPath = string.Join(Path.DirectorySeparatorChar.ToString(), pathSegments.Take(depth + 1)); - if (expectedPath.StartsWith("//")) - expectedPath = expectedPath.Substring(1); - if (!expectedPath.EndsWith(Path.DirectorySeparatorChar)) - expectedPath += Path.DirectorySeparatorChar; - node.Path.Should().EndWith(expectedPath); - - // if the node is a drive or directory, check its children recursively - if (node.ItemType is FileSystemItemType.Root or FileSystemItemType.Directory) - { - node.Children.Should().NotBeNull(); - foreach (FileSystemTreeNodeResponse childNode in node.Children) - { - if (childNode.ItemType != FileSystemItemType.File) // go deeper one level, if the iterated node's children is also a directory - ValidateNode(childNode, depth + 1); - else if (childNode.ItemType is FileSystemItemType.File) - { - childNode.Children.Should().BeEmpty(); // files should not have children - childNode.Name.Should().Be("TestFile_2.txt"); - } - } - } - } - FileSystemTreeNodeResponse rootNode = treeNodes.First(); - ValidateNode(rootNode, 0); - } - finally - { - fileSystemFixture.CleanupFileSystemStructure(); - } - } - - [Fact] - public async Task GetDirectoryTree_WhenCalledWithValidPathAndIncludeFilesAndWithIncludeHiddenElements_ShouldReturnDirectoryTreeWithFilesAndHiddenElements() - { - // Arrange - FileSystemStructureFixture fileSystemFixture = new(); - string testPath = fileSystemFixture.CreateFileSystemStructure(); - - bool includeFiles = true; - bool includeHiddenElements = true; - try - { - // Act - HttpResponseMessage response = await _client.GetAsync($"/api/v1/directories/get-directory-tree?path={Uri.EscapeDataString(testPath)}&includeFiles={includeFiles}&includeHiddenElements={includeHiddenElements}"); - - // Assert - response.EnsureSuccessStatusCode(); - response.StatusCode.Should().Be(HttpStatusCode.OK); - - List treeNodes = []; - - using (Stream stream = await response.Content.ReadAsStreamAsync()) - { - using (JsonDocument jsonDoc = await JsonDocument.ParseAsync(stream)) - { - foreach (JsonElement element in jsonDoc.RootElement.EnumerateArray()) - { - FileSystemTreeNodeResponse? node = JsonSerializer.Deserialize(element.GetRawText(), _jsonOptions); - if (node is not null) - treeNodes.Add(node); - } - } - } - treeNodes.Should().NotBeNull(); - treeNodes!.Should().NotBeEmpty(); - - string[] pathSegments = testPath.Split(Path.DirectorySeparatorChar, StringSplitOptions.RemoveEmptyEntries); - if (s_isLinux) // on UNIX, the leading slash is considered "the drive", the root location - add it! - pathSegments = new string[] { "/" }.Concat(pathSegments).ToArray(); - - // recursively validate the tree structure - void ValidateNode(FileSystemTreeNodeResponse node, int depth) - { - // ensure the current node's name and path match the expected segment - string expectedSegment = pathSegments[depth]; - - if (depth == 0 && node.ItemType == FileSystemItemType.Root && expectedSegment.Length == 2 && char.IsLetter(expectedSegment[0]) && expectedSegment[1] == ':' - && !expectedSegment.EndsWith(Path.DirectorySeparatorChar)) - expectedSegment += Path.DirectorySeparatorChar; - - node.Name.Should().Be(expectedSegment); - - string expectedPath = string.Join(Path.DirectorySeparatorChar.ToString(), pathSegments.Take(depth + 1)); - if (!expectedPath.EndsWith(Path.DirectorySeparatorChar)) - expectedPath += Path.DirectorySeparatorChar; - if (expectedPath.StartsWith("//")) - expectedPath = expectedPath.Substring(1); - node.Path.Should().EndWith(expectedPath); - - // if the node is a drive or directory, check its children recursively - if (node.ItemType is FileSystemItemType.Root or FileSystemItemType.Directory) - { - node.Children.Should().NotBeNull(); - foreach (FileSystemTreeNodeResponse childNode in node.Children) - { - if (childNode.ItemType != FileSystemItemType.File) // go deeper one level, if the iterated node's children is also a directory - ValidateNode(childNode, depth + 1); - else if (childNode.ItemType is FileSystemItemType.File) - { - childNode.Children.Should().BeEmpty(); // files should not have children - childNode.Name.Should().BeOneOf((s_isLinux ? "." : string.Empty) + "TestFile_1.txt", "TestFile_2.txt"); - } - } - } - } - FileSystemTreeNodeResponse rootNode = treeNodes.First(); - ValidateNode(rootNode, 0); - } - finally - { - fileSystemFixture.CleanupFileSystemStructure(); - } - } - - [Fact] - public async Task GetDirectoryTree_WhenCalledWithValidPathAndNotIncludeFilesAndNotIncludeHiddenElements_ShouldReturnDirectoryTreeWithoutFiles() - { - // Arrange - FileSystemStructureFixture fileSystemFixture = new(); - string testPath = fileSystemFixture.CreateFileSystemStructure(); - - bool includeFiles = false; - bool includeHiddenElements = false; - try - { - // Act - HttpResponseMessage response = await _client.GetAsync($"/api/v1/directories/get-directory-tree?path={Uri.EscapeDataString(testPath)}&includeFiles={includeFiles}&includeHiddenElements={includeHiddenElements}"); - - // Assert - response.EnsureSuccessStatusCode(); - response.StatusCode.Should().Be(HttpStatusCode.OK); - - List treeNodes = []; - - using (Stream stream = await response.Content.ReadAsStreamAsync()) - { - using (JsonDocument jsonDoc = await JsonDocument.ParseAsync(stream)) - { - foreach (JsonElement element in jsonDoc.RootElement.EnumerateArray()) - { - FileSystemTreeNodeResponse? node = JsonSerializer.Deserialize(element.GetRawText(), _jsonOptions); - if (node is not null) - treeNodes.Add(node); - } - } - } - treeNodes.Should().NotBeNull(); - treeNodes!.Should().NotBeEmpty(); - - // there should not be a File node - treeNodes.Should().AllSatisfy(node => node.ItemType.Should().BeOneOf(FileSystemItemType.Directory, FileSystemItemType.Root)); - - string[] pathSegments = testPath.Split(Path.DirectorySeparatorChar, StringSplitOptions.RemoveEmptyEntries); - if (s_isLinux) // on UNIX, the leading slash is considered "the drive", the root location - add it! - pathSegments = new string[] { "/" }.Concat(pathSegments).ToArray(); - - // recursively validate the tree structure - void ValidateNode(FileSystemTreeNodeResponse node, int depth) - { - // ensure the current node's name and path match the expected segment - string expectedSegment = pathSegments[depth]; - - if (depth == 0 && node.ItemType == FileSystemItemType.Root && expectedSegment.Length == 2 && char.IsLetter(expectedSegment[0]) && expectedSegment[1] == ':' - && !expectedSegment.EndsWith(Path.DirectorySeparatorChar)) - expectedSegment += Path.DirectorySeparatorChar; - - node.Name.Should().Be(expectedSegment); - - string expectedPath = string.Join(Path.DirectorySeparatorChar.ToString(), pathSegments.Take(depth + 1)); - if (!expectedPath.EndsWith(Path.DirectorySeparatorChar)) - expectedPath += Path.DirectorySeparatorChar; - if (expectedPath.StartsWith("//")) - expectedPath = expectedPath.Substring(1); - node.Path.Should().EndWith(expectedPath); - - node.Children.Should().NotBeNull(); - foreach (FileSystemTreeNodeResponse childNode in node.Children) - ValidateNode(childNode, depth + 1); - } - FileSystemTreeNodeResponse rootNode = treeNodes.First(); - ValidateNode(rootNode, 0); - } - finally - { - fileSystemFixture.CleanupFileSystemStructure(); - } - } - - [Fact] - public async Task GetDirectoryTree_WhenCalledWithValidPathAndNotIncludeFilesAndIncludeHiddenElements_ShouldReturnDirectoryTreeWithoutFiles() - { - // Arrange - FileSystemStructureFixture fileSystemFixture = new(); - string testPath = fileSystemFixture.CreateFileSystemStructure(); - - bool includeFiles = false; - bool includeHiddenElements = true; - try - { - // Act - HttpResponseMessage response = await _client.GetAsync($"/api/v1/directories/get-directory-tree?path={Uri.EscapeDataString(testPath)}&includeFiles={includeFiles}&includeHiddenElements={includeHiddenElements}"); - - // Assert - response.EnsureSuccessStatusCode(); - response.StatusCode.Should().Be(HttpStatusCode.OK); - - List treeNodes = []; - - using (Stream stream = await response.Content.ReadAsStreamAsync()) - { - using (JsonDocument jsonDoc = await JsonDocument.ParseAsync(stream)) - { - foreach (JsonElement element in jsonDoc.RootElement.EnumerateArray()) - { - FileSystemTreeNodeResponse? node = JsonSerializer.Deserialize(element.GetRawText(), _jsonOptions); - if (node is not null) - treeNodes.Add(node); - } - } - } - treeNodes.Should().NotBeNull(); - treeNodes!.Should().NotBeEmpty(); - - // there should not be a File node - treeNodes.Should().AllSatisfy(node => node.ItemType.Should().BeOneOf(FileSystemItemType.Directory, FileSystemItemType.Root)); - - string[] pathSegments = testPath.Split(Path.DirectorySeparatorChar, StringSplitOptions.RemoveEmptyEntries); - if (s_isLinux) // on UNIX, the leading slash is considered "the drive", the root location - add it! - pathSegments = new string[] { "/" }.Concat(pathSegments).ToArray(); - - // recursively validate the tree structure - void ValidateNode(FileSystemTreeNodeResponse node, int depth) - { - // ensure the current node's name and path match the expected segment - string expectedSegment = pathSegments[depth]; - - if (depth == 0 && node.ItemType == FileSystemItemType.Root && expectedSegment.Length == 2 && char.IsLetter(expectedSegment[0]) && expectedSegment[1] == ':' - && !expectedSegment.EndsWith(Path.DirectorySeparatorChar)) - expectedSegment += Path.DirectorySeparatorChar; - - node.Name.Should().Be(expectedSegment); - - string expectedPath = string.Join(Path.DirectorySeparatorChar.ToString(), pathSegments.Take(depth + 1)); - if (!expectedPath.EndsWith(Path.DirectorySeparatorChar)) - expectedPath += Path.DirectorySeparatorChar; - if (expectedPath.StartsWith("//")) - expectedPath = expectedPath.Substring(1); - node.Path.Should().EndWith(expectedPath); - - node.Children.Should().NotBeNull(); - foreach (FileSystemTreeNodeResponse childNode in node.Children) - ValidateNode(childNode, depth + 1); - } - FileSystemTreeNodeResponse rootNode = treeNodes.First(); - ValidateNode(rootNode, 0); - } - finally - { - fileSystemFixture.CleanupFileSystemStructure(); - } - } - - [Fact] - public async Task GetTreeDirectories_WhenCalledWithValidPathAndNotIncludeHiddenElements_ShouldReturnTreeDirectoriesWithoutHiddenElements() - { - // Arrange - FileSystemStructureFixture fileSystemFixture = new(); - string testPath = fileSystemFixture.CreateFileSystemStructure(); - testPath = Path.GetDirectoryName(testPath) ?? testPath; - bool includeHiddenElements = false; - try - { - // Act - HttpResponseMessage response = await _client.GetAsync($"/api/v1/directories/get-tree-directories?path={Uri.EscapeDataString(testPath)}&includeHiddenElements={includeHiddenElements}"); - - // Assert - response.EnsureSuccessStatusCode(); - response.StatusCode.Should().Be(HttpStatusCode.OK); - - List treeNodes = []; - - using (Stream stream = await response.Content.ReadAsStreamAsync()) - { - using (JsonDocument jsonDoc = await JsonDocument.ParseAsync(stream)) - { - foreach (JsonElement element in jsonDoc.RootElement.EnumerateArray()) - { - FileSystemTreeNodeResponse? node = JsonSerializer.Deserialize(element.GetRawText(), _jsonOptions); - if (node is not null) - treeNodes.Add(node); - } - } - } - treeNodes.Should().NotBeNull(); - treeNodes!.Should().NotBeEmpty(); - - string[] pathSegments = testPath.Split(Path.DirectorySeparatorChar, StringSplitOptions.RemoveEmptyEntries); - - - FileSystemTreeNodeResponse firstNode = treeNodes.First(); - firstNode.Name.Should().Be("NestedDirectory_3"); - firstNode.Path.Should().Be(Path.Combine(testPath, "NestedDirectory_3" + Path.DirectorySeparatorChar)); - firstNode.ItemType.Should().Be(FileSystemItemType.Directory); - treeNodes.Should().AllSatisfy(n => n.ItemType.Should().Be(FileSystemItemType.Directory)); - treeNodes.Count.Should().Be(1); // only directories - } - finally - { - fileSystemFixture.CleanupFileSystemStructure(); - } - } - - [Fact] - public async Task GetTreeDirectories_WhenCalledWithValidPathAndHiddenChildrenAndNotIncludeHiddenElements_ShouldReturnNoTreeDirectories() - { - // Arrange - FileSystemStructureFixture fileSystemFixture = new(); - string testPath = fileSystemFixture.CreateFileSystemStructure(); - testPath = Path.GetDirectoryName(testPath) ?? testPath; - testPath = Path.GetDirectoryName(testPath) ?? testPath; // two levels to get to the element that has a hidden element as child - bool includeHiddenElements = false; - try - { - // Act - HttpResponseMessage response = await _client.GetAsync($"/api/v1/directories/get-tree-directories?path={Uri.EscapeDataString(testPath)}&includeHiddenElements={includeHiddenElements}"); - - // Assert - response.EnsureSuccessStatusCode(); - response.StatusCode.Should().Be(HttpStatusCode.OK); - - List treeNodes = []; - - using (Stream stream = await response.Content.ReadAsStreamAsync()) - { - using (JsonDocument jsonDoc = await JsonDocument.ParseAsync(stream)) - { - foreach (JsonElement element in jsonDoc.RootElement.EnumerateArray()) - { - FileSystemTreeNodeResponse? node = JsonSerializer.Deserialize(element.GetRawText(), _jsonOptions); - if (node is not null) - treeNodes.Add(node); - } - } - } - treeNodes.Should().NotBeNull(); - treeNodes!.Should().BeEmpty(); - } - finally - { - fileSystemFixture.CleanupFileSystemStructure(); - } - } - - [Fact] - public async Task GetTreeDirectories_WhenCalledWithValidPathAndWithIncludeHiddenElements_ShouldReturnTreeDirectoriesWithHiddenElements() - { - // Arrange - FileSystemStructureFixture fileSystemFixture = new(); - string testPath = fileSystemFixture.CreateFileSystemStructure(); - testPath = Path.GetDirectoryName(testPath) ?? testPath; - testPath = Path.GetDirectoryName(testPath) ?? testPath; // two levels to get to the element that has a hidden element as child - bool includeHiddenElements = true; - try - { - // Act - HttpResponseMessage response = await _client.GetAsync($"/api/v1/directories/get-tree-directories?path={Uri.EscapeDataString(testPath)}&includeHiddenElements={includeHiddenElements}"); - - // Assert - response.EnsureSuccessStatusCode(); - response.StatusCode.Should().Be(HttpStatusCode.OK); - - List treeNodes = []; - - using (Stream stream = await response.Content.ReadAsStreamAsync()) - { - using (JsonDocument jsonDoc = await JsonDocument.ParseAsync(stream)) - { - foreach (JsonElement element in jsonDoc.RootElement.EnumerateArray()) - { - FileSystemTreeNodeResponse? node = JsonSerializer.Deserialize(element.GetRawText(), _jsonOptions); - if (node is not null) - treeNodes.Add(node); - } - } - } - treeNodes.Should().NotBeNull(); - treeNodes!.Should().NotBeEmpty(); - - string[] pathSegments = testPath.Split(Path.DirectorySeparatorChar, StringSplitOptions.RemoveEmptyEntries); - - - FileSystemTreeNodeResponse firstNode = treeNodes.First(); - firstNode.Name.Should().Be((s_isLinux ? "." : string.Empty) + "NestedDirectory_2"); - firstNode.Path.Should().Be(Path.Combine(testPath, (s_isLinux ? "." : string.Empty) + "NestedDirectory_2" + Path.DirectorySeparatorChar)); - firstNode.ItemType.Should().Be(FileSystemItemType.Directory); - treeNodes.Should().AllSatisfy(n => n.ItemType.Should().Be(FileSystemItemType.Directory)); - treeNodes.Count.Should().Be(1); // only directories - } - finally - { - fileSystemFixture.CleanupFileSystemStructure(); - } - } - - [Fact] - public async Task GetDirectories_WhenCalledWithValidPathAndNotIncludeHiddenElements_ShouldReturnDirectoriesWithoutHiddenElements() - { - // Arrange - FileSystemStructureFixture fileSystemFixture = new(); - string testPath = fileSystemFixture.CreateFileSystemStructure(); - testPath = Path.GetDirectoryName(testPath) ?? testPath; - bool includeHiddenElements = false; - try - { - // Act - HttpResponseMessage response = await _client.GetAsync($"/api/v1/directories/get-directories?path={Uri.EscapeDataString(testPath)}&includeHiddenElements={includeHiddenElements}"); - - // Assert - response.EnsureSuccessStatusCode(); - response.StatusCode.Should().Be(HttpStatusCode.OK); - - List directories = []; - - using (Stream stream = await response.Content.ReadAsStreamAsync()) - { - using (JsonDocument jsonDoc = await JsonDocument.ParseAsync(stream)) - { - foreach (JsonElement element in jsonDoc.RootElement.EnumerateArray()) - { - DirectoryResponse? directory = JsonSerializer.Deserialize(element.GetRawText(), _jsonOptions); - if (directory is not null) - directories.Add(directory); - } - } - } - directories.Should().NotBeNull(); - directories!.Should().NotBeEmpty(); - - string[] pathSegments = testPath.Split(Path.DirectorySeparatorChar, StringSplitOptions.RemoveEmptyEntries); - - - DirectoryResponse firstDirectory = directories.First(); - firstDirectory.Name.Should().Be("NestedDirectory_3"); - firstDirectory.Path.Should().Be(Path.Combine(testPath, "NestedDirectory_3" + Path.DirectorySeparatorChar)); - directories.Count.Should().Be(1); // only directories - } - finally - { - fileSystemFixture.CleanupFileSystemStructure(); - } - } - - [Fact] - public async Task GetDirectories_WhenCalledWithValidPathAndHiddenChildrenAndNotIncludeHiddenElements_ShouldReturnNoDirectories() - { - // Arrange - FileSystemStructureFixture fileSystemFixture = new(); - string testPath = fileSystemFixture.CreateFileSystemStructure(); - testPath = Path.GetDirectoryName(testPath) ?? testPath; - testPath = Path.GetDirectoryName(testPath) ?? testPath; // two levels to get to the element that has a hidden element as child - bool includeHiddenElements = false; - try - { - // Act - HttpResponseMessage response = await _client.GetAsync($"/api/v1/directories/get-directories?path={Uri.EscapeDataString(testPath)}&includeHiddenElements={includeHiddenElements}"); - - // Assert - response.EnsureSuccessStatusCode(); - response.StatusCode.Should().Be(HttpStatusCode.OK); - - List directories = []; - - using (Stream stream = await response.Content.ReadAsStreamAsync()) - { - using (JsonDocument jsonDoc = await JsonDocument.ParseAsync(stream)) - { - foreach (JsonElement element in jsonDoc.RootElement.EnumerateArray()) - { - DirectoryResponse? directory = JsonSerializer.Deserialize(element.GetRawText(), _jsonOptions); - if (directory is not null) - directories.Add(directory); - } - } - } - directories.Should().NotBeNull(); - directories!.Should().BeEmpty(); - } - finally - { - fileSystemFixture.CleanupFileSystemStructure(); - } - } - - [Fact] - public async Task GetDirectories_WhenCalledWithValidPathAndWithIncludeHiddenElements_ShouldReturnDirectoriesWithHiddenElements() - { - // Arrange - FileSystemStructureFixture fileSystemFixture = new(); - string testPath = fileSystemFixture.CreateFileSystemStructure(); - testPath = Path.GetDirectoryName(testPath) ?? testPath; - testPath = Path.GetDirectoryName(testPath) ?? testPath; // two levels to get to the element that has a hidden element as child - bool includeHiddenElements = true; - try - { - // Act - HttpResponseMessage response = await _client.GetAsync($"/api/v1/directories/get-directories?path={Uri.EscapeDataString(testPath)}&includeHiddenElements={includeHiddenElements}"); - - // Assert - response.EnsureSuccessStatusCode(); - response.StatusCode.Should().Be(HttpStatusCode.OK); - - List directories = []; - - using (Stream stream = await response.Content.ReadAsStreamAsync()) - { - using (JsonDocument jsonDoc = await JsonDocument.ParseAsync(stream)) - { - foreach (JsonElement element in jsonDoc.RootElement.EnumerateArray()) - { - DirectoryResponse? directory = JsonSerializer.Deserialize(element.GetRawText(), _jsonOptions); - if (directory is not null) - directories.Add(directory); - } - } - } - directories.Should().NotBeNull(); - directories!.Should().NotBeEmpty(); - - string[] pathSegments = testPath.Split(Path.DirectorySeparatorChar, StringSplitOptions.RemoveEmptyEntries); - - - DirectoryResponse firstDirectory = directories.First(); - firstDirectory.Name.Should().Be((s_isLinux ? "." : string.Empty) + "NestedDirectory_2"); - firstDirectory.Path.Should().Be(Path.Combine(testPath, (s_isLinux ? "." : string.Empty) + "NestedDirectory_2" + Path.DirectorySeparatorChar)); - directories.Count.Should().Be(1); // only directories - } - finally - { - fileSystemFixture.CleanupFileSystemStructure(); - } - } -} diff --git a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Controllers/FileManagement/FilesControllerTests.cs b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Controllers/FileManagement/FilesControllerTests.cs deleted file mode 100644 index 478db481..00000000 --- a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Controllers/FileManagement/FilesControllerTests.cs +++ /dev/null @@ -1,329 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using FluentAssertions; -using Lumina.Contracts.Responses.FileManagement; -using Lumina.Presentation.Api.IntegrationTests.Common.Setup; -using Lumina.Presentation.Api.IntegrationTests.Core.Controllers.FileManagement.Fixtures; -using System; -using System.Collections.Generic; -using System.Diagnostics.CodeAnalysis; -using System.IO; -using System.Linq; -using System.Net; -using System.Net.Http; -using System.Runtime.InteropServices; -using System.Text.Json; -using System.Text.Json.Serialization; -using System.Threading; -using System.Threading.Tasks; -#endregion - -namespace Lumina.Presentation.Api.IntegrationTests.Core.Controllers.FileManagement; - -/// -/// Contains integration tests for the class. -/// -[ExcludeFromCodeCoverage] -public class FilesControllerTests : IClassFixture -{ - private readonly HttpClient _client; - private readonly JsonSerializerOptions _jsonOptions = new() - { - ReferenceHandler = ReferenceHandler.Preserve, - PropertyNameCaseInsensitive = true, - Converters = { new JsonStringEnumConverter(JsonNamingPolicy.CamelCase) } - }; - private static readonly bool s_isLinux = RuntimeInformation.IsOSPlatform(OSPlatform.Linux); - - /// - /// Initializes a new instance of the class. - /// - /// Injected in-memory API factory. - public FilesControllerTests(LuminaApiFactory apiFactory) - { - _client = apiFactory.CreateClient(); - } - - [Fact] - public async Task GetTreeFiles_WhenCalledWithValidPathAndNotIncludeHiddenElements_ShouldReturnTreeFilesWithoutHiddenElements() - { - // Arrange - FileSystemStructureFixture fileSystemFixture = new(); - string testPath = fileSystemFixture.CreateFileSystemStructure(); - testPath = Path.GetDirectoryName(testPath) ?? testPath; - bool includeHiddenElements = false; - try - { - // Act - HttpResponseMessage response = await _client.GetAsync($"/api/v1/files/get-tree-files?path={Uri.EscapeDataString(testPath)}&includeHiddenElements={includeHiddenElements}"); - - // Assert - response.EnsureSuccessStatusCode(); - response.StatusCode.Should().Be(HttpStatusCode.OK); - - List files = []; - - using (Stream stream = await response.Content.ReadAsStreamAsync()) - { - using (JsonDocument jsonDoc = await JsonDocument.ParseAsync(stream)) - { - foreach (JsonElement element in jsonDoc.RootElement.EnumerateArray()) - { - FileSystemTreeNodeResponse? file = JsonSerializer.Deserialize(element.GetRawText(), _jsonOptions); - if (file is not null) - files.Add(file); - } - } - } - files.Should().NotBeNull(); - files!.Should().NotBeEmpty(); - - string[] pathSegments = testPath.Split(Path.DirectorySeparatorChar, StringSplitOptions.RemoveEmptyEntries); - - - FileSystemTreeNodeResponse firstDirectory = files.First(); - firstDirectory.Name.Should().Be("TestFile_2.txt"); - firstDirectory.Path.Should().Be(Path.Combine(testPath, "TestFile_2.txt")); - files.Count.Should().Be(1); // only files - } - finally - { - fileSystemFixture.CleanupFileSystemStructure(); - } - } - - [Fact] - public async Task GetTreeFiles_WhenCalledWithValidPathAndHiddenChildrenAndNotIncludeHiddenElements_ShouldReturnNoTreeFiles() - { - // Arrange - FileSystemStructureFixture fileSystemFixture = new(); - string testPath = fileSystemFixture.CreateFileSystemStructure(); - testPath = Path.GetDirectoryName(testPath) ?? testPath; - testPath = Path.GetDirectoryName(testPath) ?? testPath; // two levels to get to the element that has a hidden element as child - bool includeHiddenElements = false; - try - { - // Act - HttpResponseMessage response = await _client.GetAsync($"/api/v1/files/get-tree-files?path={Uri.EscapeDataString(testPath)}&includeHiddenElements={includeHiddenElements}"); - - // Assert - response.EnsureSuccessStatusCode(); - response.StatusCode.Should().Be(HttpStatusCode.OK); - - List files = []; - - using (Stream stream = await response.Content.ReadAsStreamAsync()) - { - using (JsonDocument jsonDoc = await JsonDocument.ParseAsync(stream)) - { - foreach (JsonElement element in jsonDoc.RootElement.EnumerateArray()) - { - FileSystemTreeNodeResponse? file = JsonSerializer.Deserialize(element.GetRawText(), _jsonOptions); - if (file is not null) - files.Add(file); - } - } - } - files.Should().NotBeNull(); - FileSystemTreeNodeResponse firstDirectory = files.First(); - firstDirectory.Name.Should().Be("TestFile_2.txt"); - firstDirectory.Path.Should().Be(Path.Combine(testPath, "TestFile_2.txt")); - } - finally - { - fileSystemFixture.CleanupFileSystemStructure(); - } - } - - [Fact] - public async Task GetTreeFiles_WhenCalledWithValidPathAndWithIncludeHiddenElements_ShouldReturnTreeFilesWithHiddenElements() - { - // Arrange - FileSystemStructureFixture fileSystemFixture = new(); - string testPath = fileSystemFixture.CreateFileSystemStructure(); - testPath = Path.GetDirectoryName(testPath) ?? testPath; - testPath = Path.GetDirectoryName(testPath) ?? testPath; // two levels to get to the element that has a hidden element as child - bool includeHiddenElements = true; - try - { - // Act - HttpResponseMessage response = await _client.GetAsync($"/api/v1/files/get-tree-files?path={Uri.EscapeDataString(testPath)}&includeHiddenElements={includeHiddenElements}"); - - // Assert - response.EnsureSuccessStatusCode(); - response.StatusCode.Should().Be(HttpStatusCode.OK); - - List files = []; - - using (Stream stream = await response.Content.ReadAsStreamAsync()) - { - using (JsonDocument jsonDoc = await JsonDocument.ParseAsync(stream)) - { - foreach (JsonElement element in jsonDoc.RootElement.EnumerateArray()) - { - FileSystemTreeNodeResponse? file = JsonSerializer.Deserialize(element.GetRawText(), _jsonOptions); - if (file is not null) - files.Add(file); - } - } - } - files.Should().NotBeNull(); - files!.Should().NotBeEmpty(); - - string[] pathSegments = testPath.Split(Path.DirectorySeparatorChar, StringSplitOptions.RemoveEmptyEntries); - - FileSystemTreeNodeResponse firstDirectory = files.First(); - firstDirectory.Name.Should().Be((s_isLinux ? "." : string.Empty) + "TestFile_1.txt"); - firstDirectory.Path.Should().Be(Path.Combine(testPath, (s_isLinux ? "." : string.Empty) + "TestFile_1.txt")); - FileSystemTreeNodeResponse secondDirectory = files.Last(); - secondDirectory.Name.Should().Be("TestFile_2.txt"); - secondDirectory.Path.Should().Be(Path.Combine(testPath, "TestFile_2.txt")); - files.Count.Should().Be(2); - } - finally - { - fileSystemFixture.CleanupFileSystemStructure(); - } - } - - [Fact] - public async Task GetFiles_WhenCalledWithValidPathAndNotIncludeHiddenElements_ShouldReturnFilesWithoutHiddenElements() - { - // Arrange - FileSystemStructureFixture fileSystemFixture = new(); - string testPath = fileSystemFixture.CreateFileSystemStructure(); - testPath = Path.GetDirectoryName(testPath) ?? testPath; - bool includeHiddenElements = false; - try - { - // Act - HttpResponseMessage response = await _client.GetAsync($"/api/v1/files/get-files?path={Uri.EscapeDataString(testPath)}&includeHiddenElements={includeHiddenElements}"); - - // Assert - response.EnsureSuccessStatusCode(); - response.StatusCode.Should().Be(HttpStatusCode.OK); - - List files = []; - - using (Stream stream = await response.Content.ReadAsStreamAsync()) - { - using (JsonDocument jsonDoc = await JsonDocument.ParseAsync(stream)) - { - foreach (JsonElement element in jsonDoc.RootElement.EnumerateArray()) - { - FileResponse? file = JsonSerializer.Deserialize(element.GetRawText(), _jsonOptions); - if (file is not null) - files.Add(file); - } - } - } - files.Should().NotBeNull(); - files!.Should().NotBeEmpty(); - - string[] pathSegments = testPath.Split(Path.DirectorySeparatorChar, StringSplitOptions.RemoveEmptyEntries); - - - FileResponse firstDirectory = files.First(); - firstDirectory.Name.Should().Be("TestFile_2.txt"); - firstDirectory.Path.Should().Be(Path.Combine(testPath, "TestFile_2.txt")); - files.Count.Should().Be(1); // only files - } - finally - { - fileSystemFixture.CleanupFileSystemStructure(); - } - } - - [Fact] - public async Task GetFiles_WhenCalledWithValidPathAndHiddenChildrenAndNotIncludeHiddenElements_ShouldReturnNoFiles() - { - // Arrange - FileSystemStructureFixture fileSystemFixture = new(); - string testPath = fileSystemFixture.CreateFileSystemStructure(); - testPath = Path.GetDirectoryName(testPath) ?? testPath; - testPath = Path.GetDirectoryName(testPath) ?? testPath; // two levels to get to the element that has a hidden element as child - bool includeHiddenElements = false; - try - { - // Act - HttpResponseMessage response = await _client.GetAsync($"/api/v1/files/get-files?path={Uri.EscapeDataString(testPath)}&includeHiddenElements={includeHiddenElements}"); - - // Assert - response.EnsureSuccessStatusCode(); - response.StatusCode.Should().Be(HttpStatusCode.OK); - - List files = []; - - using (Stream stream = await response.Content.ReadAsStreamAsync()) - { - using (JsonDocument jsonDoc = await JsonDocument.ParseAsync(stream)) - { - foreach (JsonElement element in jsonDoc.RootElement.EnumerateArray()) - { - FileResponse? file = JsonSerializer.Deserialize(element.GetRawText(), _jsonOptions); - if (file is not null) - files.Add(file); - } - } - } - files.Should().NotBeNull(); - FileResponse firstDirectory = files.First(); - firstDirectory.Name.Should().Be("TestFile_2.txt"); - firstDirectory.Path.Should().Be(Path.Combine(testPath, "TestFile_2.txt")); - } - finally - { - fileSystemFixture.CleanupFileSystemStructure(); - } - } - - [Fact] - public async Task GetFiles_WhenCalledWithValidPathAndWithIncludeHiddenElements_ShouldReturnFilesWithHiddenElements() - { - // Arrange - FileSystemStructureFixture fileSystemFixture = new(); - string testPath = fileSystemFixture.CreateFileSystemStructure(); - testPath = Path.GetDirectoryName(testPath) ?? testPath; - testPath = Path.GetDirectoryName(testPath) ?? testPath; // two levels to get to the element that has a hidden element as child - bool includeHiddenElements = true; - try - { - // Act - HttpResponseMessage response = await _client.GetAsync($"/api/v1/files/get-files?path={Uri.EscapeDataString(testPath)}&includeHiddenElements={includeHiddenElements}"); - - // Assert - response.EnsureSuccessStatusCode(); - response.StatusCode.Should().Be(HttpStatusCode.OK); - - List files = []; - - using (Stream stream = await response.Content.ReadAsStreamAsync()) - { - using (JsonDocument jsonDoc = await JsonDocument.ParseAsync(stream)) - { - foreach (JsonElement element in jsonDoc.RootElement.EnumerateArray()) - { - FileResponse? file = JsonSerializer.Deserialize(element.GetRawText(), _jsonOptions); - if (file is not null) - files.Add(file); - } - } - } - files.Should().NotBeNull(); - files!.Should().NotBeEmpty(); - - string[] pathSegments = testPath.Split(Path.DirectorySeparatorChar, StringSplitOptions.RemoveEmptyEntries); - - FileResponse firstDirectory = files.First(); - firstDirectory.Name.Should().Be( (s_isLinux ? "." : string.Empty) + "TestFile_1.txt"); - firstDirectory.Path.Should().Be(Path.Combine(testPath, (s_isLinux ? "." : string.Empty) + "TestFile_1.txt")); - FileResponse secondDirectory = files.Last(); - secondDirectory.Name.Should().Be("TestFile_2.txt"); - secondDirectory.Path.Should().Be(Path.Combine(testPath, "TestFile_2.txt")); - files.Count.Should().Be(2); - } - finally - { - fileSystemFixture.CleanupFileSystemStructure(); - } - } -} diff --git a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Controllers/FileManagement/PathControllerTests.cs b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Controllers/FileManagement/PathControllerTests.cs deleted file mode 100644 index 73fd421f..00000000 --- a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Controllers/FileManagement/PathControllerTests.cs +++ /dev/null @@ -1,634 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using FluentAssertions; -using Lumina.Contracts.Responses.FileManagement; -using Lumina.Presentation.Api.Core.Controllers.FileManagement; -using Lumina.Presentation.Api.IntegrationTests.Common.Setup; -using Microsoft.AspNetCore.Mvc; -using System; -using System.Collections.Generic; -using System.Diagnostics.CodeAnalysis; -using System.IO; -using System.Linq; -using System.Net; -using System.Net.Http; -using System.Runtime.InteropServices; -using System.Text.Json; -using System.Text.Json.Serialization; -using System.Threading; -using System.Threading.Tasks; -#endregion - -namespace Lumina.Presentation.Api.IntegrationTests.Core.Controllers.FileManagement; - -/// -/// Contains integration tests for the class. -/// -[ExcludeFromCodeCoverage] -public class PathControllerTests : IClassFixture -{ - private readonly HttpClient _client; - private readonly JsonSerializerOptions _jsonOptions = new() - { - ReferenceHandler = ReferenceHandler.Preserve, - PropertyNameCaseInsensitive = true, - Converters = { new JsonStringEnumConverter(JsonNamingPolicy.CamelCase) } - }; - private static readonly bool s_isLinux = RuntimeInformation.IsOSPlatform(OSPlatform.Linux); - - /// - /// Initializes a new instance of the class. - /// - /// Injected in-memory API factory. - public PathControllerTests(LuminaApiFactory apiFactory) - { - _client = apiFactory.CreateClient(); - } - - [Fact] - public async Task GetPathRoot_WhenCalledWithValidPath_ShouldReturnOkResultWithPathSegmentResponse() - { - // Arrange - string testPath = System.IO.Path.GetTempPath(); - string encodedPath = Uri.EscapeDataString(testPath); - - // Act - HttpResponseMessage response = await _client.GetAsync($"/api/v1.0/path/get-path-root?path={encodedPath}"); - - // Assert - response.StatusCode.Should().Be(HttpStatusCode.OK); - string content = await response.Content.ReadAsStringAsync(); - PathSegmentResponse? result = JsonSerializer.Deserialize(content, _jsonOptions); - result.Should().NotBeNull(); - result!.Path.Should().NotBeNullOrEmpty(); - } - - [Fact] - public async Task GetPathRoot_WhenCalledWithInvalidPath_ShouldReturnProblemDetails() - { - // Arrange - string invalidPath = "invalid:path"; - string encodedPath = Uri.EscapeDataString(invalidPath); - - // Act - HttpResponseMessage response = await _client.GetAsync($"/api/v1.0/path/get-path-root?path={encodedPath}"); - - // Assert - response.StatusCode.Should().Be(HttpStatusCode.BadRequest); - string content = await response.Content.ReadAsStringAsync(); - ProblemDetails? problemDetails = JsonSerializer.Deserialize(content, _jsonOptions); - problemDetails.Should().NotBeNull(); - } - - [Fact] - public async Task GetPathRoot_WhenCalledWithEmptyPath_ShouldReturnBadRequestWithValidationError() - { - // Arrange - string emptyPath = ""; - string encodedPath = Uri.EscapeDataString(emptyPath); - - // Act - HttpResponseMessage response = await _client.GetAsync($"/api/v1.0/path/get-path-root?path={encodedPath}"); - - // Assert - response.StatusCode.Should().Be(HttpStatusCode.BadRequest); - string content = await response.Content.ReadAsStringAsync(); - ValidationProblemDetails? problemDetails = JsonSerializer.Deserialize(content, _jsonOptions); - problemDetails.Should().NotBeNull(); - problemDetails!.Title.Should().Be("One or more validation errors occurred."); - problemDetails.Errors["General.Validation"].Should().BeEquivalentTo("PathCannotBeEmpty"); - } - - [Fact] - public async Task GetPathRoot_WhenCalledWithCancellationToken_ShouldCompleteSuccessfully() - { - // Arrange - string testPath = System.IO.Path.GetTempPath(); - string encodedPath = Uri.EscapeDataString(testPath); - using CancellationTokenSource cts = new(TimeSpan.FromSeconds(5)); - - // Act - Func act = async () => await _client.GetAsync($"/api/v1.0/path/get-path-root?path={encodedPath}", cts.Token); - - // Assert - await act.Should().NotThrowAsync(); - } - - [Fact] - public async Task GetPathRoot_WhenCancellationTokenIsCancelled_ShouldThrowTaskCanceledException() - { - // Arrange - string testPath = System.IO.Path.GetTempPath(); - string encodedPath = Uri.EscapeDataString(testPath); - using CancellationTokenSource cts = new(); - - // Act - Func act = async () => - { - cts.Cancel(); // Cancel the token immediately - await _client.GetAsync($"/api/v1.0/path/get-path-root?path={encodedPath}", cts.Token); - }; - - // Assert - await act.Should().ThrowAsync(); - } - - [Fact] - public async Task GetPathSeparator_WhenCalled_ShouldReturnOkResultWithPathSeparatorResponse() - { - // Act - HttpResponseMessage response = await _client.GetAsync("/api/v1.0/path/get-path-separator"); - - // Assert - response.StatusCode.Should().Be(HttpStatusCode.OK); - string content = await response.Content.ReadAsStringAsync(); - PathSeparatorResponse? result = JsonSerializer.Deserialize(content, _jsonOptions); - result.Should().NotBeNull(); - result!.Separator.Should().BeOneOf("/", "\\"); - } - - [Fact] - public async Task GetPathSeparator_WhenCalledMultipleTimes_ShouldReturnConsistentResults() - { - // Act - HttpResponseMessage response1 = await _client.GetAsync("/api/v1.0/path/get-path-separator"); - HttpResponseMessage response2 = await _client.GetAsync("/api/v1.0/path/get-path-separator"); - - // Assert - response1.StatusCode.Should().Be(HttpStatusCode.OK); - response2.StatusCode.Should().Be(HttpStatusCode.OK); - - string content1 = await response1.Content.ReadAsStringAsync(); - string content2 = await response2.Content.ReadAsStringAsync(); - - PathSeparatorResponse? result1 = JsonSerializer.Deserialize(content1, _jsonOptions); - PathSeparatorResponse? result2 = JsonSerializer.Deserialize(content2, _jsonOptions); - - result1.Should().NotBeNull(); - result2.Should().NotBeNull(); - result1.Should().BeEquivalentTo(result2); - } - - [Fact] - public async Task GetPathSeparator_WhenCalledWithCancellationToken_ShouldCompleteSuccessfully() - { - // Arrange - using CancellationTokenSource cts = new(TimeSpan.FromSeconds(5)); - - // Act - Func act = async () => await _client.GetAsync("/api/v1.0/path/get-path-separator", cts.Token); - - // Assert - await act.Should().NotThrowAsync(); - } - - [Fact] - public async Task GetPathSeparator_WhenCancellationTokenIsCancelled_ShouldThrowTaskCanceledException() - { - // Arrange - using CancellationTokenSource cts = new(); - - // Act - Func act = async () => - { - cts.Cancel(); // Cancel the token immediately - await _client.GetAsync("/api/v1.0/path/get-path-separator", cts.Token); - }; - - // Assert - await act.Should().ThrowAsync(); - } - - [Fact] - public async Task GetPathParent_WhenCalledWithValidPath_ShouldReturnOkResultWithPathSegmentResponses() - { - // Arrange - string testPath = System.IO.Path.Combine(System.IO.Path.GetTempPath(), "testDirectory", "testFile.txt"); - string encodedPath = Uri.EscapeDataString(testPath); - - // Act - HttpResponseMessage response = await _client.GetAsync($"/api/v1.0/path/get-path-parent?path={encodedPath}"); - - // Assert - response.StatusCode.Should().Be(HttpStatusCode.OK); - string content = await response.Content.ReadAsStringAsync(); - IEnumerable? result = JsonSerializer.Deserialize>(content, _jsonOptions); - result.Should().NotBeNull(); - result!.Should().NotBeEmpty(); - - List hierarchy = []; - string path = System.IO.Path.GetDirectoryName(testPath)!; - while (!string.IsNullOrEmpty(path)) - { - string segment = s_isLinux && path == Path.DirectorySeparatorChar.ToString() ? path : System.IO.Path.GetFileName(path); - if (string.IsNullOrEmpty(segment)) - { - hierarchy.Add(System.IO.Path.GetPathRoot(path)!.TrimEnd(System.IO.Path.DirectorySeparatorChar)); - break; - } - hierarchy.Add(segment); - path = System.IO.Path.GetDirectoryName(path)!; - } - hierarchy.Reverse(); - - result!.Select(r => r.Path).Should().BeEquivalentTo(hierarchy, options => options.WithStrictOrdering()); - } - - [Fact] - public async Task GetPathParent_WhenCalledWithRootPath_ShouldReturnOkResultWithEmptyList() - { - // Arrange - string rootPath = System.IO.Path.GetPathRoot(System.IO.Path.GetTempPath())!; - string encodedPath = Uri.EscapeDataString(rootPath); - - // Act - HttpResponseMessage response = await _client.GetAsync($"/api/v1.0/path/get-path-parent?path={encodedPath}"); - - // Assert - response.StatusCode.Should().Be(HttpStatusCode.Forbidden); - string content = await response.Content.ReadAsStringAsync(); - ProblemDetails? problemDetails = JsonSerializer.Deserialize(content, _jsonOptions); - problemDetails.Should().NotBeNull(); - problemDetails!.Title.Should().Be("Failure"); - JsonElement jsonElement = (JsonElement)problemDetails!.Extensions["errors"]!; - string?[] errors = jsonElement.EnumerateArray() - .Select(element => element.GetString()) - .ToArray(); - errors.Should().BeEquivalentTo(["CannotNavigateUp"]); - - } - - [Fact] - public async Task GetPathParent_WhenCalledWithInvalidPath_ShouldReturnBadRequest() - { - // Arrange - string invalidPath = "invalid:path"; - string encodedPath = Uri.EscapeDataString(invalidPath); - - // Act - HttpResponseMessage response = await _client.GetAsync($"/api/v1.0/path/get-path-parent?path={encodedPath}"); - - // Assert - response.StatusCode.Should().Be(HttpStatusCode.BadRequest); - string content = await response.Content.ReadAsStringAsync(); - ProblemDetails? problemDetails = JsonSerializer.Deserialize(content, _jsonOptions); - problemDetails.Should().NotBeNull(); - } - - [Fact] - public async Task GetPathParent_WhenCalledWithEmptyPath_ShouldReturnBadRequestWithValidationError() - { - // Arrange - string emptyPath = ""; - string encodedPath = Uri.EscapeDataString(emptyPath); - - // Act - HttpResponseMessage response = await _client.GetAsync($"/api/v1.0/path/get-path-parent?path={encodedPath}"); - - // Assert - response.StatusCode.Should().Be(HttpStatusCode.BadRequest); - string content = await response.Content.ReadAsStringAsync(); - ValidationProblemDetails? problemDetails = JsonSerializer.Deserialize(content, _jsonOptions); - problemDetails.Should().NotBeNull(); - problemDetails!.Title.Should().Be("One or more validation errors occurred."); - problemDetails.Errors["General.Validation"].Should().BeEquivalentTo("PathCannotBeEmpty"); - } - - [Fact] - public async Task GetPathParent_WhenCalledWithCancellationToken_ShouldCompleteSuccessfully() - { - // Arrange - string testPath = System.IO.Path.Combine(System.IO.Path.GetTempPath(), "testDirectory"); - string encodedPath = Uri.EscapeDataString(testPath); - using CancellationTokenSource cts = new(TimeSpan.FromSeconds(5)); - - // Act - Func act = async () => await _client.GetAsync($"/api/v1.0/path/get-path-parent?path={encodedPath}", cts.Token); - - // Assert - await act.Should().NotThrowAsync(); - } - - [Fact] - public async Task GetPathParent_WhenCancellationTokenIsCancelled_ShouldThrowTaskCanceledException() - { - // Arrange - string testPath = System.IO.Path.Combine(System.IO.Path.GetTempPath(), "testDirectory"); - string encodedPath = Uri.EscapeDataString(testPath); - using CancellationTokenSource cts = new(); - - // Act - Func act = async () => - { - cts.Cancel(); // Cancel the token immediately - await _client.GetAsync($"/api/v1.0/path/get-path-parent?path={encodedPath}", cts.Token); - }; - - // Assert - await act.Should().ThrowAsync(); - } - - [Fact] - public async Task CombinePath_WhenCalledWithValidPaths_ShouldReturnOkResultWithCombinedPath() - { - // Arrange - string originalPath = System.IO.Path.GetTempPath(); - string newPath = "testDirectory"; - string expectedPath = System.IO.Path.Combine(System.IO.Path.GetTempPath(), "testDirectory"); - if (!expectedPath.EndsWith(System.IO.Path.DirectorySeparatorChar)) - expectedPath += System.IO.Path.DirectorySeparatorChar; - - // Act - HttpResponseMessage response = await _client.GetAsync($"/api/v1.0/path/combine?originalPath={Uri.EscapeDataString(originalPath)}&newPath={Uri.EscapeDataString(newPath)}"); - - // Assert - response.StatusCode.Should().Be(HttpStatusCode.OK); - string content = await response.Content.ReadAsStringAsync(); - PathSegmentResponse? result = JsonSerializer.Deserialize(content, _jsonOptions); - result.Should().NotBeNull(); - result!.Path.Should().Be(expectedPath); - } - - [Fact] - public async Task CombinePath_WhenCalledWithEmptyPaths_ShouldReturnOkResultWithEmptyPath() - { - // Arrange - string originalPath = ""; - string newPath = ""; - - // Act - HttpResponseMessage response = await _client.GetAsync($"/api/v1.0/path/combine?originalPath={Uri.EscapeDataString(originalPath)}&newPath={Uri.EscapeDataString(newPath)}"); - - // Assert - response.StatusCode.Should().Be(HttpStatusCode.BadRequest); - string content = await response.Content.ReadAsStringAsync(); - ValidationProblemDetails? problemDetails = JsonSerializer.Deserialize(content, _jsonOptions); - problemDetails.Should().NotBeNull(); - problemDetails!.Title.Should().Be("One or more validation errors occurred."); - problemDetails.Errors["General.Validation"].Should().BeEquivalentTo("PathCannotBeEmpty", "PathCannotBeEmpty"); - } - - [Fact] - public async Task CombinePath_WhenCalledWithCancellationToken_ShouldCompleteSuccessfully() - { - // Arrange - string originalPath = "/home/user"; - string newPath = "documents"; - using CancellationTokenSource cts = new(TimeSpan.FromSeconds(5)); - - // Act - Func act = async () => await _client.GetAsync($"/api/v1.0/path/combine?originalPath={Uri.EscapeDataString(originalPath)}&newPath={Uri.EscapeDataString(newPath)}", cts.Token); - - // Assert - await act.Should().NotThrowAsync(); - } - - [Fact] - public async Task CombinePath_WhenCancellationTokenIsCancelled_ShouldThrowTaskCanceledException() - { - // Arrange - string originalPath = System.IO.Path.GetTempPath(); - string newPath = "testFile.txt"; - using CancellationTokenSource cts = new(); - - // Act - Func act = async () => - { - cts.Cancel(); // Cancel the token immediately - await _client.GetAsync($"/api/v1.0/path/combine?originalPath={Uri.EscapeDataString(originalPath)}&newPath={Uri.EscapeDataString(newPath)}", cts.Token); - }; - - // Assert - await act.Should().ThrowAsync(); - } - - [Fact] - public async Task SplitPath_WhenCalledWithValidPath_ShouldReturnOkResultWithSplitSegments() - { - // Arrange - string tempPath = System.IO.Path.GetTempPath(); - string testPath = System.IO.Path.Combine(tempPath, "testFolder", "testFile.txt"); - - // Act - HttpResponseMessage response = await _client.GetAsync($"/api/v1.0/path/split?path={Uri.EscapeDataString(testPath)}"); - - // Assert - response.StatusCode.Should().Be(HttpStatusCode.OK); - string content = await response.Content.ReadAsStringAsync(); - IEnumerable? result = JsonSerializer.Deserialize>(content, _jsonOptions); - result.Should().NotBeNull(); - result!.Should().HaveCountGreaterThanOrEqualTo(3); - result!.Select(r => r.Path).Should().Contain(["testFolder", "testFile.txt"]); - } - - [Fact] - public async Task SplitPath_WhenCalledWithEmptyPath_ShouldReturnOkResultWithEmptySegments() - { - // Arrange - string path = ""; - - // Act - HttpResponseMessage response = await _client.GetAsync($"/api/v1.0/path/split?path={Uri.EscapeDataString(path)}"); - - // Assert - response.StatusCode.Should().Be(HttpStatusCode.BadRequest); - string content = await response.Content.ReadAsStringAsync(); - ValidationProblemDetails? problemDetails = JsonSerializer.Deserialize(content, _jsonOptions); - problemDetails.Should().NotBeNull(); - problemDetails!.Title.Should().Be("One or more validation errors occurred."); - problemDetails.Errors["General.Validation"].Should().BeEquivalentTo("PathCannotBeEmpty"); - } - - [Fact] - public async Task SplitPath_WhenCalledWithInvalidPath_ShouldReturnProblemDetails() - { - // Arrange - string path = "invalid:path"; - - // Act - HttpResponseMessage response = await _client.GetAsync($"/api/v1.0/path/split?path={Uri.EscapeDataString(path)}"); - - // Assert - response.StatusCode.Should().Be(HttpStatusCode.BadRequest); - string content = await response.Content.ReadAsStringAsync(); - ProblemDetails? problemDetails = JsonSerializer.Deserialize(content, _jsonOptions); - problemDetails.Should().NotBeNull(); - problemDetails!.Title.Should().Be("One or more validation errors occurred."); - } - - [Fact] - public async Task SplitPath_WhenCancellationTokenIsCancelled_ShouldThrowTaskCanceledException() - { - // Arrange - string testPath = System.IO.Path.Combine(System.IO.Path.GetTempPath(), "testDirectory"); - string encodedPath = Uri.EscapeDataString(testPath); - using CancellationTokenSource cts = new(); - - // Act - Func act = async () => - { - cts.Cancel(); // Cancel the token immediately - await _client.GetAsync($"/api/v1.0/path/split?path={encodedPath}", cts.Token); - }; - - // Assert - await act.Should().ThrowAsync(); - } - - [Fact] - public async Task ValidatePath_WhenCalledWithValidPath_ShouldReturnOkResultWithIsValidTrue() - { - // Arrange - string tempPath = System.IO.Path.GetTempPath(); - string testPath = System.IO.Path.Combine(tempPath, "testFolder", "testFile.txt"); - - // Act - HttpResponseMessage response = await _client.GetAsync($"/api/v1.0/path/validate?path={Uri.EscapeDataString(testPath)}"); - - // Assert - response.StatusCode.Should().Be(HttpStatusCode.OK); - string content = await response.Content.ReadAsStringAsync(); - PathValidResponse? result = JsonSerializer.Deserialize(content, _jsonOptions); - result.Should().NotBeNull(); - result!.IsValid.Should().BeTrue(); - } - - [Fact] - public async Task ValidatePath_WhenCalledWithInvalidPath_ShouldReturnOkResultWithIsValidFalse() - { - // Arrange - string invalidPath = "invalid:path"; - - // Act - HttpResponseMessage response = await _client.GetAsync($"/api/v1.0/path/validate?path={Uri.EscapeDataString(invalidPath)}"); - - // Assert - response.StatusCode.Should().Be(HttpStatusCode.OK); - string content = await response.Content.ReadAsStringAsync(); - PathValidResponse? result = JsonSerializer.Deserialize(content, _jsonOptions); - result.Should().NotBeNull(); - result!.IsValid.Should().BeFalse(); - } - - [Fact] - public async Task ValidatePath_WhenCalledWithEmptyPath_ShouldReturnBadRequest() - { - // Arrange - string path = ""; - - // Act - HttpResponseMessage response = await _client.GetAsync($"/api/v1.0/path/validate?path={Uri.EscapeDataString(path)}"); - - // Assert - response.StatusCode.Should().Be(HttpStatusCode.OK); - string content = await response.Content.ReadAsStringAsync(); - PathValidResponse? result = JsonSerializer.Deserialize(content, _jsonOptions); - result.Should().NotBeNull(); - result!.IsValid.Should().BeFalse(); - } - - [Fact] - public async Task ValidatePath_WhenCancellationTokenIsCancelled_ShouldThrowTaskCanceledException() - { - // Arrange - string testPath = System.IO.Path.Combine(System.IO.Path.GetTempPath(), "testDirectory"); - string encodedPath = Uri.EscapeDataString(testPath); - using CancellationTokenSource cts = new(); - - // Act - Func act = async () => - { - cts.Cancel(); // Cancel the token immediately - await _client.GetAsync($"/api/v1.0/path/validate?path={encodedPath}", cts.Token); - }; - - // Assert - await act.Should().ThrowAsync(); - } - - [Fact] - public async Task CheckPathExists_WhenCalledWithExistingPath_ShouldReturnOkResultWithExistsTrue() - { - // Arrange - string tempPath = System.IO.Path.GetTempPath(); - - // Act - HttpResponseMessage response = await _client.GetAsync($"/api/v1.0/path/check-path-exists?path={Uri.EscapeDataString(tempPath)}&includeHiddenElements=false"); - - // Assert - response.StatusCode.Should().Be(HttpStatusCode.OK); - string content = await response.Content.ReadAsStringAsync(); - PathExistsResponse? result = JsonSerializer.Deserialize(content, _jsonOptions); - result.Should().NotBeNull(); - result!.Exists.Should().BeTrue(); - } - - [Fact] - public async Task CheckPathExists_WhenCalledWithNonExistingPath_ShouldReturnOkResultWithExistsFalse() - { - // Arrange - string nonExistingPath = System.IO.Path.Combine(System.IO.Path.GetTempPath(), Guid.NewGuid().ToString()); - - // Act - HttpResponseMessage response = await _client.GetAsync($"/api/v1.0/path/check-path-exists?path={Uri.EscapeDataString(nonExistingPath)}&includeHiddenElements=false"); - - // Assert - response.StatusCode.Should().Be(HttpStatusCode.OK); - string content = await response.Content.ReadAsStringAsync(); - PathExistsResponse? result = JsonSerializer.Deserialize(content, _jsonOptions); - result.Should().NotBeNull(); - result!.Exists.Should().BeFalse(); - } - - [Fact] - public async Task CheckPathExists_WhenCalledWithEmptyPath_ShouldReturnBadRequest() - { - // Arrange - string path = ""; - - // Act - HttpResponseMessage response = await _client.GetAsync($"/api/v1.0/path/check-path-exists?path={Uri.EscapeDataString(path)}&includeHiddenElements=false"); - - // Assert - response.StatusCode.Should().Be(HttpStatusCode.OK); - string content = await response.Content.ReadAsStringAsync(); - PathExistsResponse? result = JsonSerializer.Deserialize(content, _jsonOptions); - result.Should().NotBeNull(); - result!.Exists.Should().BeFalse(); - } - - [Fact] - public async Task CheckPathExists_WhenCalledWithInvalidPath_ShouldReturnBadRequest() - { - // Arrange - string invalidPath = "invalid:path"; - - // Act - HttpResponseMessage response = await _client.GetAsync($"/api/v1.0/path/check-path-exists?path={Uri.EscapeDataString(invalidPath)}&includeHiddenElements=false"); - - // Assert - response.StatusCode.Should().Be(HttpStatusCode.OK); - string content = await response.Content.ReadAsStringAsync(); - PathExistsResponse? result = JsonSerializer.Deserialize(content, _jsonOptions); - result.Should().NotBeNull(); - result!.Exists.Should().BeFalse(); - } - - [Fact] - public async Task CheckPathExists_WhenCancellationTokenIsCancelled_ShouldThrowTaskCanceledException() - { - // Arrange - string testPath = System.IO.Path.GetTempPath(); - string encodedPath = Uri.EscapeDataString(testPath); - using CancellationTokenSource cts = new(); - - // Act - Func act = async () => - { - cts.Cancel(); // Cancel the token immediately - await _client.GetAsync($"/api/v1.0/path/check-path-exists?path={encodedPath}&includeHiddenElements=false", cts.Token); - }; - - // Assert - await act.Should().ThrowAsync(); - } -} diff --git a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Controllers/FileManagement/ThumbnailsControllerTests.cs b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Controllers/FileManagement/ThumbnailsControllerTests.cs deleted file mode 100644 index 3c2900ed..00000000 --- a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Controllers/FileManagement/ThumbnailsControllerTests.cs +++ /dev/null @@ -1,130 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using FluentAssertions; -using Lumina.Presentation.Api.IntegrationTests.Common.Setup; -using Lumina.Presentation.Api.IntegrationTests.Core.Controllers.FileManagement.Fixtures; -using Microsoft.AspNetCore.Mvc; -using System; -using System.Diagnostics.CodeAnalysis; -using System.Net; -using System.Net.Http; -using System.Text.Json; -using System.Text.Json.Serialization; -using System.Threading; -using System.Threading.Tasks; -#endregion - -namespace Lumina.Presentation.Api.IntegrationTests.Core.Controllers.FileManagement; - -/// -/// Contains integration tests for the class. -/// -[ExcludeFromCodeCoverage] -public class ThumbnailsControllerTests : IClassFixture, IClassFixture -{ - private readonly HttpClient _client; - private readonly JsonSerializerOptions _jsonOptions = new() - { - ReferenceHandler = ReferenceHandler.Preserve, - PropertyNameCaseInsensitive = true, - Converters = { new JsonStringEnumConverter(JsonNamingPolicy.CamelCase) } - }; - private readonly string _testImagePath; - - /// - /// Initializes a new instance of the class. - /// - /// Injected in-memory API factory. - /// Fixture for creating and managing test images. - public ThumbnailsControllerTests(LuminaApiFactory apiFactory, TestImageFixture imageFixture) - { - _client = apiFactory.CreateClient(); - _testImagePath = imageFixture.ImagePath; - } - - [Fact] - public async Task GetThumbnail_WhenCalledWithValidPathAndQuality_ShouldReturnOkResultWithThumbnail() - { - // Arrange - int quality = 80; - - // Act - HttpResponseMessage response = await _client.GetAsync($"/api/v1.0/thumbnails/get-thumbnail?path={Uri.EscapeDataString(_testImagePath)}&quality={quality}"); - - // Assert - response.StatusCode.Should().Be(HttpStatusCode.OK); - response.Content.Headers.ContentType!.MediaType.Should().Be("image/jpeg"); - byte[] content = await response.Content.ReadAsByteArrayAsync(); - content.Should().NotBeEmpty(); - } - - [Fact] - public async Task GetThumbnail_WhenCalledWithInvalidPath_ShouldReturnForbidden() - { - // Arrange - string invalidImagePath = "/path/to/nonexistent/image.jpg"; - int quality = 80; - - // Act - HttpResponseMessage response = await _client.GetAsync($"/api/v1.0/thumbnails/get-thumbnail?path={Uri.EscapeDataString(invalidImagePath)}&quality={quality}"); - - // Assert - response.StatusCode.Should().Be(HttpStatusCode.Forbidden); - string content = await response.Content.ReadAsStringAsync(); - ProblemDetails? problemDetails = JsonSerializer.Deserialize(content, _jsonOptions); - problemDetails.Should().NotBeNull(); - } - - [Fact] - public async Task GetThumbnail_WhenCalledWithEmptyPath_ShouldReturnForbidden() - { - // Arrange - string invalidImagePath = ""; - int quality = 80; - - // Act - HttpResponseMessage response = await _client.GetAsync($"/api/v1.0/thumbnails/get-thumbnail?path={Uri.EscapeDataString(invalidImagePath)}&quality={quality}"); - - // Assert - response.StatusCode.Should().Be(HttpStatusCode.BadRequest); - string content = await response.Content.ReadAsStringAsync(); - ValidationProblemDetails? problemDetails = JsonSerializer.Deserialize(content, _jsonOptions); - problemDetails.Should().NotBeNull(); - problemDetails!.Title.Should().Be("One or more validation errors occurred."); - problemDetails.Errors["General.Validation"].Should().BeEquivalentTo("PathCannotBeEmpty"); - } - - [Fact] - public async Task GetThumbnail_WhenCalledWithInvalidQuality_ShouldReturnForbidden() - { - // Arrange - int invalidQuality = -1; - - // Act - HttpResponseMessage response = await _client.GetAsync($"/api/v1.0/thumbnails/get-thumbnail?path={Uri.EscapeDataString(_testImagePath)}&quality={invalidQuality}"); - - // Assert - response.StatusCode.Should().Be(HttpStatusCode.BadRequest); - string content = await response.Content.ReadAsStringAsync(); - ValidationProblemDetails? problemDetails = JsonSerializer.Deserialize(content, _jsonOptions); - problemDetails.Should().NotBeNull(); - problemDetails!.Title.Should().Be("One or more validation errors occurred."); - } - - [Fact] - public async Task GetThumbnail_WhenCancellationTokenIsCancelled_ShouldThrowTaskCanceledException() - { - // Arrange - int quality = 80; - using CancellationTokenSource cts = new(); - - // Act - Func act = async () => - { - cts.Cancel(); // Cancel the token immediately - await _client.GetAsync($"/api/v1.0/thumbnails/get-thumbnail?path={Uri.EscapeDataString(_testImagePath)}&quality={quality}", cts.Token); - }; - - // Assert - await act.Should().ThrowAsync(); - } -} diff --git a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/FileSystemManagement/Directories/GetDirectoriesEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/FileSystemManagement/Directories/GetDirectoriesEndpointTests.cs new file mode 100644 index 00000000..86e96a6c --- /dev/null +++ b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/FileSystemManagement/Directories/GetDirectoriesEndpointTests.cs @@ -0,0 +1,204 @@ +#region ========================================================================= USING ===================================================================================== +using FluentAssertions; +using Lumina.Contracts.Responses.FileSystemManagement.Directories; +using Lumina.Presentation.Api.IntegrationTests.Common.Setup; +using Lumina.Presentation.Api.IntegrationTests.Core.Endpoints.FileSystemManagement.Fixtures; +using Microsoft.AspNetCore.Http; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +using System.Net; +using System.Net.Http; +using System.Runtime.InteropServices; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Api.IntegrationTests.Core.Endpoints.FileSystemManagement.Directories; + +/// +/// Contains integration tests for the class. +/// +[ExcludeFromCodeCoverage] +public class GetDirectoriesEndpointTests : IClassFixture +{ + private readonly HttpClient _client; + private readonly JsonSerializerOptions _jsonOptions = new() + { + ReferenceHandler = ReferenceHandler.Preserve, + PropertyNameCaseInsensitive = true, + Converters = { new JsonStringEnumConverter(JsonNamingPolicy.CamelCase) } + }; + private static readonly bool s_isLinux = RuntimeInformation.IsOSPlatform(OSPlatform.Linux); + + /// + /// Initializes a new instance of the class. + /// + /// Injected in-memory API factory. + public GetDirectoriesEndpointTests(LuminaApiFactory apiFactory) + { + _client = apiFactory.CreateClient(); + } + + [Fact] + public async Task GetDirectories_WhenCalledWithValidPathAndHiddenChildrenAndNotIncludeHiddenElements_ShouldReturnNoDirectories() + { + // Arrange + FileSystemStructureFixture fileSystemFixture = new(); + string testPath = fileSystemFixture.CreateFileSystemStructure(); + testPath = System.IO.Path.GetDirectoryName(testPath) ?? testPath; + testPath = System.IO.Path.GetDirectoryName(testPath) ?? testPath; // two levels to get to the element that has a hidden element as child + string encodedPath = Uri.EscapeDataString(testPath); + bool includeHiddenElements = false; + try + { + // Act + HttpResponseMessage response = await _client.GetAsync($"/api/v1/directories/get-directories?path={encodedPath}&includeHiddenElements={includeHiddenElements}"); + + // Assert + response.EnsureSuccessStatusCode(); + response.StatusCode.Should().Be(HttpStatusCode.OK); + + string content = await response.Content.ReadAsStringAsync(); + List? directories = JsonSerializer.Deserialize>(content, _jsonOptions); + + directories.Should().NotBeNull(); + directories!.Should().BeEmpty(); + } + finally + { + fileSystemFixture.CleanupFileSystemStructure(); + } + } + + [Fact] + public async Task GetDirectories_WhenCalledWithValidPathAndWithIncludeHiddenElements_ShouldReturnDirectoriesWithHiddenElements() + { + // Arrange + FileSystemStructureFixture fileSystemFixture = new(); + string testPath = fileSystemFixture.CreateFileSystemStructure(); + testPath = System.IO.Path.GetDirectoryName(testPath) ?? testPath; + testPath = System.IO.Path.GetDirectoryName(testPath) ?? testPath; // two levels to get to the element that has a hidden element as child + string encodedPath = Uri.EscapeDataString(testPath); + bool includeHiddenElements = true; + try + { + // Act + HttpResponseMessage response = await _client.GetAsync($"/api/v1/directories/get-directories?path={encodedPath}&includeHiddenElements={includeHiddenElements}"); + + // Assert + response.EnsureSuccessStatusCode(); + response.StatusCode.Should().Be(HttpStatusCode.OK); + + string content = await response.Content.ReadAsStringAsync(); + List? directories = JsonSerializer.Deserialize>(content, _jsonOptions); + + directories.Should().NotBeNull(); + directories!.Should().NotBeEmpty(); + + string[] pathSegments = testPath.Split(System.IO.Path.DirectorySeparatorChar, StringSplitOptions.RemoveEmptyEntries); + + + DirectoryResponse firstDirectory = directories!.First(); + firstDirectory.Name.Should().Be((s_isLinux ? "." : string.Empty) + "NestedDirectory_2"); + firstDirectory.Path.Should().Be(System.IO.Path.Combine(testPath, (s_isLinux ? "." : string.Empty) + "NestedDirectory_2" + System.IO.Path.DirectorySeparatorChar)); + directories!.Count.Should().Be(1); // only directories + } + finally + { + fileSystemFixture.CleanupFileSystemStructure(); + } + } + + [Fact] + public async Task ExecuteAsync_WhenCalledWithInvalidPath_ShouldReturnForbiddenResult() + { + // Arrange + string invalidPath = "invalid:path"; + string encodedPath = Uri.EscapeDataString(invalidPath); + bool includeHiddenElements = true; + + // Act + HttpResponseMessage response = await _client.GetAsync($"/api/v1/directories/get-directories?path={encodedPath}&includeHiddenElements={includeHiddenElements}"); + + // Assert + response.StatusCode.Should().Be(HttpStatusCode.Forbidden); + string content = await response.Content.ReadAsStringAsync(); + + Dictionary? problemDetails = JsonSerializer.Deserialize>(content, _jsonOptions); + problemDetails.Should().NotBeNull(); + problemDetails!["status"].GetInt32().Should().Be(StatusCodes.Status403Forbidden); + problemDetails["title"].GetString().Should().Be("General.Failure"); + problemDetails["instance"].GetString().Should().Be("/api/v1/directories/get-directories"); + problemDetails["detail"].GetString().Should().Be("UnauthorizedAccess"); + problemDetails["type"].GetString().Should().Be("https://tools.ietf.org/html/rfc9110#section-15.5.4"); + problemDetails["traceId"].GetString().Should().NotBeNullOrWhiteSpace(); + } + + [Fact] + public async Task ExecuteAsync_WhenCalledWithEmptyPath_ShouldReturnValidationProblemResult() + { + // Arrange + string emptyPath = ""; + string encodedPath = Uri.EscapeDataString(emptyPath); + bool includeHiddenElements = true; + + // Act + HttpResponseMessage response = await _client.GetAsync($"/api/v1/directories/get-directories?path={encodedPath}&includeHiddenElements={includeHiddenElements}"); + + // Assert + response.StatusCode.Should().Be(HttpStatusCode.UnprocessableContent); + response.Content.Headers.ContentType?.MediaType.Should().Be("application/problem+json"); + string content = await response.Content.ReadAsStringAsync(); + Dictionary? problemDetails = JsonSerializer.Deserialize>(content, _jsonOptions); + problemDetails.Should().NotBeNull(); + problemDetails!["status"].GetInt32().Should().Be(StatusCodes.Status422UnprocessableEntity); + problemDetails["title"].GetString().Should().Be("Validation Error"); + problemDetails["instance"].GetString().Should().Be("/api/v1/directories/get-directories"); + problemDetails["detail"].GetString().Should().Be("One or more validation errors occurred."); + problemDetails["type"].GetString().Should().Be("https://tools.ietf.org/html/rfc4918#section-11.2"); + problemDetails["traceId"].GetString().Should().NotBeNullOrWhiteSpace(); + + Dictionary? errors = problemDetails["errors"].Deserialize>(_jsonOptions); + errors.Should().ContainKey("General.Validation").WhoseValue.Should().BeEquivalentTo(["PathCannotBeEmpty"]); + } + + [Fact] + public async Task ExecuteAsync_WhenCalledWithCancellationToken_ShouldCompleteSuccessfully() + { + // Arrange + string testPath = System.IO.Path.Combine(System.IO.Path.GetTempPath(), "testDirectory"); + string encodedPath = Uri.EscapeDataString(testPath); + bool includeHiddenElements = true; + using CancellationTokenSource cts = new(TimeSpan.FromSeconds(5)); + + // Act + Func act = async () => await _client.GetAsync($"/api/v1/directories/get-directories?path={encodedPath}&includeHiddenElements={includeHiddenElements}", cts.Token); + + // Assert + await act.Should().NotThrowAsync(); + } + + [Fact] + public async Task ExecuteAsync_WhenCancellationTokenIsCancelled_ShouldThrowTaskCanceledException() + { + // Arrange + string testPath = System.IO.Path.Combine(System.IO.Path.GetTempPath(), "testDirectory"); + string encodedPath = Uri.EscapeDataString(testPath); + bool includeHiddenElements = true; + using CancellationTokenSource cts = new(); + + // Act + Func act = async () => + { + cts.Cancel(); // Cancel the token immediately + await _client.GetAsync($"/api/v1/directories/get-directories?path={encodedPath}&includeHiddenElements={includeHiddenElements}", cts.Token); + }; + + // Assert + await act.Should().ThrowAsync(); + } +} diff --git a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/FileSystemManagement/Directories/GetDirectoryTreeEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/FileSystemManagement/Directories/GetDirectoryTreeEndpointTests.cs new file mode 100644 index 00000000..b73bbc1e --- /dev/null +++ b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/FileSystemManagement/Directories/GetDirectoryTreeEndpointTests.cs @@ -0,0 +1,411 @@ +#region ========================================================================= USING ===================================================================================== +using FluentAssertions; +using Lumina.Contracts.Enums.FileSystem; +using Lumina.Contracts.Responses.FileSystemManagement.Common; +using Lumina.Presentation.Api.IntegrationTests.Common.Setup; +using Lumina.Presentation.Api.IntegrationTests.Core.Endpoints.FileSystemManagement.Fixtures; +using Microsoft.AspNetCore.Http; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +using System.Net; +using System.Net.Http; +using System.Runtime.InteropServices; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Api.IntegrationTests.Core.Endpoints.FileSystemManagement.Directories; + +/// +/// Contains integration tests for the class. +/// +[ExcludeFromCodeCoverage] +public class GetDirectoryTreeEndpointTests : IClassFixture +{ + private readonly HttpClient _client; + private readonly JsonSerializerOptions _jsonOptions = new() + { + ReferenceHandler = ReferenceHandler.Preserve, + PropertyNameCaseInsensitive = true, + Converters = { new JsonStringEnumConverter(JsonNamingPolicy.CamelCase) } + }; + private static readonly bool s_isLinux = RuntimeInformation.IsOSPlatform(OSPlatform.Linux); + + /// + /// Initializes a new instance of the class. + /// + /// Injected in-memory API factory. + public GetDirectoryTreeEndpointTests(LuminaApiFactory apiFactory) + { + _client = apiFactory.CreateClient(); + } + + [Fact] + public async Task ExecuteAsync_WhenCalledWithValidPathAndIncludeFilesAndNotIncludeHiddenElements_ShouldReturnDirectoryTreeWithFilesAndNotHiddenElements() + { + // Arrange + FileSystemStructureFixture fileSystemFixture = new(); + string testPath = fileSystemFixture.CreateFileSystemStructure(); + + bool includeFiles = true; + bool includeHiddenElements = false; + try + { + // Act + HttpResponseMessage response = await _client.GetAsync($"/api/v1/directories/get-directory-tree?path={Uri.EscapeDataString(testPath)}&includeFiles={includeFiles}&includeHiddenElements={includeHiddenElements}"); + + // Assert + response.EnsureSuccessStatusCode(); + response.StatusCode.Should().Be(HttpStatusCode.OK); + + string content = await response.Content.ReadAsStringAsync(); + List? treeNodes = JsonSerializer.Deserialize>(content, _jsonOptions); + + treeNodes.Should().NotBeNull(); + treeNodes!.Should().NotBeEmpty(); + + string[] pathSegments = testPath.Split(System.IO.Path.DirectorySeparatorChar, StringSplitOptions.RemoveEmptyEntries); + if (s_isLinux) // on UNIX, the leading slash is considered "the drive", the root location - add it! + pathSegments = ["/", .. pathSegments]; + // recursively validate the tree structure + void ValidateNode(FileSystemTreeNodeResponse node, int depth) + { + // ensure the current node's name and path match the expected segment + string expectedSegment = pathSegments[depth]; + + if (depth == 0 && node.ItemType == FileSystemItemType.Root && expectedSegment.Length == 2 && char.IsLetter(expectedSegment[0]) && expectedSegment[1] == ':' + && !expectedSegment.EndsWith(System.IO.Path.DirectorySeparatorChar)) + expectedSegment += System.IO.Path.DirectorySeparatorChar; + + node.Name.Should().Be(expectedSegment); + + string expectedPath = string.Join(System.IO.Path.DirectorySeparatorChar.ToString(), pathSegments.Take(depth + 1)); + if (expectedPath.StartsWith("//")) + expectedPath = expectedPath[1..]; + if (!expectedPath.EndsWith(System.IO.Path.DirectorySeparatorChar)) + expectedPath += System.IO.Path.DirectorySeparatorChar; + node.Path.Should().EndWith(expectedPath); + + // if the node is a drive or directory, check its children recursively + if (node.ItemType is FileSystemItemType.Root or FileSystemItemType.Directory) + { + node.Children.Should().NotBeNull(); + foreach (FileSystemTreeNodeResponse childNode in node.Children) + { + if (childNode.ItemType != FileSystemItemType.File) // go deeper one level, if the iterated node's children is also a directory + ValidateNode(childNode, depth + 1); + else if (childNode.ItemType is FileSystemItemType.File) + { + childNode.Children.Should().BeEmpty(); // files should not have children + childNode.Name.Should().Be("TestFile_2.txt"); + } + } + } + } + FileSystemTreeNodeResponse rootNode = treeNodes!.First(); + ValidateNode(rootNode, 0); + } + finally + { + fileSystemFixture.CleanupFileSystemStructure(); + } + } + + [Fact] + public async Task ExecuteAsync_WhenCalledWithValidPathAndIncludeFilesAndWithIncludeHiddenElements_ShouldReturnDirectoryTreeWithFilesAndHiddenElements() + { + // Arrange + FileSystemStructureFixture fileSystemFixture = new(); + string testPath = fileSystemFixture.CreateFileSystemStructure(); + + bool includeFiles = true; + bool includeHiddenElements = true; + try + { + // Act + HttpResponseMessage response = await _client.GetAsync($"/api/v1/directories/get-directory-tree?path={Uri.EscapeDataString(testPath)}&includeFiles={includeFiles}&includeHiddenElements={includeHiddenElements}"); + + // Assert + response.EnsureSuccessStatusCode(); + response.StatusCode.Should().Be(HttpStatusCode.OK); + + string content = await response.Content.ReadAsStringAsync(); + List? treeNodes = JsonSerializer.Deserialize>(content, _jsonOptions); + + treeNodes.Should().NotBeNull(); + treeNodes!.Should().NotBeEmpty(); + + string[] pathSegments = testPath.Split(System.IO.Path.DirectorySeparatorChar, StringSplitOptions.RemoveEmptyEntries); + if (s_isLinux) // on UNIX, the leading slash is considered "the drive", the root location - add it! + pathSegments = ["/", .. pathSegments]; + + // recursively validate the tree structure + void ValidateNode(FileSystemTreeNodeResponse node, int depth) + { + // ensure the current node's name and path match the expected segment + string expectedSegment = pathSegments[depth]; + + if (depth == 0 && node.ItemType == FileSystemItemType.Root && expectedSegment.Length == 2 && char.IsLetter(expectedSegment[0]) && expectedSegment[1] == ':' + && !expectedSegment.EndsWith(System.IO.Path.DirectorySeparatorChar)) + expectedSegment += System.IO.Path.DirectorySeparatorChar; + + node.Name.Should().Be(expectedSegment); + + string expectedPath = string.Join(System.IO.Path.DirectorySeparatorChar.ToString(), pathSegments.Take(depth + 1)); + if (!expectedPath.EndsWith(System.IO.Path.DirectorySeparatorChar)) + expectedPath += System.IO.Path.DirectorySeparatorChar; + if (expectedPath.StartsWith("//")) + expectedPath = expectedPath[1..]; + node.Path.Should().EndWith(expectedPath); + + // if the node is a drive or directory, check its children recursively + if (node.ItemType is FileSystemItemType.Root or FileSystemItemType.Directory) + { + node.Children.Should().NotBeNull(); + foreach (FileSystemTreeNodeResponse childNode in node.Children) + { + if (childNode.ItemType != FileSystemItemType.File) // go deeper one level, if the iterated node's children is also a directory + ValidateNode(childNode, depth + 1); + else if (childNode.ItemType is FileSystemItemType.File) + { + childNode.Children.Should().BeEmpty(); // files should not have children + childNode.Name.Should().BeOneOf((s_isLinux ? "." : string.Empty) + "TestFile_1.txt", "TestFile_2.txt"); + } + } + } + } + FileSystemTreeNodeResponse rootNode = treeNodes!.First(); + ValidateNode(rootNode, 0); + } + finally + { + fileSystemFixture.CleanupFileSystemStructure(); + } + } + + [Fact] + public async Task ExecuteAsync_WhenCalledWithValidPathAndNotIncludeFilesAndNotIncludeHiddenElements_ShouldReturnDirectoryTreeWithoutFiles() + { + // Arrange + FileSystemStructureFixture fileSystemFixture = new(); + string testPath = fileSystemFixture.CreateFileSystemStructure(); + + bool includeFiles = false; + bool includeHiddenElements = false; + try + { + // Act + HttpResponseMessage response = await _client.GetAsync($"/api/v1/directories/get-directory-tree?path={Uri.EscapeDataString(testPath)}&includeFiles={includeFiles}&includeHiddenElements={includeHiddenElements}"); + + // Assert + response.EnsureSuccessStatusCode(); + response.StatusCode.Should().Be(HttpStatusCode.OK); + + string content = await response.Content.ReadAsStringAsync(); + List? treeNodes = JsonSerializer.Deserialize>(content, _jsonOptions); + + treeNodes.Should().NotBeNull(); + treeNodes!.Should().NotBeEmpty(); + + // there should not be a File node + treeNodes.Should().AllSatisfy(node => node.ItemType.Should().BeOneOf(FileSystemItemType.Directory, FileSystemItemType.Root)); + + string[] pathSegments = testPath.Split(System.IO.Path.DirectorySeparatorChar, StringSplitOptions.RemoveEmptyEntries); + if (s_isLinux) // on UNIX, the leading slash is considered "the drive", the root location - add it! + pathSegments = ["/", .. pathSegments]; + + // recursively validate the tree structure + void ValidateNode(FileSystemTreeNodeResponse node, int depth) + { + // ensure the current node's name and path match the expected segment + string expectedSegment = pathSegments[depth]; + + if (depth == 0 && node.ItemType == FileSystemItemType.Root && expectedSegment.Length == 2 && char.IsLetter(expectedSegment[0]) && expectedSegment[1] == ':' + && !expectedSegment.EndsWith(System.IO.Path.DirectorySeparatorChar)) + expectedSegment += System.IO.Path.DirectorySeparatorChar; + + node.Name.Should().Be(expectedSegment); + + string expectedPath = string.Join(System.IO.Path.DirectorySeparatorChar.ToString(), pathSegments.Take(depth + 1)); + if (!expectedPath.EndsWith(System.IO.Path.DirectorySeparatorChar)) + expectedPath += System.IO.Path.DirectorySeparatorChar; + if (expectedPath.StartsWith("//")) + expectedPath = expectedPath[1..]; + node.Path.Should().EndWith(expectedPath); + + node.Children.Should().NotBeNull(); + foreach (FileSystemTreeNodeResponse childNode in node.Children) + ValidateNode(childNode, depth + 1); + } + FileSystemTreeNodeResponse rootNode = treeNodes!.First(); + ValidateNode(rootNode, 0); + } + finally + { + fileSystemFixture.CleanupFileSystemStructure(); + } + } + + [Fact] + public async Task ExecuteAsync_WhenCalledWithValidPathAndNotIncludeFilesAndIncludeHiddenElements_ShouldReturnDirectoryTreeWithoutFiles() + { + // Arrange + FileSystemStructureFixture fileSystemFixture = new(); + string testPath = fileSystemFixture.CreateFileSystemStructure(); + + bool includeFiles = false; + bool includeHiddenElements = true; + try + { + // Act + HttpResponseMessage response = await _client.GetAsync($"/api/v1/directories/get-directory-tree?path={Uri.EscapeDataString(testPath)}&includeFiles={includeFiles}&includeHiddenElements={includeHiddenElements}"); + + // Assert + response.EnsureSuccessStatusCode(); + response.StatusCode.Should().Be(HttpStatusCode.OK); + + string content = await response.Content.ReadAsStringAsync(); + List? treeNodes = JsonSerializer.Deserialize>(content, _jsonOptions); + + treeNodes.Should().NotBeNull(); + treeNodes!.Should().NotBeEmpty(); + + // there should not be a File node + treeNodes.Should().AllSatisfy(node => node.ItemType.Should().BeOneOf(FileSystemItemType.Directory, FileSystemItemType.Root)); + + string[] pathSegments = testPath.Split(System.IO.Path.DirectorySeparatorChar, StringSplitOptions.RemoveEmptyEntries); + if (s_isLinux) // on UNIX, the leading slash is considered "the drive", the root location - add it! + pathSegments = ["/", .. pathSegments]; + + // recursively validate the tree structure + void ValidateNode(FileSystemTreeNodeResponse node, int depth) + { + // ensure the current node's name and path match the expected segment + string expectedSegment = pathSegments[depth]; + + if (depth == 0 && node.ItemType == FileSystemItemType.Root && expectedSegment.Length == 2 && char.IsLetter(expectedSegment[0]) && expectedSegment[1] == ':' + && !expectedSegment.EndsWith(System.IO.Path.DirectorySeparatorChar)) + expectedSegment += System.IO.Path.DirectorySeparatorChar; + + node.Name.Should().Be(expectedSegment); + + string expectedPath = string.Join(System.IO.Path.DirectorySeparatorChar.ToString(), pathSegments.Take(depth + 1)); + if (!expectedPath.EndsWith(System.IO.Path.DirectorySeparatorChar)) + expectedPath += System.IO.Path.DirectorySeparatorChar; + if (expectedPath.StartsWith("//")) + expectedPath = expectedPath[1..]; + node.Path.Should().EndWith(expectedPath); + + node.Children.Should().NotBeNull(); + foreach (FileSystemTreeNodeResponse childNode in node.Children) + ValidateNode(childNode, depth + 1); + } + FileSystemTreeNodeResponse rootNode = treeNodes!.First(); + ValidateNode(rootNode, 0); + } + finally + { + fileSystemFixture.CleanupFileSystemStructure(); + } + } + + [Fact] + public async Task ExecuteAsync_WhenCalledWithInvalidPath_ShouldReturnValidationProblemResult() + { + // Arrange + string invalidPath = "invalid:path"; + string encodedPath = Uri.EscapeDataString(invalidPath); + bool includeFiles = false; + bool includeHiddenElements = true; + + // Act + HttpResponseMessage response = await _client.GetAsync($"/api/v1/directories/get-directory-tree?path={Uri.EscapeDataString(encodedPath)}&includeFiles={includeFiles}&includeHiddenElements={includeHiddenElements}"); + + // Assert + response.StatusCode.Should().Be(HttpStatusCode.UnprocessableContent); + response.Content.Headers.ContentType?.MediaType.Should().Be("application/problem+json"); + string content = await response.Content.ReadAsStringAsync(); + Dictionary? problemDetails = JsonSerializer.Deserialize>(content, _jsonOptions); + problemDetails.Should().NotBeNull(); + problemDetails!["status"].GetInt32().Should().Be(StatusCodes.Status422UnprocessableEntity); + problemDetails["title"].GetString().Should().Be("Validation Error"); + problemDetails["instance"].GetString().Should().Be("/api/v1/directories/get-directory-tree"); + problemDetails["detail"].GetString().Should().Be("One or more validation errors occurred."); + problemDetails["type"].GetString().Should().Be("https://tools.ietf.org/html/rfc4918#section-11.2"); + problemDetails["traceId"].GetString().Should().NotBeNullOrWhiteSpace(); + + Dictionary? errors = problemDetails["errors"].Deserialize>(_jsonOptions); + errors.Should().ContainKey("General.Validation").WhoseValue.Should().BeEquivalentTo(["InvalidPath"]); + } + + [Fact] + public async Task ExecuteAsync_WhenCalledWithEmptyPath_ShouldReturnValidationProblemResult() + { + // Arrange + string emptyPath = ""; + string encodedPath = Uri.EscapeDataString(emptyPath); + bool includeFiles = false; + bool includeHiddenElements = true; + + // Act + HttpResponseMessage response = await _client.GetAsync($"/api/v1/directories/get-directory-tree?path={Uri.EscapeDataString(encodedPath)}&includeFiles={includeFiles}&includeHiddenElements={includeHiddenElements}"); + + // Assert + response.StatusCode.Should().Be(HttpStatusCode.UnprocessableContent); + response.Content.Headers.ContentType?.MediaType.Should().Be("application/problem+json"); + string content = await response.Content.ReadAsStringAsync(); + Dictionary? problemDetails = JsonSerializer.Deserialize>(content, _jsonOptions); + problemDetails.Should().NotBeNull(); + problemDetails!["status"].GetInt32().Should().Be(StatusCodes.Status422UnprocessableEntity); + problemDetails["title"].GetString().Should().Be("Validation Error"); + problemDetails["instance"].GetString().Should().Be("/api/v1/directories/get-directory-tree"); + problemDetails["detail"].GetString().Should().Be("One or more validation errors occurred."); + problemDetails["type"].GetString().Should().Be("https://tools.ietf.org/html/rfc4918#section-11.2"); + problemDetails["traceId"].GetString().Should().NotBeNullOrWhiteSpace(); + + Dictionary? errors = problemDetails["errors"].Deserialize>(_jsonOptions); + errors.Should().ContainKey("General.Validation").WhoseValue.Should().BeEquivalentTo(["PathCannotBeEmpty"]); + } + + [Fact] + public async Task ExecuteAsync_WhenCalledWithCancellationToken_ShouldCompleteSuccessfully() + { + // Arrange + string testPath = System.IO.Path.Combine(System.IO.Path.GetTempPath(), "testDirectory"); + string encodedPath = Uri.EscapeDataString(testPath); + bool includeFiles = false; + bool includeHiddenElements = true; + using CancellationTokenSource cts = new(TimeSpan.FromSeconds(5)); + + // Act + Func act = async () => await _client.GetAsync($"/api/v1/directories/get-directory-tree?path={Uri.EscapeDataString(encodedPath)}&includeFiles={includeFiles}&includeHiddenElements={includeHiddenElements}", cts.Token); + + // Assert + await act.Should().NotThrowAsync(); + } + + [Fact] + public async Task ExecuteAsync_WhenCancellationTokenIsCancelled_ShouldThrowTaskCanceledException() + { + // Arrange + string testPath = System.IO.Path.Combine(System.IO.Path.GetTempPath(), "testDirectory"); + string encodedPath = Uri.EscapeDataString(testPath); + bool includeFiles = false; + bool includeHiddenElements = true; + using CancellationTokenSource cts = new(); + + // Act + Func act = async () => + { + cts.Cancel(); // Cancel the token immediately + await _client.GetAsync($"/api/v1/directories/get-directory-tree?path={Uri.EscapeDataString(encodedPath)}&includeFiles={includeFiles}&includeHiddenElements={includeHiddenElements}", cts.Token); + }; + + // Assert + await act.Should().ThrowAsync(); + } +} diff --git a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/FileSystemManagement/Directories/GetTreeDirectoriesEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/FileSystemManagement/Directories/GetTreeDirectoriesEndpointTests.cs new file mode 100644 index 00000000..0be3268e --- /dev/null +++ b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/FileSystemManagement/Directories/GetTreeDirectoriesEndpointTests.cs @@ -0,0 +1,247 @@ +#region ========================================================================= USING ===================================================================================== +using FluentAssertions; +using Lumina.Contracts.Enums.FileSystem; +using Lumina.Contracts.Responses.FileSystemManagement.Common; +using Lumina.Presentation.Api.IntegrationTests.Common.Setup; +using Lumina.Presentation.Api.IntegrationTests.Core.Endpoints.FileSystemManagement.Fixtures; +using Microsoft.AspNetCore.Http; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +using System.Net; +using System.Net.Http; +using System.Runtime.InteropServices; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Api.IntegrationTests.Core.Endpoints.FileSystemManagement.Directories; + +/// +/// Contains integration tests for the class. +/// +[ExcludeFromCodeCoverage] +public class GetTreeDirectoriesEndpointTests : IClassFixture +{ + private readonly HttpClient _client; + private readonly JsonSerializerOptions _jsonOptions = new() + { + ReferenceHandler = ReferenceHandler.Preserve, + PropertyNameCaseInsensitive = true, + Converters = { new JsonStringEnumConverter(JsonNamingPolicy.CamelCase) } + }; + private static readonly bool s_isLinux = RuntimeInformation.IsOSPlatform(OSPlatform.Linux); + + /// + /// Initializes a new instance of the class. + /// + /// Injected in-memory API factory. + public GetTreeDirectoriesEndpointTests(LuminaApiFactory apiFactory) + { + _client = apiFactory.CreateClient(); + } + + [Fact] + public async Task ExecuteAsync_WhenCalledWithValidPathAndNotIncludeHiddenElements_ShouldReturnTreeDirectoriesWithoutHiddenElements() + { + // Arrange + FileSystemStructureFixture fileSystemFixture = new(); + string testPath = fileSystemFixture.CreateFileSystemStructure(); + testPath = System.IO.Path.GetDirectoryName(testPath) ?? testPath; + string encodedPath = Uri.EscapeDataString(testPath); + bool includeHiddenElements = false; + try + { + // Act + HttpResponseMessage response = await _client.GetAsync($"/api/v1/directories/get-tree-directories?path={encodedPath}&includeHiddenElements={includeHiddenElements}"); + + // Assert + response.EnsureSuccessStatusCode(); + response.StatusCode.Should().Be(HttpStatusCode.OK); + + string content = await response.Content.ReadAsStringAsync(); + List? treeNodes = JsonSerializer.Deserialize>(content, _jsonOptions); + + treeNodes.Should().NotBeNull(); + treeNodes!.Should().NotBeEmpty(); + + string[] pathSegments = testPath.Split(System.IO.Path.DirectorySeparatorChar, StringSplitOptions.RemoveEmptyEntries); + + + FileSystemTreeNodeResponse firstNode = treeNodes!.First(); + firstNode.Name.Should().Be("NestedDirectory_3"); + firstNode.Path.Should().Be(System.IO.Path.Combine(testPath, "NestedDirectory_3" + System.IO.Path.DirectorySeparatorChar)); + firstNode.ItemType.Should().Be(FileSystemItemType.Directory); + treeNodes.Should().AllSatisfy(n => n.ItemType.Should().Be(FileSystemItemType.Directory)); + treeNodes!.Count.Should().Be(1); // only directories + } + finally + { + fileSystemFixture.CleanupFileSystemStructure(); + } + } + + [Fact] + public async Task ExecuteAsync_WhenCalledWithValidPathAndNotIncludeHiddenElements_ShouldReturnNoTreeDirectories() + { + // Arrange + FileSystemStructureFixture fileSystemFixture = new(); + string testPath = fileSystemFixture.CreateFileSystemStructure(); + testPath = System.IO.Path.GetDirectoryName(testPath) ?? testPath; + testPath = System.IO.Path.GetDirectoryName(testPath) ?? testPath; // two levels to get to the element that has a hidden element as child + string encodedPath = Uri.EscapeDataString(testPath); + bool includeHiddenElements = false; + try + { + // Act + HttpResponseMessage response = await _client.GetAsync($"/api/v1/directories/get-tree-directories?path={encodedPath}&includeHiddenElements={includeHiddenElements}"); + + // Assert + response.EnsureSuccessStatusCode(); + response.StatusCode.Should().Be(HttpStatusCode.OK); + + string content = await response.Content.ReadAsStringAsync(); + List? treeNodes = JsonSerializer.Deserialize>(content, _jsonOptions); + + treeNodes.Should().NotBeNull(); + treeNodes!.Should().BeEmpty(); + } + finally + { + fileSystemFixture.CleanupFileSystemStructure(); + } + } + + [Fact] + public async Task ExecuteAsync_WhenCalledWithValidPathAndWithIncludeHiddenElements_ShouldReturnTreeDirectoriesWithHiddenElements() + { + // Arrange + FileSystemStructureFixture fileSystemFixture = new(); + string testPath = fileSystemFixture.CreateFileSystemStructure(); + testPath = System.IO.Path.GetDirectoryName(testPath) ?? testPath; + testPath = System.IO.Path.GetDirectoryName(testPath) ?? testPath; // two levels to get to the element that has a hidden element as child + string encodedPath = Uri.EscapeDataString(testPath); + bool includeHiddenElements = true; + try + { + // Act + HttpResponseMessage response = await _client.GetAsync($"/api/v1/directories/get-tree-directories?path={encodedPath}&includeHiddenElements={includeHiddenElements}"); + + // Assert + response.EnsureSuccessStatusCode(); + response.StatusCode.Should().Be(HttpStatusCode.OK); + + string content = await response.Content.ReadAsStringAsync(); + List? treeNodes = JsonSerializer.Deserialize>(content, _jsonOptions); + + treeNodes.Should().NotBeNull(); + treeNodes!.Should().NotBeEmpty(); + + string[] pathSegments = testPath.Split(System.IO.Path.DirectorySeparatorChar, StringSplitOptions.RemoveEmptyEntries); + + + FileSystemTreeNodeResponse firstNode = treeNodes!.First(); + firstNode.Name.Should().Be((s_isLinux ? "." : string.Empty) + "NestedDirectory_2"); + firstNode.Path.Should().Be(System.IO.Path.Combine(testPath, (s_isLinux ? "." : string.Empty) + "NestedDirectory_2" + System.IO.Path.DirectorySeparatorChar)); + firstNode.ItemType.Should().Be(FileSystemItemType.Directory); + treeNodes.Should().AllSatisfy(n => n.ItemType.Should().Be(FileSystemItemType.Directory)); + treeNodes!.Count.Should().Be(1); // only directories + } + finally + { + fileSystemFixture.CleanupFileSystemStructure(); + } + } + + [Fact] + public async Task ExecuteAsync_WhenCalledWithInvalidPath_ShouldReturnForbiddenResult() + { + // Arrange + string invalidPath = "invalid:path"; + string encodedPath = Uri.EscapeDataString(invalidPath); + bool includeHiddenElements = true; + + // Act + HttpResponseMessage response = await _client.GetAsync($"/api/v1/directories/get-tree-directories?path={encodedPath}&includeHiddenElements={includeHiddenElements}"); + + // Assert + response.StatusCode.Should().Be(HttpStatusCode.Forbidden); + string content = await response.Content.ReadAsStringAsync(); + + Dictionary? problemDetails = JsonSerializer.Deserialize>(content, _jsonOptions); + problemDetails.Should().NotBeNull(); + problemDetails!["status"].GetInt32().Should().Be(StatusCodes.Status403Forbidden); + problemDetails["title"].GetString().Should().Be("General.Failure"); + problemDetails["instance"].GetString().Should().Be("/api/v1/directories/get-tree-directories"); + problemDetails["detail"].GetString().Should().Be("UnauthorizedAccess"); + problemDetails["type"].GetString().Should().Be("https://tools.ietf.org/html/rfc9110#section-15.5.4"); + problemDetails["traceId"].GetString().Should().NotBeNullOrWhiteSpace(); + } + + [Fact] + public async Task ExecuteAsync_WhenCalledWithEmptyPath_ShouldReturnValidationProblemResult() + { + // Arrange + string emptyPath = ""; + string encodedPath = Uri.EscapeDataString(emptyPath); + bool includeHiddenElements = true; + + // Act + HttpResponseMessage response = await _client.GetAsync($"/api/v1/directories/get-tree-directories?path={encodedPath}&includeHiddenElements={includeHiddenElements}"); + + // Assert + response.StatusCode.Should().Be(HttpStatusCode.UnprocessableContent); + response.Content.Headers.ContentType?.MediaType.Should().Be("application/problem+json"); + string content = await response.Content.ReadAsStringAsync(); + Dictionary? problemDetails = JsonSerializer.Deserialize>(content, _jsonOptions); + problemDetails.Should().NotBeNull(); + problemDetails!["status"].GetInt32().Should().Be(StatusCodes.Status422UnprocessableEntity); + problemDetails["title"].GetString().Should().Be("Validation Error"); + problemDetails["instance"].GetString().Should().Be("/api/v1/directories/get-tree-directories"); + problemDetails["detail"].GetString().Should().Be("One or more validation errors occurred."); + problemDetails["type"].GetString().Should().Be("https://tools.ietf.org/html/rfc4918#section-11.2"); + problemDetails["traceId"].GetString().Should().NotBeNullOrWhiteSpace(); + + Dictionary? errors = problemDetails["errors"].Deserialize>(_jsonOptions); + errors.Should().ContainKey("General.Validation").WhoseValue.Should().BeEquivalentTo(["PathCannotBeEmpty"]); + } + + [Fact] + public async Task ExecuteAsync_WhenCalledWithCancellationToken_ShouldCompleteSuccessfully() + { + // Arrange + string testPath = System.IO.Path.Combine(System.IO.Path.GetTempPath(), "testDirectory"); + string encodedPath = Uri.EscapeDataString(testPath); + bool includeHiddenElements = true; + using CancellationTokenSource cts = new(TimeSpan.FromSeconds(5)); + + // Act + Func act = async () => await _client.GetAsync($"/api/v1/directories/get-tree-directories?path={encodedPath}&includeHiddenElements={includeHiddenElements}", cts.Token); + + // Assert + await act.Should().NotThrowAsync(); + } + + [Fact] + public async Task ExecuteAsync_WhenCancellationTokenIsCancelled_ShouldThrowTaskCanceledException() + { + // Arrange + string testPath = System.IO.Path.Combine(System.IO.Path.GetTempPath(), "testDirectory"); + string encodedPath = Uri.EscapeDataString(testPath); + bool includeHiddenElements = true; + using CancellationTokenSource cts = new(); + + // Act + Func act = async () => + { + cts.Cancel(); // Cancel the token immediately + await _client.GetAsync($"/api/v1/directories/get-tree-directories?path={encodedPath}&includeHiddenElements={includeHiddenElements}", cts.Token); + }; + + // Assert + await act.Should().ThrowAsync(); + } +} diff --git a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Controllers/FileManagement/DrivesControllerTests.cs b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/FileSystemManagement/Drives/GetDrivesEndpointTests.cs similarity index 57% rename from tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Controllers/FileManagement/DrivesControllerTests.cs rename to tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/FileSystemManagement/Drives/GetDrivesEndpointTests.cs index 0506b51e..16ad6306 100644 --- a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Controllers/FileManagement/DrivesControllerTests.cs +++ b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/FileSystemManagement/Drives/GetDrivesEndpointTests.cs @@ -1,28 +1,26 @@ #region ========================================================================= USING ===================================================================================== using FluentAssertions; using Lumina.Contracts.Enums.FileSystem; -using Lumina.Contracts.Responses.FileManagement; +using Lumina.Contracts.Responses.FileSystemManagement.Common; using Lumina.Presentation.Api.IntegrationTests.Common.Setup; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; -using System.IO; using System.Linq; using System.Net; using System.Net.Http; using System.Runtime.InteropServices; using System.Text.Json; using System.Text.Json.Serialization; -using System.Threading; using System.Threading.Tasks; #endregion -namespace Lumina.Presentation.Api.IntegrationTests.Core.Controllers.FileManagement; +namespace Lumina.Presentation.Api.IntegrationTests.Core.Endpoints.FileSystemManagement.Drives; /// -/// Contains integration tests for the class. +/// Contains integration tests for the class. /// [ExcludeFromCodeCoverage] -public class DrivesControllerTests : IClassFixture +public class GetDrivesEndpointTests : IClassFixture { private readonly HttpClient _client; private readonly JsonSerializerOptions _jsonOptions = new() @@ -34,17 +32,16 @@ public class DrivesControllerTests : IClassFixture private static readonly bool s_isLinux = RuntimeInformation.IsOSPlatform(OSPlatform.Linux); /// - /// Initializes a new instance of the class. + /// Initializes a new instance of the class. /// /// Injected in-memory API factory. - public DrivesControllerTests(LuminaApiFactory apiFactory) + public GetDrivesEndpointTests(LuminaApiFactory apiFactory) { _client = apiFactory.CreateClient(); } - [Fact] - public async Task GetDrives_WhenCalled_ShouldReturnDrives() + public async Task ExecuteAsync_WhenCalled_ShouldReturnDrives() { // Act HttpResponseMessage response = await _client.GetAsync($"/api/v1/drives/get-drives"); @@ -53,27 +50,16 @@ public class DrivesControllerTests : IClassFixture response.EnsureSuccessStatusCode(); response.StatusCode.Should().Be(HttpStatusCode.OK); - List drives = []; + string content = await response.Content.ReadAsStringAsync(); + List? drives = JsonSerializer.Deserialize>(content, _jsonOptions); - using (Stream stream = await response.Content.ReadAsStreamAsync()) - { - using (JsonDocument jsonDoc = await JsonDocument.ParseAsync(stream)) - { - foreach (JsonElement element in jsonDoc.RootElement.EnumerateArray()) - { - FileSystemTreeNodeResponse? drive = JsonSerializer.Deserialize(element.GetRawText(), _jsonOptions); - if (drive is not null) - drives.Add(drive); - } - } - } drives.Should().NotBeNull(); drives.Should().NotBeEmpty(); - FileSystemTreeNodeResponse firstDrive = drives.First(); + FileSystemTreeNodeResponse firstDrive = drives!.First(); firstDrive.Name.Should().Be(s_isLinux ? "/" : "C:\\"); firstDrive.Path.Should().Be(s_isLinux ? "/" : "C:\\"); firstDrive.ItemType.Should().Be(FileSystemItemType.Root); - drives.Count.Should().BeGreaterThanOrEqualTo(1); + drives!.Count.Should().BeGreaterThanOrEqualTo(1); } } diff --git a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Controllers/FileManagement/FileSystemControllerTests.cs b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/FileSystemManagement/FileSystem/GetTypeEndpointTests.cs similarity index 72% rename from tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Controllers/FileManagement/FileSystemControllerTests.cs rename to tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/FileSystemManagement/FileSystem/GetTypeEndpointTests.cs index 329aa1a2..f90e256a 100644 --- a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Controllers/FileManagement/FileSystemControllerTests.cs +++ b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/FileSystemManagement/FileSystem/GetTypeEndpointTests.cs @@ -1,14 +1,10 @@ #region ========================================================================= USING ===================================================================================== using FluentAssertions; using Lumina.Contracts.Enums.FileSystem; -using Lumina.Contracts.Responses.FileManagement; +using Lumina.Contracts.Responses.FileSystemManagement.FileSystem; using Lumina.Presentation.Api.IntegrationTests.Common.Setup; -using Lumina.Presentation.Api.IntegrationTests.Core.Controllers.FileManagement.Fixtures; using System; -using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; -using System.IO; -using System.Linq; using System.Net; using System.Net.Http; using System.Text.Json; @@ -17,13 +13,13 @@ using System.Threading; using System.Threading.Tasks; #endregion -namespace Lumina.Presentation.Api.IntegrationTests.Core.Controllers.FileManagement; +namespace Lumina.Presentation.Api.IntegrationTests.Core.Endpoints.FileSystemManagement.FileSystem; /// -/// Contains integration tests for the class. +/// Contains integration tests for the class. /// [ExcludeFromCodeCoverage] -public class FileSystemControllerTests : IClassFixture +public class GetTypeEndpointTests : IClassFixture { private readonly HttpClient _client; private readonly JsonSerializerOptions _jsonOptions = new() @@ -34,19 +30,19 @@ public class FileSystemControllerTests : IClassFixture }; /// - /// Initializes a new instance of the class. + /// Initializes a new instance of the class. /// /// Injected in-memory API factory. - public FileSystemControllerTests(LuminaApiFactory apiFactory) + public GetTypeEndpointTests(LuminaApiFactory apiFactory) { _client = apiFactory.CreateClient(); } [Fact] - public async Task GetType_WhenCalled_ShouldReturnOkResultWithFileSystemTypeResponse() + public async Task ExecuteAsync_WhenCalled_ShouldReturnOkResultWithFileSystemTypeResponse() { // Act - HttpResponseMessage response = await _client.GetAsync("/api/v1.0/file-system/get-type"); + HttpResponseMessage response = await _client.GetAsync("/api/v1/file-system/get-type"); // Assert response.StatusCode.Should().Be(HttpStatusCode.OK); @@ -57,11 +53,11 @@ public class FileSystemControllerTests : IClassFixture } [Fact] - public async Task GetType_WhenCalledMultipleTimes_ShouldReturnConsistentResults() + public async Task ExecuteAsync_WhenCalledMultipleTimes_ShouldReturnConsistentResults() { // Act - HttpResponseMessage response1 = await _client.GetAsync("/api/v1.0/file-system/get-type"); - HttpResponseMessage response2 = await _client.GetAsync("/api/v1.0/file-system/get-type"); + HttpResponseMessage response1 = await _client.GetAsync("/api/v1/file-system/get-type"); + HttpResponseMessage response2 = await _client.GetAsync("/api/v1/file-system/get-type"); // Assert response1.StatusCode.Should().Be(HttpStatusCode.OK); @@ -79,13 +75,13 @@ public class FileSystemControllerTests : IClassFixture } [Fact] - public async Task GetType_WhenCalledWithCancellationToken_ShouldCompleteSuccessfully() + public async Task ExecuteAsync_WhenCalledWithCancellationToken_ShouldCompleteSuccessfully() { // Arrange using CancellationTokenSource cts = new(TimeSpan.FromSeconds(5)); // Act - Func act = async () => await _client.GetAsync("/api/v1.0/file-system/get-type", cts.Token); + Func act = async () => await _client.GetAsync("/api/v1/file-system/get-type", cts.Token); // Assert await act.Should().NotThrowAsync(); diff --git a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/FileSystemManagement/Files/GetFilesEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/FileSystemManagement/Files/GetFilesEndpointTests.cs new file mode 100644 index 00000000..e8e8f114 --- /dev/null +++ b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/FileSystemManagement/Files/GetFilesEndpointTests.cs @@ -0,0 +1,243 @@ +#region ========================================================================= USING ===================================================================================== +using FluentAssertions; +using Lumina.Contracts.Responses.FileSystemManagement.Files; +using Lumina.Presentation.Api.IntegrationTests.Common.Setup; +using Lumina.Presentation.Api.IntegrationTests.Core.Endpoints.FileSystemManagement.Fixtures; +using Microsoft.AspNetCore.Http; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +using System.Net; +using System.Net.Http; +using System.Runtime.InteropServices; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Api.IntegrationTests.Core.Endpoints.FileSystemManagement.Files; + +/// +/// Contains integration tests for the class. +/// +[ExcludeFromCodeCoverage] +public class GetFilesEndpointTests : IClassFixture +{ + private readonly HttpClient _client; + private readonly JsonSerializerOptions _jsonOptions = new() + { + ReferenceHandler = ReferenceHandler.Preserve, + PropertyNameCaseInsensitive = true, + Converters = { new JsonStringEnumConverter(JsonNamingPolicy.CamelCase) } + }; + private static readonly bool s_isLinux = RuntimeInformation.IsOSPlatform(OSPlatform.Linux); + + /// + /// Initializes a new instance of the class. + /// + /// Injected in-memory API factory. + public GetFilesEndpointTests(LuminaApiFactory apiFactory) + { + _client = apiFactory.CreateClient(); + } + + [Fact] + public async Task ExecuteAsync_WhenCalledWithValidPathAndNotIncludeHiddenElements_ShouldReturnFilesWithoutHiddenElements() + { + // Arrange + FileSystemStructureFixture fileSystemFixture = new(); + string testPath = fileSystemFixture.CreateFileSystemStructure(); + testPath = System.IO.Path.GetDirectoryName(testPath) ?? testPath; + bool includeHiddenElements = false; + try + { + // Act + HttpResponseMessage response = await _client.GetAsync($"/api/v1/files/get-files?path={Uri.EscapeDataString(testPath)}&includeHiddenElements={includeHiddenElements}"); + + // Assert + response.EnsureSuccessStatusCode(); + response.StatusCode.Should().Be(HttpStatusCode.OK); + + string content = await response.Content.ReadAsStringAsync(); + List? files = JsonSerializer.Deserialize>(content, _jsonOptions); + + files.Should().NotBeNull(); + files!.Should().NotBeEmpty(); + + string[] pathSegments = testPath.Split(System.IO.Path.DirectorySeparatorChar, StringSplitOptions.RemoveEmptyEntries); + + + FileResponse firstDirectory = files!.First(); + firstDirectory.Name.Should().Be("TestFile_2.txt"); + firstDirectory.Path.Should().Be(System.IO.Path.Combine(testPath, "TestFile_2.txt")); + files!.Count.Should().Be(1); // only files + } + finally + { + fileSystemFixture.CleanupFileSystemStructure(); + } + } + + [Fact] + public async Task ExecuteAsync_WhenCalledWithValidPathAndHiddenChildrenAndNotIncludeHiddenElements_ShouldReturnNoFiles() + { + // Arrange + FileSystemStructureFixture fileSystemFixture = new(); + string testPath = fileSystemFixture.CreateFileSystemStructure(); + testPath = System.IO.Path.GetDirectoryName(testPath) ?? testPath; + testPath = System.IO.Path.GetDirectoryName(testPath) ?? testPath; // two levels to get to the element that has a hidden element as child + bool includeHiddenElements = false; + try + { + // Act + HttpResponseMessage response = await _client.GetAsync($"/api/v1/files/get-files?path={Uri.EscapeDataString(testPath)}&includeHiddenElements={includeHiddenElements}"); + + // Assert + response.EnsureSuccessStatusCode(); + response.StatusCode.Should().Be(HttpStatusCode.OK); + + string content = await response.Content.ReadAsStringAsync(); + List? files = JsonSerializer.Deserialize>(content, _jsonOptions); + + files.Should().NotBeNull(); + FileResponse firstDirectory = files!.First(); + firstDirectory.Name.Should().Be("TestFile_2.txt"); + firstDirectory.Path.Should().Be(System.IO.Path.Combine(testPath, "TestFile_2.txt")); + } + finally + { + fileSystemFixture.CleanupFileSystemStructure(); + } + } + + [Fact] + public async Task ExecuteAsync_WhenCalledWithValidPathAndWithIncludeHiddenElements_ShouldReturnFilesWithHiddenElements() + { + // Arrange + FileSystemStructureFixture fileSystemFixture = new(); + string testPath = fileSystemFixture.CreateFileSystemStructure(); + testPath = System.IO.Path.GetDirectoryName(testPath) ?? testPath; + testPath = System.IO.Path.GetDirectoryName(testPath) ?? testPath; // two levels to get to the element that has a hidden element as child + bool includeHiddenElements = true; + try + { + // Act + HttpResponseMessage response = await _client.GetAsync($"/api/v1/files/get-files?path={Uri.EscapeDataString(testPath)}&includeHiddenElements={includeHiddenElements}"); + + // Assert + response.EnsureSuccessStatusCode(); + response.StatusCode.Should().Be(HttpStatusCode.OK); + + string content = await response.Content.ReadAsStringAsync(); + List? files = JsonSerializer.Deserialize>(content, _jsonOptions); + + files.Should().NotBeNull(); + files!.Should().NotBeEmpty(); + + string[] pathSegments = testPath.Split(System.IO.Path.DirectorySeparatorChar, StringSplitOptions.RemoveEmptyEntries); + + FileResponse firstDirectory = files!.First(); + firstDirectory.Name.Should().Be((s_isLinux ? "." : string.Empty) + "TestFile_1.txt"); + firstDirectory.Path.Should().Be(System.IO.Path.Combine(testPath, (s_isLinux ? "." : string.Empty) + "TestFile_1.txt")); + FileResponse secondDirectory = files!.Last(); + secondDirectory.Name.Should().Be("TestFile_2.txt"); + secondDirectory.Path.Should().Be(System.IO.Path.Combine(testPath, "TestFile_2.txt")); + files!.Count.Should().Be(2); + } + finally + { + fileSystemFixture.CleanupFileSystemStructure(); + } + } + + [Fact] + public async Task ExecuteAsync_WhenCalledWithInvalidPath_ShouldReturnForbiddenResult() + { + // Arrange + string invalidPath = "invalid:path"; + string encodedPath = Uri.EscapeDataString(invalidPath); + bool includeHiddenElements = true; + + // Act + HttpResponseMessage response = await _client.GetAsync($"/api/v1/files/get-files?path={encodedPath}&includeHiddenElements={includeHiddenElements}"); + + // Assert + response.StatusCode.Should().Be(HttpStatusCode.Forbidden); + string content = await response.Content.ReadAsStringAsync(); + + Dictionary? problemDetails = JsonSerializer.Deserialize>(content, _jsonOptions); + problemDetails.Should().NotBeNull(); + problemDetails!["status"].GetInt32().Should().Be(StatusCodes.Status403Forbidden); + problemDetails["title"].GetString().Should().Be("General.Failure"); + problemDetails["instance"].GetString().Should().Be("/api/v1/files/get-files"); + problemDetails["detail"].GetString().Should().Be("UnauthorizedAccess"); + problemDetails["type"].GetString().Should().Be("https://tools.ietf.org/html/rfc9110#section-15.5.4"); + problemDetails["traceId"].GetString().Should().NotBeNullOrWhiteSpace(); + } + + [Fact] + public async Task ExecuteAsync_WhenCalledWithEmptyPath_ShouldReturnValidationProblemResult() + { + // Arrange + string emptyPath = ""; + string encodedPath = Uri.EscapeDataString(emptyPath); + bool includeHiddenElements = true; + + // Act + HttpResponseMessage response = await _client.GetAsync($"/api/v1/files/get-files?path={encodedPath}&includeHiddenElements={includeHiddenElements}"); + + // Assert + response.StatusCode.Should().Be(HttpStatusCode.UnprocessableContent); + response.Content.Headers.ContentType?.MediaType.Should().Be("application/problem+json"); + string content = await response.Content.ReadAsStringAsync(); + Dictionary? problemDetails = JsonSerializer.Deserialize>(content, _jsonOptions); + problemDetails.Should().NotBeNull(); + problemDetails!["status"].GetInt32().Should().Be(StatusCodes.Status422UnprocessableEntity); + problemDetails["title"].GetString().Should().Be("Validation Error"); + problemDetails["instance"].GetString().Should().Be("/api/v1/files/get-files"); + problemDetails["detail"].GetString().Should().Be("One or more validation errors occurred."); + problemDetails["type"].GetString().Should().Be("https://tools.ietf.org/html/rfc4918#section-11.2"); + problemDetails["traceId"].GetString().Should().NotBeNullOrWhiteSpace(); + + Dictionary? errors = problemDetails["errors"].Deserialize>(_jsonOptions); + errors.Should().ContainKey("General.Validation").WhoseValue.Should().BeEquivalentTo(["PathCannotBeEmpty"]); + } + + [Fact] + public async Task ExecuteAsync_WhenCalledWithCancellationToken_ShouldCompleteSuccessfully() + { + // Arrange + string testPath = System.IO.Path.Combine(System.IO.Path.GetTempPath(), "testDirectory"); + string encodedPath = Uri.EscapeDataString(testPath); + bool includeHiddenElements = true; + using CancellationTokenSource cts = new(TimeSpan.FromSeconds(5)); + + // Act + Func act = async () => await _client.GetAsync($"/api/v1/files/get-files?path={encodedPath}&includeHiddenElements={includeHiddenElements}", cts.Token); + + // Assert + await act.Should().NotThrowAsync(); + } + + [Fact] + public async Task ExecuteAsync_WhenCancellationTokenIsCancelled_ShouldThrowTaskCanceledException() + { + // Arrange + string testPath = System.IO.Path.Combine(System.IO.Path.GetTempPath(), "testDirectory"); + string encodedPath = Uri.EscapeDataString(testPath); + bool includeHiddenElements = true; + using CancellationTokenSource cts = new(); + + // Act + Func act = async () => + { + cts.Cancel(); // Cancel the token immediately + await _client.GetAsync($"/api/v1/files/get-files?path={encodedPath}&includeHiddenElements={includeHiddenElements}", cts.Token); + }; + + // Assert + await act.Should().ThrowAsync(); + } +} diff --git a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/FileSystemManagement/Files/GetTreeFilesEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/FileSystemManagement/Files/GetTreeFilesEndpointTests.cs new file mode 100644 index 00000000..219e9754 --- /dev/null +++ b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/FileSystemManagement/Files/GetTreeFilesEndpointTests.cs @@ -0,0 +1,243 @@ +#region ========================================================================= USING ===================================================================================== +using FluentAssertions; +using Lumina.Contracts.Responses.FileSystemManagement.Common; +using Lumina.Presentation.Api.IntegrationTests.Common.Setup; +using Lumina.Presentation.Api.IntegrationTests.Core.Endpoints.FileSystemManagement.Fixtures; +using Microsoft.AspNetCore.Http; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +using System.Net; +using System.Net.Http; +using System.Runtime.InteropServices; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Api.IntegrationTests.Core.Endpoints.FileSystemManagement.Files; + +/// +/// Contains integration tests for the class. +/// +[ExcludeFromCodeCoverage] +public class GetTreeFilesEndpointTests : IClassFixture +{ + private readonly HttpClient _client; + private readonly JsonSerializerOptions _jsonOptions = new() + { + ReferenceHandler = ReferenceHandler.Preserve, + PropertyNameCaseInsensitive = true, + Converters = { new JsonStringEnumConverter(JsonNamingPolicy.CamelCase) } + }; + private static readonly bool s_isLinux = RuntimeInformation.IsOSPlatform(OSPlatform.Linux); + + /// + /// Initializes a new instance of the class. + /// + /// Injected in-memory API factory. + public GetTreeFilesEndpointTests(LuminaApiFactory apiFactory) + { + _client = apiFactory.CreateClient(); + } + + [Fact] + public async Task ExecuteAsync_WhenCalledWithValidPathAndNotIncludeHiddenElements_ShouldReturnTreeFilesWithoutHiddenElements() + { + // Arrange + FileSystemStructureFixture fileSystemFixture = new(); + string testPath = fileSystemFixture.CreateFileSystemStructure(); + testPath = System.IO.Path.GetDirectoryName(testPath) ?? testPath; + bool includeHiddenElements = false; + try + { + // Act + HttpResponseMessage response = await _client.GetAsync($"/api/v1/files/get-tree-files?path={Uri.EscapeDataString(testPath)}&includeHiddenElements={includeHiddenElements}"); + + // Assert + response.EnsureSuccessStatusCode(); + response.StatusCode.Should().Be(HttpStatusCode.OK); + + string content = await response.Content.ReadAsStringAsync(); + List? files = JsonSerializer.Deserialize>(content, _jsonOptions); + + files.Should().NotBeNull(); + files!.Should().NotBeEmpty(); + + string[] pathSegments = testPath.Split(System.IO.Path.DirectorySeparatorChar, StringSplitOptions.RemoveEmptyEntries); + + + FileSystemTreeNodeResponse firstDirectory = files!.First(); + firstDirectory.Name.Should().Be("TestFile_2.txt"); + firstDirectory.Path.Should().Be(System.IO.Path.Combine(testPath, "TestFile_2.txt")); + files!.Count.Should().Be(1); // only files + } + finally + { + fileSystemFixture.CleanupFileSystemStructure(); + } + } + + [Fact] + public async Task ExecuteAsync_WhenCalledWithValidPathAndHiddenChildrenAndNotIncludeHiddenElements_ShouldReturnNoTreeFiles() + { + // Arrange + FileSystemStructureFixture fileSystemFixture = new(); + string testPath = fileSystemFixture.CreateFileSystemStructure(); + testPath = System.IO.Path.GetDirectoryName(testPath) ?? testPath; + testPath = System.IO.Path.GetDirectoryName(testPath) ?? testPath; // two levels to get to the element that has a hidden element as child + bool includeHiddenElements = false; + try + { + // Act + HttpResponseMessage response = await _client.GetAsync($"/api/v1/files/get-tree-files?path={Uri.EscapeDataString(testPath)}&includeHiddenElements={includeHiddenElements}"); + + // Assert + response.EnsureSuccessStatusCode(); + response.StatusCode.Should().Be(HttpStatusCode.OK); + + string content = await response.Content.ReadAsStringAsync(); + List? files = JsonSerializer.Deserialize>(content, _jsonOptions); + + files.Should().NotBeNull(); + + FileSystemTreeNodeResponse firstDirectory = files!.First(); + firstDirectory.Name.Should().Be("TestFile_2.txt"); + firstDirectory.Path.Should().Be(System.IO.Path.Combine(testPath, "TestFile_2.txt")); + } + finally + { + fileSystemFixture.CleanupFileSystemStructure(); + } + } + + [Fact] + public async Task ExecuteAsync_WhenCalledWithValidPathAndWithIncludeHiddenElements_ShouldReturnTreeFilesWithHiddenElements() + { + // Arrange + FileSystemStructureFixture fileSystemFixture = new(); + string testPath = fileSystemFixture.CreateFileSystemStructure(); + testPath = System.IO.Path.GetDirectoryName(testPath) ?? testPath; + testPath = System.IO.Path.GetDirectoryName(testPath) ?? testPath; // two levels to get to the element that has a hidden element as child + bool includeHiddenElements = true; + try + { + // Act + HttpResponseMessage response = await _client.GetAsync($"/api/v1/files/get-tree-files?path={Uri.EscapeDataString(testPath)}&includeHiddenElements={includeHiddenElements}"); + + // Assert + response.EnsureSuccessStatusCode(); + response.StatusCode.Should().Be(HttpStatusCode.OK); + + string content = await response.Content.ReadAsStringAsync(); + List? files = JsonSerializer.Deserialize>(content, _jsonOptions); + + files.Should().NotBeNull(); + files!.Should().NotBeEmpty(); + + string[] pathSegments = testPath.Split(System.IO.Path.DirectorySeparatorChar, StringSplitOptions.RemoveEmptyEntries); + + FileSystemTreeNodeResponse firstDirectory = files!.First(); + firstDirectory.Name.Should().Be((s_isLinux ? "." : string.Empty) + "TestFile_1.txt"); + firstDirectory.Path.Should().Be(System.IO.Path.Combine(testPath, (s_isLinux ? "." : string.Empty) + "TestFile_1.txt")); + FileSystemTreeNodeResponse secondDirectory = files!.Last(); + secondDirectory.Name.Should().Be("TestFile_2.txt"); + secondDirectory.Path.Should().Be(System.IO.Path.Combine(testPath, "TestFile_2.txt")); + files!.Count.Should().Be(2); + } + finally + { + fileSystemFixture.CleanupFileSystemStructure(); + } + } + [Fact] + public async Task ExecuteAsync_WhenCalledWithInvalidPath_ShouldReturnForbiddenResult() + { + // Arrange + string invalidPath = "invalid:path"; + string encodedPath = Uri.EscapeDataString(invalidPath); + bool includeHiddenElements = true; + + // Act + HttpResponseMessage response = await _client.GetAsync($"/api/v1/files/get-tree-files?path={encodedPath}&includeHiddenElements={includeHiddenElements}"); + + // Assert + response.StatusCode.Should().Be(HttpStatusCode.Forbidden); + string content = await response.Content.ReadAsStringAsync(); + + Dictionary? problemDetails = JsonSerializer.Deserialize>(content, _jsonOptions); + problemDetails.Should().NotBeNull(); + problemDetails!["status"].GetInt32().Should().Be(StatusCodes.Status403Forbidden); + problemDetails["title"].GetString().Should().Be("General.Failure"); + problemDetails["instance"].GetString().Should().Be("/api/v1/files/get-tree-files"); + problemDetails["detail"].GetString().Should().Be("UnauthorizedAccess"); + problemDetails["type"].GetString().Should().Be("https://tools.ietf.org/html/rfc9110#section-15.5.4"); + problemDetails["traceId"].GetString().Should().NotBeNullOrWhiteSpace(); + } + + [Fact] + public async Task ExecuteAsync_WhenCalledWithEmptyPath_ShouldReturnValidationProblemResult() + { + // Arrange + string emptyPath = ""; + string encodedPath = Uri.EscapeDataString(emptyPath); + bool includeHiddenElements = true; + + // Act + HttpResponseMessage response = await _client.GetAsync($"/api/v1/files/get-tree-files?path={encodedPath}&includeHiddenElements={includeHiddenElements}"); + + // Assert + response.StatusCode.Should().Be(HttpStatusCode.UnprocessableContent); + response.Content.Headers.ContentType?.MediaType.Should().Be("application/problem+json"); + string content = await response.Content.ReadAsStringAsync(); + Dictionary? problemDetails = JsonSerializer.Deserialize>(content, _jsonOptions); + problemDetails.Should().NotBeNull(); + problemDetails!["status"].GetInt32().Should().Be(StatusCodes.Status422UnprocessableEntity); + problemDetails["title"].GetString().Should().Be("Validation Error"); + problemDetails["instance"].GetString().Should().Be("/api/v1/files/get-tree-files"); + problemDetails["detail"].GetString().Should().Be("One or more validation errors occurred."); + problemDetails["type"].GetString().Should().Be("https://tools.ietf.org/html/rfc4918#section-11.2"); + problemDetails["traceId"].GetString().Should().NotBeNullOrWhiteSpace(); + + Dictionary? errors = problemDetails["errors"].Deserialize>(_jsonOptions); + errors.Should().ContainKey("General.Validation").WhoseValue.Should().BeEquivalentTo(["PathCannotBeEmpty"]); + } + + [Fact] + public async Task ExecuteAsync_WhenCalledWithCancellationToken_ShouldCompleteSuccessfully() + { + // Arrange + string testPath = System.IO.Path.Combine(System.IO.Path.GetTempPath(), "testDirectory"); + string encodedPath = Uri.EscapeDataString(testPath); + bool includeHiddenElements = true; + using CancellationTokenSource cts = new(TimeSpan.FromSeconds(5)); + + // Act + Func act = async () => await _client.GetAsync($"/api/v1/files/get-tree-files?path={encodedPath}&includeHiddenElements={includeHiddenElements}", cts.Token); + + // Assert + await act.Should().NotThrowAsync(); + } + + [Fact] + public async Task ExecuteAsync_WhenCancellationTokenIsCancelled_ShouldThrowTaskCanceledException() + { + // Arrange + string testPath = System.IO.Path.Combine(System.IO.Path.GetTempPath(), "testDirectory"); + string encodedPath = Uri.EscapeDataString(testPath); + bool includeHiddenElements = true; + using CancellationTokenSource cts = new(); + + // Act + Func act = async () => + { + cts.Cancel(); // Cancel the token immediately + await _client.GetAsync($"/api/v1/files/get-tree-files?path={encodedPath}&includeHiddenElements={includeHiddenElements}", cts.Token); + }; + + // Assert + await act.Should().ThrowAsync(); + } +} diff --git a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Controllers/FileManagement/Fixtures/FileSystemStructureFixture.cs b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/FileSystemManagement/Fixtures/FileSystemStructureFixture.cs similarity index 82% rename from tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Controllers/FileManagement/Fixtures/FileSystemStructureFixture.cs rename to tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/FileSystemManagement/Fixtures/FileSystemStructureFixture.cs index 659627df..a5532b69 100644 --- a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Controllers/FileManagement/Fixtures/FileSystemStructureFixture.cs +++ b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/FileSystemManagement/Fixtures/FileSystemStructureFixture.cs @@ -5,7 +5,7 @@ using System.Diagnostics.CodeAnalysis; using System.IO; #endregion -namespace Lumina.Presentation.Api.IntegrationTests.Core.Controllers.FileManagement.Fixtures; +namespace Lumina.Presentation.Api.IntegrationTests.Core.Endpoints.FileSystemManagement.Fixtures; /// /// Fixture class for creating and managing a file system structure for integration testing purposes. @@ -21,7 +21,7 @@ public class FileSystemStructureFixture /// public FileSystemStructureFixture() { - _rootPath = Path.Combine(AppContext.BaseDirectory, "TestFileSystemStructure_" + Guid.NewGuid()); + _rootPath = System.IO.Path.Combine(AppContext.BaseDirectory, "TestFileSystemStructure_" + Guid.NewGuid()); } @@ -38,13 +38,13 @@ public class FileSystemStructureFixture for (int i = 1; i <= 3; i++) { // create a nested subdirectory - currentPath = Path.Combine(currentPath, $"NestedDirectory_{i}"); + currentPath = System.IO.Path.Combine(currentPath, $"NestedDirectory_{i}"); Directory.CreateDirectory(currentPath); // create two text files in the current directory for (int j = 1; j <= 2; j++) { - string filePath = Path.Combine(currentPath, $"TestFile_{j}.txt"); + string filePath = System.IO.Path.Combine(currentPath, $"TestFile_{j}.txt"); File.WriteAllText(filePath, _faker.Lorem.Paragraph()); // make the first file in each directory hidden if (j == 1) @@ -68,9 +68,9 @@ public class FileSystemStructureFixture else if (OperatingSystem.IsLinux() || OperatingSystem.IsMacOS()) { // On Unix-like systems, rename the file/directory to start with a dot - string directory = Path.GetDirectoryName(path)!; - string name = Path.GetFileName(path); - string newPath = Path.Combine(directory, "." + name); + string directory = System.IO.Path.GetDirectoryName(path)!; + string name = System.IO.Path.GetFileName(path); + string newPath = System.IO.Path.Combine(directory, "." + name); if (Directory.Exists(path)) Directory.Move(path, newPath); else if (File.Exists(path)) diff --git a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Controllers/FileManagement/Fixtures/FileSystemTreeNodeResponseFixture.cs b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/FileSystemManagement/Fixtures/FileSystemTreeNodeResponseFixture.cs similarity index 94% rename from tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Controllers/FileManagement/Fixtures/FileSystemTreeNodeResponseFixture.cs rename to tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/FileSystemManagement/Fixtures/FileSystemTreeNodeResponseFixture.cs index afa4b15f..27050cd4 100644 --- a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Controllers/FileManagement/Fixtures/FileSystemTreeNodeResponseFixture.cs +++ b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/FileSystemManagement/Fixtures/FileSystemTreeNodeResponseFixture.cs @@ -1,13 +1,13 @@ #region ========================================================================= USING ===================================================================================== using Bogus; using Lumina.Contracts.Enums.FileSystem; -using Lumina.Contracts.Responses.FileManagement; +using Lumina.Contracts.Responses.FileSystemManagement.Common; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Linq; #endregion -namespace Lumina.Presentation.Api.IntegrationTests.Core.Controllers.FileManagement.Fixtures; +namespace Lumina.Presentation.Api.IntegrationTests.Core.Endpoints.FileSystemManagement.Fixtures; /// /// Fixture class for the class. diff --git a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Controllers/FileManagement/Fixtures/TestImageFixture.cs b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/FileSystemManagement/Fixtures/TestImageFixture.cs similarity index 86% rename from tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Controllers/FileManagement/Fixtures/TestImageFixture.cs rename to tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/FileSystemManagement/Fixtures/TestImageFixture.cs index 553bb330..79a4ed7b 100644 --- a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Controllers/FileManagement/Fixtures/TestImageFixture.cs +++ b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/FileSystemManagement/Fixtures/TestImageFixture.cs @@ -7,7 +7,7 @@ using System.Diagnostics.CodeAnalysis; using System.IO; #endregion -namespace Lumina.Presentation.Api.IntegrationTests.Core.Controllers.FileManagement.Fixtures; +namespace Lumina.Presentation.Api.IntegrationTests.Core.Endpoints.FileSystemManagement.Fixtures; /// /// Fixture class for creating and managing a test image for integration testing purposes. @@ -25,7 +25,7 @@ public class TestImageFixture : IDisposable /// public TestImageFixture() { - ImagePath = Path.Combine(Path.GetTempPath(), $"TestImage_{Guid.NewGuid()}.jpg"); + ImagePath = System.IO.Path.Combine(System.IO.Path.GetTempPath(), $"TestImage_{Guid.NewGuid()}.jpg"); CreateTestImage(); } diff --git a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/FileSystemManagement/Path/CheckPathExistsEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/FileSystemManagement/Path/CheckPathExistsEndpointTests.cs new file mode 100644 index 00000000..d54789f9 --- /dev/null +++ b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/FileSystemManagement/Path/CheckPathExistsEndpointTests.cs @@ -0,0 +1,126 @@ +#region ========================================================================= USING ===================================================================================== +using FluentAssertions; +using Lumina.Contracts.Responses.FileSystemManagement.Path; +using Lumina.Presentation.Api.IntegrationTests.Common.Setup; +using System; +using System.Diagnostics.CodeAnalysis; +using System.Net; +using System.Net.Http; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Api.IntegrationTests.Core.Endpoints.FileSystemManagement.Path; + +/// +/// Contains integration tests for the class. +/// +[ExcludeFromCodeCoverage] +public class CheckPathExistsEndpointTests : IClassFixture +{ + private readonly HttpClient _client; + private readonly JsonSerializerOptions _jsonOptions = new() + { + ReferenceHandler = ReferenceHandler.Preserve, + PropertyNameCaseInsensitive = true, + Converters = { new JsonStringEnumConverter(JsonNamingPolicy.CamelCase) } + }; + + /// + /// Initializes a new instance of the class. + /// + /// Injected in-memory API factory. + public CheckPathExistsEndpointTests(LuminaApiFactory apiFactory) + { + _client = apiFactory.CreateClient(); + } + + [Fact] + public async Task ExecuteAsync_WhenCalledWithExistingPath_ShouldReturnOkResultWithExistsTrue() + { + // Arrange + string tempPath = System.IO.Path.GetTempPath(); + + // Act + HttpResponseMessage response = await _client.GetAsync($"/api/v1/path/check-path-exists?path={Uri.EscapeDataString(tempPath)}&includeHiddenElements=false"); + + // Assert + response.StatusCode.Should().Be(HttpStatusCode.OK); + string content = await response.Content.ReadAsStringAsync(); + PathExistsResponse? result = JsonSerializer.Deserialize(content, _jsonOptions); + result.Should().NotBeNull(); + result!.Exists.Should().BeTrue(); + } + + [Fact] + public async Task ExecuteAsync_WhenCalledWithNonExistingPath_ShouldReturnOkResultWithExistsFalse() + { + // Arrange + string nonExistingPath = System.IO.Path.Combine(System.IO.Path.GetTempPath(), Guid.NewGuid().ToString()); + + // Act + HttpResponseMessage response = await _client.GetAsync($"/api/v1/path/check-path-exists?path={Uri.EscapeDataString(nonExistingPath)}&includeHiddenElements=false"); + + // Assert + response.StatusCode.Should().Be(HttpStatusCode.OK); + string content = await response.Content.ReadAsStringAsync(); + PathExistsResponse? result = JsonSerializer.Deserialize(content, _jsonOptions); + result.Should().NotBeNull(); + result!.Exists.Should().BeFalse(); + } + + [Fact] + public async Task ExecuteAsync_WhenCalledWithEmptyPath_ShouldReturnOkResultWithExistsFalse() + { + // Arrange + string path = ""; + + // Act + HttpResponseMessage response = await _client.GetAsync($"/api/v1/path/check-path-exists?path={Uri.EscapeDataString(path)}&includeHiddenElements=false"); + + // Assert + response.StatusCode.Should().Be(HttpStatusCode.OK); + string content = await response.Content.ReadAsStringAsync(); + PathExistsResponse? result = JsonSerializer.Deserialize(content, _jsonOptions); + result.Should().NotBeNull(); + result!.Exists.Should().BeFalse(); + } + + [Fact] + public async Task ExecuteAsync_WhenCalledWithInvalidPath_ShouldReturnOkResultWithExistsFalse() + { + // Arrange + string invalidPath = "invalid:path"; + + // Act + HttpResponseMessage response = await _client.GetAsync($"/api/v1/path/check-path-exists?path={Uri.EscapeDataString(invalidPath)}&includeHiddenElements=false"); + + // Assert + response.StatusCode.Should().Be(HttpStatusCode.OK); + string content = await response.Content.ReadAsStringAsync(); + PathExistsResponse? result = JsonSerializer.Deserialize(content, _jsonOptions); + result.Should().NotBeNull(); + result!.Exists.Should().BeFalse(); + } + + [Fact] + public async Task ExecuteAsync_WhenCancellationTokenIsCancelled_ShouldThrowTaskCanceledException() + { + // Arrange + string testPath = System.IO.Path.GetTempPath(); + string encodedPath = Uri.EscapeDataString(testPath); + using CancellationTokenSource cts = new(); + + // Act + Func act = async () => + { + cts.Cancel(); // Cancel the token immediately + await _client.GetAsync($"/api/v1/path/check-path-exists?path={encodedPath}&includeHiddenElements=false", cts.Token); + }; + + // Assert + await act.Should().ThrowAsync(); + } +} diff --git a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/FileSystemManagement/Path/CombinePathEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/FileSystemManagement/Path/CombinePathEndpointTests.cs new file mode 100644 index 00000000..87af0661 --- /dev/null +++ b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/FileSystemManagement/Path/CombinePathEndpointTests.cs @@ -0,0 +1,123 @@ +#region ========================================================================= USING ===================================================================================== +using FluentAssertions; +using Lumina.Contracts.Responses.FileSystemManagement.Path; +using Lumina.Presentation.Api.IntegrationTests.Common.Setup; +using Microsoft.AspNetCore.Http; +using System; +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; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Api.IntegrationTests.Core.Endpoints.FileSystemManagement.Path; + +/// +/// Contains integration tests for the class. +/// +[ExcludeFromCodeCoverage] +public class CombinePathEndpointTests : IClassFixture +{ + private readonly HttpClient _client; + private readonly JsonSerializerOptions _jsonOptions = new() + { + ReferenceHandler = ReferenceHandler.Preserve, + PropertyNameCaseInsensitive = true, + Converters = { new JsonStringEnumConverter(JsonNamingPolicy.CamelCase) } + }; + + /// + /// Initializes a new instance of the class. + /// + /// Injected in-memory API factory. + public CombinePathEndpointTests(LuminaApiFactory apiFactory) + { + _client = apiFactory.CreateClient(); + } + + [Fact] + public async Task ExecuteAsync_WhenCalledWithValidPaths_ShouldReturnOkResultWithCombinedPath() + { + // Arrange + string originalPath = System.IO.Path.GetTempPath(); + string newPath = "testDirectory"; + string expectedPath = System.IO.Path.Combine(System.IO.Path.GetTempPath(), "testDirectory"); + if (!expectedPath.EndsWith(System.IO.Path.DirectorySeparatorChar)) + expectedPath += System.IO.Path.DirectorySeparatorChar; + + // Act + HttpResponseMessage response = await _client.GetAsync($"/api/v1/path/combine?originalPath={Uri.EscapeDataString(originalPath)}&newPath={Uri.EscapeDataString(newPath)}"); + + // Assert + response.StatusCode.Should().Be(HttpStatusCode.OK); + string content = await response.Content.ReadAsStringAsync(); + PathSegmentResponse? result = JsonSerializer.Deserialize(content, _jsonOptions); + result.Should().NotBeNull(); + result!.Path.Should().Be(expectedPath); + } + + [Fact] + public async Task ExecuteAsync_WhenCalledWithEmptyPaths_ShouldReturnValidationProblemResult() + { + // Arrange + string originalPath = ""; + string newPath = ""; + + // Act + HttpResponseMessage response = await _client.GetAsync($"/api/v1/path/combine?originalPath={Uri.EscapeDataString(originalPath)}&newPath={Uri.EscapeDataString(newPath)}"); + + // Assert + response.StatusCode.Should().Be(HttpStatusCode.UnprocessableContent); + response.Content.Headers.ContentType?.MediaType.Should().Be("application/problem+json"); + string content = await response.Content.ReadAsStringAsync(); + Dictionary? problemDetails = JsonSerializer.Deserialize>(content, _jsonOptions); + problemDetails.Should().NotBeNull(); + problemDetails!["status"].GetInt32().Should().Be(StatusCodes.Status422UnprocessableEntity); + problemDetails["title"].GetString().Should().Be("Validation Error"); + problemDetails["instance"].GetString().Should().Be("/api/v1/path/combine"); + problemDetails["detail"].GetString().Should().Be("One or more validation errors occurred."); + problemDetails["type"].GetString().Should().Be("https://tools.ietf.org/html/rfc4918#section-11.2"); + problemDetails["traceId"].GetString().Should().NotBeNullOrWhiteSpace(); + + Dictionary? errors = problemDetails["errors"].Deserialize>(_jsonOptions); + errors.Should().ContainKey("General.Validation").WhoseValue.Should().BeEquivalentTo(["PathCannotBeEmpty"]); + } + + [Fact] + public async Task ExecuteAsync_WhenCalledWithCancellationToken_ShouldCompleteSuccessfully() + { + // Arrange + string originalPath = "/home/user"; + string newPath = "documents"; + using CancellationTokenSource cts = new(TimeSpan.FromSeconds(5)); + + // Act + Func act = async () => await _client.GetAsync($"/api/v1/path/combine?originalPath={Uri.EscapeDataString(originalPath)}&newPath={Uri.EscapeDataString(newPath)}", cts.Token); + + // Assert + await act.Should().NotThrowAsync(); + } + + [Fact] + public async Task ExecuteAsync_WhenCancellationTokenIsCancelled_ShouldThrowTaskCanceledException() + { + // Arrange + string originalPath = System.IO.Path.GetTempPath(); + string newPath = "testFile.txt"; + using CancellationTokenSource cts = new(); + + // Act + Func act = async () => + { + cts.Cancel(); // Cancel the token immediately + await _client.GetAsync($"/api/v1/path/combine?originalPath={Uri.EscapeDataString(originalPath)}&newPath={Uri.EscapeDataString(newPath)}", cts.Token); + }; + + // Assert + await act.Should().ThrowAsync(); + } +} diff --git a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/FileSystemManagement/Path/GetPathParentEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/FileSystemManagement/Path/GetPathParentEndpointTests.cs new file mode 100644 index 00000000..0f077e13 --- /dev/null +++ b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/FileSystemManagement/Path/GetPathParentEndpointTests.cs @@ -0,0 +1,191 @@ +#region ========================================================================= USING ===================================================================================== +using FluentAssertions; +using Lumina.Contracts.Responses.FileSystemManagement.Path; +using Lumina.Presentation.Api.IntegrationTests.Common.Setup; +using Microsoft.AspNetCore.Http; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +using System.Net; +using System.Net.Http; +using System.Runtime.InteropServices; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Api.IntegrationTests.Core.Endpoints.FileSystemManagement.Path; + +/// +/// Contains integration tests for the class. +/// +[ExcludeFromCodeCoverage] +public class GetPathParentEndpointTests : IClassFixture +{ + private readonly HttpClient _client; + private readonly JsonSerializerOptions _jsonOptions = new() + { + ReferenceHandler = ReferenceHandler.Preserve, + PropertyNameCaseInsensitive = true, + Converters = { new JsonStringEnumConverter(JsonNamingPolicy.CamelCase) } + }; + private static readonly bool s_isLinux = RuntimeInformation.IsOSPlatform(OSPlatform.Linux); + + /// + /// Initializes a new instance of the class. + /// + /// Injected in-memory API factory. + public GetPathParentEndpointTests(LuminaApiFactory apiFactory) + { + _client = apiFactory.CreateClient(); + } + + [Fact] + public async Task ExecuteAsync_WhenCalledWithValidPath_ShouldReturnOkResultWithPathSegmentResponses() + { + // Arrange + string testPath = System.IO.Path.Combine(System.IO.Path.GetTempPath(), "testDirectory", "testFile.txt"); + string encodedPath = Uri.EscapeDataString(testPath); + + // Act + HttpResponseMessage response = await _client.GetAsync($"/api/v1/path/get-path-parent?path={encodedPath}"); + + // Assert + response.StatusCode.Should().Be(HttpStatusCode.OK); + string content = await response.Content.ReadAsStringAsync(); + IEnumerable? result = JsonSerializer.Deserialize>(content, _jsonOptions); + result.Should().NotBeNull(); + result!.Should().NotBeEmpty(); + + List hierarchy = []; + string path = System.IO.Path.GetDirectoryName(testPath)!; + while (!string.IsNullOrEmpty(path)) + { + string segment = s_isLinux && path == System.IO.Path.DirectorySeparatorChar.ToString() ? path : System.IO.Path.GetFileName(path); + if (string.IsNullOrEmpty(segment)) + { + hierarchy.Add(System.IO.Path.GetPathRoot(path)!.TrimEnd(System.IO.Path.DirectorySeparatorChar)); + break; + } + hierarchy.Add(segment); + path = System.IO.Path.GetDirectoryName(path)!; + } + hierarchy.Reverse(); + + result!.Select(r => r.Path).Should().BeEquivalentTo(hierarchy, options => options.WithStrictOrdering()); + } + + [Fact] + public async Task ExecuteAsync_WhenCalledWithRootPath_ShouldReturnForbiddenResult() + { + // Arrange + string rootPath = System.IO.Path.GetPathRoot(System.IO.Path.GetTempPath())!; + string encodedPath = Uri.EscapeDataString(rootPath); + + // Act + HttpResponseMessage response = await _client.GetAsync($"/api/v1/path/get-path-parent?path={encodedPath}"); + + // Assert + response.StatusCode.Should().Be(HttpStatusCode.Forbidden); + string content = await response.Content.ReadAsStringAsync(); + + Dictionary? problemDetails = JsonSerializer.Deserialize>(content, _jsonOptions); + problemDetails.Should().NotBeNull(); + problemDetails!["status"].GetInt32().Should().Be(StatusCodes.Status403Forbidden); + problemDetails["title"].GetString().Should().Be("General.Failure"); + problemDetails["instance"].GetString().Should().Be("/api/v1/path/get-path-parent"); + problemDetails["detail"].GetString().Should().Be("CannotNavigateUp"); + problemDetails["type"].GetString().Should().Be("https://tools.ietf.org/html/rfc9110#section-15.5.4"); + problemDetails["traceId"].GetString().Should().NotBeNullOrWhiteSpace(); + } + + [Fact] + public async Task ExecuteAsync_WhenCalledWithInvalidPath_ShouldReturnValidationProblemResult() + { + // Arrange + string invalidPath = "invalid:path"; + string encodedPath = Uri.EscapeDataString(invalidPath); + + // Act + HttpResponseMessage response = await _client.GetAsync($"/api/v1/path/get-path-parent?path={encodedPath}"); + + // Assert + response.StatusCode.Should().Be(HttpStatusCode.UnprocessableContent); + response.Content.Headers.ContentType?.MediaType.Should().Be("application/problem+json"); + string content = await response.Content.ReadAsStringAsync(); + Dictionary? problemDetails = JsonSerializer.Deserialize>(content, _jsonOptions); + problemDetails.Should().NotBeNull(); + problemDetails!["status"].GetInt32().Should().Be(StatusCodes.Status422UnprocessableEntity); + problemDetails["title"].GetString().Should().Be("Validation Error"); + problemDetails["instance"].GetString().Should().Be("/api/v1/path/get-path-parent"); + problemDetails["detail"].GetString().Should().Be("One or more validation errors occurred."); + problemDetails["type"].GetString().Should().Be("https://tools.ietf.org/html/rfc4918#section-11.2"); + problemDetails["traceId"].GetString().Should().NotBeNullOrWhiteSpace(); + + Dictionary? errors = problemDetails["errors"].Deserialize>(_jsonOptions); + errors.Should().ContainKey("General.Validation").WhoseValue.Should().BeEquivalentTo(["InvalidPath"]); + } + + [Fact] + public async Task ExecuteAsync_WhenCalledWithEmptyPath_ShouldReturnValidationProblemResult() + { + // Arrange + string emptyPath = ""; + string encodedPath = Uri.EscapeDataString(emptyPath); + + // Act + HttpResponseMessage response = await _client.GetAsync($"/api/v1/path/get-path-parent?path={encodedPath}"); + + // Assert + response.StatusCode.Should().Be(HttpStatusCode.UnprocessableContent); + response.Content.Headers.ContentType?.MediaType.Should().Be("application/problem+json"); + string content = await response.Content.ReadAsStringAsync(); + Dictionary? problemDetails = JsonSerializer.Deserialize>(content, _jsonOptions); + problemDetails.Should().NotBeNull(); + problemDetails!["status"].GetInt32().Should().Be(StatusCodes.Status422UnprocessableEntity); + problemDetails["title"].GetString().Should().Be("Validation Error"); + problemDetails["instance"].GetString().Should().Be("/api/v1/path/get-path-parent"); + problemDetails["detail"].GetString().Should().Be("One or more validation errors occurred."); + problemDetails["type"].GetString().Should().Be("https://tools.ietf.org/html/rfc4918#section-11.2"); + problemDetails["traceId"].GetString().Should().NotBeNullOrWhiteSpace(); + + Dictionary? errors = problemDetails["errors"].Deserialize>(_jsonOptions); + errors.Should().ContainKey("General.Validation").WhoseValue.Should().BeEquivalentTo(["PathCannotBeEmpty"]); + } + + [Fact] + public async Task ExecuteAsync_WhenCalledWithCancellationToken_ShouldCompleteSuccessfully() + { + // Arrange + string testPath = System.IO.Path.Combine(System.IO.Path.GetTempPath(), "testDirectory"); + string encodedPath = Uri.EscapeDataString(testPath); + using CancellationTokenSource cts = new(TimeSpan.FromSeconds(5)); + + // Act + Func act = async () => await _client.GetAsync($"/api/v1/path/get-path-parent?path={encodedPath}", cts.Token); + + // Assert + await act.Should().NotThrowAsync(); + } + + [Fact] + public async Task ExecuteAsync_WhenCancellationTokenIsCancelled_ShouldThrowTaskCanceledException() + { + // Arrange + string testPath = System.IO.Path.Combine(System.IO.Path.GetTempPath(), "testDirectory"); + string encodedPath = Uri.EscapeDataString(testPath); + using CancellationTokenSource cts = new(); + + // Act + Func act = async () => + { + cts.Cancel(); // Cancel the token immediately + await _client.GetAsync($"/api/v1/path/get-path-parent?path={encodedPath}", cts.Token); + }; + + // Assert + await act.Should().ThrowAsync(); + } +} diff --git a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/FileSystemManagement/Path/GetPathRootEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/FileSystemManagement/Path/GetPathRootEndpointTests.cs new file mode 100644 index 00000000..ea284760 --- /dev/null +++ b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/FileSystemManagement/Path/GetPathRootEndpointTests.cs @@ -0,0 +1,149 @@ +#region ========================================================================= USING ===================================================================================== +using FluentAssertions; +using Lumina.Contracts.Responses.FileSystemManagement.Path; +using Lumina.Presentation.Api.IntegrationTests.Common.Setup; +using Microsoft.AspNetCore.Http; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Net; +using System.Net.Http; +using System.Runtime.InteropServices; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Api.IntegrationTests.Core.Endpoints.FileSystemManagement.Path; + +/// +/// Contains integration tests for the class. +/// +[ExcludeFromCodeCoverage] +public class GetPathRootEndpointTests : IClassFixture +{ + private readonly HttpClient _client; + private readonly JsonSerializerOptions _jsonOptions = new() + { + ReferenceHandler = ReferenceHandler.Preserve, + PropertyNameCaseInsensitive = true, + Converters = { new JsonStringEnumConverter(JsonNamingPolicy.CamelCase) } + }; + + /// + /// Initializes a new instance of the class. + /// + /// Injected in-memory API factory. + public GetPathRootEndpointTests(LuminaApiFactory apiFactory) + { + _client = apiFactory.CreateClient(); + } + + [Fact] + public async Task ExecuteAsync_WhenCalledWithValidPath_ShouldReturnOkResultWithPathSegmentResponse() + { + // Arrange + string testPath = System.IO.Path.GetTempPath(); + string encodedPath = Uri.EscapeDataString(testPath); + + // Act + HttpResponseMessage response = await _client.GetAsync($"/api/v1/path/get-path-root?path={encodedPath}"); + + // Assert + response.StatusCode.Should().Be(HttpStatusCode.OK); + string content = await response.Content.ReadAsStringAsync(); + PathSegmentResponse? result = JsonSerializer.Deserialize(content, _jsonOptions); + result.Should().NotBeNull(); + result!.Path.Should().NotBeNullOrEmpty(); + } + + [Fact] + public async Task ExecuteAsync_WhenCalledWithInvalidPath_ShouldReturnValidationProblemResult() + { + // Arrange + string invalidPath = "invalid:path"; + string encodedPath = Uri.EscapeDataString(invalidPath); + + // Act + HttpResponseMessage response = await _client.GetAsync($"/api/v1/path/get-path-root?path={encodedPath}"); + + // Assert + response.StatusCode.Should().Be(HttpStatusCode.UnprocessableContent); + response.Content.Headers.ContentType?.MediaType.Should().Be("application/problem+json"); + string content = await response.Content.ReadAsStringAsync(); + Dictionary? problemDetails = JsonSerializer.Deserialize>(content, _jsonOptions); + problemDetails.Should().NotBeNull(); + problemDetails!["status"].GetInt32().Should().Be(StatusCodes.Status422UnprocessableEntity); + problemDetails["title"].GetString().Should().Be("Validation Error"); + problemDetails["instance"].GetString().Should().Be("/api/v1/path/get-path-root"); + problemDetails["detail"].GetString().Should().Be("One or more validation errors occurred."); + problemDetails["type"].GetString().Should().Be("https://tools.ietf.org/html/rfc4918#section-11.2"); + problemDetails["traceId"].GetString().Should().NotBeNullOrWhiteSpace(); + + Dictionary? errors = problemDetails["errors"].Deserialize>(_jsonOptions); + errors.Should().ContainKey("General.Validation").WhoseValue.Should().BeEquivalentTo(["InvalidPath"]); + } + + [Fact] + public async Task ExecuteAsync_WhenCalledWithEmptyPath_ShouldReturnValidationProblemResult() + { + // Arrange + string emptyPath = ""; + string encodedPath = Uri.EscapeDataString(emptyPath); + + // Act + HttpResponseMessage response = await _client.GetAsync($"/api/v1/path/get-path-root?path={encodedPath}"); + + // Assert + response.StatusCode.Should().Be(HttpStatusCode.UnprocessableContent); + response.Content.Headers.ContentType?.MediaType.Should().Be("application/problem+json"); + string content = await response.Content.ReadAsStringAsync(); + Dictionary? problemDetails = JsonSerializer.Deserialize>(content, _jsonOptions); + problemDetails.Should().NotBeNull(); + problemDetails!["status"].GetInt32().Should().Be(StatusCodes.Status422UnprocessableEntity); + problemDetails["title"].GetString().Should().Be("Validation Error"); + problemDetails["instance"].GetString().Should().Be("/api/v1/path/get-path-root"); + problemDetails["detail"].GetString().Should().Be("One or more validation errors occurred."); + problemDetails["type"].GetString().Should().Be("https://tools.ietf.org/html/rfc4918#section-11.2"); + problemDetails["traceId"].GetString().Should().NotBeNullOrWhiteSpace(); + + Dictionary? errors = problemDetails["errors"].Deserialize>(_jsonOptions); + errors.Should().ContainKey("General.Validation").WhoseValue.Should().BeEquivalentTo(["PathCannotBeEmpty"]); + } + + [Fact] + public async Task ExecuteAsync_WhenCalledWithCancellationToken_ShouldCompleteSuccessfully() + { + // Arrange + string testPath = System.IO.Path.GetTempPath(); + string encodedPath = Uri.EscapeDataString(testPath); + using CancellationTokenSource cts = new(TimeSpan.FromSeconds(5)); + + // Act + Func act = async () => await _client.GetAsync($"/api/v1/path/get-path-root?path={encodedPath}", cts.Token); + + // Assert + await act.Should().NotThrowAsync(); + } + + [Fact] + public async Task ExecuteAsync_WhenCancellationTokenIsCancelled_ShouldThrowTaskCanceledException() + { + // Arrange + string testPath = System.IO.Path.GetTempPath(); + string encodedPath = Uri.EscapeDataString(testPath); + using CancellationTokenSource cts = new(); + + // Act + Func act = async () => + { + cts.Cancel(); // Cancel the token immediately + await _client.GetAsync($"/api/v1/path/get-path-root?path={encodedPath}", cts.Token); + }; + + // Assert + await act.Should().ThrowAsync(); + } + +} diff --git a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/FileSystemManagement/Path/GetPathSeparatorEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/FileSystemManagement/Path/GetPathSeparatorEndpointTests.cs new file mode 100644 index 00000000..b1b241d6 --- /dev/null +++ b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/FileSystemManagement/Path/GetPathSeparatorEndpointTests.cs @@ -0,0 +1,105 @@ +#region ========================================================================= USING ===================================================================================== +using FluentAssertions; +using Lumina.Contracts.Responses.FileSystemManagement.Path; +using Lumina.Presentation.Api.IntegrationTests.Common.Setup; +using System; +using System.Diagnostics.CodeAnalysis; +using System.Net; +using System.Net.Http; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Api.IntegrationTests.Core.Endpoints.FileSystemManagement.Path; + +/// +/// Contains integration tests for the class. +/// +[ExcludeFromCodeCoverage] +public class GetPathSeparatorEndpointTests : IClassFixture +{ + private readonly HttpClient _client; + private readonly JsonSerializerOptions _jsonOptions = new() + { + ReferenceHandler = ReferenceHandler.Preserve, + PropertyNameCaseInsensitive = true, + Converters = { new JsonStringEnumConverter(JsonNamingPolicy.CamelCase) } + }; + + /// + /// Initializes a new instance of the class. + /// + /// Injected in-memory API factory. + public GetPathSeparatorEndpointTests(LuminaApiFactory apiFactory) + { + _client = apiFactory.CreateClient(); + } + + [Fact] + public async Task ExecuteAsync_WhenCalled_ShouldReturnOkResultWithPathSeparatorResponse() + { + // Act + HttpResponseMessage response = await _client.GetAsync("/api/v1/path/get-path-separator"); + + // Assert + response.StatusCode.Should().Be(HttpStatusCode.OK); + string content = await response.Content.ReadAsStringAsync(); + PathSeparatorResponse? result = JsonSerializer.Deserialize(content, _jsonOptions); + result.Should().NotBeNull(); + result!.Separator.Should().BeOneOf("/", "\\"); + } + + [Fact] + public async Task ExecuteAsync_WhenCalledMultipleTimes_ShouldReturnConsistentResults() + { + // Act + HttpResponseMessage response1 = await _client.GetAsync("/api/v1/path/get-path-separator"); + HttpResponseMessage response2 = await _client.GetAsync("/api/v1/path/get-path-separator"); + + // Assert + response1.StatusCode.Should().Be(HttpStatusCode.OK); + response2.StatusCode.Should().Be(HttpStatusCode.OK); + + string content1 = await response1.Content.ReadAsStringAsync(); + string content2 = await response2.Content.ReadAsStringAsync(); + + PathSeparatorResponse? result1 = JsonSerializer.Deserialize(content1, _jsonOptions); + PathSeparatorResponse? result2 = JsonSerializer.Deserialize(content2, _jsonOptions); + + result1.Should().NotBeNull(); + result2.Should().NotBeNull(); + result1.Should().BeEquivalentTo(result2); + } + + [Fact] + public async Task ExecuteAsync_WhenCalledWithCancellationToken_ShouldCompleteSuccessfully() + { + // Arrange + using CancellationTokenSource cts = new(TimeSpan.FromSeconds(5)); + + // Act + Func act = async () => await _client.GetAsync("/api/v1/path/get-path-separator", cts.Token); + + // Assert + await act.Should().NotThrowAsync(); + } + + [Fact] + public async Task ExecuteAsync_WhenCancellationTokenIsCancelled_ShouldThrowTaskCanceledException() + { + // Arrange + using CancellationTokenSource cts = new(); + + // Act + Func act = async () => + { + cts.Cancel(); // Cancel the token immediately + await _client.GetAsync("/api/v1/path/get-path-separator", cts.Token); + }; + + // Assert + await act.Should().ThrowAsync(); + } +} diff --git a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/FileSystemManagement/Path/SplitPathEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/FileSystemManagement/Path/SplitPathEndpointTests.cs new file mode 100644 index 00000000..41b9fe0e --- /dev/null +++ b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/FileSystemManagement/Path/SplitPathEndpointTests.cs @@ -0,0 +1,132 @@ +#region ========================================================================= USING ===================================================================================== +using FluentAssertions; +using Lumina.Contracts.Responses.FileSystemManagement.Path; +using Lumina.Presentation.Api.IntegrationTests.Common.Setup; +using Microsoft.AspNetCore.Http; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +using System.Net; +using System.Net.Http; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Api.IntegrationTests.Core.Endpoints.FileSystemManagement.Path; + +/// +/// Contains integration tests for the class. +/// +[ExcludeFromCodeCoverage] +public class SplitPathEndpointTests : IClassFixture +{ + private readonly HttpClient _client; + private readonly JsonSerializerOptions _jsonOptions = new() + { + ReferenceHandler = ReferenceHandler.Preserve, + PropertyNameCaseInsensitive = true, + Converters = { new JsonStringEnumConverter(JsonNamingPolicy.CamelCase) } + }; + + /// + /// Initializes a new instance of the class. + /// + /// Injected in-memory API factory. + public SplitPathEndpointTests(LuminaApiFactory apiFactory) + { + _client = apiFactory.CreateClient(); + } + + [Fact] + public async Task ExecuteAsync_WhenCalledWithValidPath_ShouldReturnOkResultWithSplitSegments() + { + // Arrange + string tempPath = System.IO.Path.GetTempPath(); + string testPath = System.IO.Path.Combine(tempPath, "testFolder", "testFile.txt"); + + // Act + HttpResponseMessage response = await _client.GetAsync($"/api/v1/path/split?path={Uri.EscapeDataString(testPath)}"); + + // Assert + response.StatusCode.Should().Be(HttpStatusCode.OK); + string content = await response.Content.ReadAsStringAsync(); + IEnumerable? result = JsonSerializer.Deserialize>(content, _jsonOptions); + result.Should().NotBeNull(); + result!.Should().HaveCountGreaterThanOrEqualTo(3); + result!.Select(r => r.Path).Should().Contain(["testFolder", "testFile.txt"]); + } + + [Fact] + public async Task ExecuteAsync_WhenCalledWithEmptyPath_ShouldReturnValidationProblemResult() + { + // Arrange + string path = ""; + + // Act + HttpResponseMessage response = await _client.GetAsync($"/api/v1/path/split?path={Uri.EscapeDataString(path)}"); + + // Assert + response.StatusCode.Should().Be(HttpStatusCode.UnprocessableContent); + response.Content.Headers.ContentType?.MediaType.Should().Be("application/problem+json"); + string content = await response.Content.ReadAsStringAsync(); + Dictionary? problemDetails = JsonSerializer.Deserialize>(content, _jsonOptions); + problemDetails.Should().NotBeNull(); + problemDetails!["status"].GetInt32().Should().Be(StatusCodes.Status422UnprocessableEntity); + problemDetails["title"].GetString().Should().Be("Validation Error"); + problemDetails["instance"].GetString().Should().Be("/api/v1/path/split"); + problemDetails["detail"].GetString().Should().Be("One or more validation errors occurred."); + problemDetails["type"].GetString().Should().Be("https://tools.ietf.org/html/rfc4918#section-11.2"); + problemDetails["traceId"].GetString().Should().NotBeNullOrWhiteSpace(); + + Dictionary? errors = problemDetails["errors"].Deserialize>(_jsonOptions); + errors.Should().ContainKey("General.Validation").WhoseValue.Should().BeEquivalentTo(["PathCannotBeEmpty"]); + } + + [Fact] + public async Task ExecuteAsync_WhenCalledWithInvalidPath_ShouldReturnProblemDetails() + { + // Arrange + string path = "invalid:path"; + + // Act + HttpResponseMessage response = await _client.GetAsync($"/api/v1/path/split?path={Uri.EscapeDataString(path)}"); + + // Assert + response.StatusCode.Should().Be(HttpStatusCode.UnprocessableContent); + response.Content.Headers.ContentType?.MediaType.Should().Be("application/problem+json"); + string content = await response.Content.ReadAsStringAsync(); + Dictionary? problemDetails = JsonSerializer.Deserialize>(content, _jsonOptions); + problemDetails.Should().NotBeNull(); + problemDetails!["status"].GetInt32().Should().Be(StatusCodes.Status422UnprocessableEntity); + problemDetails["title"].GetString().Should().Be("Validation Error"); + problemDetails["instance"].GetString().Should().Be("/api/v1/path/split"); + problemDetails["detail"].GetString().Should().Be("One or more validation errors occurred."); + problemDetails["type"].GetString().Should().Be("https://tools.ietf.org/html/rfc4918#section-11.2"); + problemDetails["traceId"].GetString().Should().NotBeNullOrWhiteSpace(); + + Dictionary? errors = problemDetails["errors"].Deserialize>(_jsonOptions); + errors.Should().ContainKey("General.Validation").WhoseValue.Should().BeEquivalentTo(["InvalidPath"]); + } + + [Fact] + public async Task ExecuteAsync_WhenCancellationTokenIsCancelled_ShouldThrowTaskCanceledException() + { + // Arrange + string testPath = System.IO.Path.Combine(System.IO.Path.GetTempPath(), "testDirectory"); + string encodedPath = Uri.EscapeDataString(testPath); + using CancellationTokenSource cts = new(); + + // Act + Func act = async () => + { + cts.Cancel(); // Cancel the token immediately + await _client.GetAsync($"/api/v1/path/split?path={encodedPath}", cts.Token); + }; + + // Assert + await act.Should().ThrowAsync(); + } +} diff --git a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/FileSystemManagement/Path/ValidatePathEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/FileSystemManagement/Path/ValidatePathEndpointTests.cs new file mode 100644 index 00000000..ddc0202f --- /dev/null +++ b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/FileSystemManagement/Path/ValidatePathEndpointTests.cs @@ -0,0 +1,110 @@ +#region ========================================================================= USING ===================================================================================== +using FluentAssertions; +using Lumina.Contracts.Responses.FileSystemManagement.Path; +using Lumina.Presentation.Api.IntegrationTests.Common.Setup; +using System; +using System.Diagnostics.CodeAnalysis; +using System.Net; +using System.Net.Http; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Api.IntegrationTests.Core.Endpoints.FileSystemManagement.Path; + +/// +/// Contains integration tests for the class. +/// +[ExcludeFromCodeCoverage] +public class ValidatePathEndpointTests : IClassFixture +{ + private readonly HttpClient _client; + private readonly JsonSerializerOptions _jsonOptions = new() + { + ReferenceHandler = ReferenceHandler.Preserve, + PropertyNameCaseInsensitive = true, + Converters = { new JsonStringEnumConverter(JsonNamingPolicy.CamelCase) } + }; + + /// + /// Initializes a new instance of the class. + /// + /// Injected in-memory API factory. + public ValidatePathEndpointTests(LuminaApiFactory apiFactory) + { + _client = apiFactory.CreateClient(); + } + + [Fact] + public async Task ExecuteAsync_WhenCalledWithValidPath_ShouldReturnOkResultWithIsValidTrue() + { + // Arrange + string tempPath = System.IO.Path.GetTempPath(); + string testPath = System.IO.Path.Combine(tempPath, "testFolder", "testFile.txt"); + + // Act + HttpResponseMessage response = await _client.GetAsync($"/api/v1/path/validate?path={Uri.EscapeDataString(testPath)}"); + + // Assert + response.StatusCode.Should().Be(HttpStatusCode.OK); + string content = await response.Content.ReadAsStringAsync(); + PathValidResponse? result = JsonSerializer.Deserialize(content, _jsonOptions); + result.Should().NotBeNull(); + result!.IsValid.Should().BeTrue(); + } + + [Fact] + public async Task ExecuteAsync_WhenCalledWithInvalidPath_ShouldReturnOkResultWithIsValidFalse() + { + // Arrange + string invalidPath = "invalid:path"; + + // Act + HttpResponseMessage response = await _client.GetAsync($"/api/v1/path/validate?path={Uri.EscapeDataString(invalidPath)}"); + + // Assert + response.StatusCode.Should().Be(HttpStatusCode.OK); + string content = await response.Content.ReadAsStringAsync(); + PathValidResponse? result = JsonSerializer.Deserialize(content, _jsonOptions); + result.Should().NotBeNull(); + result!.IsValid.Should().BeFalse(); + } + + [Fact] + public async Task ExecuteAsync_WhenCalledWithEmptyPath_ShouldReturnOkResultWithIsValidFalse() + { + // Arrange + string path = ""; + + // Act + HttpResponseMessage response = await _client.GetAsync($"/api/v1/path/validate?path={Uri.EscapeDataString(path)}"); + + // Assert + response.StatusCode.Should().Be(HttpStatusCode.OK); + string content = await response.Content.ReadAsStringAsync(); + PathValidResponse? result = JsonSerializer.Deserialize(content, _jsonOptions); + result.Should().NotBeNull(); + result!.IsValid.Should().BeFalse(); + } + + [Fact] + public async Task ExecuteAsync_WhenCancellationTokenIsCancelled_ShouldThrowTaskCanceledException() + { + // Arrange + string testPath = System.IO.Path.Combine(System.IO.Path.GetTempPath(), "testDirectory"); + string encodedPath = Uri.EscapeDataString(testPath); + using CancellationTokenSource cts = new(); + + // Act + Func act = async () => + { + cts.Cancel(); // Cancel the token immediately + await _client.GetAsync($"/api/v1/path/validate?path={encodedPath}", cts.Token); + }; + + // Assert + await act.Should().ThrowAsync(); + } +} diff --git a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/FileSystemManagement/Thumbnails/GetThumbnailEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/FileSystemManagement/Thumbnails/GetThumbnailEndpointTests.cs new file mode 100644 index 00000000..67a97b4d --- /dev/null +++ b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/FileSystemManagement/Thumbnails/GetThumbnailEndpointTests.cs @@ -0,0 +1,155 @@ +#region ========================================================================= USING ===================================================================================== +using FluentAssertions; +using Lumina.Presentation.Api.IntegrationTests.Common.Setup; +using Lumina.Presentation.Api.IntegrationTests.Core.Endpoints.FileSystemManagement.Fixtures; +using Microsoft.AspNetCore.Http; +using System; +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; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Api.IntegrationTests.Core.Endpoints.FileSystemManagement.Thumbnails; + +/// +/// Contains integration tests for the class. +/// +[ExcludeFromCodeCoverage] +public class GetThumbnailEndpointTests : IClassFixture, IClassFixture +{ + private readonly HttpClient _client; + private readonly JsonSerializerOptions _jsonOptions = new() + { + ReferenceHandler = ReferenceHandler.Preserve, + PropertyNameCaseInsensitive = true, + Converters = { new JsonStringEnumConverter(JsonNamingPolicy.CamelCase) } + }; + private readonly string _testImagePath; + + /// + /// Initializes a new instance of the class. + /// + /// Injected in-memory API factory. + /// Fixture for creating and managing test images. + public GetThumbnailEndpointTests(LuminaApiFactory apiFactory, TestImageFixture imageFixture) + { + _client = apiFactory.CreateClient(); + _testImagePath = imageFixture.ImagePath; + } + + [Fact] + public async Task ExecuteAsync_WhenCalledWithValidPathAndQuality_ShouldReturnOkResultWithThumbnail() + { + // Arrange + int quality = 80; + + // Act + HttpResponseMessage response = await _client.GetAsync($"/api/v1/thumbnails/get-thumbnail?path={Uri.EscapeDataString(_testImagePath)}&quality={quality}"); + + // Assert + response.StatusCode.Should().Be(HttpStatusCode.OK); + response.Content.Headers.ContentType!.MediaType.Should().Be("image/jpeg"); + byte[] content = await response.Content.ReadAsByteArrayAsync(); + content.Should().NotBeEmpty(); + } + + [Fact] + public async Task ExecuteAsync_WhenCalledWithInvalidPath_ShouldReturnForbiddenResult() + { + // Arrange + string invalidImagePath = "/path/to/nonexistent/image.jpg"; + int quality = 80; + + // Act + HttpResponseMessage response = await _client.GetAsync($"/api/v1/thumbnails/get-thumbnail?path={Uri.EscapeDataString(invalidImagePath)}&quality={quality}"); + + // Assert + response.StatusCode.Should().Be(HttpStatusCode.Forbidden); + string content = await response.Content.ReadAsStringAsync(); + + Dictionary? problemDetails = JsonSerializer.Deserialize>(content, _jsonOptions); + problemDetails.Should().NotBeNull(); + problemDetails!["status"].GetInt32().Should().Be(StatusCodes.Status403Forbidden); + problemDetails["title"].GetString().Should().Be("General.Failure"); + problemDetails["instance"].GetString().Should().Be("/api/v1/thumbnails/get-thumbnail"); + problemDetails["detail"].GetString().Should().Be("UnauthorizedAccess"); + problemDetails["type"].GetString().Should().Be("https://tools.ietf.org/html/rfc9110#section-15.5.4"); + problemDetails["traceId"].GetString().Should().NotBeNullOrWhiteSpace(); + } + + [Fact] + public async Task ExecuteAsync_WhenCalledWithEmptyPath_ShouldReturnValidationProblemResult() + { + // Arrange + string invalidImagePath = ""; + int quality = 80; + + // Act + HttpResponseMessage response = await _client.GetAsync($"/api/v1/thumbnails/get-thumbnail?path={Uri.EscapeDataString(invalidImagePath)}&quality={quality}"); + + // Assert + response.StatusCode.Should().Be(HttpStatusCode.UnprocessableContent); + response.Content.Headers.ContentType?.MediaType.Should().Be("application/problem+json"); + string content = await response.Content.ReadAsStringAsync(); + Dictionary? problemDetails = JsonSerializer.Deserialize>(content, _jsonOptions); + problemDetails.Should().NotBeNull(); + problemDetails!["status"].GetInt32().Should().Be(StatusCodes.Status422UnprocessableEntity); + problemDetails["title"].GetString().Should().Be("Validation Error"); + problemDetails["instance"].GetString().Should().Be("/api/v1/thumbnails/get-thumbnail"); + problemDetails["detail"].GetString().Should().Be("One or more validation errors occurred."); + problemDetails["type"].GetString().Should().Be("https://tools.ietf.org/html/rfc4918#section-11.2"); + problemDetails["traceId"].GetString().Should().NotBeNullOrWhiteSpace(); + + Dictionary? errors = problemDetails["errors"].Deserialize>(_jsonOptions); + errors.Should().ContainKey("General.Validation").WhoseValue.Should().BeEquivalentTo(["PathCannotBeEmpty"]); + } + + [Fact] + public async Task ExecuteAsync_WhenCalledWithInvalidQuality_ShouldReturnValidationProblemResult() + { + // Arrange + int invalidQuality = -1; + + // Act + HttpResponseMessage response = await _client.GetAsync($"/api/v1/thumbnails/get-thumbnail?path={Uri.EscapeDataString(_testImagePath)}&quality={invalidQuality}"); + + // Assert + response.StatusCode.Should().Be(HttpStatusCode.UnprocessableContent); + response.Content.Headers.ContentType?.MediaType.Should().Be("application/problem+json"); + string content = await response.Content.ReadAsStringAsync(); + Dictionary? problemDetails = JsonSerializer.Deserialize>(content, _jsonOptions); + problemDetails.Should().NotBeNull(); + problemDetails!["status"].GetInt32().Should().Be(StatusCodes.Status422UnprocessableEntity); + problemDetails["title"].GetString().Should().Be("Validation Error"); + problemDetails["instance"].GetString().Should().Be("/api/v1/thumbnails/get-thumbnail"); + problemDetails["detail"].GetString().Should().Be("One or more validation errors occurred."); + problemDetails["type"].GetString().Should().Be("https://tools.ietf.org/html/rfc4918#section-11.2"); + problemDetails["traceId"].GetString().Should().NotBeNullOrWhiteSpace(); + + Dictionary? errors = problemDetails["errors"].Deserialize>(_jsonOptions); + errors.Should().ContainKey("General.Validation").WhoseValue.Should().BeEquivalentTo(["ImageQaulityMustBeBetweenZeroAndOneHundred"]); + } + + [Fact] + public async Task ExecuteAsync_WhenCancellationTokenIsCancelled_ShouldThrowTaskCanceledException() + { + // Arrange + int quality = 80; + using CancellationTokenSource cts = new(); + + // Act + Func act = async () => + { + cts.Cancel(); // Cancel the token immediately + await _client.GetAsync($"/api/v1/thumbnails/get-thumbnail?path={Uri.EscapeDataString(_testImagePath)}&quality={quality}", cts.Token); + }; + + // Assert + await act.Should().ThrowAsync(); + } +} diff --git a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Controllers/WrittenContentLibrary/BookLibrary/Books/BooksControllerTests.cs b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/WrittenContentLibrary/BookLibrary/Books/AddBookEndpointTests.cs similarity index 75% rename from tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Controllers/WrittenContentLibrary/BookLibrary/Books/BooksControllerTests.cs rename to tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/WrittenContentLibrary/BookLibrary/Books/AddBookEndpointTests.cs index 936fe778..12460b0b 100644 --- a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Controllers/WrittenContentLibrary/BookLibrary/Books/BooksControllerTests.cs +++ b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/WrittenContentLibrary/BookLibrary/Books/AddBookEndpointTests.cs @@ -1,14 +1,9 @@ #region ========================================================================= USING ===================================================================================== -using Bogus; using FluentAssertions; -using Lumina.Contracts.Enums.BookLibrary; -using Lumina.Contracts.Requests.WrittenContentLibrary.BookLibrary; -using Lumina.Domain.Common.Errors; using Lumina.Domain.Core.Aggregates.WrittenContentLibrary.BookLibraryAggregate; -using Lumina.Presentation.Api.IntegrationTests.Common.Converters; using Lumina.Presentation.Api.IntegrationTests.Common.Setup; -using Lumina.Presentation.Api.IntegrationTests.Core.Controllers.Books.Fixtures; -using Microsoft.AspNetCore.Mvc; +using Lumina.Presentation.Api.IntegrationTests.Core.Endpoints.WrittenContentLibrary.BookLibrary.Books.Fixtures; +using Microsoft.AspNetCore.Http; using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; @@ -17,48 +12,43 @@ using System.Net; using System.Net.Http; using System.Net.Http.Json; using System.Text.Json; +using System.Text.Json.Serialization; using System.Threading.Tasks; +using Lumina.Domain.Common.Errors; +using Bogus; +using Lumina.Contracts.Enums.BookLibrary; +using Lumina.Contracts.Requests.WrittenContentLibrary.BookLibrary.Books; +using Lumina.Presentation.Api.IntegrationTests.Common.Converters; #endregion -namespace Lumina.Presentation.Api.IntegrationTests.Core.Controllers.WrittenContentLibrary.BookLibrary.Books; +namespace Lumina.Presentation.Api.IntegrationTests.Core.Endpoints.WrittenContentLibrary.BookLibrary.Books; /// -/// Contains integration tests for the class. +/// Contains integration tests for the class. /// [ExcludeFromCodeCoverage] -public class BooksControllerTests : IClassFixture +public class AddBookEndpointTests : IClassFixture { - private readonly LuminaApiFactory _apiFactory; private readonly HttpClient _client; + private readonly JsonSerializerOptions _jsonOptions = new() + { + ReferenceHandler = ReferenceHandler.Preserve, + PropertyNameCaseInsensitive = true, + Converters = { + new JsonStringEnumConverter(JsonNamingPolicy.CamelCase), + new BookJsonConverter() + } + }; private readonly AddBookRequestFixture _requestBookFixture; - private readonly JsonSerializerOptions _jsonOptions = new(); /// - /// Initializes a new instance of the class. + /// Initializes a new instance of the class. /// /// Injected in-memory API factory. - public BooksControllerTests(LuminaApiFactory apiFactory) + public AddBookEndpointTests(LuminaApiFactory apiFactory) { - _apiFactory = apiFactory; - _client = _apiFactory.CreateClient(); + _client = apiFactory.CreateClient(); _requestBookFixture = new AddBookRequestFixture(); - _jsonOptions.Converters.Add(new BookJsonConverter()); - } - - [Fact] - public async Task GetBooks_WhenCalled_ShouldReturnBooks() - { - // Arrange - HttpResponseMessage response = await _client.GetAsync("/api/v1/books"); - - // Act - response.EnsureSuccessStatusCode(); - - // Assert - response.EnsureSuccessStatusCode(); - response.StatusCode.Should().Be(HttpStatusCode.OK); - Book[]? bookResponse = await response.Content.ReadFromJsonAsync(_jsonOptions); - bookResponse.Should().NotBeNull(); } [Fact] @@ -68,7 +58,7 @@ public class BooksControllerTests : IClassFixture AddBookRequest bookRequest = _requestBookFixture.CreateRequestBook(); // Act - HttpResponseMessage response = await _client.PostAsJsonAsync("api/v1/books", bookRequest); + HttpResponseMessage response = await _client.PostAsJsonAsync("/api/v1/books", bookRequest); // Assert response.EnsureSuccessStatusCode(); @@ -151,7 +141,7 @@ public class BooksControllerTests : IClassFixture // check Location header response.Headers.Location.Should().NotBeNull(); string locationUri = response.Headers.Location!.ToString(); - locationUri.Should().StartWith("/api/v1/books/"); + locationUri.Should().EndWith("/api/v1/books/" + bookResponse.Id.Value); // extract ID from Location header string idFromHeader = locationUri.Split('/').Last(); @@ -161,31 +151,31 @@ public class BooksControllerTests : IClassFixture } [Fact] - public async Task AddBook_WhenCalledWithEmptyTitle_ShouldReturnBadRequest() + public async Task AddBook_WhenCalledWithEmptyTitle_ShouldReturnUnprocessableEntity() { // Arrange AddBookRequest bookRequest = _requestBookFixture.CreateRequestBook(); bookRequest = bookRequest with { Metadata = bookRequest.Metadata! with { Title = null! } }; // Act - HttpResponseMessage response = await _client.PostAsJsonAsync("api/v1/books", bookRequest); + HttpResponseMessage response = await _client.PostAsJsonAsync("/api/v1/books", bookRequest); // Assert - await AssertBadRequestWithValidationErrors(response, Errors.Metadata.TitleCannotBeEmpty.Code); + await AssertUnprocessableEntityWithValidationErrors(response, Errors.Metadata.TitleCannotBeEmpty.Description); } [Fact] - public async Task AddBook_WhenCalledWithInvalidLengthTitle_ShouldReturnBadRequest() + public async Task AddBook_WhenCalledWithInvalidLengthTitle_ShouldReturnUnprocessableEntity() { // Arrange AddBookRequest bookRequest = _requestBookFixture.CreateRequestBook(); bookRequest = bookRequest with { Metadata = bookRequest.Metadata! with { Title = new Faker().Random.String2(300) } }; // Act - HttpResponseMessage response = await _client.PostAsJsonAsync("api/v1/books", bookRequest); + HttpResponseMessage response = await _client.PostAsJsonAsync("/api/v1/books", bookRequest); // Assert - await AssertBadRequestWithValidationErrors(response, Errors.Metadata.TitleMustBeMaximum255CharactersLong.Code); + await AssertUnprocessableEntityWithValidationErrors(response, Errors.Metadata.TitleMustBeMaximum255CharactersLong.Description); } [Fact] @@ -200,17 +190,17 @@ public class BooksControllerTests : IClassFixture } [Fact] - public async Task AddBook_WhenCalledWithInvalidLengthOriginalTitle_ShouldReturnBadRequest() + public async Task AddBook_WhenCalledWithInvalidLengthOriginalTitle_ShouldReturnUnprocessableEntity() { // Arrange AddBookRequest bookRequest = _requestBookFixture.CreateRequestBook(); bookRequest = bookRequest with { Metadata = bookRequest.Metadata! with { OriginalTitle = new Faker().Random.String2(300) } }; // Act - HttpResponseMessage response = await _client.PostAsJsonAsync("api/v1/books", bookRequest); + HttpResponseMessage response = await _client.PostAsJsonAsync("/api/v1/books", bookRequest); // Assert - await AssertBadRequestWithValidationErrors(response, Errors.Metadata.OriginalTitleMustBeMaximum255CharactersLong.Code); + await AssertUnprocessableEntityWithValidationErrors(response, Errors.Metadata.OriginalTitleMustBeMaximum255CharactersLong.Description); } [Fact] @@ -225,31 +215,31 @@ public class BooksControllerTests : IClassFixture } [Fact] - public async Task AddBook_WhenCalledWithInvalidLengthDescription_ShouldReturnBadRequest() + public async Task AddBook_WhenCalledWithInvalidLengthDescription_ShouldReturnUnprocessableEntity() { // Arrange AddBookRequest bookRequest = _requestBookFixture.CreateRequestBook(); bookRequest = bookRequest with { Metadata = bookRequest.Metadata! with { Description = new Faker().Random.String2(2001) } }; // Act - HttpResponseMessage response = await _client.PostAsJsonAsync("api/v1/books", bookRequest); + HttpResponseMessage response = await _client.PostAsJsonAsync("/api/v1/books", bookRequest); // Assert - await AssertBadRequestWithValidationErrors(response, Errors.Metadata.DescriptionMustBeMaximum2000CharactersLong.Code); + await AssertUnprocessableEntityWithValidationErrors(response, Errors.Metadata.DescriptionMustBeMaximum2000CharactersLong.Description); } [Fact] - public async Task AddBook_WhenCalledWithNullReleaseInfo_ShouldReturnBadRequest() + public async Task AddBook_WhenCalledWithNullReleaseInfo_ShouldReturnUnprocessableEntity() { // Arrange AddBookRequest bookRequest = _requestBookFixture.CreateRequestBook(); bookRequest = bookRequest with { Metadata = bookRequest.Metadata! with { ReleaseInfo = null! } }; // Act - HttpResponseMessage response = await _client.PostAsJsonAsync("api/v1/books", bookRequest); + HttpResponseMessage response = await _client.PostAsJsonAsync("/api/v1/books", bookRequest); // Assert - await AssertBadRequestWithValidationErrors(response, Errors.Metadata.ReleaseInfoCannotBeNull.Code); + await AssertUnprocessableEntityWithValidationErrors(response, Errors.Metadata.ReleaseInfoCannotBeNull.Description); } [Fact] @@ -264,17 +254,17 @@ public class BooksControllerTests : IClassFixture } [Fact] - public async Task AddBook_WhenCalledWithInvalidValueOriginalReleaseYear_ShouldReturnBadRequest() + public async Task AddBook_WhenCalledWithInvalidValueOriginalReleaseYear_ShouldReturnUnprocessableEntity() { // Arrange AddBookRequest bookRequest = _requestBookFixture.CreateRequestBook(); bookRequest = bookRequest with { Metadata = bookRequest.Metadata! with { ReleaseInfo = bookRequest.Metadata.ReleaseInfo! with { OriginalReleaseYear = 10000 } } }; // Act - HttpResponseMessage response = await _client.PostAsJsonAsync("api/v1/books", bookRequest); + HttpResponseMessage response = await _client.PostAsJsonAsync("/api/v1/books", bookRequest); // Assert - await AssertBadRequestWithValidationErrors(response, Errors.Metadata.OriginalReleaseYearMustBeBetween1And9999.Code); + await AssertUnprocessableEntityWithValidationErrors(response, Errors.Metadata.OriginalReleaseYearMustBeBetween1And9999.Description); } [Fact] @@ -289,7 +279,7 @@ public class BooksControllerTests : IClassFixture } [Fact] - public async Task AddBook_WhenCalledWithInvalidValueReReleaseYear_ShouldReturnBadRequest() + public async Task AddBook_WhenCalledWithInvalidValueReReleaseYear_ShouldReturnUnprocessableEntity() { // Arrange AddBookRequest bookRequest = _requestBookFixture.CreateRequestBook(); @@ -304,10 +294,10 @@ public class BooksControllerTests : IClassFixture }; // Act - HttpResponseMessage response = await _client.PostAsJsonAsync("api/v1/books", bookRequest); + HttpResponseMessage response = await _client.PostAsJsonAsync("/api/v1/books", bookRequest); // Assert - await AssertBadRequestWithValidationErrors(response, Errors.Metadata.ReReleaseYearMustBeBetween1And9999.Code); + await AssertUnprocessableEntityWithValidationErrors(response, Errors.Metadata.ReReleaseYearMustBeBetween1And9999.Description); } [Fact] @@ -322,7 +312,7 @@ public class BooksControllerTests : IClassFixture } [Fact] - public async Task AddBook_WhenCalledWithInvalidValueReleaseCountry_ShouldReturnBadRequest() + public async Task AddBook_WhenCalledWithInvalidValueReleaseCountry_ShouldReturnUnprocessableEntity() { // Arrange AddBookRequest bookRequest = _requestBookFixture.CreateRequestBook(); @@ -335,10 +325,10 @@ public class BooksControllerTests : IClassFixture }; // Act - HttpResponseMessage response = await _client.PostAsJsonAsync("api/v1/books", bookRequest); + HttpResponseMessage response = await _client.PostAsJsonAsync("/api/v1/books", bookRequest); // Assert - await AssertBadRequestWithValidationErrors(response, Errors.Metadata.CountryCodeMustBe2CharactersLong.Code); + await AssertUnprocessableEntityWithValidationErrors(response, Errors.Metadata.CountryCodeMustBe2CharactersLong.Description); } [Fact] @@ -353,7 +343,7 @@ public class BooksControllerTests : IClassFixture } [Fact] - public async Task AddBook_WhenCalledWithInvalidValueReleasVersion_ShouldReturnBadRequest() + public async Task AddBook_WhenCalledWithInvalidValueReleasVersion_ShouldReturnUnprocessableEntity() { // Arrange AddBookRequest bookRequest = _requestBookFixture.CreateRequestBook(); @@ -366,10 +356,10 @@ public class BooksControllerTests : IClassFixture }; // Act - HttpResponseMessage response = await _client.PostAsJsonAsync("api/v1/books", bookRequest); + HttpResponseMessage response = await _client.PostAsJsonAsync("/api/v1/books", bookRequest); // Assert - await AssertBadRequestWithValidationErrors(response, Errors.Metadata.ReleaseVersionMustBeMaximum50CharactersLong.Code); + await AssertUnprocessableEntityWithValidationErrors(response, Errors.Metadata.ReleaseVersionMustBeMaximum50CharactersLong.Description); } [Fact] @@ -392,7 +382,7 @@ public class BooksControllerTests : IClassFixture } [Fact] - public async Task AddBook_WhenReReleaseYearIsBeforeReleaseYear_ShouldReturnBadRequest() + public async Task AddBook_WhenReReleaseYearIsBeforeReleaseYear_ShouldReturnUnprocessableEntity() { // Arrange AddBookRequest bookRequest = _requestBookFixture.CreateRequestBook(); @@ -407,10 +397,10 @@ public class BooksControllerTests : IClassFixture }; // Act - HttpResponseMessage response = await _client.PostAsJsonAsync("api/v1/books", bookRequest); + HttpResponseMessage response = await _client.PostAsJsonAsync("/api/v1/books", bookRequest); // Assert - await AssertBadRequestWithValidationErrors(response, Errors.Metadata.ReReleaseYearCannotBeEarlierThanOriginalReleaseYear.Code); + await AssertUnprocessableEntityWithValidationErrors(response, Errors.Metadata.ReReleaseYearCannotBeEarlierThanOriginalReleaseYear.Description); } [Fact] @@ -433,7 +423,7 @@ public class BooksControllerTests : IClassFixture } [Fact] - public async Task AddBook_WhenReReleaseDateIsBeforeReleaseDate_ShouldReturnBadRequest() + public async Task AddBook_WhenReReleaseDateIsBeforeReleaseDate_ShouldReturnUnprocessableEntity() { // Arrange AddBookRequest bookRequest = _requestBookFixture.CreateRequestBook(); @@ -448,28 +438,28 @@ public class BooksControllerTests : IClassFixture }; // Act - HttpResponseMessage response = await _client.PostAsJsonAsync("api/v1/books", bookRequest); + HttpResponseMessage response = await _client.PostAsJsonAsync("/api/v1/books", bookRequest); // Assert - await AssertBadRequestWithValidationErrors(response, Errors.Metadata.ReReleaseDateCannotBeEarlierThanOriginalReleaseDate.Code); + await AssertUnprocessableEntityWithValidationErrors(response, Errors.Metadata.ReReleaseDateCannotBeEarlierThanOriginalReleaseDate.Description); } [Fact] - public async Task AddBook_WhenCalledWithNullGenres_ShouldReturnBadRequest() + public async Task AddBook_WhenCalledWithNullGenres_ShouldReturnUnprocessableEntity() { // Arrange AddBookRequest bookRequest = _requestBookFixture.CreateRequestBook(); bookRequest = bookRequest with { Metadata = bookRequest.Metadata! with { Genres = null! } }; // Act - HttpResponseMessage response = await _client.PostAsJsonAsync("api/v1/books", bookRequest); + HttpResponseMessage response = await _client.PostAsJsonAsync("/api/v1/books", bookRequest); // Assert - await AssertBadRequestWithValidationErrors(response, Errors.Metadata.GenresListCannotBeNull.Code); + await AssertUnprocessableEntityWithValidationErrors(response, Errors.Metadata.GenresListCannotBeNull.Description); } [Fact] - public async Task AddBook_WhenCalledWithEmptyGenreName_ShouldReturnBadRequest() + public async Task AddBook_WhenCalledWithEmptyGenreName_ShouldReturnUnprocessableEntity() { // Arrange AddBookRequest bookRequest = _requestBookFixture.CreateRequestBook(); @@ -482,14 +472,14 @@ public class BooksControllerTests : IClassFixture }; // Act - HttpResponseMessage response = await _client.PostAsJsonAsync("api/v1/books", bookRequest); + HttpResponseMessage response = await _client.PostAsJsonAsync("/api/v1/books", bookRequest); // Assert - await AssertBadRequestWithValidationErrors(response, Errors.Metadata.GenreNameCannotBeEmpty.Code); + await AssertUnprocessableEntityWithValidationErrors(response, Errors.Metadata.GenreNameCannotBeEmpty.Description); } [Fact] - public async Task AddBook_WhenCalledWithInvalidLengthGenreName_ShouldReturnBadRequest() + public async Task AddBook_WhenCalledWithInvalidLengthGenreName_ShouldReturnUnprocessableEntity() { // Arrange AddBookRequest bookRequest = _requestBookFixture.CreateRequestBook(); @@ -501,28 +491,28 @@ public class BooksControllerTests : IClassFixture } }; // Act - HttpResponseMessage response = await _client.PostAsJsonAsync("api/v1/books", bookRequest); + HttpResponseMessage response = await _client.PostAsJsonAsync("/api/v1/books", bookRequest); // Assert - await AssertBadRequestWithValidationErrors(response, Errors.Metadata.GenreNameMustBeMaximum50CharactersLong.Code); + await AssertUnprocessableEntityWithValidationErrors(response, Errors.Metadata.GenreNameMustBeMaximum50CharactersLong.Description); } [Fact] - public async Task AddBook_WhenCalledWithNullTags_ShouldReturnBadRequest() + public async Task AddBook_WhenCalledWithNullTags_ShouldReturnUnprocessableEntity() { // Arrange AddBookRequest bookRequest = _requestBookFixture.CreateRequestBook(); bookRequest = bookRequest with { Metadata = bookRequest.Metadata! with { Tags = null! } }; // Act - HttpResponseMessage response = await _client.PostAsJsonAsync("api/v1/books", bookRequest); + HttpResponseMessage response = await _client.PostAsJsonAsync("/api/v1/books", bookRequest); // Assert - await AssertBadRequestWithValidationErrors(response, Errors.Metadata.TagsListCannotBeNull.Code); + await AssertUnprocessableEntityWithValidationErrors(response, Errors.Metadata.TagsListCannotBeNull.Description); } [Fact] - public async Task AddBook_WhenCalledWithEmptyTagName_ShouldReturnBadRequest() + public async Task AddBook_WhenCalledWithEmptyTagName_ShouldReturnUnprocessableEntity() { // Arrange AddBookRequest bookRequest = _requestBookFixture.CreateRequestBook(); @@ -535,14 +525,14 @@ public class BooksControllerTests : IClassFixture }; // Act - HttpResponseMessage response = await _client.PostAsJsonAsync("api/v1/books", bookRequest); + HttpResponseMessage response = await _client.PostAsJsonAsync("/api/v1/books", bookRequest); // Assert - await AssertBadRequestWithValidationErrors(response, Errors.Metadata.TagNameCannotBeEmpty.Code); + await AssertUnprocessableEntityWithValidationErrors(response, Errors.Metadata.TagNameCannotBeEmpty.Description); } [Fact] - public async Task AddBook_WhenCalledWithInvalidLengthTagName_ShouldReturnBadRequest() + public async Task AddBook_WhenCalledWithInvalidLengthTagName_ShouldReturnUnprocessableEntity() { // Arrange AddBookRequest bookRequest = _requestBookFixture.CreateRequestBook(); @@ -554,10 +544,10 @@ public class BooksControllerTests : IClassFixture } }; // Act - HttpResponseMessage response = await _client.PostAsJsonAsync("api/v1/books", bookRequest); + HttpResponseMessage response = await _client.PostAsJsonAsync("/api/v1/books", bookRequest); // Assert - await AssertBadRequestWithValidationErrors(response, Errors.Metadata.TagNameMustBeMaximum50CharactersLong.Code); + await AssertUnprocessableEntityWithValidationErrors(response, Errors.Metadata.TagNameMustBeMaximum50CharactersLong.Description); } [Fact] @@ -572,21 +562,21 @@ public class BooksControllerTests : IClassFixture } [Fact] - public async Task AddBook_WhenCalledWithEmptyLanguageCode_ShouldReturnBadRequest() + public async Task AddBook_WhenCalledWithEmptyLanguageCode_ShouldReturnUnprocessableEntity() { // Arrange AddBookRequest bookRequest = _requestBookFixture.CreateRequestBook(); bookRequest = bookRequest with { Metadata = bookRequest.Metadata! with { Language = bookRequest.Metadata.Language! with { LanguageCode = null } } }; // Act - HttpResponseMessage response = await _client.PostAsJsonAsync("api/v1/books", bookRequest); + HttpResponseMessage response = await _client.PostAsJsonAsync("/api/v1/books", bookRequest); // Assert - await AssertBadRequestWithValidationErrors(response, Errors.Metadata.LanguageCodeCannotBeEmpty.Code); + await AssertUnprocessableEntityWithValidationErrors(response, Errors.Metadata.LanguageCodeCannotBeEmpty.Description); } [Fact] - public async Task AddBook_WhenCalledWithInvalidLengthLanguageCode_ShouldReturnBadRequest() + public async Task AddBook_WhenCalledWithInvalidLengthLanguageCode_ShouldReturnUnprocessableEntity() { // Arrange AddBookRequest bookRequest = _requestBookFixture.CreateRequestBook(); @@ -602,28 +592,28 @@ public class BooksControllerTests : IClassFixture }; // Act - HttpResponseMessage response = await _client.PostAsJsonAsync("api/v1/books", bookRequest); + HttpResponseMessage response = await _client.PostAsJsonAsync("/api/v1/books", bookRequest); // Assert - await AssertBadRequestWithValidationErrors(response, Errors.Metadata.LanguageCodeMustBe2CharactersLong.Code); + await AssertUnprocessableEntityWithValidationErrors(response, Errors.Metadata.LanguageCodeMustBe2CharactersLong.Description); } [Fact] - public async Task AddBook_WhenCalledWithEmptyLanguageName_ShouldReturnBadRequest() + public async Task AddBook_WhenCalledWithEmptyLanguageName_ShouldReturnUnprocessableEntity() { // Arrange AddBookRequest bookRequest = _requestBookFixture.CreateRequestBook(); bookRequest = bookRequest with { Metadata = bookRequest.Metadata! with { Language = bookRequest.Metadata.Language! with { LanguageName = null } } }; // Act - HttpResponseMessage response = await _client.PostAsJsonAsync("api/v1/books", bookRequest); + HttpResponseMessage response = await _client.PostAsJsonAsync("/api/v1/books", bookRequest); // Assert - await AssertBadRequestWithValidationErrors(response, Errors.Metadata.LanguageNameCannotBeEmpty.Code); + await AssertUnprocessableEntityWithValidationErrors(response, Errors.Metadata.LanguageNameCannotBeEmpty.Description); } [Fact] - public async Task AddBook_WhenCalledWithInvalidLengthLanguageName_ShouldReturnBadRequest() + public async Task AddBook_WhenCalledWithInvalidLengthLanguageName_ShouldReturnUnprocessableEntity() { // Arrange AddBookRequest bookRequest = _requestBookFixture.CreateRequestBook(); @@ -639,10 +629,10 @@ public class BooksControllerTests : IClassFixture }; // Act - HttpResponseMessage response = await _client.PostAsJsonAsync("api/v1/books", bookRequest); + HttpResponseMessage response = await _client.PostAsJsonAsync("/api/v1/books", bookRequest); // Assert - await AssertBadRequestWithValidationErrors(response, Errors.Metadata.LanguageNameMustBeMaximum50CharactersLong.Code); + await AssertUnprocessableEntityWithValidationErrors(response, Errors.Metadata.LanguageNameMustBeMaximum50CharactersLong.Description); } [Fact] @@ -657,7 +647,7 @@ public class BooksControllerTests : IClassFixture } [Fact] - public async Task AddBook_WhenCalledWithInvalidLengthNativeLanguageName_ShouldReturnBadRequest() + public async Task AddBook_WhenCalledWithInvalidLengthNativeLanguageName_ShouldReturnUnprocessableEntity() { // Arrange AddBookRequest bookRequest = _requestBookFixture.CreateRequestBook(); @@ -673,10 +663,10 @@ public class BooksControllerTests : IClassFixture }; // Act - HttpResponseMessage response = await _client.PostAsJsonAsync("api/v1/books", bookRequest); + HttpResponseMessage response = await _client.PostAsJsonAsync("/api/v1/books", bookRequest); // Assert - await AssertBadRequestWithValidationErrors(response, Errors.Metadata.LanguageNativeNameMustBeMaximum50CharactersLong.Code); + await AssertUnprocessableEntityWithValidationErrors(response, Errors.Metadata.LanguageNativeNameMustBeMaximum50CharactersLong.Description); } [Fact] @@ -691,21 +681,21 @@ public class BooksControllerTests : IClassFixture } [Fact] - public async Task AddBook_WhenCalledWithEmptyOriginalLanguageCode_ShouldReturnBadRequest() + public async Task AddBook_WhenCalledWithEmptyOriginalLanguageCode_ShouldReturnUnprocessableEntity() { // Arrange AddBookRequest bookRequest = _requestBookFixture.CreateRequestBook(); bookRequest = bookRequest with { Metadata = bookRequest.Metadata! with { OriginalLanguage = bookRequest.Metadata.Language! with { LanguageCode = null } } }; // Act - HttpResponseMessage response = await _client.PostAsJsonAsync("api/v1/books", bookRequest); + HttpResponseMessage response = await _client.PostAsJsonAsync("/api/v1/books", bookRequest); // Assert - await AssertBadRequestWithValidationErrors(response, Errors.Metadata.LanguageCodeCannotBeEmpty.Code); + await AssertUnprocessableEntityWithValidationErrors(response, Errors.Metadata.LanguageCodeCannotBeEmpty.Description); } [Fact] - public async Task AddBook_WhenCalledWithInvalidLengthOriginalLanguageCode_ShouldReturnBadRequest() + public async Task AddBook_WhenCalledWithInvalidLengthOriginalLanguageCode_ShouldReturnUnprocessableEntity() { // Arrange AddBookRequest bookRequest = _requestBookFixture.CreateRequestBook(); @@ -721,28 +711,28 @@ public class BooksControllerTests : IClassFixture }; // Act - HttpResponseMessage response = await _client.PostAsJsonAsync("api/v1/books", bookRequest); + HttpResponseMessage response = await _client.PostAsJsonAsync("/api/v1/books", bookRequest); // Assert - await AssertBadRequestWithValidationErrors(response, Errors.Metadata.LanguageCodeMustBe2CharactersLong.Code); + await AssertUnprocessableEntityWithValidationErrors(response, Errors.Metadata.LanguageCodeMustBe2CharactersLong.Description); } [Fact] - public async Task AddBook_WhenCalledWithEmptyOriginalLanguageName_ShouldReturnBadRequest() + public async Task AddBook_WhenCalledWithEmptyOriginalLanguageName_ShouldReturnUnprocessableEntity() { // Arrange AddBookRequest bookRequest = _requestBookFixture.CreateRequestBook(); bookRequest = bookRequest with { Metadata = bookRequest.Metadata! with { OriginalLanguage = bookRequest.Metadata.Language! with { LanguageName = null } } }; // Act - HttpResponseMessage response = await _client.PostAsJsonAsync("api/v1/books", bookRequest); + HttpResponseMessage response = await _client.PostAsJsonAsync("/api/v1/books", bookRequest); // Assert - await AssertBadRequestWithValidationErrors(response, Errors.Metadata.LanguageNameCannotBeEmpty.Code); + await AssertUnprocessableEntityWithValidationErrors(response, Errors.Metadata.LanguageNameCannotBeEmpty.Description); } [Fact] - public async Task AddBook_WhenCalledWithInvalidLengthOriginalLanguageName_ShouldReturnBadRequest() + public async Task AddBook_WhenCalledWithInvalidLengthOriginalLanguageName_ShouldReturnUnprocessableEntity() { // Arrange AddBookRequest bookRequest = _requestBookFixture.CreateRequestBook(); @@ -758,14 +748,14 @@ public class BooksControllerTests : IClassFixture }; // Act - HttpResponseMessage response = await _client.PostAsJsonAsync("api/v1/books", bookRequest); + HttpResponseMessage response = await _client.PostAsJsonAsync("/api/v1/books", bookRequest); // Assert - await AssertBadRequestWithValidationErrors(response, Errors.Metadata.LanguageNameMustBeMaximum50CharactersLong.Code); + await AssertUnprocessableEntityWithValidationErrors(response, Errors.Metadata.LanguageNameMustBeMaximum50CharactersLong.Description); } [Fact] - public async Task AddBook_WhenCalledWithInvalidLengthOriginalNativeLanguageName_ShouldReturnBadRequest() + public async Task AddBook_WhenCalledWithInvalidLengthOriginalNativeLanguageName_ShouldReturnUnprocessableEntity() { // Arrange AddBookRequest bookRequest = _requestBookFixture.CreateRequestBook(); @@ -781,10 +771,10 @@ public class BooksControllerTests : IClassFixture }; // Act - HttpResponseMessage response = await _client.PostAsJsonAsync("api/v1/books", bookRequest); + HttpResponseMessage response = await _client.PostAsJsonAsync("/api/v1/books", bookRequest); // Assert - await AssertBadRequestWithValidationErrors(response, Errors.Metadata.LanguageNativeNameMustBeMaximum50CharactersLong.Code); + await AssertUnprocessableEntityWithValidationErrors(response, Errors.Metadata.LanguageNativeNameMustBeMaximum50CharactersLong.Description); } [Fact] @@ -810,17 +800,17 @@ public class BooksControllerTests : IClassFixture } [Fact] - public async Task AddBook_WhenCalledWithInvalidLengthPublisher_ShouldReturnBadRequest() + public async Task AddBook_WhenCalledWithInvalidLengthPublisher_ShouldReturnUnprocessableEntity() { // Arrange AddBookRequest bookRequest = _requestBookFixture.CreateRequestBook(); bookRequest = bookRequest with { Metadata = bookRequest.Metadata! with { Publisher = new Faker().Random.String2(150) } }; // Act - HttpResponseMessage response = await _client.PostAsJsonAsync("api/v1/books", bookRequest); + HttpResponseMessage response = await _client.PostAsJsonAsync("/api/v1/books", bookRequest); // Assert - await AssertBadRequestWithValidationErrors(response, Errors.WrittenContent.PublisherMustBeMaximum100CharactersLong.Code); + await AssertUnprocessableEntityWithValidationErrors(response, Errors.WrittenContent.PublisherMustBeMaximum100CharactersLong.Description); } [Fact] @@ -835,17 +825,17 @@ public class BooksControllerTests : IClassFixture } [Fact] - public async Task AddBook_WhenCalledWithNegativePageCount_ShouldReturnBadRequest() + public async Task AddBook_WhenCalledWithNegativePageCount_ShouldReturnUnprocessableEntity() { // Arrange AddBookRequest bookRequest = _requestBookFixture.CreateRequestBook(); bookRequest = bookRequest with { Metadata = bookRequest.Metadata! with { PageCount = -1 } }; // Act - HttpResponseMessage response = await _client.PostAsJsonAsync("api/v1/books", bookRequest); + HttpResponseMessage response = await _client.PostAsJsonAsync("/api/v1/books", bookRequest); // Assert - await AssertBadRequestWithValidationErrors(response, Errors.WrittenContent.PageCountMustBeGreaterThanZero.Code); + await AssertUnprocessableEntityWithValidationErrors(response, Errors.WrittenContent.PageCountMustBeGreaterThanZero.Description); } [Fact] @@ -860,17 +850,17 @@ public class BooksControllerTests : IClassFixture } [Fact] - public async Task AddBook_WhenCalledWithInvalidFormat_ShouldReturnBadRequest() + public async Task AddBook_WhenCalledWithInvalidFormat_ShouldReturnUnprocessableEntity() { // Arrange AddBookRequest bookRequest = _requestBookFixture.CreateRequestBook(); bookRequest = bookRequest with { Format = (BookFormat)99 }; // Act - HttpResponseMessage response = await _client.PostAsJsonAsync("api/v1/books", bookRequest); + HttpResponseMessage response = await _client.PostAsJsonAsync("/api/v1/books", bookRequest); // Assert - await AssertBadRequestWithValidationErrors(response, Errors.WrittenContent.UnknownBookFormat.Code); + await AssertUnprocessableEntityWithValidationErrors(response, Errors.WrittenContent.UnknownBookFormat.Description); } [Fact] @@ -885,17 +875,17 @@ public class BooksControllerTests : IClassFixture } [Fact] - public async Task AddBook_WhenCalledWithInvalidLengthEdition_ShouldReturnBadRequest() + public async Task AddBook_WhenCalledWithInvalidLengthEdition_ShouldReturnUnprocessableEntity() { // Arrange AddBookRequest bookRequest = _requestBookFixture.CreateRequestBook(); bookRequest = bookRequest with { Edition = new Faker().Random.String2(100) }; // Act - HttpResponseMessage response = await _client.PostAsJsonAsync("api/v1/books", bookRequest); + HttpResponseMessage response = await _client.PostAsJsonAsync("/api/v1/books", bookRequest); // Assert - await AssertBadRequestWithValidationErrors(response, Errors.WrittenContent.EditionMustBeMaximum50CharactersLong.Code); + await AssertUnprocessableEntityWithValidationErrors(response, Errors.WrittenContent.EditionMustBeMaximum50CharactersLong.Description); } [Fact] @@ -910,17 +900,17 @@ public class BooksControllerTests : IClassFixture } [Fact] - public async Task AddBook_WhenCalledWithNegativeVolumeNumber_ShouldReturnBadRequest() + public async Task AddBook_WhenCalledWithNegativeVolumeNumber_ShouldReturnUnprocessableEntity() { // Arrange AddBookRequest bookRequest = _requestBookFixture.CreateRequestBook(); bookRequest = bookRequest with { VolumeNumber = -1 }; // Act - HttpResponseMessage response = await _client.PostAsJsonAsync("api/v1/books", bookRequest); + HttpResponseMessage response = await _client.PostAsJsonAsync("/api/v1/books", bookRequest); // Assert - await AssertBadRequestWithValidationErrors(response, Errors.WrittenContent.VolumeNumberMustBeGreaterThanZero.Code); + await AssertUnprocessableEntityWithValidationErrors(response, Errors.WrittenContent.VolumeNumberMustBeGreaterThanZero.Description); } [Fact] @@ -935,7 +925,7 @@ public class BooksControllerTests : IClassFixture } //[Fact] - //public async Task AddBook_WhenCalledWithEmptySeriesTitle_ShouldReturnBadRequest() + //public async Task AddBook_WhenCalledWithEmptySeriesTitle_ShouldReturnUnprocessableEntity() //{ // // Arrange // var bookRequest = _requestBookFixture.CreateRequestBook(); @@ -945,24 +935,24 @@ public class BooksControllerTests : IClassFixture // }; // // Act - // var response = await _client.PostAsJsonAsync("api/v1/books", bookRequest); + // var response = await _client.PostAsJsonAsync("/api/v1/books", bookRequest); // // Assert - // await AssertBadRequestWithValidationErrors(response, Errors.Metadata.TitleCannotBeEmpty.Code); + // await AssertUnprocessableEntityWithValidationErrors(response, Errors.Metadata.TitleCannotBeEmpty.Description); //} //[Fact] - //public async Task AddBook_WhenCalledWithInvalidLengthSeriesTitle_ShouldReturnBadRequest() + //public async Task AddBook_WhenCalledWithInvalidLengthSeriesTitle_ShouldReturnUnprocessableEntity() //{ // // Arrange // var bookRequest = _requestBookFixture.CreateRequestBook(); // bookRequest = bookRequest with { Series = bookRequest.Series! with { Title = new Faker().Random.String2(300) } }; // // Act - // var response = await _client.PostAsJsonAsync("api/v1/books", bookRequest); + // var response = await _client.PostAsJsonAsync("/api/v1/books", bookRequest); // // Assert - // await AssertBadRequestWithValidationErrors(response, Errors.Metadata.TitleMustBeMaximum255CharactersLong.Code); + // await AssertUnprocessableEntityWithValidationErrors(response, Errors.Metadata.TitleMustBeMaximum255CharactersLong.Description); //} [Fact] @@ -977,17 +967,17 @@ public class BooksControllerTests : IClassFixture } [Fact] - public async Task AddBook_WhenCalledWithInvalidLengthAsin_ShouldReturnBadRequest() + public async Task AddBook_WhenCalledWithInvalidLengthAsin_ShouldReturnUnprocessableEntity() { // Arrange AddBookRequest bookRequest = _requestBookFixture.CreateRequestBook(); bookRequest = bookRequest with { ASIN = new Faker().Random.String2(15) }; // Act - HttpResponseMessage response = await _client.PostAsJsonAsync("api/v1/books", bookRequest); + HttpResponseMessage response = await _client.PostAsJsonAsync("/api/v1/books", bookRequest); // Assert - await AssertBadRequestWithValidationErrors(response, Errors.WrittenContent.AsinMustBe10CharactersLong.Code); + await AssertUnprocessableEntityWithValidationErrors(response, Errors.WrittenContent.AsinMustBe10CharactersLong.Description); } [Fact] @@ -1002,17 +992,17 @@ public class BooksControllerTests : IClassFixture } [Fact] - public async Task AddBook_WhenCalledWithInvalidGoodreadsId_ShouldReturnBadRequest() + public async Task AddBook_WhenCalledWithInvalidGoodreadsId_ShouldReturnUnprocessableEntity() { // Arrange AddBookRequest bookRequest = _requestBookFixture.CreateRequestBook(); bookRequest = bookRequest with { GoodreadsId = new Faker().Random.String2(2) }; // Act - HttpResponseMessage response = await _client.PostAsJsonAsync("api/v1/books", bookRequest); + HttpResponseMessage response = await _client.PostAsJsonAsync("/api/v1/books", bookRequest); // Assert - await AssertBadRequestWithValidationErrors(response, Errors.WrittenContent.GoodreadsIdMustBeNumeric.Code); + await AssertUnprocessableEntityWithValidationErrors(response, Errors.WrittenContent.GoodreadsIdMustBeNumeric.Description); } [Fact] @@ -1027,17 +1017,17 @@ public class BooksControllerTests : IClassFixture } [Fact] - public async Task AddBook_WhenCalledWithInvalidLccn_ShouldReturnBadRequest() + public async Task AddBook_WhenCalledWithInvalidLccn_ShouldReturnUnprocessableEntity() { // Arrange AddBookRequest bookRequest = _requestBookFixture.CreateRequestBook(); bookRequest = bookRequest with { LCCN = new Faker().Random.String2(200) }; // Act - HttpResponseMessage response = await _client.PostAsJsonAsync("api/v1/books", bookRequest); + HttpResponseMessage response = await _client.PostAsJsonAsync("/api/v1/books", bookRequest); // Assert - await AssertBadRequestWithValidationErrors(response, Errors.WrittenContent.InvalidLccnFormat.Code); + await AssertUnprocessableEntityWithValidationErrors(response, Errors.WrittenContent.InvalidLccnFormat.Description); } [Fact] @@ -1052,17 +1042,17 @@ public class BooksControllerTests : IClassFixture } [Fact] - public async Task AddBook_WhenCalledWithInvalidOclcNumber_ShouldReturnBadRequest() + public async Task AddBook_WhenCalledWithInvalidOclcNumber_ShouldReturnUnprocessableEntity() { // Arrange AddBookRequest bookRequest = _requestBookFixture.CreateRequestBook(); bookRequest = bookRequest with { OCLCNumber = new Faker().Random.String2(200) }; // Act - HttpResponseMessage response = await _client.PostAsJsonAsync("api/v1/books", bookRequest); + HttpResponseMessage response = await _client.PostAsJsonAsync("/api/v1/books", bookRequest); // Assert - await AssertBadRequestWithValidationErrors(response, Errors.WrittenContent.InvalidOclcFormat.Code); + await AssertUnprocessableEntityWithValidationErrors(response, Errors.WrittenContent.InvalidOclcFormat.Description); } [Fact] @@ -1077,17 +1067,17 @@ public class BooksControllerTests : IClassFixture } [Fact] - public async Task AddBook_WhenCalledWithInvalidOpenLibraryId_ShouldReturnBadRequest() + public async Task AddBook_WhenCalledWithInvalidOpenLibraryId_ShouldReturnUnprocessableEntity() { // Arrange AddBookRequest bookRequest = _requestBookFixture.CreateRequestBook(); bookRequest = bookRequest with { OpenLibraryId = new Faker().Random.String2(200) }; // Act - HttpResponseMessage response = await _client.PostAsJsonAsync("api/v1/books", bookRequest); + HttpResponseMessage response = await _client.PostAsJsonAsync("/api/v1/books", bookRequest); // Assert - await AssertBadRequestWithValidationErrors(response, Errors.WrittenContent.InvalidOpenLibraryId.Code); + await AssertUnprocessableEntityWithValidationErrors(response, Errors.WrittenContent.InvalidOpenLibraryId.Description); } [Fact] @@ -1102,17 +1092,17 @@ public class BooksControllerTests : IClassFixture } [Fact] - public async Task AddBook_WhenCalledWithInvalidLengthLibraryThingId_ShouldReturnBadRequest() + public async Task AddBook_WhenCalledWithInvalidLengthLibraryThingId_ShouldReturnUnprocessableEntity() { // Arrange AddBookRequest bookRequest = _requestBookFixture.CreateRequestBook(); bookRequest = bookRequest with { LibraryThingId = new Faker().Random.String2(200) }; // Act - HttpResponseMessage response = await _client.PostAsJsonAsync("api/v1/books", bookRequest); + HttpResponseMessage response = await _client.PostAsJsonAsync("/api/v1/books", bookRequest); // Assert - await AssertBadRequestWithValidationErrors(response, Errors.WrittenContent.LibraryThingIdMustBeMaximum50CharactersLong.Code); + await AssertUnprocessableEntityWithValidationErrors(response, Errors.WrittenContent.LibraryThingIdMustBeMaximum50CharactersLong.Description); } [Fact] @@ -1127,31 +1117,31 @@ public class BooksControllerTests : IClassFixture } [Fact] - public async Task AddBook_WhenCalledWithInvalidLengthGoogleBooksId_ShouldReturnBadRequest() + public async Task AddBook_WhenCalledWithInvalidLengthGoogleBooksId_ShouldReturnUnprocessableEntity() { // Arrange AddBookRequest bookRequest = _requestBookFixture.CreateRequestBook(); bookRequest = bookRequest with { GoogleBooksId = new Faker().Random.String2(20) }; // Act - HttpResponseMessage response = await _client.PostAsJsonAsync("api/v1/books", bookRequest); + HttpResponseMessage response = await _client.PostAsJsonAsync("/api/v1/books", bookRequest); // Assert - await AssertBadRequestWithValidationErrors(response, Errors.WrittenContent.GoogleBooksIdMustBe12CharactersLong.Code); + await AssertUnprocessableEntityWithValidationErrors(response, Errors.WrittenContent.GoogleBooksIdMustBe12CharactersLong.Description); } [Fact] - public async Task AddBook_WhenCalledWithInvalidGoogleBooksId_ShouldReturnBadRequest() + public async Task AddBook_WhenCalledWithInvalidGoogleBooksId_ShouldReturnUnprocessableEntity() { // Arrange AddBookRequest bookRequest = _requestBookFixture.CreateRequestBook(); bookRequest = bookRequest with { GoogleBooksId = new Faker().Random.String2(11) + " " }; // Act - HttpResponseMessage response = await _client.PostAsJsonAsync("api/v1/books", bookRequest); + HttpResponseMessage response = await _client.PostAsJsonAsync("/api/v1/books", bookRequest); // Assert - await AssertBadRequestWithValidationErrors(response, Errors.WrittenContent.InvalidGoogleBooksIdFormat.Code); + await AssertUnprocessableEntityWithValidationErrors(response, Errors.WrittenContent.InvalidGoogleBooksIdFormat.Description); } [Fact] @@ -1166,31 +1156,31 @@ public class BooksControllerTests : IClassFixture } [Fact] - public async Task AddBook_WhenCalledWithInvalidLengthBarnesAndNobleId_ShouldReturnBadRequest() + public async Task AddBook_WhenCalledWithInvalidLengthBarnesAndNobleId_ShouldReturnUnprocessableEntity() { // Arrange AddBookRequest bookRequest = _requestBookFixture.CreateRequestBook(); bookRequest = bookRequest with { BarnesAndNobleId = new Faker().Random.String2(20) }; // Act - HttpResponseMessage response = await _client.PostAsJsonAsync("api/v1/books", bookRequest); + HttpResponseMessage response = await _client.PostAsJsonAsync("/api/v1/books", bookRequest); // Assert - await AssertBadRequestWithValidationErrors(response, Errors.WrittenContent.BarnesAndNoblesIdMustBe10CharactersLong.Code); + await AssertUnprocessableEntityWithValidationErrors(response, Errors.WrittenContent.BarnesAndNoblesIdMustBe10CharactersLong.Description); } [Fact] - public async Task AddBook_WhenCalledWithInvalidBarnesAndNobleId_ShouldReturnBadRequest() + public async Task AddBook_WhenCalledWithInvalidBarnesAndNobleId_ShouldReturnUnprocessableEntity() { // Arrange AddBookRequest bookRequest = _requestBookFixture.CreateRequestBook(); bookRequest = bookRequest with { BarnesAndNobleId = new Faker().Random.String2(10) }; // Act - HttpResponseMessage response = await _client.PostAsJsonAsync("api/v1/books", bookRequest); + HttpResponseMessage response = await _client.PostAsJsonAsync("/api/v1/books", bookRequest); // Assert - await AssertBadRequestWithValidationErrors(response, Errors.WrittenContent.InvalidBarnesAndNoblesIdFormat.Code); + await AssertUnprocessableEntityWithValidationErrors(response, Errors.WrittenContent.InvalidBarnesAndNoblesIdFormat.Description); } [Fact] @@ -1205,35 +1195,35 @@ public class BooksControllerTests : IClassFixture } [Fact] - public async Task AddBook_WhenCalledWithInvalidAppleBooksId_ShouldReturnBadRequest() + public async Task AddBook_WhenCalledWithInvalidAppleBooksId_ShouldReturnUnprocessableEntity() { // Arrange AddBookRequest bookRequest = _requestBookFixture.CreateRequestBook(); bookRequest = bookRequest with { AppleBooksId = new Faker().Random.String2(10) }; // Act - HttpResponseMessage response = await _client.PostAsJsonAsync("api/v1/books", bookRequest); + HttpResponseMessage response = await _client.PostAsJsonAsync("/api/v1/books", bookRequest); // Assert - await AssertBadRequestWithValidationErrors(response, Errors.WrittenContent.InvalidAppleBooksIdFormat.Code); + await AssertUnprocessableEntityWithValidationErrors(response, Errors.WrittenContent.InvalidAppleBooksIdFormat.Description); } [Fact] - public async Task AddBook_WhenCalledWithNullIsbns_ShouldReturnBadRequest() + public async Task AddBook_WhenCalledWithNullIsbns_ShouldReturnUnprocessableEntity() { // Arrange AddBookRequest bookRequest = _requestBookFixture.CreateRequestBook(); bookRequest = bookRequest with { ISBNs = null! }; // Act - HttpResponseMessage response = await _client.PostAsJsonAsync("api/v1/books", bookRequest); + HttpResponseMessage response = await _client.PostAsJsonAsync("/api/v1/books", bookRequest); // Assert - await AssertBadRequestWithValidationErrors(response, Errors.WrittenContent.IsbnListCannotBeNull.Code); + await AssertUnprocessableEntityWithValidationErrors(response, Errors.WrittenContent.IsbnListCannotBeNull.Description); } [Fact] - public async Task AddBook_WhenCalledWithEmptyIsbnValue_ShouldReturnBadRequest() + public async Task AddBook_WhenCalledWithEmptyIsbnValue_ShouldReturnUnprocessableEntity() { // Arrange AddBookRequest bookRequest = _requestBookFixture.CreateRequestBook(); @@ -1243,14 +1233,14 @@ public class BooksControllerTests : IClassFixture }; // Act - HttpResponseMessage response = await _client.PostAsJsonAsync("api/v1/books", bookRequest); + HttpResponseMessage response = await _client.PostAsJsonAsync("/api/v1/books", bookRequest); // Assert - await AssertBadRequestWithValidationErrors(response, Errors.WrittenContent.IsbnValueCannotBeEmpty.Code); + await AssertUnprocessableEntityWithValidationErrors(response, Errors.WrittenContent.IsbnValueCannotBeEmpty.Description); } [Fact] - public async Task AddBook_WhenCalledWithInvalidIsbn10Value_ShouldReturnBadRequest() + public async Task AddBook_WhenCalledWithInvalidIsbn10Value_ShouldReturnUnprocessableEntity() { // Arrange AddBookRequest bookRequest = _requestBookFixture.CreateRequestBook(); @@ -1260,14 +1250,14 @@ public class BooksControllerTests : IClassFixture }; // Act - HttpResponseMessage response = await _client.PostAsJsonAsync("api/v1/books", bookRequest); + HttpResponseMessage response = await _client.PostAsJsonAsync("/api/v1/books", bookRequest); // Assert - await AssertBadRequestWithValidationErrors(response, Errors.WrittenContent.InvalidIsbn10Format.Code); + await AssertUnprocessableEntityWithValidationErrors(response, Errors.WrittenContent.InvalidIsbn10Format.Description); } [Fact] - public async Task AddBook_WhenCalledWithInvalidIsbn13Value_ShouldReturnBadRequest() + public async Task AddBook_WhenCalledWithInvalidIsbn13Value_ShouldReturnUnprocessableEntity() { // Arrange AddBookRequest bookRequest = _requestBookFixture.CreateRequestBook(); @@ -1277,14 +1267,14 @@ public class BooksControllerTests : IClassFixture }; // Act - HttpResponseMessage response = await _client.PostAsJsonAsync("api/v1/books", bookRequest); + HttpResponseMessage response = await _client.PostAsJsonAsync("/api/v1/books", bookRequest); // Assert - await AssertBadRequestWithValidationErrors(response, Errors.WrittenContent.InvalidIsbn13Format.Code); + await AssertUnprocessableEntityWithValidationErrors(response, Errors.WrittenContent.InvalidIsbn13Format.Description); } [Fact] - public async Task AddBook_WhenCalledWithInvalidIsbnFormat_ShouldReturnBadRequest() + public async Task AddBook_WhenCalledWithInvalidIsbnFormat_ShouldReturnUnprocessableEntity() { // Arrange AddBookRequest bookRequest = _requestBookFixture.CreateRequestBook(); @@ -1293,28 +1283,28 @@ public class BooksControllerTests : IClassFixture ISBNs = bookRequest.ISBNs!.Select((isbn, index) => index == 0 ? isbn with { Format = (IsbnFormat)99 } : isbn).ToList() }; // Act - HttpResponseMessage response = await _client.PostAsJsonAsync("api/v1/books", bookRequest); + HttpResponseMessage response = await _client.PostAsJsonAsync("/api/v1/books", bookRequest); // Assert - await AssertBadRequestWithValidationErrors(response, Errors.WrittenContent.UnknownIsbnFormat.Code); + await AssertUnprocessableEntityWithValidationErrors(response, Errors.WrittenContent.UnknownIsbnFormat.Description); } [Fact] - public async Task AddBook_WhenCalledWithNullContributors_ShouldReturnBadRequest() + public async Task AddBook_WhenCalledWithNullContributors_ShouldReturnUnprocessableEntity() { // Arrange AddBookRequest bookRequest = _requestBookFixture.CreateRequestBook(); bookRequest = bookRequest with { Contributors = null! }; // Act - HttpResponseMessage response = await _client.PostAsJsonAsync("api/v1/books", bookRequest); + HttpResponseMessage response = await _client.PostAsJsonAsync("/api/v1/books", bookRequest); // Assert - await AssertBadRequestWithValidationErrors(response, Errors.MediaContributor.ContributorsListCannotBeNull.Code); + await AssertUnprocessableEntityWithValidationErrors(response, Errors.MediaContributor.ContributorsListCannotBeNull.Description); } [Fact] - public async Task AddBook_WhenCalledWithNullContributorName_ShouldReturnBadRequest() + public async Task AddBook_WhenCalledWithNullContributorName_ShouldReturnUnprocessableEntity() { // Arrange AddBookRequest bookRequest = _requestBookFixture.CreateRequestBook(); @@ -1324,14 +1314,14 @@ public class BooksControllerTests : IClassFixture }; // Act - HttpResponseMessage response = await _client.PostAsJsonAsync("api/v1/books", bookRequest); + HttpResponseMessage response = await _client.PostAsJsonAsync("/api/v1/books", bookRequest); // Assert - await AssertBadRequestWithValidationErrors(response, Errors.MediaContributor.ContributorNameCannotBeEmpty.Code); + await AssertUnprocessableEntityWithValidationErrors(response, Errors.MediaContributor.ContributorNameCannotBeEmpty.Description); } [Fact] - public async Task AddBook_WhenCalledWithEmptyContributorDisplayName_ShouldReturnBadRequest() + public async Task AddBook_WhenCalledWithEmptyContributorDisplayName_ShouldReturnUnprocessableEntity() { // Arrange AddBookRequest bookRequest = _requestBookFixture.CreateRequestBook(); @@ -1341,14 +1331,14 @@ public class BooksControllerTests : IClassFixture }; // Act - HttpResponseMessage response = await _client.PostAsJsonAsync("api/v1/books", bookRequest); + HttpResponseMessage response = await _client.PostAsJsonAsync("/api/v1/books", bookRequest); // Assert - await AssertBadRequestWithValidationErrors(response, Errors.MediaContributor.ContributorDisplayNameCannotBeEmpty.Code); + await AssertUnprocessableEntityWithValidationErrors(response, Errors.MediaContributor.ContributorDisplayNameCannotBeEmpty.Description); } [Fact] - public async Task AddBook_WhenCalledWithNullContributorDisplayName_ShouldReturnBadRequest() + public async Task AddBook_WhenCalledWithNullContributorDisplayName_ShouldReturnUnprocessableEntity() { // Arrange AddBookRequest bookRequest = _requestBookFixture.CreateRequestBook(); @@ -1358,14 +1348,14 @@ public class BooksControllerTests : IClassFixture }; // Act - HttpResponseMessage response = await _client.PostAsJsonAsync("api/v1/books", bookRequest); + HttpResponseMessage response = await _client.PostAsJsonAsync("/api/v1/books", bookRequest); // Assert - await AssertBadRequestWithValidationErrors(response, Errors.MediaContributor.ContributorDisplayNameCannotBeEmpty.Code); + await AssertUnprocessableEntityWithValidationErrors(response, Errors.MediaContributor.ContributorDisplayNameCannotBeEmpty.Description); } [Fact] - public async Task AddBook_WhenCalledWithInvalidLengthContributorDisplayName_ShouldReturnBadRequest() + public async Task AddBook_WhenCalledWithInvalidLengthContributorDisplayName_ShouldReturnUnprocessableEntity() { // Arrange AddBookRequest bookRequest = _requestBookFixture.CreateRequestBook(); @@ -1375,14 +1365,14 @@ public class BooksControllerTests : IClassFixture }; // Act - HttpResponseMessage response = await _client.PostAsJsonAsync("api/v1/books", bookRequest); + HttpResponseMessage response = await _client.PostAsJsonAsync("/api/v1/books", bookRequest); // Assert - await AssertBadRequestWithValidationErrors(response, Errors.MediaContributor.ContributorDisplayNameMustBeMaximum100CharactersLong.Code); + await AssertUnprocessableEntityWithValidationErrors(response, Errors.MediaContributor.ContributorDisplayNameMustBeMaximum100CharactersLong.Description); } [Fact] - public async Task AddBook_WhenCalledWithInvalidLengthContributorLegalName_ShouldReturnBadRequest() + public async Task AddBook_WhenCalledWithInvalidLengthContributorLegalName_ShouldReturnUnprocessableEntity() { // Arrange AddBookRequest bookRequest = _requestBookFixture.CreateRequestBook(); @@ -1392,14 +1382,14 @@ public class BooksControllerTests : IClassFixture }; // Act - HttpResponseMessage response = await _client.PostAsJsonAsync("api/v1/books", bookRequest); + HttpResponseMessage response = await _client.PostAsJsonAsync("/api/v1/books", bookRequest); // Assert - await AssertBadRequestWithValidationErrors(response, Errors.MediaContributor.ContributorLegalNameMustBeMaximum100CharactersLong.Code); + await AssertUnprocessableEntityWithValidationErrors(response, Errors.MediaContributor.ContributorLegalNameMustBeMaximum100CharactersLong.Description); } [Fact] - public async Task AddBook_WhenCalledWithEmptyContributorRole_ShouldReturnBadRequest() + public async Task AddBook_WhenCalledWithEmptyContributorRole_ShouldReturnUnprocessableEntity() { // Arrange AddBookRequest bookRequest = _requestBookFixture.CreateRequestBook(); @@ -1409,14 +1399,14 @@ public class BooksControllerTests : IClassFixture }; // Act - HttpResponseMessage response = await _client.PostAsJsonAsync("api/v1/books", bookRequest); + HttpResponseMessage response = await _client.PostAsJsonAsync("/api/v1/books", bookRequest); // Assert - await AssertBadRequestWithValidationErrors(response, Errors.MediaContributor.ContributorRoleCannotBeNull.Code); + await AssertUnprocessableEntityWithValidationErrors(response, Errors.MediaContributor.ContributorRoleCannotBeNull.Description); } [Fact] - public async Task AddBook_WhenCalledWithEmptyContributorRoleName_ShouldReturnBadRequest() + public async Task AddBook_WhenCalledWithEmptyContributorRoleName_ShouldReturnUnprocessableEntity() { // Arrange AddBookRequest bookRequest = _requestBookFixture.CreateRequestBook(); @@ -1427,14 +1417,14 @@ public class BooksControllerTests : IClassFixture }; // Act - HttpResponseMessage response = await _client.PostAsJsonAsync("api/v1/books", bookRequest); + HttpResponseMessage response = await _client.PostAsJsonAsync("/api/v1/books", bookRequest); // Assert - await AssertBadRequestWithValidationErrors(response, Errors.MediaContributor.RoleNameCannotBeEmpty.Code); + await AssertUnprocessableEntityWithValidationErrors(response, Errors.MediaContributor.RoleNameCannotBeEmpty.Description); } [Fact] - public async Task AddBook_WhenCalledWithInvalidLengthContributorRoleName_ShouldReturnBadRequest() + public async Task AddBook_WhenCalledWithInvalidLengthContributorRoleName_ShouldReturnUnprocessableEntity() { // Arrange AddBookRequest bookRequest = _requestBookFixture.CreateRequestBook(); @@ -1445,14 +1435,14 @@ public class BooksControllerTests : IClassFixture }; // Act - HttpResponseMessage response = await _client.PostAsJsonAsync("api/v1/books", bookRequest); + HttpResponseMessage response = await _client.PostAsJsonAsync("/api/v1/books", bookRequest); // Assert - await AssertBadRequestWithValidationErrors(response, Errors.MediaContributor.RoleNameMustBeMaximum50CharactersLong.Code); + await AssertUnprocessableEntityWithValidationErrors(response, Errors.MediaContributor.RoleNameMustBeMaximum50CharactersLong.Description); } [Fact] - public async Task AddBook_WhenCalledWithEmptyContributorRoleCategory_ShouldReturnBadRequest() + public async Task AddBook_WhenCalledWithEmptyContributorRoleCategory_ShouldReturnUnprocessableEntity() { // Arrange AddBookRequest bookRequest = _requestBookFixture.CreateRequestBook(); @@ -1463,14 +1453,14 @@ public class BooksControllerTests : IClassFixture }; // Act - HttpResponseMessage response = await _client.PostAsJsonAsync("api/v1/books", bookRequest); + HttpResponseMessage response = await _client.PostAsJsonAsync("/api/v1/books", bookRequest); // Assert - await AssertBadRequestWithValidationErrors(response, Errors.MediaContributor.RoleCategoryCannotBeEmpty.Code); + await AssertUnprocessableEntityWithValidationErrors(response, Errors.MediaContributor.RoleCategoryCannotBeEmpty.Description); } [Fact] - public async Task AddBook_WhenCalledWithInvalidLengthContributorRoleCategory_ShouldReturnBadRequest() + public async Task AddBook_WhenCalledWithInvalidLengthContributorRoleCategory_ShouldReturnUnprocessableEntity() { // Arrange AddBookRequest bookRequest = _requestBookFixture.CreateRequestBook(); @@ -1481,28 +1471,28 @@ public class BooksControllerTests : IClassFixture }; // Act - HttpResponseMessage response = await _client.PostAsJsonAsync("api/v1/books", bookRequest); + HttpResponseMessage response = await _client.PostAsJsonAsync("/api/v1/books", bookRequest); // Assert - await AssertBadRequestWithValidationErrors(response, Errors.MediaContributor.RoleCategoryMustBeMaximum50CharactersLong.Code); + await AssertUnprocessableEntityWithValidationErrors(response, Errors.MediaContributor.RoleCategoryMustBeMaximum50CharactersLong.Description); } [Fact] - public async Task AddBook_WhenCalledWithNullRatings_ShouldReturnBadRequest() + public async Task AddBook_WhenCalledWithNullRatings_ShouldReturnUnprocessableEntity() { // Arrange AddBookRequest bookRequest = _requestBookFixture.CreateRequestBook(); bookRequest = bookRequest with { Ratings = null! }; // Act - HttpResponseMessage response = await _client.PostAsJsonAsync("api/v1/books", bookRequest); + HttpResponseMessage response = await _client.PostAsJsonAsync("/api/v1/books", bookRequest); // Assert - await AssertBadRequestWithValidationErrors(response, Errors.Metadata.RatingsListCannotBeNull.Code); + await AssertUnprocessableEntityWithValidationErrors(response, Errors.Metadata.RatingsListCannotBeNull.Description); } [Fact] - public async Task AddBook_WhenCalledWithNegativeRatingValue_ShouldReturnBadRequest() + public async Task AddBook_WhenCalledWithNegativeRatingValue_ShouldReturnUnprocessableEntity() { // Arrange AddBookRequest bookRequest = _requestBookFixture.CreateRequestBook(); @@ -1511,14 +1501,14 @@ public class BooksControllerTests : IClassFixture Ratings = bookRequest.Ratings!.Select((rating, index) => index == 0 ? rating with { Value = -3 } : rating).ToList() }; // Act - HttpResponseMessage response = await _client.PostAsJsonAsync("api/v1/books", bookRequest); + HttpResponseMessage response = await _client.PostAsJsonAsync("/api/v1/books", bookRequest); // Assert - await AssertBadRequestWithValidationErrors(response, Errors.Metadata.RatingValueMustBePositive.Code); + await AssertUnprocessableEntityWithValidationErrors(response, Errors.Metadata.RatingValueMustBePositive.Description); } [Fact] - public async Task AddBook_WhenCalledWithRatingValueGreaterThanMaxValue_ShouldReturnBadRequest() + public async Task AddBook_WhenCalledWithRatingValueGreaterThanMaxValue_ShouldReturnUnprocessableEntity() { // Arrange AddBookRequest bookRequest = _requestBookFixture.CreateRequestBook(); @@ -1527,14 +1517,14 @@ public class BooksControllerTests : IClassFixture Ratings = bookRequest.Ratings!.Select((rating, index) => index == 0 ? rating with { Value = 3, MaxValue = 2 } : rating).ToList() }; // Act - HttpResponseMessage response = await _client.PostAsJsonAsync("api/v1/books", bookRequest); + HttpResponseMessage response = await _client.PostAsJsonAsync("/api/v1/books", bookRequest); // Assert - await AssertBadRequestWithValidationErrors(response, Errors.Metadata.RatingValueCannotBeGreaterThanMaxValue.Code); + await AssertUnprocessableEntityWithValidationErrors(response, Errors.Metadata.RatingValueCannotBeGreaterThanMaxValue.Description); } [Fact] - public async Task AddBook_WhenCalledWithNegativeMaxRatingValue_ShouldReturnBadRequest() + public async Task AddBook_WhenCalledWithNegativeMaxRatingValue_ShouldReturnUnprocessableEntity() { // Arrange AddBookRequest bookRequest = _requestBookFixture.CreateRequestBook(); @@ -1543,10 +1533,10 @@ public class BooksControllerTests : IClassFixture Ratings = bookRequest.Ratings!.Select((rating, index) => index == 0 ? rating with { MaxValue = -3 } : rating).ToList() }; // Act - HttpResponseMessage response = await _client.PostAsJsonAsync("api/v1/books", bookRequest); + HttpResponseMessage response = await _client.PostAsJsonAsync("/api/v1/books", bookRequest); // Assert - await AssertBadRequestWithValidationErrors(response, Errors.Metadata.RatingMaxValueMustBePositive.Code); + await AssertUnprocessableEntityWithValidationErrors(response, Errors.Metadata.RatingMaxValueMustBePositive.Description); } [Fact] @@ -1563,7 +1553,7 @@ public class BooksControllerTests : IClassFixture } [Fact] - public async Task AddBook_WhenCalledWithNegativeVoteCount_ShouldReturnBadRequest() + public async Task AddBook_WhenCalledWithNegativeVoteCount_ShouldReturnUnprocessableEntity() { // Arrange AddBookRequest bookRequest = _requestBookFixture.CreateRequestBook(); @@ -1572,39 +1562,34 @@ public class BooksControllerTests : IClassFixture Ratings = bookRequest.Ratings!.Select((rating, index) => index == 0 ? rating with { VoteCount = -3 } : rating).ToList() }; // Act - HttpResponseMessage response = await _client.PostAsJsonAsync("api/v1/books", bookRequest); + HttpResponseMessage response = await _client.PostAsJsonAsync("/api/v1/books", bookRequest); // Assert - await AssertBadRequestWithValidationErrors(response, Errors.Metadata.RatingVoteCountMustBePositive.Code); + await AssertUnprocessableEntityWithValidationErrors(response, Errors.Metadata.RatingVoteCountMustBePositive.Description); } - private static async Task AssertBadRequestWithValidationErrors(HttpResponseMessage response, params string[] expectedErrorCodes) + private async Task AssertUnprocessableEntityWithValidationErrors(HttpResponseMessage response, params string[] expectedErrorCodes) { - response.StatusCode.Should().Be(HttpStatusCode.BadRequest); + response.StatusCode.Should().Be(HttpStatusCode.UnprocessableContent); response.Content.Headers.ContentType?.MediaType.Should().Be("application/problem+json"); - ProblemDetails? problemDetails = await response.Content.ReadFromJsonAsync(); + string content = await response.Content.ReadAsStringAsync(); + Dictionary? problemDetails = JsonSerializer.Deserialize>(content, _jsonOptions); problemDetails.Should().NotBeNull(); - problemDetails!.Type.Should().Be("https://tools.ietf.org/html/rfc9110#section-15.5.1"); - problemDetails.Title.Should().Be("One or more validation errors occurred."); // TODO: update when localization is implemented - problemDetails.Status.Should().Be(400); + problemDetails!["status"].GetInt32().Should().Be(StatusCodes.Status422UnprocessableEntity); + problemDetails["title"].GetString().Should().Be("Validation Error"); + problemDetails["instance"].GetString().Should().Be("/api/v1/books"); + problemDetails["detail"].GetString().Should().Be("One or more validation errors occurred."); + problemDetails["type"].GetString().Should().Be("https://tools.ietf.org/html/rfc4918#section-11.2"); + problemDetails["traceId"].GetString().Should().NotBeNullOrWhiteSpace(); - JsonElement? errors = problemDetails.Extensions["errors"] as JsonElement?; - errors.Should().NotBeNull(); - - List actualErrorCodes = []; - foreach (JsonProperty property in errors!.Value.EnumerateObject()) - actualErrorCodes.AddRange(property.Value.EnumerateArray().Select(e => e.GetString()!)); - actualErrorCodes.Should().Contain(expectedErrorCodes, because: "all expected error codes should be present"); - Console.WriteLine($"All error codes: {string.Join(", ", actualErrorCodes)}"); - - problemDetails.Extensions.Should().ContainKey("traceId"); - problemDetails.Extensions["traceId"]!.ToString().Should().MatchRegex(@"^[\da-f]{2}-[\da-f]{32}-[\da-f]{16}-[\da-f]{2}$"); + Dictionary? errors = problemDetails["errors"].Deserialize>(_jsonOptions); + errors.Should().ContainKey("General.Validation").WhoseValue.Should().Contain(expectedErrorCodes); } private async Task AssertCreated(AddBookRequest bookRequest) { - HttpResponseMessage response = await _client.PostAsJsonAsync("api/v1/books", bookRequest); + HttpResponseMessage response = await _client.PostAsJsonAsync("/api/v1/books", bookRequest); response.EnsureSuccessStatusCode(); Book? bookResponse = await response.Content.ReadFromJsonAsync(_jsonOptions); response.StatusCode.Should().Be(HttpStatusCode.Created); diff --git a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Controllers/WrittenContentLibrary/BookLibrary/Books/Fixtures/AddBookRequestFixture.cs b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/WrittenContentLibrary/BookLibrary/Books/Fixtures/AddBookRequestFixture.cs similarity index 70% rename from tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Controllers/WrittenContentLibrary/BookLibrary/Books/Fixtures/AddBookRequestFixture.cs rename to tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/WrittenContentLibrary/BookLibrary/Books/Fixtures/AddBookRequestFixture.cs index 402f05ce..91ae03fb 100644 --- a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Controllers/WrittenContentLibrary/BookLibrary/Books/Fixtures/AddBookRequestFixture.cs +++ b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/WrittenContentLibrary/BookLibrary/Books/Fixtures/AddBookRequestFixture.cs @@ -1,12 +1,12 @@ #region ========================================================================= USING ===================================================================================== using AutoFixture; using Bogus; +using Lumina.Contracts.Entities.Common; +using Lumina.Contracts.Entities.MediaContributors; +using Lumina.Contracts.Entities.WrittenContentLibrary; +using Lumina.Contracts.Entities.WrittenContentLibrary.BookLibrary; using Lumina.Contracts.Enums.BookLibrary; -using Lumina.Contracts.Models.Common; -using Lumina.Contracts.Models.MediaContributors; -using Lumina.Contracts.Models.WrittenContentLibrary; -using Lumina.Contracts.Models.WrittenContentLibrary.BookLibrary; -using Lumina.Contracts.Requests.WrittenContentLibrary.BookLibrary; +using Lumina.Contracts.Requests.WrittenContentLibrary.BookLibrary.Books; using Lumina.Presentation.Api.IntegrationTests.Common.Setup; using System; using System.Collections.Generic; @@ -14,7 +14,7 @@ using System.Diagnostics.CodeAnalysis; using System.Linq; #endregion -namespace Lumina.Presentation.Api.IntegrationTests.Core.Controllers.Books.Fixtures; +namespace Lumina.Presentation.Api.IntegrationTests.Core.Endpoints.WrittenContentLibrary.BookLibrary.Books.Fixtures; /// /// Fixture class for the class. @@ -46,8 +46,8 @@ public class AddBookRequestFixture int releaseYear = _random.Next(2000, 2010); int reReleaseYear = _random.Next(2010, 2020); - ReleaseInfoModel releaseInfo = new Faker() - .CustomInstantiator(f => new ReleaseInfoModel( + ReleaseInfoEntity releaseInfo = new Faker() + .CustomInstantiator(f => new ReleaseInfoEntity( default, default, default, @@ -63,44 +63,44 @@ public class AddBookRequestFixture .RuleFor(x => x.ReleaseVersion, f => f.Random.String2(f.Random.Number(1, 50))) .Generate(); - Faker genre = new Faker() - .CustomInstantiator(f => new GenreModel( + Faker genre = new Faker() + .CustomInstantiator(f => new GenreEntity( default! )) .RuleFor(e => e.Name, f => f.Random.String2(f.Random.Number(1, 50))); - Faker tag = new Faker() - .CustomInstantiator(f => new TagModel( + Faker tag = new Faker() + .CustomInstantiator(f => new TagEntity( default! )) .RuleFor(e => e.Name, f => f.Random.String2(f.Random.Number(1, 50))); - Faker mediaContributorRole = new Faker() - .CustomInstantiator(f => new MediaContributorRoleModel( + Faker mediaContributorRole = new Faker() + .CustomInstantiator(f => new MediaContributorRoleEntity( default!, default! )) .RuleFor(e => e.Name, f => f.Random.String2(f.Random.Number(1, 50))) .RuleFor(e => e.Category, f => f.Random.String2(f.Random.Number(1, 50))); - Faker mediaContributorName = new Faker() - .CustomInstantiator(f => new MediaContributorNameModel( + Faker mediaContributorName = new Faker() + .CustomInstantiator(f => new MediaContributorNameEntity( default!, default! )) .RuleFor(e => e.DisplayName, f => f.Random.String2(f.Random.Number(1, 50))) .RuleFor(e => e.LegalName, f => f.Random.String2(f.Random.Number(1, 50))); - Faker mediaContributor = new Faker() - .CustomInstantiator(f => new MediaContributorModel( + Faker mediaContributor = new Faker() + .CustomInstantiator(f => new MediaContributorEntity( default!, default! )) .RuleFor(e => e.Name, mediaContributorName) .RuleFor(e => e.Role, mediaContributorRole); - Faker rating = new Faker() - .CustomInstantiator(f => new BookRatingModel( + Faker rating = new Faker() + .CustomInstantiator(f => new BookRatingEntity( default, default, default, @@ -111,8 +111,8 @@ public class AddBookRequestFixture .RuleFor(e => e.Source, _fixture.Create()) .RuleFor(e => e.VoteCount, _random.Next(1, 1000)); - Faker language = new Faker() - .CustomInstantiator(f => new LanguageInfoModel( + Faker language = new Faker() + .CustomInstantiator(f => new LanguageInfoEntity( default!, default!, default @@ -121,8 +121,8 @@ public class AddBookRequestFixture .RuleFor(e => e.LanguageCode, f => f.Random.String2(2)) .RuleFor(e => e.NativeName, f => f.Random.String2(f.Random.Number(1, 50))); - Faker originalLanguage = new Faker() - .CustomInstantiator(f => new LanguageInfoModel( + Faker originalLanguage = new Faker() + .CustomInstantiator(f => new LanguageInfoEntity( default!, default!, default @@ -131,8 +131,8 @@ public class AddBookRequestFixture .RuleFor(e => e.LanguageCode, f => f.Random.String2(2)) .RuleFor(e => e.NativeName, f => f.Random.String2(f.Random.Number(1, 50))); - Faker metadata = new Faker() - .CustomInstantiator(f => new WrittenContentMetadataModel( + Faker metadata = new Faker() + .CustomInstantiator(f => new WrittenContentMetadataEntity( default!, default, default, @@ -155,8 +155,8 @@ public class AddBookRequestFixture .RuleFor(x => x.Publisher, f => f.Random.String2(f.Random.Number(1, 100))) .RuleFor(x => x.PageCount, _random.Next(100, 300)); - Faker isbn = new Faker() - .CustomInstantiator(f => new IsbnModel( + Faker isbn = new Faker() + .CustomInstantiator(f => new IsbnEntity( default!, default )) @@ -272,72 +272,4 @@ public class AddBookRequestFixture .RuleFor(p => p.Ratings, f => rating.Generate(f.Random.Number(1, 5))) .RuleFor(x => x.Contributors, f => mediaContributor.Generate(f.Random.Number(1, 5))); } - - private void ConfigureCustomRequestTypes() - { - int releaseYear = _random.Next(2000, 2010); - int reReleaseYear = _random.Next(2010, 2020); - - _fixture.Register(() => new ReleaseInfoModel( - _faker.DateOnlyBetween(new DateOnly(releaseYear, 1, 1), new DateOnly(releaseYear, 12, 31)), - releaseYear, - _faker.DateOnlyBetween(new DateOnly(reReleaseYear, 1, 1), new DateOnly(reReleaseYear, 12, 31)), - reReleaseYear, - _fixture.Create()[2..], - _fixture.Create())); - - _fixture.Register(() => new GenreModel( - _fixture.Create() - )); - _fixture.Register(() => new TagModel( - _fixture.Create() - )); - _fixture.Register(() => new LanguageInfoModel( - _fixture.Create(), - _fixture.Create(), - _fixture.Create() - )); - _fixture.Register(() => new IsbnModel( - _fixture.Create(), - _fixture.Create() - )); - _fixture.Register(() => new BookRatingModel( - _fixture.Create(), - _fixture.Create(), - _fixture.Create(), - _fixture.Create() - )); - _fixture.Register(() => new WrittenContentMetadataModel( - _fixture.Create()[255..], - LimitStringLength(_fixture.Create(), 255), - LimitStringLength(_fixture.Create(), 2000), - _fixture.Create(), - _fixture.Create>(), - _fixture.Create>(), - _fixture.Create(), - _fixture.Create(), - _fixture.Create(), - _fixture.Create() - )); - _fixture.Register(() => new BookSeriesModel( - _fixture.Create() - )); - _fixture.Register(() => new MediaContributorRoleModel( - _fixture.Create(), - _fixture.Create() - )); - _fixture.Register(() => new MediaContributorNameModel( - _fixture.Create(), - _fixture.Create() - )); - _fixture.Register(() => new MediaContributorModel( - _fixture.Create(), - _fixture.Create() - )); - } - - private static string? LimitStringLength(string? input, int maxLength) - { - return input?.Length > maxLength ? input[..maxLength] : input; - } } diff --git a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Controllers/WrittenContentLibrary/BookLibrary/Books/Fixtures/DomainBookFixture.cs b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/WrittenContentLibrary/BookLibrary/Books/Fixtures/DomainBookFixture.cs similarity index 97% rename from tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Controllers/WrittenContentLibrary/BookLibrary/Books/Fixtures/DomainBookFixture.cs rename to tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/WrittenContentLibrary/BookLibrary/Books/Fixtures/DomainBookFixture.cs index 7bad9004..1d63a096 100644 --- a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Controllers/WrittenContentLibrary/BookLibrary/Books/Fixtures/DomainBookFixture.cs +++ b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/WrittenContentLibrary/BookLibrary/Books/Fixtures/DomainBookFixture.cs @@ -13,7 +13,7 @@ using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; #endregion -namespace Lumina.Presentation.Api.IntegrationTests.Core.Controllers.Books.Fixtures; +namespace Lumina.Presentation.Api.IntegrationTests.Core.Endpoints.WrittenContentLibrary.BookLibrary.Books.Fixtures; /// /// Fixture class for the domain entity. diff --git a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/WrittenContentLibrary/BookLibrary/Books/GetBooksEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/WrittenContentLibrary/BookLibrary/Books/GetBooksEndpointTests.cs new file mode 100644 index 00000000..3b79f349 --- /dev/null +++ b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/WrittenContentLibrary/BookLibrary/Books/GetBooksEndpointTests.cs @@ -0,0 +1,86 @@ +#region ========================================================================= USING ===================================================================================== +using FluentAssertions; +using Lumina.Domain.Core.Aggregates.WrittenContentLibrary.BookLibraryAggregate; +using Lumina.Presentation.Api.IntegrationTests.Common.Setup; +using Microsoft.AspNetCore.Http; +using System; +using System.Diagnostics.CodeAnalysis; +using System.Net; +using System.Net.Http; +using System.Net.Http.Json; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Api.IntegrationTests.Core.Endpoints.WrittenContentLibrary.BookLibrary.Books; + +/// +/// Contains integration tests for the class. +/// +[ExcludeFromCodeCoverage] +public class GetBooksEndpointTests : IClassFixture +{ + private readonly HttpClient _client; + private readonly JsonSerializerOptions _jsonOptions = new() + { + ReferenceHandler = ReferenceHandler.Preserve, + PropertyNameCaseInsensitive = true, + Converters = { new JsonStringEnumConverter(JsonNamingPolicy.CamelCase) } + }; + + /// + /// Initializes a new instance of the class. + /// + /// Injected in-memory API factory. + public GetBooksEndpointTests(LuminaApiFactory apiFactory) + { + _client = apiFactory.CreateClient(); + } + + [Fact] + public async Task GetBooks_WhenCalled_ShouldReturnBooks() + { + // Arrange + HttpResponseMessage response = await _client.GetAsync("/api/v1/books"); + + // Act + response.EnsureSuccessStatusCode(); + + // Assert + response.EnsureSuccessStatusCode(); + response.StatusCode.Should().Be(HttpStatusCode.OK); + Book[]? bookResponse = await response.Content.ReadFromJsonAsync(_jsonOptions); + bookResponse.Should().NotBeNull(); + } + [Fact] + public async Task ExecuteAsync_WhenCalledWithCancellationToken_ShouldCompleteSuccessfully() + { + // Arrange + using CancellationTokenSource cts = new(TimeSpan.FromSeconds(5)); + + // Act + Func act = async () => await _client.GetAsync($"/api/v1/books", cts.Token); + + // Assert + await act.Should().NotThrowAsync(); + } + + [Fact] + public async Task ExecuteAsync_WhenCancellationTokenIsCancelled_ShouldThrowTaskCanceledException() + { + // Arrange + using CancellationTokenSource cts = new(); + + // Act + Func act = async () => + { + cts.Cancel(); // Cancel the token immediately + await _client.GetAsync($"/api/v1/books", cts.Token); + }; + + // Assert + await act.Should().ThrowAsync(); + } +} diff --git a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Lumina.Presentation.Api.IntegrationTests.csproj b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Lumina.Presentation.Api.IntegrationTests.csproj index 91980a4b..cd3185ae 100644 --- a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Lumina.Presentation.Api.IntegrationTests.csproj +++ b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Lumina.Presentation.Api.IntegrationTests.csproj @@ -17,12 +17,12 @@ all runtime; build; native; contentfiles; analyzers; buildtransitive - - - - + + + + - + all runtime; build; native; contentfiles; analyzers; buildtransitive diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Common/Converters/Fixtures/OptionalJsonConverterFactoryFixture.cs b/tests/UnitTests/Lumina.Application.UnitTests/Common/Converters/Fixtures/OptionalJsonConverterFactoryFixture.cs deleted file mode 100644 index e4f39081..00000000 --- a/tests/UnitTests/Lumina.Application.UnitTests/Common/Converters/Fixtures/OptionalJsonConverterFactoryFixture.cs +++ /dev/null @@ -1,13 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using System.Diagnostics.CodeAnalysis; -#endregion - -namespace Lumina.Application.UnitTests.Common.Converters.Fixtures; - -/// -/// Fixture class for the class. -/// -[ExcludeFromCodeCoverage] -public class OptionalJsonConverterFactoryFixture -{ -} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Common/Converters/OptionalJsonConverterFactoryTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Common/Converters/OptionalJsonConverterFactoryTests.cs deleted file mode 100644 index 7ff52afb..00000000 --- a/tests/UnitTests/Lumina.Application.UnitTests/Common/Converters/OptionalJsonConverterFactoryTests.cs +++ /dev/null @@ -1,111 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using FluentAssertions; -using Lumina.Application.Common.Converters; -using Lumina.Application.UnitTests.Common.Converters.Fixtures; -using Lumina.Domain.Common.Primitives; -using System; -using System.Collections.Generic; -using System.Diagnostics.CodeAnalysis; -using System.Text.Json; -using System.Text.Json.Serialization; -#endregion - -namespace Lumina.Application.UnitTests.Common.Converters; - -/// -/// Contains unit tests for the class. -/// -[ExcludeFromCodeCoverage] -public class OptionalJsonConverterFactoryTests -{ - private readonly OptionalJsonConverterFactory _factory; - - /// - /// Initializes a new instance of the class. - /// - public OptionalJsonConverterFactoryTests() - { - _factory = new OptionalJsonConverterFactory(); - } - - [Fact] - public void CanConvert_WhenTypeIsOptional_ShouldReturnTrue() - { - // Arrange - Type typeToConvert = typeof(Optional); - - // Act - bool result = _factory.CanConvert(typeToConvert); - - // Assert - result.Should().BeTrue(); - } - - [Fact] - public void CanConvert_WhenTypeIsNotOptional_ShouldReturnFalse() - { - // Arrange - Type typeToConvert = typeof(string); - - // Act - bool result = _factory.CanConvert(typeToConvert); - - // Assert - result.Should().BeFalse(); - } - - [Fact] - public void CanConvert_WhenTypeIsGenericButNotOptional_ShouldReturnFalse() - { - // Arrange - Type typeToConvert = typeof(List); - - // Act - bool result = _factory.CanConvert(typeToConvert); - - // Assert - result.Should().BeFalse(); - } - - [Fact] - public void CreateConverter_WhenTypeIsOptionalString_ShouldReturnCorrectConverterType() - { - // Arrange - Type typeToConvert = typeof(Optional); - JsonSerializerOptions options = new(); - - // Act - JsonConverter converter = _factory.CreateConverter(typeToConvert, options); - - // Assert - converter.Should().BeOfType>(); - } - - [Fact] - public void CreateConverter_WhenTypeIsOptionalInt_ShouldReturnCorrectConverterType() - { - // Arrange - Type typeToConvert = typeof(Optional); - JsonSerializerOptions options = new(); - - // Act - JsonConverter converter = _factory.CreateConverter(typeToConvert, options); - - // Assert - converter.Should().BeOfType>(); - } - - [Fact] - public void CreateConverter_WhenTypeIsOptionalCustomClass_ShouldReturnCorrectConverterType() - { - // Arrange - Type typeToConvert = typeof(Optional); - JsonSerializerOptions options = new(); - - // Act - JsonConverter converter = _factory.CreateConverter(typeToConvert, options); - - // Assert - converter.Should().BeOfType>(); - } -} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Common/Converters/OptionalJsonConverterTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Common/Converters/OptionalJsonConverterTests.cs deleted file mode 100644 index 0114ddfc..00000000 --- a/tests/UnitTests/Lumina.Application.UnitTests/Common/Converters/OptionalJsonConverterTests.cs +++ /dev/null @@ -1,136 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using FluentAssertions; -using Lumina.Application.Common.Converters; -using Lumina.Domain.Common.Primitives; -using System.Diagnostics.CodeAnalysis; -using System.Text.Json; -#endregion - -namespace Lumina.Application.UnitTests.Common.Converters; - -/// -/// Contains unit tests for the class. -/// -[ExcludeFromCodeCoverage] -public class OptionalJsonConverterTests -{ - private readonly JsonSerializerOptions _options; - - /// - /// Initializes a new instance of the class. - /// - public OptionalJsonConverterTests() - { - _options = new JsonSerializerOptions(); - _options.Converters.Add(new OptionalJsonConverter()); - _options.Converters.Add(new OptionalJsonConverter()); - } - - [Fact] - public void Read_WhenJsonIsNull_ShouldReturnNone() - { - // Arrange - string json = "null"; - - // Act - Optional result = JsonSerializer.Deserialize>(json, _options); - - // Assert - result.HasValue.Should().BeFalse(); - } - - [Fact] - public void Read_WhenJsonHasStringValue_ShouldReturnSomeWithCorrectValue() - { - // Arrange - string json = "\"test\""; - - // Act - Optional result = JsonSerializer.Deserialize>(json, _options); - - // Assert - result.HasValue.Should().BeTrue(); - result.Value.Should().Be("test"); - } - - [Fact] - public void Read_WhenJsonHasIntValue_ShouldReturnSomeWithCorrectValue() - { - // Arrange - string json = "42"; - - // Act - Optional result = JsonSerializer.Deserialize>(json, _options); - - // Assert - result.HasValue.Should().BeTrue(); - result.Value.Should().Be(42); - } - - [Fact] - public void Write_WhenOptionalHasNoValue_ShouldWriteNull() - { - // Arrange - Optional optional = Optional.None(); - - // Act - string json = JsonSerializer.Serialize(optional, _options); - - // Assert - json.Should().Be("null"); - } - - [Fact] - public void Write_WhenOptionalHasStringValue_ShouldWriteCorrectJson() - { - // Arrange - Optional optional = Optional.Some("test"); - - // Act - string json = JsonSerializer.Serialize(optional, _options); - - // Assert - json.Should().Be("\"test\""); - } - - [Fact] - public void Write_WhenOptionalHasIntValue_ShouldWriteCorrectJson() - { - // Arrange - Optional optional = Optional.Some(42); - - // Act - string json = JsonSerializer.Serialize(optional, _options); - - // Assert - json.Should().Be("42"); - } - - [Fact] - public void ReadWrite_WhenSerializingAndDeserializingSomeValue_ShouldPreserveValue() - { - // Arrange - Optional original = Optional.Some("test"); - - // Act - string json = JsonSerializer.Serialize(original, _options); - Optional deserialized = JsonSerializer.Deserialize>(json, _options); - - // Assert - deserialized.Should().Be(original); - } - - [Fact] - public void ReadWrite_WhenSerializingAndDeserializingNone_ShouldPreserveNone() - { - // Arrange - Optional original = Optional.None(); - - // Act - string json = JsonSerializer.Serialize(original, _options); - Optional deserialized = JsonSerializer.Deserialize>(json, _options); - - // Assert - deserialized.Should().Be(original); - } -} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Common/Metadata/GenreMappingTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Common/Metadata/GenreMappingTests.cs new file mode 100644 index 00000000..f3e0c158 --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Common/Metadata/GenreMappingTests.cs @@ -0,0 +1,78 @@ +#region ========================================================================= USING ===================================================================================== +using ErrorOr; +using FluentAssertions; +using Lumina.Application.Common.Mapping.Common.Metadata; +using Lumina.Contracts.Entities.Common; +using Lumina.Domain.Common.ValueObjects.Metadata; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Application.UnitTests.Common.Mapping.Common.Metadata; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class GenreMappingTests +{ + [Fact] + public void ToRepositoryEntity_WhenMappingGenre_ShouldMapCorrectly() + { + // Arrange + ErrorOr createResult = Genre.Create("Rock"); + createResult.IsError.Should().BeFalse(); + Genre genre = createResult.Value; + + // Act + GenreEntity result = genre.ToRepositoryEntity(); + + // Assert + result.Should().NotBeNull(); + result.Name.Should().Be(genre.Name); + } + + [Theory] + [InlineData("Rock")] + [InlineData("Jazz")] + [InlineData("Classical")] + [InlineData("Pop")] + public void ToRepositoryEntity_WhenMappingDifferentGenres_ShouldMapCorrectly(string name) + { + // Arrange + ErrorOr createResult = Genre.Create(name); + createResult.IsError.Should().BeFalse(); + Genre genre = createResult.Value; + + // Act + GenreEntity result = genre.ToRepositoryEntity(); + + // Assert + result.Should().NotBeNull(); + result.Name.Should().Be(genre.Name); + } + + [Fact] + public void ToRepositoryEntities_WhenMappingMultipleGenres_ShouldMapAllCorrectly() + { + // Arrange + List genres = + [ + Genre.Create("Rock").Value, + Genre.Create("Jazz").Value, + Genre.Create("Classical").Value, + Genre.Create("Pop").Value + ]; + + // Act + IEnumerable results = genres.ToRepositoryEntities(); + + // Assert + results.Should().NotBeNull(); + results.Should().HaveCount(genres.Count); + List resultList = results.ToList(); + for (int i = 0; i < genres.Count; i++) + resultList[i].Name.Should().Be(genres[i].Name); + } +} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Common/Metadata/GenreModelMappingTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Common/Metadata/GenreModelMappingTests.cs new file mode 100644 index 00000000..6a62c96c --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Common/Metadata/GenreModelMappingTests.cs @@ -0,0 +1,127 @@ +#region ========================================================================= USING ===================================================================================== +using ErrorOr; +using FluentAssertions; +using Lumina.Application.Common.Mapping.Common.Metadata; +using Lumina.Contracts.Entities.Common; +using Lumina.Domain.Common.ValueObjects.Metadata; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Application.UnitTests.Common.Mapping.Common.Metadata; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class GenreModelMappingTests +{ + [Fact] + public void ToDomainModel_WhenMappingValidGenreEntity_ShouldMapCorrectly() + { + // Arrange + GenreEntity genreEntity = new("Rock"); + + // Act + ErrorOr result = genreEntity.ToDomainModel(); + + // Assert + result.IsError.Should().BeFalse(); + result.Value.Should().NotBeNull(); + result.Value.Name.Should().Be(genreEntity.Name); + } + + [Theory] + [InlineData("Rock")] + [InlineData("Jazz")] + [InlineData("Classical")] + [InlineData("Pop")] + public void ToDomainModel_WhenMappingDifferentValidGenreEntities_ShouldMapCorrectly(string name) + { + // Arrange + GenreEntity genreEntity = new(name); + + // Act + ErrorOr result = genreEntity.ToDomainModel(); + + // Assert + result.IsError.Should().BeFalse(); + result.Value.Should().NotBeNull(); + result.Value.Name.Should().Be(genreEntity.Name); + } + + [Theory] + [InlineData("")] + [InlineData(" ")] + [InlineData(null)] + public void ToDomainModel_WhenMappingInvalidGenreEntity_ShouldReturnError(string? invalidName) + { + // Arrange + GenreEntity genreEntity = new(invalidName); + + // Act + ErrorOr result = genreEntity.ToDomainModel(); + + // Assert + result.IsError.Should().BeTrue(); + } + + [Fact] + public void ToDomainModels_WhenMappingMultipleValidGenreEntities_ShouldMapAllCorrectly() + { + // Arrange + List genreEntities = + [ + new GenreEntity("Rock"), + new GenreEntity("Jazz"), + new GenreEntity("Classical"), + new GenreEntity("Pop") + ]; + + // Act + IEnumerable> results = genreEntities.ToDomainModels(); + + // Assert + results.Should().NotBeNull(); + results.Should().HaveCount(genreEntities.Count); + + List> resultList = results.ToList(); + for (int i = 0; i < genreEntities.Count; i++) + { + resultList[i].IsError.Should().BeFalse(); + resultList[i].Value.Name.Should().Be(genreEntities[i].Name); + } + } + + [Fact] + public void ToDomainModels_WhenMappingMixedValidAndInvalidGenreEntities_ShouldReturnMixedResults() + { + // Arrange + List genreEntities = + [ + new GenreEntity("Rock"), + new GenreEntity(""), + new GenreEntity("Jazz"), + new GenreEntity(" ") + ]; + + // Act + IEnumerable> results = genreEntities.ToDomainModels(); + + // Assert + results.Should().NotBeNull(); + results.Should().HaveCount(genreEntities.Count); + + List> resultList = results.ToList(); + resultList[0].IsError.Should().BeFalse(); + resultList[0].Value.Name.Should().Be("Rock"); + + resultList[1].IsError.Should().BeTrue(); + + resultList[2].IsError.Should().BeFalse(); + resultList[2].Value.Name.Should().Be("Jazz"); + + resultList[3].IsError.Should().BeTrue(); + } +} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Common/Metadata/TagMappingTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Common/Metadata/TagMappingTests.cs new file mode 100644 index 00000000..11fb9538 --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Common/Metadata/TagMappingTests.cs @@ -0,0 +1,80 @@ +#region ========================================================================= USING ===================================================================================== +using ErrorOr; +using FluentAssertions; +using Lumina.Application.Common.Mapping.Common.Metadata; +using Lumina.Contracts.Entities.Common; +using Lumina.Domain.Common.ValueObjects.Metadata; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Application.UnitTests.Common.Mapping.Common.Metadata; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class TagMappingTests +{ + [Fact] + public void ToRepositoryEntity_WhenMappingTag_ShouldMapCorrectly() + { + // Arrange + ErrorOr createResult = Tag.Create("indie"); + createResult.IsError.Should().BeFalse(); + Tag tag = createResult.Value; + + // Act + TagEntity result = tag.ToRepositoryEntity(); + + // Assert + result.Should().NotBeNull(); + result.Name.Should().Be(tag.Name); + } + + [Theory] + [InlineData("indie")] + [InlineData("electronic")] + [InlineData("instrumental")] + [InlineData("live")] + [InlineData("acoustic")] + public void ToRepositoryEntity_WhenMappingDifferentTags_ShouldMapCorrectly(string name) + { + // Arrange + ErrorOr createResult = Tag.Create(name); + createResult.IsError.Should().BeFalse(); + Tag tag = createResult.Value; + + // Act + TagEntity result = tag.ToRepositoryEntity(); + + // Assert + result.Should().NotBeNull(); + result.Name.Should().Be(tag.Name); + } + + [Fact] + public void ToRepositoryEntities_WhenMappingMultipleTags_ShouldMapAllCorrectly() + { + // Arrange + List tags = + [ + Tag.Create("indie").Value, + Tag.Create("electronic").Value, + Tag.Create("instrumental").Value, + Tag.Create("live").Value, + Tag.Create("acoustic").Value + ]; + + // Act + IEnumerable results = tags.ToRepositoryEntities(); + + // Assert + results.Should().NotBeNull(); + results.Should().HaveCount(tags.Count); + List resultList = results.ToList(); + for (int i = 0; i < tags.Count; i++) + resultList[i].Name.Should().Be(tags[i].Name); + } +} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Common/Metadata/TagModelMappingTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Common/Metadata/TagModelMappingTests.cs new file mode 100644 index 00000000..c626085a --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Common/Metadata/TagModelMappingTests.cs @@ -0,0 +1,128 @@ +#region ========================================================================= USING ===================================================================================== +using ErrorOr; +using FluentAssertions; +using Lumina.Application.Common.Mapping.Common.Metadata; +using Lumina.Contracts.Entities.Common; +using Lumina.Domain.Common.ValueObjects.Metadata; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Application.UnitTests.Common.Mapping.Common.Metadata; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class TagModelMappingTests +{ + [Fact] + public void ToDomainModel_WhenMappingValidTagEntity_ShouldMapCorrectly() + { + // Arrange + TagEntity tagEntity = new("indie"); + + // Act + ErrorOr result = tagEntity.ToDomainModel(); + + // Assert + result.IsError.Should().BeFalse(); + result.Value.Should().NotBeNull(); + result.Value.Name.Should().Be(tagEntity.Name); + } + + [Theory] + [InlineData("indie")] + [InlineData("electronic")] + [InlineData("instrumental")] + [InlineData("live")] + [InlineData("acoustic")] + public void ToDomainModel_WhenMappingDifferentValidTagEntities_ShouldMapCorrectly(string name) + { + // Arrange + TagEntity tagEntity = new(name); + + // Act + ErrorOr result = tagEntity.ToDomainModel(); + + // Assert + result.IsError.Should().BeFalse(); + result.Value.Should().NotBeNull(); + result.Value.Name.Should().Be(tagEntity.Name); + } + + [Theory] + [InlineData("")] + [InlineData(" ")] + [InlineData(null)] + public void ToDomainModel_WhenMappingInvalidTagEntity_ShouldReturnError(string? invalidName) + { + // Arrange + TagEntity tagEntity = new(invalidName); + + // Act + ErrorOr result = tagEntity.ToDomainModel(); + + // Assert + result.IsError.Should().BeTrue(); + } + + [Fact] + public void ToDomainModels_WhenMappingMultipleValidTagEntities_ShouldMapAllCorrectly() + { + // Arrange + List tagEntities = + [ + new TagEntity("indie"), + new TagEntity("electronic"), + new TagEntity("instrumental"), + new TagEntity("live") + ]; + + // Act + IEnumerable> results = tagEntities.ToDomainModels(); + + // Assert + results.Should().NotBeNull(); + results.Should().HaveCount(tagEntities.Count); + + List> resultList = results.ToList(); + for (int i = 0; i < tagEntities.Count; i++) + { + resultList[i].IsError.Should().BeFalse(); + resultList[i].Value.Name.Should().Be(tagEntities[i].Name); + } + } + + [Fact] + public void ToDomainModels_WhenMappingMixedValidAndInvalidTagEntities_ShouldReturnMixedResults() + { + // Arrange + List tagEntities = + [ + new TagEntity("indie"), + new TagEntity(""), + new TagEntity("electronic"), + new TagEntity(" ") + ]; + + // Act + IEnumerable> results = tagEntities.ToDomainModels(); + + // Assert + results.Should().NotBeNull(); + results.Should().HaveCount(tagEntities.Count); + + List> resultList = results.ToList(); + resultList[0].IsError.Should().BeFalse(); + resultList[0].Value.Name.Should().Be("indie"); + + resultList[1].IsError.Should().BeTrue(); + + resultList[2].IsError.Should().BeFalse(); + resultList[2].Value.Name.Should().Be("electronic"); + + resultList[3].IsError.Should().BeTrue(); + } +} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/FileManagement/DirectoryMappingConfigTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/FileManagement/DirectoryMappingConfigTests.cs deleted file mode 100644 index 50a5b555..00000000 --- a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/FileManagement/DirectoryMappingConfigTests.cs +++ /dev/null @@ -1,113 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using FluentAssertions; -using Lumina.Application.Common.Mapping.FileManagement; -using Lumina.Application.UnitTests.Core.FileManagement.Directories.Fixtures; -using Lumina.Contracts.Models.FileManagement; -using Lumina.Contracts.Responses.FileManagement; -using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate; -using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.Entities; -using Mapster; -using System; -using System.Collections.Generic; -using System.Diagnostics.CodeAnalysis; -#endregion - -namespace Lumina.Application.UnitTests.Common.Mapping.FileManagement; - -/// -/// Contains unit tests for the class. -/// -[ExcludeFromCodeCoverage] -public class DirectoryMappingConfigTests -{ - private readonly TypeAdapterConfig _config; - private readonly DirectoryMappingConfig _directoryMappingConfig; - private readonly FileSystemTreeMappingConfig _fileSystemTreeMappingConfig; - - public DirectoryMappingConfigTests() - { - _config = new TypeAdapterConfig(); - _directoryMappingConfig = new DirectoryMappingConfig(); - _fileSystemTreeMappingConfig = new FileSystemTreeMappingConfig(); - _directoryMappingConfig.Register(_config); - _fileSystemTreeMappingConfig.Register(_config); - } - - [Fact] - public void Register_WhenMappingDirectoryToFileSystemTreeNodeResponse_ShouldMapCorrectly() - { - // Arrange - DirectoryFixture directoryFixture = new(); - Directory directory = directoryFixture.CreateDirectory(); - - // create some child items - List childItems = - [ - directoryFixture.CreateDirectory(), - directoryFixture.CreateDirectory() - ]; - foreach (FileSystemItem item in childItems) - directory.AddItem(item); - - // Act - FileSystemTreeNodeResponse result = directory.Adapt(_config); - - // Assert - result.Should().NotBeNull(); - result.Name.Should().Be(directory.Name); - result.Path.Should().Be(directory.Id.Path); - result.ItemType.Should().Be(directory.Type); - result.IsExpanded.Should().BeFalse(); - result.ChildrenLoaded.Should().BeFalse(); - result.Children.Should().NotBeNull(); - result.Children.Should().HaveCount(childItems.Count); - - // Verify that each child item is correctly mapped - for (int i = 0; i < childItems.Count; i++) - { - result.Children[i].Name.Should().Be(childItems[i].Name); - result.Children[i].Path.Should().Be(childItems[i].Id.Path); - result.Children[i].ItemType.Should().Be(childItems[i].Type); - } - } - - [Fact] - public void Register_WhenMappingDirectoryToDirectoryResponse_ShouldMapCorrectly() - { - // Arrange - DirectoryFixture directoryFixture = new(); - Directory directory = directoryFixture.CreateDirectory(); - - // Act - DirectoryResponse result = directory.Adapt(_config); - - // Assert - result.Should().NotBeNull(); - result.Path.Should().Be(directory.Id.Path); - result.Name.Should().Be(directory.Name); - result.DateCreated.Should().Be(directory.DateCreated.Value); - result.DateModified.Should().Be(directory.DateModified.Value); - result.Items.Should().BeAssignableTo>(); - result.Items.Should().HaveCount(directory.Items.Count); - } - - [Fact] - public void Register_WhenMappingDirectoryToFileSystemItemModel_ShouldMapCorrectly() - { - // Arrange - DirectoryFixture directoryFixture = new(); - Directory directory = directoryFixture.CreateDirectory(); - DateTime beforeMapping = DateTime.Now; - - // Act - FileSystemItemModel result = directory.Adapt(_config); - DateTime afterMapping = DateTime.Now; - - // Assert - result.Should().NotBeNull(); - result.Path.Should().Be(directory.Id.Path); - result.Name.Should().Be(directory.Name); - result.DateCreated.Should().BeOnOrAfter(beforeMapping).And.BeOnOrBefore(afterMapping); - result.DateModified.Should().BeOnOrAfter(beforeMapping).And.BeOnOrBefore(afterMapping); - } -} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/FileManagement/FileMappingConfigTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/FileManagement/FileMappingConfigTests.cs deleted file mode 100644 index 70dccc48..00000000 --- a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/FileManagement/FileMappingConfigTests.cs +++ /dev/null @@ -1,89 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using FluentAssertions; -using Lumina.Application.Common.Mapping.FileManagement; -using Lumina.Application.UnitTests.Core.FileManagement.Files.Fixtures; -using Lumina.Contracts.Responses.FileManagement; -using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.Entities; -using Mapster; -using System.Diagnostics.CodeAnalysis; -#endregion - -namespace Lumina.Application.UnitTests.Common.Mapping.FileManagement; - -/// -/// Contains unit tests for the class. -/// -[ExcludeFromCodeCoverage] -public class FileMappingConfigTests -{ - private readonly TypeAdapterConfig _config; - private readonly FileMappingConfig _fileMappingConfig; - private readonly FileSystemTreeMappingConfig _fileSystemTreeMappingConfig; - - public FileMappingConfigTests() - { - _config = new TypeAdapterConfig(); - _fileMappingConfig = new FileMappingConfig(); - _fileSystemTreeMappingConfig = new FileSystemTreeMappingConfig(); - _fileMappingConfig.Register(_config); - _fileSystemTreeMappingConfig.Register(_config); - } - - [Fact] - public void Register_WhenMappingFileToFileSystemTreeNodeResponse_ShouldMapCorrectly() - { - // Arrange - FileFixture fileFixture = new(); - File file = fileFixture.CreateFile(); - - // Act - FileSystemTreeNodeResponse result = file.Adapt(_config); - - // Assert - result.Should().NotBeNull(); - result.Name.Should().Be(file.Name); - result.Path.Should().Be(file.Id.Path); - result.ItemType.Should().Be(file.Type); - result.IsExpanded.Should().BeFalse(); - result.ChildrenLoaded.Should().BeFalse(); - result.Children.Should().BeEmpty(); - } - - [Fact] - public void Register_WhenMappingFileToFileResponse_ShouldMapCorrectly() - { - // Arrange - FileFixture fileFixture = new(); - File file = fileFixture.CreateFile(); - - // Act - FileResponse result = file.Adapt(_config); - - // Assert - result.Should().NotBeNull(); - result.Path.Should().Be(file.Id.Path); - result.Name.Should().Be(file.Name); - result.DateCreated.Should().Be(file.DateCreated.Value); - result.DateModified.Should().Be(file.DateModified.Value); - result.Size.Should().Be(file.Size); - } - - [Fact] - public void Register_WhenMappingFileToFileResponseWithoutDates_ShouldMapCorrectly() - { - // Arrange - FileFixture fileFixture = new(); - File file = FileFixture.CreateFileWithoutDates(); - - // Act - FileResponse result = file.Adapt(_config); - - // Assert - result.Should().NotBeNull(); - result.Path.Should().Be(file.Id.Path); - result.Name.Should().Be(file.Name); - result.DateCreated.Should().Be(default); - result.DateModified.Should().Be(default); - result.Size.Should().Be(file.Size); - } -} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/FileManagement/FileSystemTreeMappingConfigTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/FileManagement/FileSystemTreeMappingConfigTests.cs deleted file mode 100644 index ed8fd17f..00000000 --- a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/FileManagement/FileSystemTreeMappingConfigTests.cs +++ /dev/null @@ -1,158 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using FluentAssertions; -using Lumina.Application.Common.Mapping.FileManagement; -using Lumina.Application.UnitTests.Core.FileManagement.Directories.Fixtures; -using Lumina.Application.UnitTests.Core.FileManagement.Files.Fixtures; -using Lumina.Contracts.Enums.FileSystem; -using Lumina.Contracts.Responses.FileManagement; -using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.Entities; -using Mapster; -using System.Diagnostics.CodeAnalysis; -#endregion - -namespace Lumina.Application.UnitTests.Common.Mapping.FileManagement; - -/// -/// Contains unit tests for the class. -/// -[ExcludeFromCodeCoverage] -public class FileSystemTreeMappingConfigTests -{ - private readonly TypeAdapterConfig _config; - private readonly FileSystemTreeMappingConfig _fileSystemTreeMappingConfig; - - public FileSystemTreeMappingConfigTests() - { - _config = new TypeAdapterConfig(); - _fileSystemTreeMappingConfig = new FileSystemTreeMappingConfig(); - _fileSystemTreeMappingConfig.Register(_config); - } - - [Fact] - public void Register_WhenMappingWindowsRootItemToFileSystemTreeNodeResponse_ShouldMapCorrectly() - { - // Arrange - WindowsRootItem windowsRoot = WindowsRootItem.Create("C:", "C:").Value; - - // Act - FileSystemTreeNodeResponse result = windowsRoot.Adapt(_config); - - // Assert - result.Should().NotBeNull(); - result.Path.Should().Be(windowsRoot.Id.Path); - result.Name.Should().Be(windowsRoot.Name); - result.ItemType.Should().Be(FileSystemItemType.Root); - result.IsExpanded.Should().BeFalse(); - result.Children.Should().NotBeNull(); - result.Children.Should().BeEmpty(); - } - - [Fact] - public void Register_WhenMappingFileSystemTreeNodeResponseToWindowsRootItem_ShouldMapCorrectly() - { - // Arrange - FileSystemTreeNodeResponse response = new() - { - Path = "D:", - Name = "D:", - ItemType = FileSystemItemType.Root, - IsExpanded = false - }; - - // Act - WindowsRootItem result = response.Adapt(_config); - - // Assert - result.Should().NotBeNull(); - result.Id.Path.Should().Be(response.Path); - result.Name.Should().Be(response.Name); - result.Type.Should().Be(FileSystemItemType.Root); - result.Status.Should().Be(FileSystemItemStatus.Accessible); - } - - [Fact] - public void Register_WhenMappingUnixRootItemToFileSystemTreeNodeResponse_ShouldMapCorrectly() - { - // Arrange - UnixRootItem unixRoot = UnixRootItem.Create().Value; - - // Act - FileSystemTreeNodeResponse result = unixRoot.Adapt(_config); - - // Assert - result.Should().NotBeNull(); - result.Path.Should().Be(unixRoot.Id.Path); - result.Name.Should().Be(unixRoot.Name); - result.ItemType.Should().Be(FileSystemItemType.Root); - result.IsExpanded.Should().BeFalse(); - result.ChildrenLoaded.Should().BeFalse(); - result.Children.Should().NotBeNull(); - result.Children.Should().BeEmpty(); - } - - [Fact] - public void Register_WhenMappingFileSystemTreeNodeResponseToUnixRootItem_ShouldMapCorrectly() - { - // Arrange - FileSystemTreeNodeResponse response = new() - { - Path = "/", - Name = "/", - ItemType = FileSystemItemType.Root, - IsExpanded = false - }; - - // Act - UnixRootItem result = response.Adapt(_config); - - // Assert - result.Should().NotBeNull(); - result.Id.Path.Should().Be("/"); - result.Name.Should().Be("/"); - result.Type.Should().Be(FileSystemItemType.Root); - result.Status.Should().Be(FileSystemItemStatus.Accessible); - } - - [Fact] - public void Register_WhenMappingDirectoryToFileSystemTreeNodeResponse_ShouldMapCorrectly() - { - // Arrange - DirectoryFixture directoryFixture = new(); - Directory directory = directoryFixture.CreateDirectory(); - directory.AddItem(directoryFixture.CreateDirectory()); - directory.AddItem(directoryFixture.CreateDirectory()); - - // Act - FileSystemTreeNodeResponse result = directory.Adapt(_config); - - // Assert - result.Should().NotBeNull(); - result.Name.Should().Be(directory.Name); - result.Path.Should().Be(directory.Id.Path); - result.ItemType.Should().Be(directory.Type); - result.IsExpanded.Should().BeFalse(); - result.ChildrenLoaded.Should().BeFalse(); - result.Children.Should().NotBeNull(); - result.Children.Should().HaveCount(2); - } - - [Fact] - public void Register_WhenMappingFileToFileSystemTreeNodeResponse_ShouldMapCorrectly() - { - // Arrange - FileFixture fileFixture = new(); - File file = fileFixture.CreateFile(); - - // Act - FileSystemTreeNodeResponse result = file.Adapt(_config); - - // Assert - result.Should().NotBeNull(); - result.Name.Should().Be(file.Name); - result.Path.Should().Be(file.Id.Path); - result.ItemType.Should().Be(file.Type); - result.IsExpanded.Should().BeFalse(); - result.ChildrenLoaded.Should().BeFalse(); - result.Children.Should().BeEmpty(); - } -} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/FileManagement/ThumbnailMappingConfigTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/FileManagement/ThumbnailMappingConfigTests.cs deleted file mode 100644 index eddeb3e5..00000000 --- a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/FileManagement/ThumbnailMappingConfigTests.cs +++ /dev/null @@ -1,109 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using Bogus; -using FluentAssertions; -using Lumina.Application.Common.Mapping.FileManagement; -using Lumina.Contracts.Enums.PhotoLibrary; -using Lumina.Contracts.Responses.FileManagement; -using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.ValueObjects; -using Mapster; -using System.Collections.Generic; -using System.Diagnostics.CodeAnalysis; -#endregion - -namespace Lumina.Application.UnitTests.Common.Mapping.FileManagement; - -/// -/// Contains unit tests for the class. -/// -[ExcludeFromCodeCoverage] -public class ThumbnailMappingConfigTests -{ - private readonly TypeAdapterConfig _config; - private readonly ThumbnailMappingConfig _thumbnailMappingConfig; - private readonly Faker _faker; - - public ThumbnailMappingConfigTests() - { - _config = new TypeAdapterConfig(); - _thumbnailMappingConfig = new ThumbnailMappingConfig(); - _thumbnailMappingConfig.Register(_config); - _faker = new Faker(); - } - - [Fact] - public void Register_WhenMappingThumbnailToThumbnailResponse_ShouldMapCorrectly() - { - // Arrange - ImageType imageType = _faker.PickRandom(); - byte[] bytes = _faker.Random.Bytes(100); - Thumbnail thumbnail = new(imageType, bytes); - - // Act - ThumbnailResponse result = thumbnail.Adapt(_config); - - // Assert - result.Should().NotBeNull(); - result.Type.Should().Be(thumbnail.Type); - result.Bytes.Should().BeEquivalentTo(thumbnail.Bytes); - } - - [Theory] - [InlineData(ImageType.JPEG)] - [InlineData(ImageType.PNG)] - [InlineData(ImageType.GIF)] - public void Register_WhenMappingDifferentImageTypes_ShouldMapCorrectly(ImageType imageType) - { - // Arrange - byte[] bytes = _faker.Random.Bytes(100); - Thumbnail thumbnail = new(imageType, bytes); - - // Act - ThumbnailResponse result = thumbnail.Adapt(_config); - - // Assert - result.Should().NotBeNull(); - result.Type.Should().Be(imageType); - result.Bytes.Should().BeEquivalentTo(bytes); - } - - [Fact] - public void Register_WhenMappingThumbnailWithEmptyBytes_ShouldMapCorrectly() - { - // Arrange - ImageType imageType = _faker.PickRandom(); - byte[] emptyBytes = []; - Thumbnail thumbnail = new(imageType, emptyBytes); - - // Act - ThumbnailResponse result = thumbnail.Adapt(_config); - - // Assert - result.Should().NotBeNull(); - result.Type.Should().Be(imageType); - result.Bytes.Should().BeEmpty(); - } - - [Fact] - public void Register_WhenMappingMultipleThumbnails_ShouldMapAllCorrectly() - { - // Arrange - List thumbnails = - [ - new Thumbnail(ImageType.JPEG, _faker.Random.Bytes(100)), - new Thumbnail(ImageType.PNG, _faker.Random.Bytes(200)), - new Thumbnail(ImageType.GIF, _faker.Random.Bytes(150)) - ]; - - // Act - List results = thumbnails.Adapt>(_config); - - // Assert - results.Should().NotBeNull(); - results.Should().HaveCount(thumbnails.Count); - for (int i = 0; i < thumbnails.Count; i++) - { - results[i].Type.Should().Be(thumbnails[i].Type); - results[i].Bytes.Should().BeEquivalentTo(thumbnails[i].Bytes); - } - } -} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/FileSystemManagement/Common/FileSystemTreeNodeResponseMappingTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/FileSystemManagement/Common/FileSystemTreeNodeResponseMappingTests.cs new file mode 100644 index 00000000..fe8bce3b --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/FileSystemManagement/Common/FileSystemTreeNodeResponseMappingTests.cs @@ -0,0 +1,61 @@ +#region ========================================================================= USING ===================================================================================== +using ErrorOr; +using FluentAssertions; +using Lumina.Application.Common.Mapping.FileSystemManagement.Common; +using Lumina.Application.UnitTests.Core.FileSystemManagement.Directories.Fixtures; +using Lumina.Contracts.Enums.FileSystem; +using Lumina.Contracts.Responses.FileSystemManagement.Common; +using Lumina.Domain.Core.Aggregates.FileSystemManagement.FileSystemManagementAggregate.Entities; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Application.UnitTests.Common.Mapping.FileSystemManagement.Common; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class FileSystemTreeNodeResponseMappingTests +{ + private readonly FileSystemTreeNodeResponseFixture _fileSystemTreeNodeResponseFixture; + + /// + /// Initializes a new instance of the class. + /// + public FileSystemTreeNodeResponseMappingTests() + { + _fileSystemTreeNodeResponseFixture = new(); + } + + [Fact] + public void ToWindowsRootItem_WhenMappingFileSystemTreeNodeResponse_ShouldMapCorrectly() + { + // Arrange + FileSystemTreeNodeResponse response = _fileSystemTreeNodeResponseFixture.Create(); + + // Act + ErrorOr result = response.ToWindowsRootItem(); + + // Assert + result.IsError.Should().BeFalse(); + result.Value.Should().NotBeNull(); + result.Value.Id.Path.Should().Be(response.Path); + result.Value.Name.Should().Be(response.Name); + result.Value.Status.Should().Be(FileSystemItemStatus.Accessible); + } + + [Fact] + public void ToUnixRootItem_WhenMappingFileSystemTreeNodeResponse_ShouldMapCorrectly() + { + // Arrange + FileSystemTreeNodeResponse response = _fileSystemTreeNodeResponseFixture.Create(); + + // Act + ErrorOr result = response.ToUnixRootItem(); + + // Assert + result.IsError.Should().BeFalse(); + result.Value.Should().NotBeNull(); + result.Value.Status.Should().Be(FileSystemItemStatus.Accessible); + } +} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/FileSystemManagement/Directories/DirectoryMappingTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/FileSystemManagement/Directories/DirectoryMappingTests.cs new file mode 100644 index 00000000..a5a9c6ce --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/FileSystemManagement/Directories/DirectoryMappingTests.cs @@ -0,0 +1,142 @@ +#region ========================================================================= USING ===================================================================================== +using FluentAssertions; +using Lumina.Application.Common.Mapping.FileSystemManagement.Directories; +using Lumina.Application.UnitTests.Core.FileSystemManagement.Directories.Fixtures; +using Lumina.Contracts.Responses.FileSystemManagement.Common; +using Lumina.Contracts.Responses.FileSystemManagement.Directories; +using Lumina.Domain.Core.Aggregates.FileSystemManagement.FileSystemManagementAggregate; +using Lumina.Domain.Core.Aggregates.FileSystemManagement.FileSystemManagementAggregate.Entities; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Application.UnitTests.Common.Mapping.FileSystemManagement.Directories; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class DirectoryMappingTests +{ + private readonly DirectoryFixture _directoryFixture; + + /// + /// Initializes a new instance of the class. + /// + public DirectoryMappingTests() + { + _directoryFixture = new DirectoryFixture(); + } + + [Fact] + public void ToFileSystemTreeNodeResponse_WhenMappingDirectory_ShouldMapCorrectly() + { + // Arrange + Directory directory = _directoryFixture.CreateDirectory(); + List childItems = + [ + _directoryFixture.CreateDirectory(), + _directoryFixture.CreateDirectory() + ]; + foreach (FileSystemItem item in childItems) + directory.AddItem(item); + + // Act + FileSystemTreeNodeResponse result = directory.ToFileSystemTreeNodeResponse(); + + // Assert + result.Should().NotBeNull(); + result.Name.Should().Be(directory.Name); + result.Path.Should().Be(directory.Id.Path); + result.ItemType.Should().Be(directory.Type); + result.IsExpanded.Should().BeFalse(); + result.ChildrenLoaded.Should().BeFalse(); + result.Children.Should().NotBeNull(); + result.Children.Should().HaveCount(childItems.Count); + + for (int i = 0; i < childItems.Count; i++) + { + result.Children[i].Name.Should().Be(childItems[i].Name); + result.Children[i].Path.Should().Be(childItems[i].Id.Path); + result.Children[i].ItemType.Should().Be(childItems[i].Type); + } + } + + [Fact] + public void ToFileSystemTreeNodeResponses_WhenMappingMultipleDirectories_ShouldMapCorrectly() + { + // Arrange + List directories = _directoryFixture.CreateMany(2); + + // Act + IEnumerable result = directories.ToFileSystemTreeNodeResponses(); + + // Assert + result.Should().NotBeNull(); + result.Should().HaveCount(directories.Count); + + List resultList = result.ToList(); + for (int i = 0; i < directories.Count; i++) + { + resultList[i].Name.Should().Be(directories[i].Name); + resultList[i].Path.Should().Be(directories[i].Id.Path); + resultList[i].ItemType.Should().Be(directories[i].Type); + } + } + + [Fact] + public void ToResponse_WhenMappingDirectory_ShouldMapCorrectly() + { + // Arrange + Directory directory = _directoryFixture.CreateDirectory(); + List childItems = + [ + _directoryFixture.CreateDirectory(), + _directoryFixture.CreateDirectory() + ]; + foreach (FileSystemItem item in childItems) + directory.AddItem(item); + + // Act + DirectoryResponse result = directory.ToResponse(); + + // Assert + result.Should().NotBeNull(); + result.Path.Should().Be(directory.Id.Path); + result.Name.Should().Be(directory.Name); + result.DateCreated.Should().Be(directory.DateCreated.Value); + result.DateModified.Should().Be(directory.DateModified.Value); + result.Items.Should().NotBeNull(); + result.Items.Should().HaveCount(childItems.Count); + + for (int i = 0; i < childItems.Count; i++) + { + result.Items[i].Name.Should().Be(childItems[i].Name); + result.Items[i].Path.Should().Be(childItems[i].Id.Path); + } + } + + [Fact] + public void ToResponses_WhenMappingMultipleDirectories_ShouldMapCorrectly() + { + // Arrange + List directories = _directoryFixture.CreateMany(2); + + // Act + IEnumerable result = directories.ToResponses(); + + // Assert + result.Should().NotBeNull(); + result.Should().HaveCount(directories.Count); + + List resultList = result.ToList(); + for (int i = 0; i < directories.Count; i++) + { + resultList[i].Path.Should().Be(directories[i].Id.Path); + resultList[i].Name.Should().Be(directories[i].Name); + resultList[i].DateCreated.Should().Be(directories[i].DateCreated.Value); + resultList[i].DateModified.Should().Be(directories[i].DateModified.Value); + } + } +} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/FileSystemManagement/Directories/GetDirectoriesRequestMappingTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/FileSystemManagement/Directories/GetDirectoriesRequestMappingTests.cs new file mode 100644 index 00000000..aff63f6a --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/FileSystemManagement/Directories/GetDirectoriesRequestMappingTests.cs @@ -0,0 +1,43 @@ +#region ========================================================================= USING ===================================================================================== +using AutoFixture; +using AutoFixture.AutoNSubstitute; +using FluentAssertions; +using Lumina.Application.Common.Mapping.FileSystemManagement.Directories; +using Lumina.Application.Core.FileSystemManagement.Directories.Queries.GetDirectories; +using Lumina.Contracts.Requests.FileSystemManagement.Directories; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Application.UnitTests.Common.Mapping.FileSystemManagement.Directories; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class GetDirectoriesRequestMappingTests +{ + private readonly IFixture _fixture; + + /// + /// Initializes a new instance of the class. + /// + public GetDirectoriesRequestMappingTests() + { + _fixture = new Fixture().Customize(new AutoNSubstituteCustomization()); + } + + [Fact] + public void ToQuery_WhenMappingGetDirectoriesRequest_ShouldMapCorrectly() + { + // Arrange + GetDirectoriesRequest request = _fixture.Create(); + + // Act + GetDirectoriesQuery result = request.ToQuery(); + + // Assert + result.Should().NotBeNull(); + result.Path.Should().Be(request.Path); + result.IncludeHiddenElements.Should().Be(request.IncludeHiddenElements); + } +} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/FileSystemManagement/Directories/GetDirectoryTreeRequestMappingTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/FileSystemManagement/Directories/GetDirectoryTreeRequestMappingTests.cs new file mode 100644 index 00000000..7520a091 --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/FileSystemManagement/Directories/GetDirectoryTreeRequestMappingTests.cs @@ -0,0 +1,44 @@ +#region ========================================================================= USING ===================================================================================== +using AutoFixture; +using AutoFixture.AutoNSubstitute; +using FluentAssertions; +using Lumina.Application.Common.Mapping.FileSystemManagement.Directories; +using Lumina.Application.Core.FileSystemManagement.Directories.Queries.GetDirectoryTree; +using Lumina.Contracts.Requests.FileSystemManagement.Directories; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Application.UnitTests.Common.Mapping.FileSystemManagement.Directories; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class GetDirectoryTreeRequestMappingTests +{ + private readonly IFixture _fixture; + + /// + /// Initializes a new instance of the class. + /// + public GetDirectoryTreeRequestMappingTests() + { + _fixture = new Fixture().Customize(new AutoNSubstituteCustomization()); + } + + [Fact] + public void ToQuery_WhenMappingGetDirectoryTreeRequest_ShouldMapCorrectly() + { + // Arrange + GetDirectoryTreeRequest request = _fixture.Create(); + + // Act + GetDirectoryTreeQuery result = request.ToQuery(); + + // Assert + result.Should().NotBeNull(); + result.Path.Should().Be(request.Path); + result.IncludeFiles.Should().Be(request.IncludeFiles); + result.IncludeHiddenElements.Should().Be(request.IncludeHiddenElements); + } +} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/FileSystemManagement/Directories/GetTreeDirectoriesRequestMappingTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/FileSystemManagement/Directories/GetTreeDirectoriesRequestMappingTests.cs new file mode 100644 index 00000000..4f249fc1 --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/FileSystemManagement/Directories/GetTreeDirectoriesRequestMappingTests.cs @@ -0,0 +1,43 @@ +#region ========================================================================= USING ===================================================================================== +using AutoFixture; +using AutoFixture.AutoNSubstitute; +using FluentAssertions; +using Lumina.Application.Common.Mapping.FileSystemManagement.Directories; +using Lumina.Application.Core.FileSystemManagement.Directories.Queries.GetTreeDirectories; +using Lumina.Contracts.Requests.FileSystemManagement.Directories; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Application.UnitTests.Common.Mapping.FileSystemManagement.Directories; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class GetTreeDirectoriesRequestMappingTests +{ + private readonly IFixture _fixture; + + /// + /// Initializes a new instance of the class. + /// + public GetTreeDirectoriesRequestMappingTests() + { + _fixture = new Fixture().Customize(new AutoNSubstituteCustomization()); + } + + [Fact] + public void ToQuery_WhenMappingGetTreeDirectoriesRequest_ShouldMapCorrectly() + { + // Arrange + GetTreeDirectoriesRequest request = _fixture.Create(); + + // Act + GetTreeDirectoriesQuery result = request.ToQuery(); + + // Assert + result.Should().NotBeNull(); + result.Path.Should().Be(request.Path); + result.IncludeHiddenElements.Should().Be(request.IncludeHiddenElements); + } +} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/FileSystemManagement/FileSystem/FileSystemItemMappingTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/FileSystemManagement/FileSystem/FileSystemItemMappingTests.cs new file mode 100644 index 00000000..93aeb856 --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/FileSystemManagement/FileSystem/FileSystemItemMappingTests.cs @@ -0,0 +1,229 @@ +#region ========================================================================= USING ===================================================================================== +using FluentAssertions; +using Lumina.Application.Common.Mapping.FileSystemManagement.FileSystem; +using Lumina.Application.UnitTests.Common.Mapping.FileSystemManagement.FileSystem.Fixtures; +using Lumina.Application.UnitTests.Core.FileSystemManagement.Directories.Fixtures; +using Lumina.Application.UnitTests.Core.FileSystemManagement.Files.Fixtures; +using Lumina.Application.UnitTests.Core.FileSystemManagement.FileSystem.Fixtures; +using Lumina.Application.UnitTests.Core.FileSystemManagement.Fixtures; +using Lumina.Contracts.Entities.FileSystemManagement; +using Lumina.Contracts.Enums.FileSystem; +using Lumina.Contracts.Responses.FileSystemManagement.Common; +using Lumina.Domain.Core.Aggregates.FileSystemManagement.FileSystemManagementAggregate; +using Lumina.Domain.Core.Aggregates.FileSystemManagement.FileSystemManagementAggregate.Entities; +using Lumina.Domain.Core.Aggregates.FileSystemManagement.FileSystemManagementAggregate.ValueObjects; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Application.UnitTests.Common.Mapping.FileSystemManagement.FileSystem; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class FileSystemItemMappingTests +{ + private readonly FileSystemPathIdFixture _fileSystemPathIdFixture; + private readonly DirectoryFixture _directoryFixture; + private readonly FileFixture _fileFixture; + private readonly WindowsRootItemFixture _windowsRootItemFixture; + private readonly UnixRootItemFixture _unixRootItemFixture; + + /// + /// Initializes a new instance of the class. + /// + public FileSystemItemMappingTests() + { + _fileSystemPathIdFixture = new FileSystemPathIdFixture(); + _directoryFixture = new DirectoryFixture(); + _fileFixture = new FileFixture(); + _windowsRootItemFixture = new WindowsRootItemFixture(); + _unixRootItemFixture = new UnixRootItemFixture(); + } + + [Fact] + public void ToFileSystemItemModel_WhenMappingFileSystemItem_ShouldMapCorrectly() + { + // Arrange + FileSystemPathId id = _fileSystemPathIdFixture.CreateFileSystemPathId(); + string name = "TestItem"; + FileSystemItemType type = FileSystemItemType.File; + FileSystemItemFixture domainModel = new(id, name, type); + + // Arrange + + // Act + FileSystemItemEntity result = domainModel.ToFileSystemItemModel(); + + // Assert + result.Should().NotBeNull(); + result.Path.Should().Be(domainModel.Id.Path); + result.Name.Should().Be(domainModel.Name); + result.DateCreated.Should().BeCloseTo(DateTime.Now, TimeSpan.FromSeconds(1)); + result.DateModified.Should().BeCloseTo(DateTime.Now, TimeSpan.FromSeconds(1)); + } + + [Fact] + public void ToTreeNodeResponse_WhenMappingDirectory_ShouldMapCorrectly() + { + // Arrange + Directory directory = _directoryFixture.CreateDirectory(); + + // Act + FileSystemTreeNodeResponse result = directory.ToTreeNodeResponse(); + + // Assert + result.Should().NotBeNull(); + result.Name.Should().Be(directory.Name); + result.Path.Should().Be(directory.Id.Path); + result.ItemType.Should().Be(directory.Type); + } + + [Fact] + public void ToTreeNodeResponse_WhenMappingFile_ShouldMapCorrectly() + { + // Arrange + File file = _fileFixture.CreateFile(); + + // Act + FileSystemTreeNodeResponse result = file.ToTreeNodeResponse(); + + // Assert + result.Should().NotBeNull(); + result.Name.Should().Be(file.Name); + result.Path.Should().Be(file.Id.Path); + result.ItemType.Should().Be(file.Type); + } + + [Fact] + public void ToTreeNodeResponse_WhenMappingWindowsRootItem_ShouldMapCorrectly() + { + // Arrange + WindowsRootItem windowsRootItem = _windowsRootItemFixture.Create(); + + // Act + FileSystemTreeNodeResponse result = windowsRootItem.ToTreeNodeResponse(); + + // Assert + result.Should().NotBeNull(); + result.Name.Should().Be(windowsRootItem.Name); + result.Path.Should().Be(windowsRootItem.Id.Path); + result.ItemType.Should().Be(windowsRootItem.Type); + result.IsExpanded.Should().BeFalse(); + result.ChildrenLoaded.Should().BeFalse(); + result.Children.Should().BeEmpty(); + } + + [Fact] + public void ToTreeNodeResponse_WhenMappingUnixRootItem_ShouldMapCorrectly() + { + // Arrange + UnixRootItem unixRootItem = _unixRootItemFixture.Create(); + + // Act + FileSystemTreeNodeResponse result = unixRootItem.ToTreeNodeResponse(); + + // Assert + result.Should().NotBeNull(); + result.Name.Should().Be(unixRootItem.Name); + result.Path.Should().Be(unixRootItem.Id.Path); + result.ItemType.Should().Be(unixRootItem.Type); + result.IsExpanded.Should().BeFalse(); + result.ChildrenLoaded.Should().BeFalse(); + result.Children.Should().BeEmpty(); + } + + [Theory] + [InlineData("TestFile.txt", FileSystemItemType.File)] + [InlineData("TestFolder", FileSystemItemType.Directory)] + public void ToFileSystemItemModel_WhenMappingDifferentFileSystemItems_ShouldMapCorrectly(string name, FileSystemItemType type) + { + // Arrange + FileSystemPathId id = _fileSystemPathIdFixture.CreateFileSystemPathId(); + FileSystemItemFixture domainModel = new(id, name, type); + + // Act + FileSystemItemEntity result = domainModel.ToFileSystemItemModel(); + + // Assert + result.Should().NotBeNull(); + result.Path.Should().Be(domainModel.Id.Path); + result.Name.Should().Be(domainModel.Name); + result.DateCreated.Should().BeCloseTo(DateTime.Now, TimeSpan.FromSeconds(1)); + result.DateModified.Should().BeCloseTo(DateTime.Now, TimeSpan.FromSeconds(1)); + } + + [Fact] + public void ToTreeNodeResponses_WhenMappingMixedFileSystemItems_ShouldMapCorrectly() + { + // Arrange + List domainModels = + [ + _directoryFixture.CreateDirectory(), + _fileFixture.CreateFile(), + _windowsRootItemFixture.Create(), + _unixRootItemFixture.Create() + ]; + + // Act + IEnumerable result = domainModels.ToTreeNodeResponses(); + + // Assert + result.Should().NotBeNull(); + result.Should().HaveCount(domainModels.Count); + + List resultList = result.ToList(); + for (int i = 0; i < resultList.Count; i++) + { + resultList[i].Name.Should().Be(domainModels[i].Name); + resultList[i].Path.Should().Be(domainModels[i].Id.Path); + resultList[i].ItemType.Should().Be(domainModels[i].Type); + resultList[i].IsExpanded.Should().BeFalse(); + resultList[i].ChildrenLoaded.Should().BeFalse(); + } + } + + [Fact] + public void ToTreeNodeResponse_WhenMappingInvalidFileSystemItem_ShouldThrowArgumentException() + { + // Arrange + FileSystemPathId id = _fileSystemPathIdFixture.CreateFileSystemPathId(); + string name = "TestItem"; + FileSystemItemType type = FileSystemItemType.File; + FileSystemItemFixture invalidItem = new(id, name, type); + + // Act & Assert + invalidItem.Invoking(item => item.ToTreeNodeResponse()) + .Should().Throw() + .WithMessage("Invalid FileSystemItem"); + } + + [Fact] + public void ToTreeNodeResponses_WhenMappingMultipleFileSystemItems_ShouldMapCorrectly() + { + // Arrange + IEnumerable domainModels = _directoryFixture.CreateMany(); + + // Act + IEnumerable result = domainModels.ToTreeNodeResponses(); + + // Assert + result.Should().NotBeNull(); + result.Should().HaveCount(domainModels.Count()); + + List resultList = result.ToList(); + List domainModelsList = domainModels.ToList(); + for (int i = 0; i < resultList.Count; i++) + { + resultList[i].Name.Should().Be(domainModelsList[i].Name); + resultList[i].Path.Should().Be(domainModelsList[i].Id.Path); + resultList[i].ItemType.Should().Be(domainModelsList[i].Type); + resultList[i].IsExpanded.Should().BeFalse(); + resultList[i].ChildrenLoaded.Should().BeFalse(); + resultList[i].Children.Should().BeEmpty(); + } + } +} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/FileSystemManagement/FileSystem/Fixtures/FileSystemItemFixture.cs b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/FileSystemManagement/FileSystem/Fixtures/FileSystemItemFixture.cs new file mode 100644 index 00000000..d728cd58 --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/FileSystemManagement/FileSystem/Fixtures/FileSystemItemFixture.cs @@ -0,0 +1,26 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Contracts.Enums.FileSystem; +using Lumina.Domain.Core.Aggregates.FileSystemManagement.FileSystemManagementAggregate; +using Lumina.Domain.Core.Aggregates.FileSystemManagement.FileSystemManagementAggregate.ValueObjects; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Application.UnitTests.Common.Mapping.FileSystemManagement.FileSystem.Fixtures; + +/// +/// Fixture class for the class. +/// +[ExcludeFromCodeCoverage] +public class FileSystemItemFixture : FileSystemItem +{ + /// + /// Initializes a new instance of the class. + /// + /// The unique identifier for the file system path. + /// The name of the file system item. + /// The type of the file system item. + public FileSystemItemFixture(FileSystemPathId id, string name, FileSystemItemType fileSystemItemType) + : base(id, name, fileSystemItemType) + { + } +} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/FileSystemManagement/FileSystem/UnixRootItemMappingTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/FileSystemManagement/FileSystem/UnixRootItemMappingTests.cs new file mode 100644 index 00000000..3c5e3d99 --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/FileSystemManagement/FileSystem/UnixRootItemMappingTests.cs @@ -0,0 +1,44 @@ +#region ========================================================================= USING ===================================================================================== +using ErrorOr; +using FluentAssertions; +using Lumina.Application.Common.Mapping.FileSystemManagement.FileSystem; +using Lumina.Application.UnitTests.Core.FileSystemManagement.Directories.Fixtures; +using Lumina.Application.UnitTests.Core.FileSystemManagement.Files.Fixtures; +using Lumina.Contracts.Enums.FileSystem; +using Lumina.Contracts.Responses.FileSystemManagement.Common; +using Lumina.Domain.Core.Aggregates.FileSystemManagement.FileSystemManagementAggregate; +using Lumina.Domain.Core.Aggregates.FileSystemManagement.FileSystemManagementAggregate.Entities; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Application.UnitTests.Common.Mapping.FileSystemManagement.FileSystem; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class UnixRootItemMappingTests +{ + [Fact] + public void ToTreeNodeResponse_WhenMappingUnixRootItem_ShouldMapCorrectly() + { + // Arrange + ErrorOr createResult = UnixRootItem.Create(); + createResult.IsError.Should().BeFalse(); + UnixRootItem domainModel = createResult.Value; + + // Act + FileSystemTreeNodeResponse result = domainModel.ToTreeNodeResponse(); + + // Assert + result.Should().NotBeNull(); + result.Path.Should().Be(domainModel.Id.Path); + result.Name.Should().Be(domainModel.Name); + result.ItemType.Should().Be(FileSystemItemType.Root); + result.IsExpanded.Should().BeFalse(); + result.ChildrenLoaded.Should().BeFalse(); + result.Children.Should().NotBeNull(); + result.Children.Should().BeEmpty(); + } +} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/FileSystemManagement/FileSystem/WindowsRootItemMappingTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/FileSystemManagement/FileSystem/WindowsRootItemMappingTests.cs new file mode 100644 index 00000000..547c016b --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/FileSystemManagement/FileSystem/WindowsRootItemMappingTests.cs @@ -0,0 +1,65 @@ +#region ========================================================================= USING ===================================================================================== +using ErrorOr; +using FluentAssertions; +using Lumina.Application.Common.Mapping.FileSystemManagement.FileSystem; +using Lumina.Contracts.Enums.FileSystem; +using Lumina.Contracts.Responses.FileSystemManagement.Common; +using Lumina.Domain.Core.Aggregates.FileSystemManagement.FileSystemManagementAggregate.Entities; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Application.UnitTests.Common.Mapping.FileSystemManagement.FileSystem; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class WindowsRootItemMappingTests +{ + [Fact] + public void ToTreeNodeResponse_WhenMappingWindowsRootItem_ShouldMapCorrectly() + { + // Arrange + string path = "C:\\"; + string name = "C:"; + ErrorOr createResult = WindowsRootItem.Create(path, name); + createResult.IsError.Should().BeFalse(); + WindowsRootItem domainModel = createResult.Value; + + // Act + FileSystemTreeNodeResponse result = domainModel.ToTreeNodeResponse(); + + // Assert + result.Should().NotBeNull(); + result.Path.Should().Be(domainModel.Id.Path); + result.Name.Should().Be(domainModel.Name); + result.ItemType.Should().Be(FileSystemItemType.Root); + result.IsExpanded.Should().BeFalse(); + result.ChildrenLoaded.Should().BeFalse(); + result.Children.Should().BeEmpty(); + } + + [Fact] + public void ToTreeNodeResponse_WhenMappingWindowsRootItemWithCustomStatus_ShouldMapCorrectly() + { + // Arrange + string path = "D:\\"; + string name = "D:"; + FileSystemItemStatus customStatus = FileSystemItemStatus.Inaccessible; + ErrorOr createResult = WindowsRootItem.Create(path, name, customStatus); + createResult.IsError.Should().BeFalse(); + WindowsRootItem domainModel = createResult.Value; + + // Act + FileSystemTreeNodeResponse result = domainModel.ToTreeNodeResponse(); + + // Assert + result.Should().NotBeNull(); + result.Path.Should().Be(domainModel.Id.Path); + result.Name.Should().Be(domainModel.Name); + result.ItemType.Should().Be(FileSystemItemType.Root); + result.IsExpanded.Should().BeFalse(); + result.ChildrenLoaded.Should().BeFalse(); + result.Children.Should().BeEmpty(); + } +} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/FileSystemManagement/Files/FileMappingTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/FileSystemManagement/Files/FileMappingTests.cs new file mode 100644 index 00000000..e75eb8b6 --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/FileSystemManagement/Files/FileMappingTests.cs @@ -0,0 +1,119 @@ +#region ========================================================================= USING ===================================================================================== +using FluentAssertions; +using Lumina.Application.Common.Mapping.FileSystemManagement.Files; +using Lumina.Application.UnitTests.Core.FileSystemManagement.Files.Fixtures; +using Lumina.Contracts.Responses.FileSystemManagement.Common; +using Lumina.Contracts.Responses.FileSystemManagement.Files; +using Lumina.Domain.Common.Primitives; +using Lumina.Domain.Core.Aggregates.FileSystemManagement.FileSystemManagementAggregate.Entities; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Application.UnitTests.Common.Mapping.FileSystemManagement.Files; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class FileMappingTests +{ + private readonly FileFixture _fileFixture; + + /// + /// Initializes a new instance of the class. + /// + public FileMappingTests() + { + _fileFixture = new(); + } + + [Fact] + public void ToFileSystemTreeNodeResponse_WhenMappingFile_ShouldMapCorrectly() + { + // Arrange + File domainModel = _fileFixture.CreateFile(); + + // Act + FileSystemTreeNodeResponse result = domainModel.ToFileSystemTreeNodeResponse(); + + // Assert + result.Should().NotBeNull(); + result.Name.Should().Be(domainModel.Name); + result.Path.Should().Be(domainModel.Id.Path); + result.ItemType.Should().Be(domainModel.Type); + result.IsExpanded.Should().BeFalse(); + result.ChildrenLoaded.Should().BeFalse(); + } + + [Fact] + public void ToFileSystemTreeNodeResponses_WhenMappingMultipleFiles_ShouldMapCorrectly() + { + // Arrange + IEnumerable domainModels = _fileFixture.CreateMany(); + + // Act + IEnumerable result = domainModels.ToFileSystemTreeNodeResponses(); + + // Assert + result.Should().NotBeNull(); + result.Should().HaveCount(domainModels.Count()); + + List resultList = result.ToList(); + List domainModelsList = domainModels.ToList(); + for (int i = 0; i < resultList.Count; i++) + { + resultList[i].Name.Should().Be(domainModelsList[i].Name); + resultList[i].Path.Should().Be(domainModelsList[i].Id.Path); + resultList[i].ItemType.Should().Be(domainModelsList[i].Type); + resultList[i].IsExpanded.Should().BeFalse(); + resultList[i].ChildrenLoaded.Should().BeFalse(); + resultList[i].Children.Should().BeEmpty(); + } + } + + [Fact] + public void ToResponse_WhenMappingFile_ShouldMapCorrectly() + { + // Arrange + File domainModel = _fileFixture.CreateFile(); + + // Act + FileResponse result = domainModel.ToResponse(); + + // Assert + result.Should().NotBeNull(); + result.Path.Should().Be(domainModel.Id.Path); + result.Name.Should().Be(domainModel.Name); + result.DateCreated.Should().Be(domainModel.DateCreated.Value); + result.DateModified.Should().Be(domainModel.DateModified.Value); + result.Size.Should().Be(domainModel.Size); + } + + [Fact] + public void ToResponses_WhenMappingMultipleFiles_ShouldMapCorrectly() + { + // Arrange + IEnumerable domainModels = _fileFixture.CreateMany(); + + // Act + IEnumerable result = domainModels.ToResponses(); + + // Assert + result.Should().NotBeNull(); + result.Should().HaveCount(domainModels.Count()); + + List resultList = result.ToList(); + List domainModelsList = domainModels.ToList(); + for (int i = 0; i < resultList.Count; i++) + { + resultList[i].Name.Should().Be(domainModelsList[i].Name); + resultList[i].Path.Should().Be(domainModelsList[i].Id.Path); + resultList[i].Size.Should().Be(domainModelsList[i].Size); + resultList[i].DateCreated.Should().Be(domainModelsList[i].DateCreated.Value); + resultList[i].DateModified.Should().Be(domainModelsList[i].DateModified.Value); + } + } +} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/FileSystemManagement/Files/GetFilesRequestMappingTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/FileSystemManagement/Files/GetFilesRequestMappingTests.cs new file mode 100644 index 00000000..34330a52 --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/FileSystemManagement/Files/GetFilesRequestMappingTests.cs @@ -0,0 +1,43 @@ +#region ========================================================================= USING ===================================================================================== +using AutoFixture; +using AutoFixture.AutoNSubstitute; +using FluentAssertions; +using Lumina.Application.Common.Mapping.FileSystemManagement.Files; +using Lumina.Application.Core.FileSystemManagement.Files.Queries.GetFiles; +using Lumina.Contracts.Requests.FileSystemManagement.Files; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Application.UnitTests.Common.Mapping.FileSystemManagement.Files; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class GetFilesRequestMappingTests +{ + private readonly IFixture _fixture; + + /// + /// Initializes a new instance of the class. + /// + public GetFilesRequestMappingTests() + { + _fixture = new Fixture().Customize(new AutoNSubstituteCustomization()); + } + + [Fact] + public void ToQuery_WhenMappingGetFilesRequest_ShouldMapCorrectly() + { + // Arrange + GetFilesRequest request = _fixture.Create(); + + // Act + GetFilesQuery result = request.ToQuery(); + + // Assert + result.Should().NotBeNull(); + result.Path.Should().Be(request.Path); + result.IncludeHiddenElements.Should().Be(request.IncludeHiddenElements); + } +} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/FileSystemManagement/Files/GetTreeFilesRequestMappingTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/FileSystemManagement/Files/GetTreeFilesRequestMappingTests.cs new file mode 100644 index 00000000..c8fd55a7 --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/FileSystemManagement/Files/GetTreeFilesRequestMappingTests.cs @@ -0,0 +1,43 @@ +#region ========================================================================= USING ===================================================================================== +using AutoFixture; +using AutoFixture.AutoNSubstitute; +using FluentAssertions; +using Lumina.Application.Common.Mapping.FileSystemManagement.Files; +using Lumina.Application.Core.FileSystemManagement.Files.Queries.GetTreeFiles; +using Lumina.Contracts.Requests.FileSystemManagement.Files; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Application.UnitTests.Common.Mapping.FileSystemManagement.Files; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class GetTreeFilesRequestMappingTests +{ + private readonly IFixture _fixture; + + /// + /// Initializes a new instance of the class. + /// + public GetTreeFilesRequestMappingTests() + { + _fixture = new Fixture().Customize(new AutoNSubstituteCustomization()); + } + + [Fact] + public void ToQuery_WhenMappingGetTreeFilesRequest_ShouldMapCorrectly() + { + // Arrange + GetTreeFilesRequest request = _fixture.Create(); + + // Act + GetTreeFilesQuery result = request.ToQuery(); + + // Assert + result.Should().NotBeNull(); + result.Path.Should().Be(request.Path); + result.IncludeHiddenElements.Should().Be(request.IncludeHiddenElements); + } +} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/FileSystemManagement/Paths/CheckPathExistsQueryMappingTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/FileSystemManagement/Paths/CheckPathExistsQueryMappingTests.cs new file mode 100644 index 00000000..351d267e --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/FileSystemManagement/Paths/CheckPathExistsQueryMappingTests.cs @@ -0,0 +1,82 @@ +#region ========================================================================= USING ===================================================================================== +using AutoFixture; +using AutoFixture.AutoNSubstitute; +using FluentAssertions; +using Lumina.Application.Common.Mapping.FileSystemManagement.Paths; +using Lumina.Application.Core.FileSystemManagement.Paths.Queries.CheckPathExists; +using Lumina.Contracts.Requests.FileSystemManagement.Path; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Application.UnitTests.Common.Mapping.FileSystemManagement.Paths; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class CheckPathExistsQueryMappingTests +{ + private readonly IFixture _fixture; + + /// + /// Initializes a new instance of the class. + /// + public CheckPathExistsQueryMappingTests() + { + _fixture = new Fixture().Customize(new AutoNSubstituteCustomization()); + } + + [Fact] + public void ToQuery_WhenMappingCheckPathExistsRequest_ShouldMapCorrectly() + { + // Arrange + CheckPathExistsRequest request = _fixture.Create(); + + // Act + CheckPathExistsQuery result = request.ToQuery(); + + // Assert + result.Should().NotBeNull(); + result.Path.Should().Be(request.Path); + result.IncludeHiddenElements.Should().Be(request.IncludeHiddenElements); + } + + [Theory] + [InlineData("/home/user/documents", true)] + [InlineData("C:\\Users\\Documents", false)] + [InlineData("/var/www/html", true)] + public void ToQuery_WhenMappingWithDifferentPathsAndHiddenElementsFlag_ShouldMapCorrectly(string path, bool includeHiddenElements) + { + // Arrange + CheckPathExistsRequest request = new(path, includeHiddenElements); + + // Act + CheckPathExistsQuery result = request.ToQuery(); + + // Assert + result.Should().NotBeNull(); + result.Path.Should().Be(path); + result.IncludeHiddenElements.Should().Be(includeHiddenElements); + } + + [Fact] + public void ToQuery_WhenMappingMultipleRequests_ShouldMapAllCorrectly() + { + // Arrange + List requests = _fixture.CreateMany().ToList(); + + // Act + List results = requests.Select(r => r.ToQuery()).ToList(); + + // Assert + results.Should().NotBeNull(); + results.Should().HaveCount(requests.Count); + for (int i = 0; i < requests.Count; i++) + { + results[i].Path.Should().Be(requests[i].Path); + results[i].IncludeHiddenElements.Should().Be(requests[i].IncludeHiddenElements); + } + } +} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/FileSystemManagement/Paths/CombinePathRequestMappingTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/FileSystemManagement/Paths/CombinePathRequestMappingTests.cs new file mode 100644 index 00000000..2740cb3a --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/FileSystemManagement/Paths/CombinePathRequestMappingTests.cs @@ -0,0 +1,82 @@ +#region ========================================================================= USING ===================================================================================== +using AutoFixture; +using AutoFixture.AutoNSubstitute; +using FluentAssertions; +using Lumina.Application.Common.Mapping.FileSystemManagement.Paths; +using Lumina.Application.Core.FileSystemManagement.Paths.Commands.CombinePath; +using Lumina.Contracts.Requests.FileSystemManagement.Path; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Application.UnitTests.Common.Mapping.FileSystemManagement.Paths; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class CombinePathRequestMappingTests +{ + private readonly IFixture _fixture; + + /// + /// Initializes a new instance of the class. + /// + public CombinePathRequestMappingTests() + { + _fixture = new Fixture().Customize(new AutoNSubstituteCustomization()); + } + + [Fact] + public void ToCommand_WhenMappingCombinePathRequest_ShouldMapCorrectly() + { + // Arrange + CombinePathRequest request = _fixture.Create(); + + // Act + CombinePathCommand result = request.ToCommand(); + + // Assert + result.Should().NotBeNull(); + result.OriginalPath.Should().Be(request.OriginalPath); + result.NewPath.Should().Be(request.NewPath); + } + + [Theory] + [InlineData("/home/user", "documents")] + [InlineData("C:\\Users", "Documents")] + [InlineData("/var/www", "html")] + public void ToCommand_WhenMappingWithDifferentPaths_ShouldMapCorrectly(string originalPath, string newPath) + { + // Arrange + CombinePathRequest request = new(originalPath, newPath); + + // Act + CombinePathCommand result = request.ToCommand(); + + // Assert + result.Should().NotBeNull(); + result.OriginalPath.Should().Be(originalPath); + result.NewPath.Should().Be(newPath); + } + + [Fact] + public void ToCommand_WhenMappingMultipleRequests_ShouldMapAllCorrectly() + { + // Arrange + List requests = _fixture.CreateMany().ToList(); + + // Act + List results = requests.Select(r => r.ToCommand()).ToList(); + + // Assert + results.Should().NotBeNull(); + results.Should().HaveCount(requests.Count); + for (int i = 0; i < requests.Count; i++) + { + results[i].OriginalPath.Should().Be(requests[i].OriginalPath); + results[i].NewPath.Should().Be(requests[i].NewPath); + } + } +} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/FileSystemManagement/Paths/GetPathParentRequestMappingTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/FileSystemManagement/Paths/GetPathParentRequestMappingTests.cs new file mode 100644 index 00000000..809caf70 --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/FileSystemManagement/Paths/GetPathParentRequestMappingTests.cs @@ -0,0 +1,79 @@ +#region ========================================================================= USING ===================================================================================== +using AutoFixture; +using AutoFixture.AutoNSubstitute; +using FluentAssertions; +using Lumina.Application.Common.Mapping.FileSystemManagement.Paths; +using Lumina.Application.Core.FileSystemManagement.Paths.Queries.GetPathParent; +using Lumina.Contracts.Requests.FileSystemManagement.Path; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Application.UnitTests.Common.Mapping.FileSystemManagement.Paths; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class GetPathParentRequestMappingTests +{ + private readonly IFixture _fixture; + + /// + /// Initializes a new instance of the class. + /// + public GetPathParentRequestMappingTests() + { + _fixture = new Fixture().Customize(new AutoNSubstituteCustomization()); + } + + [Fact] + public void ToQuery_WhenMappingGetPathParentRequest_ShouldMapCorrectly() + { + // Arrange + GetPathParentRequest request = _fixture.Create(); + + // Act + GetPathParentQuery result = request.ToQuery(); + + // Assert + result.Should().NotBeNull(); + result.Path.Should().Be(request.Path); + } + + [Theory] + [InlineData("/home/user/documents")] + [InlineData("C:\\Users\\Documents")] + [InlineData("/var/www/html")] + public void ToQuery_WhenMappingWithDifferentPaths_ShouldMapCorrectly(string path) + { + // Arrange + GetPathParentRequest request = new(path); + + // Act + GetPathParentQuery result = request.ToQuery(); + + // Assert + result.Should().NotBeNull(); + result.Path.Should().Be(path); + } + + [Fact] + public void ToQuery_WhenMappingMultipleRequests_ShouldMapAllCorrectly() + { + // Arrange + List requests = _fixture.CreateMany().ToList(); + + // Act + List results = requests.Select(r => r.ToQuery()).ToList(); + + // Assert + results.Should().NotBeNull(); + results.Should().HaveCount(requests.Count); + for (int i = 0; i < requests.Count; i++) + { + results[i].Path.Should().Be(requests[i].Path); + } + } +} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/FileSystemManagement/Paths/GetPathRootRequestMappingTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/FileSystemManagement/Paths/GetPathRootRequestMappingTests.cs new file mode 100644 index 00000000..a2eb8294 --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/FileSystemManagement/Paths/GetPathRootRequestMappingTests.cs @@ -0,0 +1,80 @@ +#region ========================================================================= USING ===================================================================================== +using AutoFixture; +using AutoFixture.AutoNSubstitute; +using FluentAssertions; +using Lumina.Application.Common.Mapping.FileSystemManagement.Paths; +using Lumina.Application.Core.FileSystemManagement.Paths.Queries.GetPathRoot; +using Lumina.Contracts.Requests.FileSystemManagement.Path; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Application.UnitTests.Common.Mapping.FileSystemManagement.Paths; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class GetPathRootRequestMappingTests +{ + private readonly IFixture _fixture; + + /// + /// Initializes a new instance of the class. + /// + public GetPathRootRequestMappingTests() + { + _fixture = new Fixture().Customize(new AutoNSubstituteCustomization()); + } + + [Fact] + public void ToQuery_WhenMappingGetPathRootRequest_ShouldMapCorrectly() + { + // Arrange + GetPathRootRequest request = _fixture.Create(); + + // Act + GetPathRootQuery result = request.ToQuery(); + + // Assert + result.Should().NotBeNull(); + result.Path.Should().Be(request.Path); + } + + [Theory] + [InlineData("/home/user/documents")] + [InlineData("C:\\Users\\Documents")] + [InlineData("/var/www/html")] + [InlineData("D:\\Projects\\MyProject")] + public void ToQuery_WhenMappingWithDifferentPaths_ShouldMapCorrectly(string path) + { + // Arrange + GetPathRootRequest request = new(path); + + // Act + GetPathRootQuery result = request.ToQuery(); + + // Assert + result.Should().NotBeNull(); + result.Path.Should().Be(path); + } + + [Fact] + public void ToQuery_WhenMappingMultipleRequests_ShouldMapAllCorrectly() + { + // Arrange + List requests = _fixture.CreateMany().ToList(); + + // Act + List results = requests.Select(r => r.ToQuery()).ToList(); + + // Assert + results.Should().NotBeNull(); + results.Should().HaveCount(requests.Count); + for (int i = 0; i < requests.Count; i++) + { + results[i].Path.Should().Be(requests[i].Path); + } + } +} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/FileManagement/PathSegmentMappingConfigTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/FileSystemManagement/Paths/PathSegmentMappingTests.cs similarity index 55% rename from tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/FileManagement/PathSegmentMappingConfigTests.cs rename to tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/FileSystemManagement/Paths/PathSegmentMappingTests.cs index 525475a9..82549e89 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/FileManagement/PathSegmentMappingConfigTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/FileSystemManagement/Paths/PathSegmentMappingTests.cs @@ -1,34 +1,24 @@ #region ========================================================================= USING ===================================================================================== using ErrorOr; using FluentAssertions; -using Lumina.Application.Common.Mapping.FileManagement; -using Lumina.Contracts.Responses.FileManagement; -using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.ValueObjects; -using Mapster; +using Lumina.Application.Common.Mapping.FileSystemManagement.Paths; +using Lumina.Contracts.Responses.FileSystemManagement.Path; +using Lumina.Domain.Core.Aggregates.FileSystemManagement.FileSystemManagementAggregate.ValueObjects; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; +using System.Linq; #endregion -namespace Lumina.Application.UnitTests.Common.Mapping.FileManagement; +namespace Lumina.Application.UnitTests.Common.Mapping.FileSystemManagement.Paths; /// -/// Contains unit tests for the class. +/// Contains unit tests for the class. /// [ExcludeFromCodeCoverage] -public class PathSegmentMappingConfigTests +public class PathSegmentMappingTests { - private readonly TypeAdapterConfig _config; - private readonly PathSegmentMappingConfig _pathSegmentMappingConfig; - - public PathSegmentMappingConfigTests() - { - _config = new TypeAdapterConfig(); - _pathSegmentMappingConfig = new PathSegmentMappingConfig(); - _pathSegmentMappingConfig.Register(_config); - } - [Fact] - public void Register_WhenMappingPathSegmentToPathSegmentResponse_ShouldMapCorrectly() + public void ToResponse_WhenMappingPathSegment_ShouldMapCorrectly() { // Arrange ErrorOr createResult = PathSegment.Create("TestSegment", true, false); @@ -36,7 +26,7 @@ public class PathSegmentMappingConfigTests PathSegment pathSegment = createResult.Value; // Act - PathSegmentResponse result = pathSegment.Adapt(_config); + PathSegmentResponse result = pathSegment.ToResponse(); // Assert result.Should().NotBeNull(); @@ -47,7 +37,7 @@ public class PathSegmentMappingConfigTests [InlineData("Folder", true, false)] [InlineData("File.txt", false, false)] [InlineData("C:", false, true)] - public void Register_WhenMappingDifferentPathSegmentTypes_ShouldMapCorrectly(string name, bool isDirectory, bool isDrive) + public void ToResponse_WhenMappingDifferentPathSegmentTypes_ShouldMapCorrectly(string name, bool isDirectory, bool isDrive) { // Arrange ErrorOr createResult = PathSegment.Create(name, isDirectory, isDrive); @@ -55,7 +45,7 @@ public class PathSegmentMappingConfigTests PathSegment pathSegment = createResult.Value; // Act - PathSegmentResponse result = pathSegment.Adapt(_config); + PathSegmentResponse result = pathSegment.ToResponse(); // Assert result.Should().NotBeNull(); @@ -63,7 +53,7 @@ public class PathSegmentMappingConfigTests } [Fact] - public void Register_WhenMappingMultiplePathSegments_ShouldMapAllCorrectly() + public void ToResponses_WhenMappingMultiplePathSegments_ShouldMapAllCorrectly() { // Arrange List pathSegments = @@ -75,14 +65,13 @@ public class PathSegmentMappingConfigTests ]; // Act - List results = pathSegments.Adapt>(_config); + IEnumerable results = pathSegments.ToResponses(); // Assert results.Should().NotBeNull(); results.Should().HaveCount(pathSegments.Count); + List resultList = results.ToList(); for (int i = 0; i < pathSegments.Count; i++) - { - results[i].Path.Should().Be(pathSegments[i].Name); - } + resultList[i].Path.Should().Be(pathSegments[i].Name); } } diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/FileSystemManagement/Paths/SplitPathRequestMappingTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/FileSystemManagement/Paths/SplitPathRequestMappingTests.cs new file mode 100644 index 00000000..2d54f9d7 --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/FileSystemManagement/Paths/SplitPathRequestMappingTests.cs @@ -0,0 +1,78 @@ +#region ========================================================================= USING ===================================================================================== +using AutoFixture; +using AutoFixture.AutoNSubstitute; +using FluentAssertions; +using Lumina.Application.Common.Mapping.FileSystemManagement.Paths; +using Lumina.Application.Core.FileSystemManagement.Paths.Commands.SplitPath; +using Lumina.Contracts.Requests.FileSystemManagement.Path; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Application.UnitTests.Common.Mapping.FileSystemManagement.Paths; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class SplitPathRequestMappingTests +{ + private readonly IFixture _fixture; + + /// + /// Initializes a new instance of the class. + /// + public SplitPathRequestMappingTests() + { + _fixture = new Fixture().Customize(new AutoNSubstituteCustomization()); + } + + [Fact] + public void ToCommand_WhenMappingSplitPathRequest_ShouldMapCorrectly() + { + // Arrange + SplitPathRequest request = _fixture.Create(); + + // Act + SplitPathCommand result = request.ToCommand(); + + // Assert + result.Should().NotBeNull(); + result.Path.Should().Be(request.Path); + } + + [Theory] + [InlineData("/home/user/documents")] + [InlineData("C:\\Users\\Documents")] + [InlineData("/var/www/html")] + [InlineData("D:\\Projects\\MyProject\\file.txt")] + public void ToCommand_WhenMappingWithDifferentPaths_ShouldMapCorrectly(string path) + { + // Arrange + SplitPathRequest request = new(path); + + // Act + SplitPathCommand result = request.ToCommand(); + + // Assert + result.Should().NotBeNull(); + result.Path.Should().Be(path); + } + + [Fact] + public void ToCommand_WhenMappingMultipleRequests_ShouldMapAllCorrectly() + { + // Arrange + List requests = _fixture.CreateMany().ToList(); + + // Act + List results = requests.Select(r => r.ToCommand()).ToList(); + + // Assert + results.Should().NotBeNull(); + results.Should().HaveCount(requests.Count); + for (int i = 0; i < requests.Count; i++) + results[i].Path.Should().Be(requests[i].Path); + } +} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/FileSystemManagement/Paths/ValidatePathRequestMappingTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/FileSystemManagement/Paths/ValidatePathRequestMappingTests.cs new file mode 100644 index 00000000..7a519661 --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/FileSystemManagement/Paths/ValidatePathRequestMappingTests.cs @@ -0,0 +1,80 @@ +#region ========================================================================= USING ===================================================================================== +using AutoFixture; +using AutoFixture.AutoNSubstitute; +using FluentAssertions; +using Lumina.Application.Common.Mapping.FileSystemManagement.Paths; +using Lumina.Application.Core.FileSystemManagement.Paths.Queries.ValidatePath; +using Lumina.Contracts.Requests.FileSystemManagement.Path; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Application.UnitTests.Common.Mapping.FileSystemManagement.Paths; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class ValidatePathRequestMappingTests +{ + private readonly IFixture _fixture; + + /// + /// Initializes a new instance of the class. + /// + public ValidatePathRequestMappingTests() + { + _fixture = new Fixture().Customize(new AutoNSubstituteCustomization()); + } + + [Fact] + public void ToQuery_WhenMappingValidatePathRequest_ShouldMapCorrectly() + { + // Arrange + ValidatePathRequest request = _fixture.Create(); + + // Act + ValidatePathQuery result = request.ToQuery(); + + // Assert + result.Should().NotBeNull(); + result.Path.Should().Be(request.Path); + } + + [Theory] + [InlineData("/home/user/documents")] + [InlineData("C:\\Users\\Documents")] + [InlineData("/var/www/html")] + [InlineData("D:\\Projects\\MyProject\\file.txt")] + [InlineData("\\\\NetworkShare\\Folder")] + [InlineData("relative/path/to/file.txt")] + public void ToQuery_WhenMappingWithDifferentPaths_ShouldMapCorrectly(string path) + { + // Arrange + ValidatePathRequest request = new(path); + + // Act + ValidatePathQuery result = request.ToQuery(); + + // Assert + result.Should().NotBeNull(); + result.Path.Should().Be(path); + } + + [Fact] + public void ToQuery_WhenMappingMultipleRequests_ShouldMapAllCorrectly() + { + // Arrange + List requests = _fixture.CreateMany().ToList(); + + // Act + List results = requests.Select(r => r.ToQuery()).ToList(); + + // Assert + results.Should().NotBeNull(); + results.Should().HaveCount(requests.Count); + for (int i = 0; i < requests.Count; i++) + results[i].Path.Should().Be(requests[i].Path); + } +} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/FileSystemManagement/Thumbnails/GetThumbnailRequestMappingTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/FileSystemManagement/Thumbnails/GetThumbnailRequestMappingTests.cs new file mode 100644 index 00000000..5bddcefd --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/FileSystemManagement/Thumbnails/GetThumbnailRequestMappingTests.cs @@ -0,0 +1,82 @@ +#region ========================================================================= USING ===================================================================================== +using AutoFixture; +using AutoFixture.AutoNSubstitute; +using FluentAssertions; +using Lumina.Application.Common.Mapping.FileSystemManagement.Thumbnails; +using Lumina.Application.Core.FileSystemManagement.Thumbnails.Queries.GetThumbnail; +using Lumina.Contracts.Requests.FileSystemManagement.Thumbnails; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Application.UnitTests.Common.Mapping.FileSystemManagement.Thumbnails; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class GetThumbnailRequestMappingTests +{ + private readonly IFixture _fixture; + + /// + /// Initializes a new instance of the class. + /// + public GetThumbnailRequestMappingTests() + { + _fixture = new Fixture().Customize(new AutoNSubstituteCustomization()); + } + + [Fact] + public void ToQuery_WhenMappingGetThumbnailRequest_ShouldMapCorrectly() + { + // Arrange + GetThumbnailRequest request = _fixture.Create(); + + // Act + GetThumbnailQuery result = request.ToQuery(); + + // Assert + result.Should().NotBeNull(); + result.Path.Should().Be(request.Path); + result.Quality.Should().Be(request.Quality); + } + + [Theory] + [InlineData("C:\\test\\image.jpg", 50)] + [InlineData("/home/user/image.png", 100)] + [InlineData("D:\\photos\\vacation\\pic.gif", 75)] + public void ToQuery_WhenMappingWithDifferentPathsAndQualities_ShouldMapCorrectly(string path, int quality) + { + // Arrange + GetThumbnailRequest request = new(path, quality); + + // Act + GetThumbnailQuery result = request.ToQuery(); + + // Assert + result.Should().NotBeNull(); + result.Path.Should().Be(path); + result.Quality.Should().Be(quality); + } + + [Fact] + public void ToQuery_WhenMappingMultipleRequests_ShouldMapAllCorrectly() + { + // Arrange + List requests = _fixture.CreateMany().ToList(); + + // Act + List results = requests.Select(r => r.ToQuery()).ToList(); + + // Assert + results.Should().NotBeNull(); + results.Should().HaveCount(requests.Count); + for (int i = 0; i < requests.Count; i++) + { + results[i].Path.Should().Be(requests[i].Path); + results[i].Quality.Should().Be(requests[i].Quality); + } + } +} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/FileSystemManagement/Thumbnails/ThumbnailMappingTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/FileSystemManagement/Thumbnails/ThumbnailMappingTests.cs new file mode 100644 index 00000000..16ba4e7d --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/FileSystemManagement/Thumbnails/ThumbnailMappingTests.cs @@ -0,0 +1,101 @@ +#region ========================================================================= USING ===================================================================================== +using AutoFixture; +using AutoFixture.AutoNSubstitute; +using FluentAssertions; +using Lumina.Application.Common.Mapping.FileSystemManagement.Thumbnails; +using Lumina.Contracts.Enums.PhotoLibrary; +using Lumina.Contracts.Responses.FileSystemManagement.Thumbnails; +using Lumina.Domain.Core.Aggregates.FileSystemManagement.FileSystemManagementAggregate.ValueObjects; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Application.UnitTests.Common.Mapping.FileSystemManagement.Thumbnails; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class ThumbnailMappingTests +{ + private readonly IFixture _fixture; + + /// + /// Initializes a new instance of the class. + /// + public ThumbnailMappingTests() + { + _fixture = new Fixture().Customize(new AutoNSubstituteCustomization()); + } + + [Fact] + public void ToResponse_WhenMappingThumbnail_ShouldMapCorrectly() + { + // Arrange + Thumbnail domainModel = _fixture.Create(); + + // Act + ThumbnailResponse result = domainModel.ToResponse(); + + // Assert + result.Should().NotBeNull(); + result.Type.Should().Be(domainModel.Type); + result.Bytes.Should().BeEquivalentTo(domainModel.Bytes); + } + + [Theory] + [InlineData(ImageType.JPEG)] + [InlineData(ImageType.PNG)] + [InlineData(ImageType.GIF)] + public void ToResponse_WhenMappingDifferentImageTypes_ShouldMapCorrectly(ImageType imageType) + { + // Arrange + byte[] bytes = _fixture.CreateMany(100).ToArray(); + Thumbnail domainModel = new(imageType, bytes); + + // Act + ThumbnailResponse result = domainModel.ToResponse(); + + // Assert + result.Should().NotBeNull(); + result.Type.Should().Be(imageType); + result.Bytes.Should().BeEquivalentTo(bytes); + } + + [Fact] + public void ToResponse_WhenMappingThumbnailWithEmptyBytes_ShouldMapCorrectly() + { + // Arrange + ImageType imageType = _fixture.Create(); + byte[] emptyBytes = []; + Thumbnail domainModel = new(imageType, emptyBytes); + + // Act + ThumbnailResponse result = domainModel.ToResponse(); + + // Assert + result.Should().NotBeNull(); + result.Type.Should().Be(imageType); + result.Bytes.Should().BeEmpty(); + } + + [Fact] + public void ToResponse_WhenMappingMultipleThumbnails_ShouldMapAllCorrectly() + { + // Arrange + List thumbnails = _fixture.CreateMany(3).ToList(); + + // Act + List results = thumbnails.Select(t => t.ToResponse()).ToList(); + + // Assert + results.Should().NotBeNull(); + results.Should().HaveCount(thumbnails.Count); + for (int i = 0; i < thumbnails.Count; i++) + { + results[i].Type.Should().Be(thumbnails[i].Type); + results[i].Bytes.Should().BeEquivalentTo(thumbnails[i].Bytes); + } + } +} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/WrittenContentLibrary/BookLibrary/Books/AddBookRequestMappingTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/WrittenContentLibrary/BookLibrary/Books/AddBookRequestMappingTests.cs new file mode 100644 index 00000000..26c8f34d --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/WrittenContentLibrary/BookLibrary/Books/AddBookRequestMappingTests.cs @@ -0,0 +1,166 @@ +#region ========================================================================= USING ===================================================================================== +using FluentAssertions; +using Lumina.Application.Common.Mapping.WrittenContentLibrary.BookLibrary.Books; +using Lumina.Application.Core.WrittenContentLibrary.BooksLibrary.Books.Commands.AddBook; +using Lumina.Application.UnitTests.Core.WrittenContentLibrary.BooksLibrary.Books.Commands.AddBook.Fixtures; +using Lumina.Contracts.Entities.MediaContributors; +using Lumina.Contracts.Entities.WrittenContentLibrary; +using Lumina.Contracts.Enums.BookLibrary; +using Lumina.Contracts.Requests.WrittenContentLibrary.BookLibrary.Books; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Application.UnitTests.Common.Mapping.WrittenContentLibrary.BookLibrary.Books; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class AddBookRequestMappingTests +{ + private readonly AddBookRequestFixture _requestFixture; + + /// + /// Initializes a new instance of the class. + /// + public AddBookRequestMappingTests() + { + _requestFixture = new AddBookRequestFixture(); + } + + [Fact] + public void ToCommand_WhenMappingCompleteRequest_ShouldMapAllPropertiesCorrectly() + { + // Arrange + AddBookRequest request = _requestFixture.CreateRequestBook(); + + // Act + AddBookCommand result = request.ToCommand(); + + // Assert + result.Should().NotBeNull(); + result.Metadata.Should().BeEquivalentTo(request.Metadata); + result.Format.Should().Be(request.Format); + result.Edition.Should().Be(request.Edition); + result.VolumeNumber.Should().Be(request.VolumeNumber); + result.Series.Should().BeEquivalentTo(request.Series); + result.ASIN.Should().Be(request.ASIN); + result.GoodreadsId.Should().Be(request.GoodreadsId); + result.LCCN.Should().Be(request.LCCN); + result.OCLCNumber.Should().Be(request.OCLCNumber); + result.OpenLibraryId.Should().Be(request.OpenLibraryId); + result.LibraryThingId.Should().Be(request.LibraryThingId); + result.GoogleBooksId.Should().Be(request.GoogleBooksId); + result.BarnesAndNobleId.Should().Be(request.BarnesAndNobleId); + result.AppleBooksId.Should().Be(request.AppleBooksId); + result.ISBNs.Should().BeEquivalentTo(request.ISBNs); + result.Contributors.Should().BeEquivalentTo(request.Contributors); + result.Ratings.Should().BeEquivalentTo(request.Ratings); + } + + [Fact] + public void ToCommand_WhenMappingMinimalRequest_ShouldMapCorrectly() + { + // Arrange + AddBookRequest request = new( + Metadata: new WrittenContentMetadataEntity( + Title: "Test Book", + OriginalTitle: null, + Description: null, + ReleaseInfo: null, + Genres: null, + Tags: null, + Language: null, + OriginalLanguage: null, + Publisher: null, + PageCount: null), + Format: null, + Edition: null, + VolumeNumber: null, + Series: null, + ASIN: null, + GoodreadsId: null, + LCCN: null, + OCLCNumber: null, + OpenLibraryId: null, + LibraryThingId: null, + GoogleBooksId: null, + BarnesAndNobleId: null, + AppleBooksId: null, + ISBNs: null, + Contributors: null, + Ratings: null); + + // Act + AddBookCommand result = request.ToCommand(); + + // Assert + result.Should().NotBeNull(); + result.Metadata.Should().BeEquivalentTo(request.Metadata); + result.Format.Should().BeNull(); + result.Edition.Should().BeNull(); + result.VolumeNumber.Should().BeNull(); + result.Series.Should().BeNull(); + result.ASIN.Should().BeNull(); + result.GoodreadsId.Should().BeNull(); + result.LCCN.Should().BeNull(); + result.OCLCNumber.Should().BeNull(); + result.OpenLibraryId.Should().BeNull(); + result.LibraryThingId.Should().BeNull(); + result.GoogleBooksId.Should().BeNull(); + result.BarnesAndNobleId.Should().BeNull(); + result.AppleBooksId.Should().BeNull(); + result.ISBNs.Should().BeNull(); + result.Contributors.Should().BeNull(); + result.Ratings.Should().BeNull(); + } + + [Fact] + public void ToCommand_WhenMappingRequestWithCollections_ShouldMapCollectionsCorrectly() + { + // Arrange + AddBookRequest request = new( + Metadata: new WrittenContentMetadataEntity( + Title: "Test Book", + OriginalTitle: null, + Description: null, + ReleaseInfo: null, + Genres: null, + Tags: null, + Language: null, + OriginalLanguage: null, + Publisher: null, + PageCount: null), + Format: null, + Edition: null, + VolumeNumber: null, + Series: null, + ASIN: null, + GoodreadsId: null, + LCCN: null, + OCLCNumber: null, + OpenLibraryId: null, + LibraryThingId: null, + GoogleBooksId: null, + BarnesAndNobleId: null, + AppleBooksId: null, + ISBNs: [new("978-0-123456-78-9", IsbnFormat.Isbn13)], + Contributors: + [ + new( + new MediaContributorNameEntity("John Doe", "John Smith Doe"), + new MediaContributorRoleEntity("Author", "Writing") + ) + ], + Ratings: [new(4.5m, 5m, BookRatingSource.Goodreads, 1000)]); + + // Act + AddBookCommand result = request.ToCommand(); + + // Assert + result.Should().NotBeNull(); + result.ISBNs.Should().BeEquivalentTo(request.ISBNs); + result.Contributors.Should().BeEquivalentTo(request.Contributors); + result.Ratings.Should().BeEquivalentTo(request.Ratings); + } +} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/WrittenContentLibrary/BookLibrary/Books/BookMappingTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/WrittenContentLibrary/BookLibrary/Books/BookMappingTests.cs new file mode 100644 index 00000000..cb8b060e --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/WrittenContentLibrary/BookLibrary/Books/BookMappingTests.cs @@ -0,0 +1,78 @@ +#region ========================================================================= USING ===================================================================================== +using FluentAssertions; +using Lumina.Application.Common.Mapping.Common.Metadata; +using Lumina.Application.Common.Mapping.WrittenContentLibrary.BookLibrary.Books; +using Lumina.Application.Common.Mapping.WrittenContentLibrary.BookLibrary.Common; +using Lumina.Application.UnitTests.Core.WrittenContentLibrary.BooksLibrary.Books.Commands.AddBook.Fixtures; +using Lumina.Contracts.Entities.WrittenContentLibrary.BookLibrary; +using Lumina.Domain.Core.Aggregates.WrittenContentLibrary.BookLibraryAggregate; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Application.UnitTests.Common.Mapping.WrittenContentLibrary.BookLibrary.Books; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class BookMappingTests +{ + private readonly DomainBookFixture _bookFixture; + + /// + /// Initializes a new instance of the class. + /// + public BookMappingTests() + { + _bookFixture = new DomainBookFixture(); + } + + [Fact] + public void ToRepositoryEntity_WhenMappingCompleteBook_ShouldMapAllPropertiesCorrectly() + { + // Arrange + Book book = _bookFixture.CreateDomainBook(); + + // Act + BookEntity result = book.ToRepositoryEntity(); + + // Assert + result.Should().NotBeNull(); + result.Id.Should().Be(book.Id.Value); + result.Title.Should().Be(book.Metadata.Title); + result.OriginalTitle.Should().Be(book.Metadata.OriginalTitle.HasValue ? book.Metadata.OriginalTitle.Value : null); + result.Description.Should().Be(book.Metadata.Description.HasValue ? book.Metadata.Description.Value : null); + result.OriginalReleaseDate.Should().Be(book.Metadata.ReleaseInfo.OriginalReleaseDate.HasValue ? book.Metadata.ReleaseInfo.OriginalReleaseDate.Value : null); + result.OriginalReleaseYear.Should().Be(book.Metadata.ReleaseInfo.OriginalReleaseYear.HasValue ? book.Metadata.ReleaseInfo.OriginalReleaseYear.Value : null); + result.ReReleaseDate.Should().Be(book.Metadata.ReleaseInfo.ReReleaseDate.HasValue ? book.Metadata.ReleaseInfo.ReReleaseDate.Value : null); + result.ReReleaseYear.Should().Be(book.Metadata.ReleaseInfo.ReReleaseYear.HasValue ? book.Metadata.ReleaseInfo.ReReleaseYear.Value : null); + result.ReleaseCountry.Should().Be(book.Metadata.ReleaseInfo.ReleaseCountry.HasValue ? book.Metadata.ReleaseInfo.ReleaseCountry.Value : null); + result.ReleaseVersion.Should().Be(book.Metadata.ReleaseInfo.ReleaseVersion.HasValue ? book.Metadata.ReleaseInfo.ReleaseVersion.Value : null); + result.LanguageCode.Should().Be(book.Metadata.Language.HasValue ? book.Metadata.Language.Value.LanguageCode : null); + result.LanguageName.Should().Be(book.Metadata.Language.HasValue ? book.Metadata.Language.Value.LanguageName : null); + result.LanguageNativeName.Should().Be(book.Metadata.Language.HasValue ? book.Metadata.Language.Value.NativeName.Value : null); + result.OriginalLanguageCode.Should().Be(book.Metadata.OriginalLanguage.HasValue ? book.Metadata.OriginalLanguage.Value.LanguageCode : null); + result.OriginalLanguageName.Should().Be(book.Metadata.OriginalLanguage.HasValue ? book.Metadata.OriginalLanguage.Value.LanguageName : null); + result.OriginalLanguageNativeName.Should().Be(book.Metadata.OriginalLanguage.HasValue ? book.Metadata.OriginalLanguage.Value.NativeName.Value : null); + result.Tags.Should().BeEquivalentTo(book.Metadata.Tags.ToRepositoryEntities()); + result.Genres.Should().BeEquivalentTo(book.Metadata.Genres.ToRepositoryEntities()); + result.Publisher.Should().Be(book.Metadata.Publisher.HasValue ? book.Metadata.Publisher.Value : null); + result.PageCount.Should().Be(book.Metadata.PageCount.HasValue ? book.Metadata.PageCount.Value : null); + result.Format.Should().Be(book.Format.ToString()); + result.Edition.Should().Be(book.Edition.HasValue ? book.Edition.Value : null); + result.VolumeNumber.Should().Be(book.VolumeNumber.HasValue ? book.VolumeNumber.Value : null); + result.ASIN.Should().Be(book.ASIN.HasValue ? book.ASIN.Value : null); + result.GoodreadsId.Should().Be(book.GoodreadsId.HasValue ? book.GoodreadsId.Value : null); + result.LCCN.Should().Be(book.LCCN.HasValue ? book.LCCN.Value : null); + result.OCLCNumber.Should().Be(book.OCLCNumber.HasValue ? book.OCLCNumber.Value : null); + result.OpenLibraryId.Should().Be(book.OpenLibraryId.HasValue ? book.OpenLibraryId.Value : null); + result.LibraryThingId.Should().Be(book.LibraryThingId.HasValue ? book.LibraryThingId.Value : null); + result.GoogleBooksId.Should().Be(book.GoogleBooksId.HasValue ? book.GoogleBooksId.Value : null); + result.BarnesAndNobleId.Should().Be(book.BarnesAndNobleId.HasValue ? book.BarnesAndNobleId.Value : null); + result.AppleBooksId.Should().Be(book.AppleBooksId.HasValue ? book.AppleBooksId.Value : null); + result.ISBNs.Should().BeEquivalentTo(book.ISBNs.ToRepositoryEntities()); + result.Ratings.Should().BeEquivalentTo(book.Ratings.ToRepositoryEntities()); + result.Created.Should().Be(book.Created); + result.Updated.Should().Be(book.Updated.HasValue ? book.Updated.Value : null); + } +} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/WrittenContentLibrary/BookLibrary/Books/BookModelMappingTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/WrittenContentLibrary/BookLibrary/Books/BookModelMappingTests.cs new file mode 100644 index 00000000..a328d739 --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/WrittenContentLibrary/BookLibrary/Books/BookModelMappingTests.cs @@ -0,0 +1,350 @@ +#region ========================================================================= USING ===================================================================================== +using ErrorOr; +using FluentAssertions; +using Lumina.Application.Common.Mapping.Common.Metadata; +using Lumina.Application.Common.Mapping.WrittenContentLibrary.BookLibrary.Books; +using Lumina.Application.Common.Mapping.WrittenContentLibrary.BookLibrary.Common; +using Lumina.Application.UnitTests.Core.WrittenContentLibrary.BooksLibrary.Books.Commands.AddBook.Fixtures; +using Lumina.Contracts.Entities.WrittenContentLibrary.BookLibrary; +using Lumina.Contracts.Enums.BookLibrary; +using Lumina.Contracts.Responses.WrittenContentLibrary.BookLibrary.Books; +using Lumina.Domain.Core.Aggregates.WrittenContentLibrary.BookLibraryAggregate; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Application.UnitTests.Common.Mapping.WrittenContentLibrary.BookLibrary.Books; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class BookModelMappingTests +{ + private readonly BookEntityFixture _bookEntityFixture; + + /// + /// Initializes a new instance of the class. + /// + public BookModelMappingTests() + { + _bookEntityFixture = new BookEntityFixture(); + } + + [Fact] + public void ToDomainModel_WhenMappingValidBookEntity_ShouldMapCorrectly() + { + // Arrange + BookEntity bookEntity = _bookEntityFixture.CreateBook(); + + // Act + ErrorOr result = bookEntity.ToDomainModel(); + + // Assert + // Assert + result.IsError.Should().BeFalse(); + result.Value.Should().NotBeNull(); + result.Value.Id.Value.Should().Be(bookEntity.Id); + result.Value.Metadata.Title.Should().Be(bookEntity.Title); + + if (bookEntity.OriginalTitle is not null) + { + result.Value.Metadata.OriginalTitle.HasValue.Should().BeTrue(); + result.Value.Metadata.OriginalTitle.Value.Should().Be(bookEntity.OriginalTitle); + } + else + result.Value.Metadata.OriginalTitle.HasValue.Should().BeFalse(); + + if (bookEntity.Description is not null) + { + result.Value.Metadata.Description.HasValue.Should().BeTrue(); + result.Value.Metadata.Description.Value.Should().Be(bookEntity.Description); + } + else + result.Value.Metadata.Description.HasValue.Should().BeFalse(); + if (bookEntity.OriginalReleaseDate.HasValue) + { + result.Value.Metadata.ReleaseInfo.OriginalReleaseDate.HasValue.Should().BeTrue(); + result.Value.Metadata.ReleaseInfo.OriginalReleaseDate.Value.Should().Be(bookEntity.OriginalReleaseDate.Value); + } + else + result.Value.Metadata.ReleaseInfo.OriginalReleaseDate.HasValue.Should().BeFalse(); + + if (bookEntity.OriginalReleaseYear.HasValue) + { + result.Value.Metadata.ReleaseInfo.OriginalReleaseYear.HasValue.Should().BeTrue(); + result.Value.Metadata.ReleaseInfo.OriginalReleaseYear.Value.Should().Be(bookEntity.OriginalReleaseYear.Value); + } + else + result.Value.Metadata.ReleaseInfo.OriginalReleaseYear.HasValue.Should().BeFalse(); + + if (bookEntity.ReReleaseDate.HasValue) + { + result.Value.Metadata.ReleaseInfo.ReReleaseDate.HasValue.Should().BeTrue(); + result.Value.Metadata.ReleaseInfo.ReReleaseDate.Value.Should().Be(bookEntity.ReReleaseDate.Value); + } + else + result.Value.Metadata.ReleaseInfo.ReReleaseDate.HasValue.Should().BeFalse(); + + if (bookEntity.ReReleaseYear.HasValue) + { + result.Value.Metadata.ReleaseInfo.ReReleaseYear.HasValue.Should().BeTrue(); + result.Value.Metadata.ReleaseInfo.ReReleaseYear.Value.Should().Be(bookEntity.ReReleaseYear.Value); + } + else + result.Value.Metadata.ReleaseInfo.ReReleaseYear.HasValue.Should().BeFalse(); + + if (bookEntity.ReleaseCountry is not null) + { + result.Value.Metadata.ReleaseInfo.ReleaseCountry.HasValue.Should().BeTrue(); + result.Value.Metadata.ReleaseInfo.ReleaseCountry.Value.Should().Be(bookEntity.ReleaseCountry); + } + else + result.Value.Metadata.ReleaseInfo.ReleaseCountry.HasValue.Should().BeFalse(); + + if (bookEntity.ReleaseVersion is not null) + { + result.Value.Metadata.ReleaseInfo.ReleaseVersion.HasValue.Should().BeTrue(); + result.Value.Metadata.ReleaseInfo.ReleaseVersion.Value.Should().Be(bookEntity.ReleaseVersion); + } + else + result.Value.Metadata.ReleaseInfo.ReleaseVersion.HasValue.Should().BeFalse(); + + if (bookEntity.LanguageCode is not null) + { + result.Value.Metadata.Language.HasValue.Should().BeTrue(); + result.Value.Metadata.Language.Value.LanguageCode.Should().Be(bookEntity.LanguageCode); + result.Value.Metadata.Language.Value.LanguageName.Should().Be(bookEntity.LanguageName); + + if (bookEntity.LanguageNativeName is not null) + { + result.Value.Metadata.Language.Value.NativeName.HasValue.Should().BeTrue(); + result.Value.Metadata.Language.Value.NativeName.Value.Should().Be(bookEntity.LanguageNativeName); + } + else + result.Value.Metadata.Language.Value.NativeName.HasValue.Should().BeFalse(); + } + else + result.Value.Metadata.Language.HasValue.Should().BeFalse(); + + if (bookEntity.OriginalLanguageCode is not null) + { + result.Value.Metadata.OriginalLanguage.HasValue.Should().BeTrue(); + result.Value.Metadata.OriginalLanguage.Value.LanguageCode.Should().Be(bookEntity.OriginalLanguageCode); + result.Value.Metadata.OriginalLanguage.Value.LanguageName.Should().Be(bookEntity.OriginalLanguageName); + + if (bookEntity.OriginalLanguageNativeName is not null) + { + result.Value.Metadata.OriginalLanguage.Value.NativeName.HasValue.Should().BeTrue(); + result.Value.Metadata.OriginalLanguage.Value.NativeName.Value.Should().Be(bookEntity.OriginalLanguageNativeName); + } + else + result.Value.Metadata.OriginalLanguage.Value.NativeName.HasValue.Should().BeFalse(); + } + else + result.Value.Metadata.OriginalLanguage.HasValue.Should().BeFalse(); + + if (bookEntity.Publisher is not null) + { + result.Value.Metadata.Publisher.HasValue.Should().BeTrue(); + result.Value.Metadata.Publisher.Value.Should().Be(bookEntity.Publisher); + } + else + result.Value.Metadata.Publisher.HasValue.Should().BeFalse(); + + if (bookEntity.PageCount.HasValue) + { + result.Value.Metadata.PageCount.HasValue.Should().BeTrue(); + result.Value.Metadata.PageCount.Value.Should().Be(bookEntity.PageCount.Value); + } + else + result.Value.Metadata.PageCount.HasValue.Should().BeFalse(); + + result.Value.Format.Value.Should().Be(Enum.Parse(bookEntity.Format)); + + if (bookEntity.Edition is not null) + { + result.Value.Edition.HasValue.Should().BeTrue(); + result.Value.Edition.Value.Should().Be(bookEntity.Edition); + } + else + result.Value.Edition.HasValue.Should().BeFalse(); + + if (bookEntity.VolumeNumber.HasValue) + { + result.Value.VolumeNumber.HasValue.Should().BeTrue(); + result.Value.VolumeNumber.Value.Should().Be(bookEntity.VolumeNumber.Value); + } + else + result.Value.VolumeNumber.HasValue.Should().BeFalse(); + + if (bookEntity.ASIN is not null) + { + result.Value.ASIN.HasValue.Should().BeTrue(); + result.Value.ASIN.Value.Should().Be(bookEntity.ASIN); + } + else + result.Value.ASIN.HasValue.Should().BeFalse(); + + if (bookEntity.GoodreadsId is not null) + { + result.Value.GoodreadsId.HasValue.Should().BeTrue(); + result.Value.GoodreadsId.Value.Should().Be(bookEntity.GoodreadsId); + } + else + result.Value.GoodreadsId.HasValue.Should().BeFalse(); + + if (bookEntity.LCCN is not null) + { + result.Value.LCCN.HasValue.Should().BeTrue(); + result.Value.LCCN.Value.Should().Be(bookEntity.LCCN); + } + else + result.Value.LCCN.HasValue.Should().BeFalse(); + + if (bookEntity.OCLCNumber is not null) + { + result.Value.OCLCNumber.HasValue.Should().BeTrue(); + result.Value.OCLCNumber.Value.Should().Be(bookEntity.OCLCNumber); + } + else + result.Value.OCLCNumber.HasValue.Should().BeFalse(); + + if (bookEntity.OpenLibraryId is not null) + { + result.Value.OpenLibraryId.HasValue.Should().BeTrue(); + result.Value.OpenLibraryId.Value.Should().Be(bookEntity.OpenLibraryId); + } + else + result.Value.OpenLibraryId.HasValue.Should().BeFalse(); + + if (bookEntity.LibraryThingId is not null) + { + result.Value.LibraryThingId.HasValue.Should().BeTrue(); + result.Value.LibraryThingId.Value.Should().Be(bookEntity.LibraryThingId); + } + else + result.Value.LibraryThingId.HasValue.Should().BeFalse(); + + if (bookEntity.GoogleBooksId is not null) + { + result.Value.GoogleBooksId.HasValue.Should().BeTrue(); + result.Value.GoogleBooksId.Value.Should().Be(bookEntity.GoogleBooksId); + } + else + result.Value.GoogleBooksId.HasValue.Should().BeFalse(); + + if (bookEntity.BarnesAndNobleId is not null) + { + result.Value.BarnesAndNobleId.HasValue.Should().BeTrue(); + result.Value.BarnesAndNobleId.Value.Should().Be(bookEntity.BarnesAndNobleId); + } + else + result.Value.BarnesAndNobleId.HasValue.Should().BeFalse(); + + if (bookEntity.AppleBooksId is not null) + { + result.Value.AppleBooksId.HasValue.Should().BeTrue(); + result.Value.AppleBooksId.Value.Should().Be(bookEntity.AppleBooksId); + } + else + result.Value.AppleBooksId.HasValue.Should().BeFalse(); + + result.Value.Created.Should().Be(bookEntity.Created); + + if (bookEntity.Updated.HasValue) + { + result.Value.Updated.HasValue.Should().BeTrue(); + result.Value.Updated!.Value.Should().Be(bookEntity.Updated.Value); + } + else + result.Value.Updated.HasValue.Should().BeFalse(); + } + + [Fact] + public void ToResponse_WhenMappingBookEntity_ShouldMapAllPropertiesCorrectly() + { + // Arrange + BookEntity bookEntity = _bookEntityFixture.CreateBook(); + + // Act + BookResponse result = bookEntity.ToResponse(); + + // Assert + result.Should().NotBeNull(); + result.Id.Should().Be(bookEntity.Id); + result.Metadata.Title.Should().Be(bookEntity.Title); + result.Metadata.OriginalTitle.Should().Be(bookEntity.OriginalTitle); + result.Metadata.Description.Should().Be(bookEntity.Description); + result.Metadata.ReleaseInfo!.OriginalReleaseDate.Should().Be(bookEntity.OriginalReleaseDate); + result.Metadata.ReleaseInfo.OriginalReleaseYear.Should().Be(bookEntity.OriginalReleaseYear); + result.Metadata.ReleaseInfo.ReReleaseDate.Should().Be(bookEntity.ReReleaseDate); + result.Metadata.ReleaseInfo.ReReleaseYear.Should().Be(bookEntity.ReReleaseYear); + result.Metadata.ReleaseInfo.ReleaseCountry.Should().Be(bookEntity.ReleaseCountry); + result.Metadata.ReleaseInfo.ReleaseVersion.Should().Be(bookEntity.ReleaseVersion); + result.Metadata.Language.Should().NotBeNull(); + result.Metadata.Language!.LanguageCode.Should().Be(bookEntity.LanguageCode); + result.Metadata.Language.LanguageName.Should().Be(bookEntity.LanguageName); + result.Metadata.Language.NativeName.Should().Be(bookEntity.LanguageNativeName); + result.Metadata.OriginalLanguage.Should().NotBeNull(); + result.Metadata.OriginalLanguage!.LanguageCode.Should().Be(bookEntity.OriginalLanguageCode); + result.Metadata.OriginalLanguage.LanguageName.Should().Be(bookEntity.OriginalLanguageName); + result.Metadata.OriginalLanguage.NativeName.Should().Be(bookEntity.OriginalLanguageNativeName); + result.Metadata.Publisher.Should().Be(bookEntity.Publisher); + result.Metadata.PageCount.Should().Be(bookEntity.PageCount); + result.Format.Should().Be(Enum.Parse(bookEntity.Format)); + result.Edition.Should().Be(bookEntity.Edition); + result.VolumeNumber.Should().Be(bookEntity.VolumeNumber); + result.ASIN.Should().Be(bookEntity.ASIN); + result.GoodreadsId.Should().Be(bookEntity.GoodreadsId); + result.LCCN.Should().Be(bookEntity.LCCN); + result.OCLCNumber.Should().Be(bookEntity.OCLCNumber); + result.OpenLibraryId.Should().Be(bookEntity.OpenLibraryId); + result.LibraryThingId.Should().Be(bookEntity.LibraryThingId); + result.GoogleBooksId.Should().Be(bookEntity.GoogleBooksId); + result.BarnesAndNobleId.Should().Be(bookEntity.BarnesAndNobleId); + result.AppleBooksId.Should().Be(bookEntity.AppleBooksId); + result.ISBNs.Should().BeEquivalentTo(bookEntity.ISBNs); + result.Ratings.Should().BeEquivalentTo(bookEntity.Ratings); + result.Created.Should().Be(bookEntity.Created); + result.Updated.Should().Be(bookEntity.Updated); + } + + [Fact] + public void ToDomainModels_WhenMappingMultipleBookEntities_ShouldMapAllCorrectly() + { + // Arrange + List bookEntities = + [ + _bookEntityFixture.CreateBook(), + _bookEntityFixture.CreateBook() + ]; + + // Act + IEnumerable> results = bookEntities.ToDomainModels(); + + // Assert + results.Should().NotBeNull(); + results.Should().HaveCount(bookEntities.Count); + results.Should().AllSatisfy(result => result.IsError.Should().BeFalse()); + } + + [Fact] + public void ToResponses_WhenMappingMultipleBookEntities_ShouldMapAllCorrectly() + { + // Arrange + List bookEntities = + [ + _bookEntityFixture.CreateBook(), + _bookEntityFixture.CreateBook() + ]; + + // Act + IEnumerable results = bookEntities.ToResponses(); + + // Assert + results.Should().NotBeNull(); + results.Should().HaveCount(bookEntities.Count); + } +} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/WrittenContentLibrary/BookLibrary/Common/BookRatingMappingTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/WrittenContentLibrary/BookLibrary/Common/BookRatingMappingTests.cs new file mode 100644 index 00000000..63ed2581 --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/WrittenContentLibrary/BookLibrary/Common/BookRatingMappingTests.cs @@ -0,0 +1,121 @@ +#region ========================================================================= USING ===================================================================================== +using FluentAssertions; +using Lumina.Application.Common.Mapping.Common.Metadata; +using Lumina.Application.Common.Mapping.WrittenContentLibrary.BookLibrary.Books; +using Lumina.Application.Common.Mapping.WrittenContentLibrary.BookLibrary.Common; +using Lumina.Application.UnitTests.Core.WrittenContentLibrary.BooksLibrary.Common.Fixtures; +using Lumina.Contracts.Entities.WrittenContentLibrary.BookLibrary; +using Lumina.Domain.Core.Aggregates.WrittenContentLibrary.BookLibraryAggregate.ValueObjects; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Application.UnitTests.Common.Mapping.WrittenContentLibrary.BookLibrary.Common; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class BookRatingMappingTests +{ + private readonly BookRatingFixture _bookRatingFixture; + + /// + /// Initializes a new instance of the class. + /// + public BookRatingMappingTests() + { + _bookRatingFixture = new BookRatingFixture(); + } + + [Fact] + public void ToRepositoryEntity_WhenMappingCompleteBookRating_ShouldMapAllPropertiesCorrectly() + { + // Arrange + BookRating bookRating = _bookRatingFixture.CreateBookRating(); + + // Act + BookRatingEntity result = bookRating.ToRepositoryEntity(); + + // Assert + result.Should().NotBeNull(); + result.Value.Should().Be(bookRating.Value); + result.MaxValue.Should().Be(bookRating.MaxValue); + result.Source.Should().Be(bookRating.Source.Value); + result.VoteCount.Should().Be(bookRating.VoteCount.Value); + } + + [Fact] + public void ToRepositoryEntity_WhenMappingBookRatingWithoutSource_ShouldMapCorrectly() + { + // Arrange + BookRating bookRating = _bookRatingFixture.CreateBookRatingWithoutSource(); + + // Act + BookRatingEntity result = bookRating.ToRepositoryEntity(); + + // Assert + result.Should().NotBeNull(); + result.Value.Should().Be(bookRating.Value); + result.MaxValue.Should().Be(bookRating.MaxValue); + result.Source.Should().BeNull(); + result.VoteCount.Should().Be(bookRating.VoteCount.Value); + } + + [Fact] + public void ToRepositoryEntity_WhenMappingBookRatingWithoutVoteCount_ShouldMapCorrectly() + { + // Arrange + BookRating bookRating = _bookRatingFixture.CreateBookRatingWithoutVoteCount(); + + // Act + BookRatingEntity result = bookRating.ToRepositoryEntity(); + + // Assert + result.Should().NotBeNull(); + result.Value.Should().Be(bookRating.Value); + result.MaxValue.Should().Be(bookRating.MaxValue); + result.Source.Should().Be(bookRating.Source.Value); + result.VoteCount.Should().BeNull(); + } + + [Fact] + public void ToRepositoryEntities_WhenMappingMultipleBookRatings_ShouldMapAllCorrectly() + { + // Arrange + List bookRatings = + [ + _bookRatingFixture.CreateBookRating(), + _bookRatingFixture.CreateBookRatingWithoutSource(), + _bookRatingFixture.CreateBookRatingWithoutVoteCount() + ]; + + // Act + IEnumerable results = bookRatings.ToRepositoryEntities(); + + // Assert + results.Should().NotBeNull(); + results.Should().HaveCount(bookRatings.Count); + + List resultList = results.ToList(); + + // Complete rating + resultList[0].Value.Should().Be(bookRatings[0].Value); + resultList[0].MaxValue.Should().Be(bookRatings[0].MaxValue); + resultList[0].Source.Should().Be(bookRatings[0].Source.Value); + resultList[0].VoteCount.Should().Be(bookRatings[0].VoteCount.Value); + + // Rating without source + resultList[1].Value.Should().Be(bookRatings[1].Value); + resultList[1].MaxValue.Should().Be(bookRatings[1].MaxValue); + resultList[1].Source.Should().BeNull(); + resultList[1].VoteCount.Should().Be(bookRatings[1].VoteCount.Value); + + // Rating without vote count + resultList[2].Value.Should().Be(bookRatings[2].Value); + resultList[2].MaxValue.Should().Be(bookRatings[2].MaxValue); + resultList[2].Source.Should().Be(bookRatings[2].Source.Value); + resultList[2].VoteCount.Should().BeNull(); + } +} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/WrittenContentLibrary/BookLibrary/Common/BookRatingModelMappingTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/WrittenContentLibrary/BookLibrary/Common/BookRatingModelMappingTests.cs new file mode 100644 index 00000000..19e4632e --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/WrittenContentLibrary/BookLibrary/Common/BookRatingModelMappingTests.cs @@ -0,0 +1,153 @@ +#region ========================================================================= USING ===================================================================================== +using ErrorOr; +using FluentAssertions; +using Lumina.Application.Common.Mapping.Common.Metadata; +using Lumina.Application.Common.Mapping.WrittenContentLibrary.BookLibrary.Books; +using Lumina.Application.Common.Mapping.WrittenContentLibrary.BookLibrary.Common; +using Lumina.Application.UnitTests.Core.WrittenContentLibrary.BooksLibrary.Common.Fixtures; +using Lumina.Contracts.Entities.WrittenContentLibrary.BookLibrary; +using Lumina.Domain.Core.Aggregates.WrittenContentLibrary.BookLibraryAggregate.ValueObjects; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Application.UnitTests.Common.Mapping.WrittenContentLibrary.BookLibrary.Common; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class BookRatingModelMappingTests +{ + private readonly BookRatingEntityFixture _bookRatingEntityFixture; + + /// + /// Initializes a new instance of the class. + /// + public BookRatingModelMappingTests() + { + _bookRatingEntityFixture = new BookRatingEntityFixture(); + } + + [Fact] + public void ToDomainModel_WhenMappingCompleteBookRatingEntity_ShouldMapAllPropertiesCorrectly() + { + // Arrange + BookRatingEntity entity = _bookRatingEntityFixture.CreateComplete(); + + // Act + ErrorOr result = entity.ToDomainModel(); + + // Assert + result.IsError.Should().BeFalse(); + result.Value.Should().NotBeNull(); + result.Value.Value.Should().Be(entity.Value!.Value); + result.Value.MaxValue.Should().Be(entity.MaxValue!.Value); + + if (entity.Source.HasValue) + { + result.Value.Source.HasValue.Should().BeTrue(); + result.Value.Source.Value.Should().Be(entity.Source.Value); + } + else + result.Value.Source.HasValue.Should().BeFalse(); + + if (entity.VoteCount.HasValue) + { + result.Value.VoteCount.HasValue.Should().BeTrue(); + result.Value.VoteCount.Value.Should().Be(entity.VoteCount.Value); + } + else + result.Value.VoteCount.HasValue.Should().BeFalse(); + } + + [Fact] + public void ToDomainModel_WhenMappingMinimalBookRatingEntity_ShouldMapRequiredPropertiesCorrectly() + { + // Arrange + BookRatingEntity entity = _bookRatingEntityFixture.CreateMinimal(); + + // Act + ErrorOr result = entity.ToDomainModel(); + + // Assert + result.IsError.Should().BeFalse(); + result.Value.Should().NotBeNull(); + result.Value.Value.Should().Be(entity.Value!.Value); + result.Value.MaxValue.Should().Be(entity.MaxValue!.Value); + result.Value.Source.HasValue.Should().BeFalse(); + result.Value.VoteCount.HasValue.Should().BeFalse(); + } + + [Fact] + public void ToDomainModel_WhenMappingInvalidBookRatingEntity_ShouldReturnError() + { + // Arrange + BookRatingEntity entity = _bookRatingEntityFixture.CreateInvalid(); + + // Act + ErrorOr result = entity.ToDomainModel(); + + // Assert + result.IsError.Should().BeTrue(); + } + + [Fact] + public void ToDomainModels_WhenMappingMultipleValidBookRatingEntities_ShouldMapAllCorrectly() + { + // Arrange + List entities = + [ + _bookRatingEntityFixture.CreateComplete(), + _bookRatingEntityFixture.CreateMinimal() + ]; + + // Act + IEnumerable> results = entities.ToDomainModels(); + + // Assert + results.Should().NotBeNull(); + results.Should().HaveCount(entities.Count); + + List> resultList = results.ToList(); + resultList.Should().AllSatisfy(result => result.IsError.Should().BeFalse()); + + // Complete rating + resultList[0].Value.Value.Should().Be(entities[0].Value!.Value); + resultList[0].Value.MaxValue.Should().Be(entities[0].MaxValue!.Value); + resultList[0].Value.Source.Value.Should().Be(entities[0].Source!.Value); + resultList[0].Value.VoteCount.Value.Should().Be(entities[0].VoteCount!.Value); + + // Minimal rating + resultList[1].Value.Value.Should().Be(entities[1].Value!.Value); + resultList[1].Value.MaxValue.Should().Be(entities[1].MaxValue!.Value); + resultList[1].Value.Source.HasValue.Should().BeFalse(); + resultList[1].Value.VoteCount.HasValue.Should().BeFalse(); + } + + [Fact] + public void ToDomainModels_WhenMappingMixedValidAndInvalidBookRatingEntities_ShouldReturnMixedResults() + { + // Arrange + List entities = + [ + _bookRatingEntityFixture.CreateComplete(), + _bookRatingEntityFixture.CreateInvalid(), + _bookRatingEntityFixture.CreateMinimal() + ]; + + // Act + IEnumerable> results = entities.ToDomainModels(); + + // Assert + results.Should().NotBeNull(); + results.Should().HaveCount(entities.Count); + + List> resultList = results.ToList(); + + resultList[0].IsError.Should().BeFalse(); + resultList[1].IsError.Should().BeTrue(); + resultList[2].IsError.Should().BeFalse(); + } +} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/WrittenContentLibrary/BookLibrary/Common/IsbnMappingTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/WrittenContentLibrary/BookLibrary/Common/IsbnMappingTests.cs new file mode 100644 index 00000000..622684c7 --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/WrittenContentLibrary/BookLibrary/Common/IsbnMappingTests.cs @@ -0,0 +1,102 @@ +#region ========================================================================= USING ===================================================================================== +using FluentAssertions; +using Lumina.Application.Common.Mapping.Common.Metadata; +using Lumina.Application.Common.Mapping.WrittenContentLibrary.BookLibrary.Books; +using Lumina.Application.Common.Mapping.WrittenContentLibrary.BookLibrary.Common; +using Lumina.Application.UnitTests.Core.WrittenContentLibrary.BooksLibrary.Common.Fixtures; +using Lumina.Contracts.Entities.WrittenContentLibrary.BookLibrary; +using Lumina.Contracts.Enums.BookLibrary; +using Lumina.Domain.Core.Aggregates.WrittenContentLibrary.BookLibraryAggregate.ValueObjects; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Application.UnitTests.Common.Mapping.WrittenContentLibrary.BookLibrary.Common; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class IsbnMappingTests +{ + private readonly IsbnFixture _isbnFixture; + + /// + /// Initializes a new instance of the class. + /// + public IsbnMappingTests() + { + _isbnFixture = new IsbnFixture(); + } + + [Fact] + public void ToRepositoryEntity_WhenMappingIsbn10_ShouldMapCorrectly() + { + // Arrange + Isbn isbn = _isbnFixture.CreateIsbn10(); + + // Act + IsbnEntity result = isbn.ToRepositoryEntity(); + + // Assert + result.Should().NotBeNull(); + result.Value.Should().Be(isbn.Value); + result.Format.Should().Be(IsbnFormat.Isbn10); + } + + [Fact] + public void ToRepositoryEntity_WhenMappingIsbn13_ShouldMapCorrectly() + { + // Arrange + Isbn isbn = _isbnFixture.CreateIsbn13(); + + // Act + IsbnEntity result = isbn.ToRepositoryEntity(); + + // Assert + result.Should().NotBeNull(); + result.Value.Should().Be(isbn.Value); + result.Format.Should().Be(IsbnFormat.Isbn13); + } + + [Fact] + public void ToRepositoryEntities_WhenMappingMultipleIsbns_ShouldMapAllCorrectly() + { + // Arrange + List isbns = + [ + _isbnFixture.CreateIsbn10(), + _isbnFixture.CreateIsbn13(), + _isbnFixture.CreateIsbn10() + ]; + + // Act + IEnumerable results = isbns.ToRepositoryEntities(); + + // Assert + results.Should().NotBeNull(); + results.Should().HaveCount(isbns.Count); + + List resultList = results.ToList(); + for (int i = 0; i < isbns.Count; i++) + { + resultList[i].Value.Should().Be(isbns[i].Value); + resultList[i].Format.Should().Be(isbns[i].Format); + } + } + + [Fact] + public void ToRepositoryEntities_WhenMappingEmptyCollection_ShouldReturnEmptyCollection() + { + // Arrange + List isbns = []; + + // Act + IEnumerable results = isbns.ToRepositoryEntities(); + + // Assert + results.Should().NotBeNull(); + results.Should().BeEmpty(); + } +} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/WrittenContentLibrary/BookLibrary/Common/IsbnModelMappingTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/WrittenContentLibrary/BookLibrary/Common/IsbnModelMappingTests.cs new file mode 100644 index 00000000..cff15340 --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/WrittenContentLibrary/BookLibrary/Common/IsbnModelMappingTests.cs @@ -0,0 +1,154 @@ +#region ========================================================================= USING ===================================================================================== +using ErrorOr; +using FluentAssertions; +using Lumina.Application.Common.Mapping.Common.Metadata; +using Lumina.Application.Common.Mapping.WrittenContentLibrary.BookLibrary.Books; +using Lumina.Application.Common.Mapping.WrittenContentLibrary.BookLibrary.Common; +using Lumina.Application.UnitTests.Core.WrittenContentLibrary.BooksLibrary.Common.Fixtures; +using Lumina.Contracts.Entities.WrittenContentLibrary.BookLibrary; +using Lumina.Contracts.Enums.BookLibrary; +using Lumina.Domain.Core.Aggregates.WrittenContentLibrary.BookLibraryAggregate.ValueObjects; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Application.UnitTests.Common.Mapping.WrittenContentLibrary.BookLibrary.Common; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class IsbnModelMappingTests +{ + private readonly IsbnEntityFixture _isbnEntityFixture; + + /// + /// Initializes a new instance of the class. + /// + public IsbnModelMappingTests() + { + _isbnEntityFixture = new IsbnEntityFixture(); + } + + [Fact] + public void ToDomainModel_WhenMappingValidIsbn10Entity_ShouldMapCorrectly() + { + // Arrange + IsbnEntity entity = _isbnEntityFixture.CreateIsbn10(); + + // Act + ErrorOr result = entity.ToDomainModel(); + + // Assert + result.IsError.Should().BeFalse(); + result.Value.Should().NotBeNull(); + result.Value.Value.Should().Be(entity.Value); + result.Value.Format.Should().Be(entity.Format!.Value); + } + + [Fact] + public void ToDomainModel_WhenMappingValidIsbn13Entity_ShouldMapCorrectly() + { + // Arrange + IsbnEntity entity = _isbnEntityFixture.CreateIsbn13(); + + // Act + ErrorOr result = entity.ToDomainModel(); + + // Assert + result.IsError.Should().BeFalse(); + result.Value.Should().NotBeNull(); + result.Value.Value.Should().Be(entity.Value); + result.Value.Format.Should().Be(entity.Format!.Value); + } + + [Fact] + public void ToDomainModel_WhenMappingEntityWithoutFormat_ShouldUseDefaultFormat() + { + // Arrange + IsbnEntity entity = _isbnEntityFixture.CreateWithoutFormat(); + + // Act + ErrorOr result = entity.ToDomainModel(); + + // Assert + result.IsError.Should().BeFalse(); + result.Value.Should().NotBeNull(); + result.Value.Value.Should().Be(entity.Value); + result.Value.Format.Should().Be(IsbnFormat.Isbn13); // Default format + } + + [Fact] + public void ToDomainModel_WhenMappingInvalidIsbnEntity_ShouldReturnError() + { + // Arrange + IsbnEntity entity = _isbnEntityFixture.CreateInvalid(); + + // Act + ErrorOr result = entity.ToDomainModel(); + + // Assert + result.IsError.Should().BeTrue(); + } + + [Fact] + public void ToDomainModels_WhenMappingMultipleValidIsbnEntities_ShouldMapAllCorrectly() + { + // Arrange + List entities = + [ + _isbnEntityFixture.CreateIsbn10(), + _isbnEntityFixture.CreateIsbn13(), + _isbnEntityFixture.CreateWithoutFormat() + ]; + + // Act + IEnumerable> results = entities.ToDomainModels(); + + // Assert + results.Should().NotBeNull(); + results.Should().HaveCount(entities.Count); + + List> resultList = results.ToList(); + resultList.Should().AllSatisfy(result => result.IsError.Should().BeFalse()); + + resultList[0].Value.Value.Should().Be(entities[0].Value); + resultList[0].Value.Format.Should().Be(entities[0].Format!.Value); + + resultList[1].Value.Value.Should().Be(entities[1].Value); + resultList[1].Value.Format.Should().Be(entities[1].Format!.Value); + + resultList[2].Value.Value.Should().Be(entities[2].Value); + resultList[2].Value.Format.Should().Be(IsbnFormat.Isbn13); // Default format + } + + [Fact] + public void ToDomainModels_WhenMappingMixedValidAndInvalidIsbnEntities_ShouldReturnMixedResults() + { + // Arrange + List entities = + [ + _isbnEntityFixture.CreateIsbn10(), + _isbnEntityFixture.CreateInvalid(), + _isbnEntityFixture.CreateIsbn13() + ]; + + // Act + IEnumerable> results = entities.ToDomainModels(); + + // Assert + results.Should().NotBeNull(); + results.Should().HaveCount(entities.Count); + + List> resultList = results.ToList(); + + resultList[0].IsError.Should().BeFalse(); + resultList[0].Value.Value.Should().Be(entities[0].Value); + + resultList[1].IsError.Should().BeTrue(); + + resultList[2].IsError.Should().BeFalse(); + resultList[2].Value.Value.Should().Be(entities[2].Value); + } +} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/FileManagement/Directories/Queries/GetTreeDirectories/GetTreeDirectoriesQueryHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/FileManagement/Directories/Queries/GetTreeDirectories/GetTreeDirectoriesQueryHandlerTests.cs deleted file mode 100644 index 23e0c60b..00000000 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/FileManagement/Directories/Queries/GetTreeDirectories/GetTreeDirectoriesQueryHandlerTests.cs +++ /dev/null @@ -1,168 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using AutoFixture; -using AutoFixture.AutoNSubstitute; -using ErrorOr; -using FluentAssertions; -using Lumina.Application.Core.FileManagement.Directories.Queries.GetDirectoryTree; -using Lumina.Application.Core.FileManagement.Directories.Queries.GetTreeDirectories; -using Lumina.Application.UnitTests.Core.FileManagement.Directories.Fixtures; -using Lumina.Application.UnitTests.Core.FileManagement.Directories.Queries.GetDirectoryTree.Fixtures; -using Lumina.Application.UnitTests.Core.FileManagement.Directories.Queries.GetTreeDirectories.Fixtures; -using Lumina.Application.UnitTests.Core.FileManagement.Files.Fixtures; -using Lumina.Application.UnitTests.Core.FileManagement.Pahs.Fixtures; -using Lumina.Contracts.Responses.FileManagement; -using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate; -using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.Entities; -using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.Services; -using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.ValueObjects; -using MapsterMapper; -using NSubstitute; -using System.Collections.Generic; -using System.Diagnostics.CodeAnalysis; -using System.Linq; -using System.Threading; -using System.Threading.Tasks; -#endregion - -namespace Lumina.Application.UnitTests.Core.FileManagement.Directories.Queries.GetTreeDirectories; - -/// -/// Contains unit tests for the class. -/// -[ExcludeFromCodeCoverage] -public class GetTreeDirectoriesQueryHandlerTests -{ - private readonly IFixture _fixture; - private readonly IMapper _mockMapper; - private readonly IDirectoryService _mockDirectoryService; - private readonly GetTreeDirectoriesQueryHandler _sut; - private readonly GetTreeDirectoriesQueryFixture _getTreeDirectoriesQueryFixture; - private readonly DirectoryFixture _directoryFixture; - private readonly FileSystemTreeNodeResponseFixture _fileSystemTreeNodeResponseFixture; - - /// - /// Initializes a new instance of the class. - /// - public GetTreeDirectoriesQueryHandlerTests() - { - _fixture = new Fixture().Customize(new AutoNSubstituteCustomization()); - _mockDirectoryService = Substitute.For(); - _mockMapper = Substitute.For(); - _sut = new GetTreeDirectoriesQueryHandler(_mockDirectoryService, _mockMapper); - _getTreeDirectoriesQueryFixture = new GetTreeDirectoriesQueryFixture(); - _directoryFixture = new DirectoryFixture(); - _fileSystemTreeNodeResponseFixture = new FileSystemTreeNodeResponseFixture(); - } - - [Fact] - public async Task Handle_WhenCalledWithValidQueryWithoutFilesIncluded_ShouldReturnSuccessResult() - { - // Arrange - GetTreeDirectoriesQuery getDirectoriesQuery = GetTreeDirectoriesQueryFixture.CreateGetTreeDirectoryQuery(false); - - IEnumerable directories = _directoryFixture.CreateMany(); - IEnumerable directoryResponses = _fileSystemTreeNodeResponseFixture.CreateMany(directories.Count()); - - _mockDirectoryService.GetSubdirectories(getDirectoriesQuery.Path, getDirectoriesQuery.IncludeHiddenElements) - .Returns(ErrorOrFactory.From(directories)); - - _mockMapper.Map>(Arg.Is>(d => d == directories)) - .Returns(directoryResponses); - - // Act - ErrorOr> result = await _sut.Handle(getDirectoriesQuery, CancellationToken.None); - - // Assert - result.IsError.Should().BeFalse(); - result.Value.Should().BeAssignableTo>(); - result.Value.Should().BeEquivalentTo(directoryResponses); - _mockDirectoryService.Received(1).GetSubdirectories(getDirectoriesQuery.Path, getDirectoriesQuery.IncludeHiddenElements); - _mockMapper.Received(1).Map>(Arg.Is>(d => d == directories)); - } - - [Fact] - public async Task Handle_WhenCalledWithValidQueryWithFilesIncluded_ShouldReturnSuccessResult() - { - // Arrange - GetTreeDirectoriesQuery getDirectoriesQuery = GetTreeDirectoriesQueryFixture.CreateGetTreeDirectoryQuery(true); - - IEnumerable directories = _directoryFixture.CreateMany(); - IEnumerable directoryResponses = _fileSystemTreeNodeResponseFixture.CreateMany(directories.Count()); - - _mockDirectoryService.GetSubdirectories(getDirectoriesQuery.Path, getDirectoriesQuery.IncludeHiddenElements) - .Returns(ErrorOrFactory.From(directories)); - - _mockMapper.Map>(Arg.Is>(d => d == directories)) - .Returns(directoryResponses); - - // Act - ErrorOr> result = await _sut.Handle(getDirectoriesQuery, CancellationToken.None); - - // Assert - result.IsError.Should().BeFalse(); - result.Value.Should().BeAssignableTo>(); - result.Value.Should().BeEquivalentTo(directoryResponses); - _mockDirectoryService.Received(1).GetSubdirectories(getDirectoriesQuery.Path, getDirectoriesQuery.IncludeHiddenElements); - _mockMapper.Received(1).Map>(Arg.Is>(d => d == directories)); - } - - [Fact] - public async Task Handle_WhenDirectoryServiceReturnsError_ShouldReturnFailureResult() - { - // Arrange - GetTreeDirectoriesQuery query = _fixture.Create(); - Error error = Error.Failure("DirectoryService.Error", "An error occurred"); - _mockDirectoryService.GetSubdirectories(query.Path, query.IncludeHiddenElements) - .Returns(error); - - // Act - ErrorOr> result = await _sut.Handle(query, CancellationToken.None); - - // Assert - result.IsError.Should().BeTrue(); - result.FirstError.Should().Be(error); - _mockDirectoryService.Received(1).GetSubdirectories(query.Path, query.IncludeHiddenElements); - } - - [Fact] - public async Task Handle_WhenDirectoryServiceReturnsEmptyList_ShouldReturnEmptySuccessResult() - { - // Arrange - GetTreeDirectoriesQuery query = _fixture.Create(); - ErrorOr> emptyList = ErrorOrFactory.From(Enumerable.Empty()); - _mockDirectoryService.GetSubdirectories(query.Path, query.IncludeHiddenElements) - .Returns(emptyList); - - // Act - ErrorOr> result = await _sut.Handle(query, CancellationToken.None); - - // Assert - result.IsError.Should().BeFalse(); - result.Value.Should().BeEmpty(); - _mockDirectoryService.Received(1).GetSubdirectories(query.Path, query.IncludeHiddenElements); - } - - [Fact] - public async Task Handle_WhenCalledWithNestedDirectories_ShouldReturnCorrectlyNestedResponse() - { - // Arrange - GetTreeDirectoriesQuery query = GetTreeDirectoriesQueryFixture.CreateGetTreeDirectoryQuery(true); - IEnumerable nestedDirectories = _directoryFixture.CreateManyNested(); - IEnumerable nestedResponses = _fileSystemTreeNodeResponseFixture.CreateMany(2, 2, 2); - - _mockDirectoryService.GetSubdirectories(query.Path, query.IncludeHiddenElements) - .Returns(ErrorOrFactory.From(nestedDirectories)); - - _mockMapper.Map>(Arg.Is>(d => d == nestedDirectories)) - .Returns(nestedResponses); - - // Act - ErrorOr> result = await _sut.Handle(query, CancellationToken.None); - - // Assert - result.IsError.Should().BeFalse(); - result.Value.Should().BeAssignableTo>(); - result.Value.Should().BeEquivalentTo(nestedResponses, options => options.IncludingNestedObjects()); - result.Value.Any(r => r.Children.Count != 0).Should().BeTrue(); - } -} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/FileManagement/Directories/Fixtures/DirectoryFixture.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Directories/Fixtures/DirectoryFixture.cs similarity index 94% rename from tests/UnitTests/Lumina.Application.UnitTests/Core/FileManagement/Directories/Fixtures/DirectoryFixture.cs rename to tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Directories/Fixtures/DirectoryFixture.cs index 5bae115b..3733d28a 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/FileManagement/Directories/Fixtures/DirectoryFixture.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Directories/Fixtures/DirectoryFixture.cs @@ -3,15 +3,15 @@ using Bogus; using ErrorOr; using Lumina.Contracts.Enums.FileSystem; using Lumina.Domain.Common.Primitives; -using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate; -using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.Entities; +using Lumina.Domain.Core.Aggregates.FileSystemManagement.FileSystemManagementAggregate; +using Lumina.Domain.Core.Aggregates.FileSystemManagement.FileSystemManagementAggregate.Entities; using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Linq; #endregion -namespace Lumina.Application.UnitTests.Core.FileManagement.Directories.Fixtures; +namespace Lumina.Application.UnitTests.Core.FileSystemManagement.Directories.Fixtures; /// /// Fixture class for the class. diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/FileManagement/Directories/Fixtures/DirectoryResponseFixture.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Directories/Fixtures/DirectoryResponseFixture.cs similarity index 91% rename from tests/UnitTests/Lumina.Application.UnitTests/Core/FileManagement/Directories/Fixtures/DirectoryResponseFixture.cs rename to tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Directories/Fixtures/DirectoryResponseFixture.cs index c3ef71d8..d24f7da1 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/FileManagement/Directories/Fixtures/DirectoryResponseFixture.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Directories/Fixtures/DirectoryResponseFixture.cs @@ -1,12 +1,12 @@ #region ========================================================================= USING ===================================================================================== using Bogus; -using Lumina.Contracts.Responses.FileManagement; +using Lumina.Contracts.Responses.FileSystemManagement.Directories; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Linq; #endregion -namespace Lumina.Application.UnitTests.Core.FileManagement.Directories.Fixtures; +namespace Lumina.Application.UnitTests.Core.FileSystemManagement.Directories.Fixtures; /// /// Fixture class for the class. diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/FileManagement/Directories/Fixtures/FileSystemItemModelFixture.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Directories/Fixtures/FileSystemItemModelFixture.cs similarity index 61% rename from tests/UnitTests/Lumina.Application.UnitTests/Core/FileManagement/Directories/Fixtures/FileSystemItemModelFixture.cs rename to tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Directories/Fixtures/FileSystemItemModelFixture.cs index d4c0a014..02c144be 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/FileManagement/Directories/Fixtures/FileSystemItemModelFixture.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Directories/Fixtures/FileSystemItemModelFixture.cs @@ -1,15 +1,15 @@ #region ========================================================================= USING ===================================================================================== using Bogus; -using Lumina.Contracts.Models.FileManagement; +using Lumina.Contracts.Entities.FileSystemManagement; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Linq; #endregion -namespace Lumina.Application.UnitTests.Core.FileManagement.Directories.Fixtures; +namespace Lumina.Application.UnitTests.Core.FileSystemManagement.Directories.Fixtures; /// -/// Fixture class for the class. +/// Fixture class for the class. /// [ExcludeFromCodeCoverage] public class FileSystemItemModelFixture @@ -17,12 +17,12 @@ public class FileSystemItemModelFixture private readonly Faker _faker = new(); /// - /// Creates a random valid . + /// Creates a random valid . /// - /// The created . - public FileSystemItemModel Create() + /// The created . + public FileSystemItemEntity Create() { - return new FileSystemItemModel( + return new FileSystemItemEntity( _faker.System.FilePath(), _faker.System.FileName(), _faker.Date.Past(), @@ -31,11 +31,11 @@ public class FileSystemItemModelFixture } /// - /// Creates a list of . + /// Creates a list of . /// /// The number of elements to create. /// The created list. - public List CreateMany(int count = 3) + public List CreateMany(int count = 3) { return Enumerable.Range(0, count).Select(_ => Create()).ToList(); } diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/FileManagement/Directories/Fixtures/FileSystemTreeNodeResponseFixture.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Directories/Fixtures/FileSystemTreeNodeResponseFixture.cs similarity index 94% rename from tests/UnitTests/Lumina.Application.UnitTests/Core/FileManagement/Directories/Fixtures/FileSystemTreeNodeResponseFixture.cs rename to tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Directories/Fixtures/FileSystemTreeNodeResponseFixture.cs index ff713dd6..f4f66edc 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/FileManagement/Directories/Fixtures/FileSystemTreeNodeResponseFixture.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Directories/Fixtures/FileSystemTreeNodeResponseFixture.cs @@ -1,13 +1,13 @@ #region ========================================================================= USING ===================================================================================== using Bogus; using Lumina.Contracts.Enums.FileSystem; -using Lumina.Contracts.Responses.FileManagement; +using Lumina.Contracts.Responses.FileSystemManagement.Common; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Linq; #endregion -namespace Lumina.Application.UnitTests.Core.FileManagement.Directories.Fixtures; +namespace Lumina.Application.UnitTests.Core.FileSystemManagement.Directories.Fixtures; /// /// Fixture class for the class. diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/FileManagement/Directories/Queries/GetDirectories/Fixtures/GetDirectoriesQueryFixture.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Directories/Queries/GetDirectories/Fixtures/GetDirectoriesQueryFixture.cs similarity index 84% rename from tests/UnitTests/Lumina.Application.UnitTests/Core/FileManagement/Directories/Queries/GetDirectories/Fixtures/GetDirectoriesQueryFixture.cs rename to tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Directories/Queries/GetDirectories/Fixtures/GetDirectoriesQueryFixture.cs index c399815c..30844e65 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/FileManagement/Directories/Queries/GetDirectories/Fixtures/GetDirectoriesQueryFixture.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Directories/Queries/GetDirectories/Fixtures/GetDirectoriesQueryFixture.cs @@ -1,10 +1,10 @@ #region ========================================================================= USING ===================================================================================== using Bogus; -using Lumina.Application.Core.FileManagement.Directories.Queries.GetDirectories; +using Lumina.Application.Core.FileSystemManagement.Directories.Queries.GetDirectories; using System.Diagnostics.CodeAnalysis; #endregion -namespace Lumina.Application.UnitTests.Core.FileManagement.Directories.Queries.GetDirectories.Fixtures; +namespace Lumina.Application.UnitTests.Core.FileSystemManagement.Directories.Queries.GetDirectories.Fixtures; /// /// Fixture class for the class. diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/FileManagement/Directories/Queries/GetDirectories/GetDirectoriesQueryHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Directories/Queries/GetDirectories/GetDirectoriesQueryHandlerTests.cs similarity index 62% rename from tests/UnitTests/Lumina.Application.UnitTests/Core/FileManagement/Directories/Queries/GetDirectories/GetDirectoriesQueryHandlerTests.cs rename to tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Directories/Queries/GetDirectories/GetDirectoriesQueryHandlerTests.cs index ca959639..ebf36933 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/FileManagement/Directories/Queries/GetDirectories/GetDirectoriesQueryHandlerTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Directories/Queries/GetDirectories/GetDirectoriesQueryHandlerTests.cs @@ -3,13 +3,12 @@ using AutoFixture; using AutoFixture.AutoNSubstitute; using ErrorOr; using FluentAssertions; -using Lumina.Application.Core.FileManagement.Directories.Queries.GetDirectories; -using Lumina.Application.UnitTests.Core.FileManagement.Directories.Fixtures; -using Lumina.Application.UnitTests.Core.FileManagement.Directories.Queries.GetDirectories.Fixtures; -using Lumina.Contracts.Responses.FileManagement; -using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.Entities; -using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.Services; -using MapsterMapper; +using Lumina.Application.Core.FileSystemManagement.Directories.Queries.GetDirectories; +using Lumina.Application.UnitTests.Core.FileSystemManagement.Directories.Fixtures; +using Lumina.Application.UnitTests.Core.FileSystemManagement.Directories.Queries.GetDirectories.Fixtures; +using Lumina.Contracts.Responses.FileSystemManagement.Directories; +using Lumina.Domain.Core.Aggregates.FileSystemManagement.FileSystemManagementAggregate.Entities; +using Lumina.Domain.Core.Aggregates.FileSystemManagement.FileSystemManagementAggregate.Services; using NSubstitute; using System; using System.Collections.Generic; @@ -19,7 +18,7 @@ using System.Threading; using System.Threading.Tasks; #endregion -namespace Lumina.Application.UnitTests.Core.FileManagement.Directories.Queries.GetDirectories; +namespace Lumina.Application.UnitTests.Core.FileSystemManagement.Directories.Queries.GetDirectories; /// /// Contains unit tests for the class. @@ -28,11 +27,9 @@ namespace Lumina.Application.UnitTests.Core.FileManagement.Directories.Queries.G public class GetDirectoriesQueryHandlerTests { private readonly IFixture _fixture; - private readonly IMapper _mockMapper; private readonly IDirectoryService _mockDirectoryService; private readonly GetDirectoriesQueryHandler _sut; private readonly DirectoryFixture _directoryFixture; - private readonly DirectoryResponseFixture _directoryResponseFixture; /// /// Initializes a new instance of the class. @@ -41,10 +38,8 @@ public class GetDirectoriesQueryHandlerTests { _fixture = new Fixture().Customize(new AutoNSubstituteCustomization()); _mockDirectoryService = Substitute.For(); - _mockMapper = Substitute.For(); - _sut = new GetDirectoriesQueryHandler(_mockDirectoryService, _mockMapper); + _sut = new GetDirectoriesQueryHandler(_mockDirectoryService); _directoryFixture = new DirectoryFixture(); - _directoryResponseFixture = new DirectoryResponseFixture(); } [Fact] @@ -54,23 +49,31 @@ public class GetDirectoriesQueryHandlerTests GetDirectoriesQuery getDirectoriesQuery = GetDirectoriesQueryFixture.CreateGetDirectoriesQuery(false); IEnumerable directories = _directoryFixture.CreateMany(); - IEnumerable directoryResponses = _directoryResponseFixture.CreateMany(directories.Count()); - _mockDirectoryService.GetSubdirectories(getDirectoriesQuery.Path, getDirectoriesQuery.IncludeHiddenElements) + _mockDirectoryService.GetSubdirectories(getDirectoriesQuery.Path!, getDirectoriesQuery.IncludeHiddenElements) .Returns(ErrorOrFactory.From(directories)); - _mockMapper.Map>(Arg.Is>(d => d == directories)) - .Returns(directoryResponses); - // Act ErrorOr> result = await _sut.Handle(getDirectoriesQuery, CancellationToken.None); // Assert result.IsError.Should().BeFalse(); result.Value.Should().BeAssignableTo>(); - result.Value.Should().BeEquivalentTo(directoryResponses); - _mockDirectoryService.Received(1).GetSubdirectories(getDirectoriesQuery.Path, getDirectoriesQuery.IncludeHiddenElements); - _mockMapper.Received(1).Map>(Arg.Is>(d => d == directories)); + result.Value.Should().HaveCount(directories.Count()); + + List resultList = result.Value.ToList(); + List directoriesList = directories.ToList(); + + for (int i = 0; i < resultList.Count; i++) + { + resultList[i].Path.Should().Be(directoriesList[i].Id.Path); + resultList[i].Name.Should().Be(directoriesList[i].Name); + resultList[i].DateCreated.Should().Be(directoriesList[i].DateCreated.Value); + resultList[i].DateModified.Should().Be(directoriesList[i].DateModified.Value); + resultList[i].Items.Should().BeEmpty(); // since files are not included + } + + _mockDirectoryService.Received(1).GetSubdirectories(getDirectoriesQuery.Path!, getDirectoriesQuery.IncludeHiddenElements); } [Fact] @@ -80,23 +83,31 @@ public class GetDirectoriesQueryHandlerTests GetDirectoriesQuery getDirectoriesQuery = GetDirectoriesQueryFixture.CreateGetDirectoriesQuery(true); IEnumerable directories = _directoryFixture.CreateMany(); - IEnumerable directoryResponses = _directoryResponseFixture.CreateMany(directories.Count()); - _mockDirectoryService.GetSubdirectories(getDirectoriesQuery.Path, getDirectoriesQuery.IncludeHiddenElements) + _mockDirectoryService.GetSubdirectories(getDirectoriesQuery.Path!, getDirectoriesQuery.IncludeHiddenElements) .Returns(ErrorOrFactory.From(directories)); - _mockMapper.Map>(Arg.Is>(d => d == directories)) - .Returns(directoryResponses); - // Act ErrorOr> result = await _sut.Handle(getDirectoriesQuery, CancellationToken.None); // Assert result.IsError.Should().BeFalse(); result.Value.Should().BeAssignableTo>(); - result.Value.Should().BeEquivalentTo(directoryResponses); - _mockDirectoryService.Received(1).GetSubdirectories(getDirectoriesQuery.Path, getDirectoriesQuery.IncludeHiddenElements); - _mockMapper.Received(1).Map>(Arg.Is>(d => d == directories)); + result.Value.Should().HaveCount(directories.Count()); + + List resultList = result.Value.ToList(); + List directoriesList = directories.ToList(); + + for (int i = 0; i < resultList.Count; i++) + { + resultList[i].Path.Should().Be(directoriesList[i].Id.Path); + resultList[i].Name.Should().Be(directoriesList[i].Name); + resultList[i].DateCreated.Should().Be(directoriesList[i].DateCreated.Value); + resultList[i].DateModified.Should().Be(directoriesList[i].DateModified.Value); + resultList[i].Items.Should().HaveCount(directoriesList[i].Items.Count); + } + + _mockDirectoryService.Received(1).GetSubdirectories(getDirectoriesQuery.Path!, getDirectoriesQuery.IncludeHiddenElements); } [Fact] @@ -105,7 +116,7 @@ public class GetDirectoriesQueryHandlerTests // Arrange GetDirectoriesQuery query = _fixture.Create(); Error error = Error.Failure("DirectoryService.Error", "An error occurred"); - _mockDirectoryService.GetSubdirectories(query.Path, query.IncludeHiddenElements) + _mockDirectoryService.GetSubdirectories(query.Path!, query.IncludeHiddenElements) .Returns(error); // Act @@ -114,7 +125,7 @@ public class GetDirectoriesQueryHandlerTests // Assert result.IsError.Should().BeTrue(); result.FirstError.Should().Be(error); - _mockDirectoryService.Received(1).GetSubdirectories(query.Path, query.IncludeHiddenElements); + _mockDirectoryService.Received(1).GetSubdirectories(query.Path!, query.IncludeHiddenElements); } [Fact] @@ -123,7 +134,7 @@ public class GetDirectoriesQueryHandlerTests // Arrange GetDirectoriesQuery query = _fixture.Create(); ErrorOr> emptyList = ErrorOrFactory.From(Enumerable.Empty()); - _mockDirectoryService.GetSubdirectories(query.Path, query.IncludeHiddenElements) + _mockDirectoryService.GetSubdirectories(query.Path!, query.IncludeHiddenElements) .Returns(emptyList); // Act @@ -132,6 +143,6 @@ public class GetDirectoriesQueryHandlerTests // Assert result.IsError.Should().BeFalse(); result.Value.Should().BeEmpty(); - _mockDirectoryService.Received(1).GetSubdirectories(query.Path, query.IncludeHiddenElements); + _mockDirectoryService.Received(1).GetSubdirectories(query.Path!, query.IncludeHiddenElements); } } diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/FileManagement/Directories/Queries/GetDirectories/GetDirectoriesQueryValidatorTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Directories/Queries/GetDirectories/GetDirectoriesQueryValidatorTests.cs similarity index 86% rename from tests/UnitTests/Lumina.Application.UnitTests/Core/FileManagement/Directories/Queries/GetDirectories/GetDirectoriesQueryValidatorTests.cs rename to tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Directories/Queries/GetDirectories/GetDirectoriesQueryValidatorTests.cs index d08c495f..64ad0dfa 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/FileManagement/Directories/Queries/GetDirectories/GetDirectoriesQueryValidatorTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Directories/Queries/GetDirectories/GetDirectoriesQueryValidatorTests.cs @@ -1,12 +1,12 @@ #region ========================================================================= USING ===================================================================================== using FluentValidation.TestHelper; -using Lumina.Application.Core.FileManagement.Directories.Queries.GetDirectories; -using Lumina.Application.UnitTests.Core.FileManagement.Directories.Queries.GetDirectories.Fixtures; +using Lumina.Application.Core.FileSystemManagement.Directories.Queries.GetDirectories; +using Lumina.Application.UnitTests.Core.FileSystemManagement.Directories.Queries.GetDirectories.Fixtures; using System.Diagnostics.CodeAnalysis; using Lumina.Domain.Common.Errors; #endregion -namespace Lumina.Application.UnitTests.Core.FileManagement.Directories.Queries.GetDirectories; +namespace Lumina.Application.UnitTests.Core.FileSystemManagement.Directories.Queries.GetDirectories; /// /// Contains unit tests for the class. @@ -36,7 +36,7 @@ public class GetDirectoriesQueryValidatorTests // Assert result.ShouldHaveValidationErrorFor(x => x.Path) - .WithErrorMessage(Errors.FileManagement.PathCannotBeEmpty.Code); + .WithErrorMessage(Errors.FileSystemManagement.PathCannotBeEmpty.Description); } [Fact] @@ -51,7 +51,7 @@ public class GetDirectoriesQueryValidatorTests // Assert result.ShouldHaveValidationErrorFor(x => x.Path) - .WithErrorMessage(Errors.FileManagement.PathCannotBeEmpty.Code); + .WithErrorMessage(Errors.FileSystemManagement.PathCannotBeEmpty.Description); } [Fact] @@ -66,7 +66,7 @@ public class GetDirectoriesQueryValidatorTests // Assert result.ShouldHaveValidationErrorFor(x => x.Path) - .WithErrorMessage(Errors.FileManagement.PathCannotBeEmpty.Code); + .WithErrorMessage(Errors.FileSystemManagement.PathCannotBeEmpty.Description); } [Fact] diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/FileManagement/Directories/Queries/GetDirectoryTree/Fixtures/GetDirectoryTreeQueryFixture.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Directories/Queries/GetDirectoryTree/Fixtures/GetDirectoryTreeQueryFixture.cs similarity index 86% rename from tests/UnitTests/Lumina.Application.UnitTests/Core/FileManagement/Directories/Queries/GetDirectoryTree/Fixtures/GetDirectoryTreeQueryFixture.cs rename to tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Directories/Queries/GetDirectoryTree/Fixtures/GetDirectoryTreeQueryFixture.cs index 02e6b1d6..44a8f634 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/FileManagement/Directories/Queries/GetDirectoryTree/Fixtures/GetDirectoryTreeQueryFixture.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Directories/Queries/GetDirectoryTree/Fixtures/GetDirectoryTreeQueryFixture.cs @@ -1,10 +1,10 @@ #region ========================================================================= USING ===================================================================================== using Bogus; -using Lumina.Application.Core.FileManagement.Directories.Queries.GetDirectoryTree; +using Lumina.Application.Core.FileSystemManagement.Directories.Queries.GetDirectoryTree; using System.Diagnostics.CodeAnalysis; #endregion -namespace Lumina.Application.UnitTests.Core.FileManagement.Directories.Queries.GetDirectoryTree.Fixtures; +namespace Lumina.Application.UnitTests.Core.FileSystemManagement.Directories.Queries.GetDirectoryTree.Fixtures; /// /// Fixture class for the class. diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/FileManagement/Directories/Queries/GetDirectoryTree/GetDirectoryTreeQueryHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Directories/Queries/GetDirectoryTree/GetDirectoryTreeQueryHandlerTests.cs similarity index 87% rename from tests/UnitTests/Lumina.Application.UnitTests/Core/FileManagement/Directories/Queries/GetDirectoryTree/GetDirectoryTreeQueryHandlerTests.cs rename to tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Directories/Queries/GetDirectoryTree/GetDirectoryTreeQueryHandlerTests.cs index f320c869..f5af804a 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/FileManagement/Directories/Queries/GetDirectoryTree/GetDirectoryTreeQueryHandlerTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Directories/Queries/GetDirectoryTree/GetDirectoryTreeQueryHandlerTests.cs @@ -1,18 +1,16 @@ #region ========================================================================= USING ===================================================================================== -using AutoFixture; -using AutoFixture.AutoNSubstitute; using ErrorOr; using FluentAssertions; -using Lumina.Application.Core.FileManagement.Directories.Queries.GetDirectoryTree; -using Lumina.Application.UnitTests.Core.FileManagement.Directories.Fixtures; -using Lumina.Application.UnitTests.Core.FileManagement.Directories.Queries.GetDirectoryTree.Fixtures; -using Lumina.Application.UnitTests.Core.FileManagement.Files.Fixtures; -using Lumina.Application.UnitTests.Core.FileManagement.Pahs.Fixtures; -using Lumina.Contracts.Responses.FileManagement; -using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate; -using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.Entities; -using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.Services; -using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.ValueObjects; +using Lumina.Application.Core.FileSystemManagement.Directories.Queries.GetDirectoryTree; +using Lumina.Application.UnitTests.Core.FileSystemManagement.Directories.Fixtures; +using Lumina.Application.UnitTests.Core.FileSystemManagement.Directories.Queries.GetDirectoryTree.Fixtures; +using Lumina.Application.UnitTests.Core.FileSystemManagement.Files.Fixtures; +using Lumina.Application.UnitTests.Core.FileSystemManagement.Pahs.Fixtures; +using Lumina.Contracts.Responses.FileSystemManagement.Common; +using Lumina.Domain.Core.Aggregates.FileSystemManagement.FileSystemManagementAggregate; +using Lumina.Domain.Core.Aggregates.FileSystemManagement.FileSystemManagementAggregate.Entities; +using Lumina.Domain.Core.Aggregates.FileSystemManagement.FileSystemManagementAggregate.Services; +using Lumina.Domain.Core.Aggregates.FileSystemManagement.FileSystemManagementAggregate.ValueObjects; using NSubstitute; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; @@ -21,7 +19,7 @@ using System.Threading; using System.Threading.Tasks; #endregion -namespace Lumina.Application.UnitTests.Core.FileManagement.Directories.Queries.GetDirectoryTree; +namespace Lumina.Application.UnitTests.Core.FileSystemManagement.Directories.Queries.GetDirectoryTree; /// /// Contains unit tests for the class. @@ -29,13 +27,11 @@ namespace Lumina.Application.UnitTests.Core.FileManagement.Directories.Queries.G [ExcludeFromCodeCoverage] public class GetDirectoryTreeQueryHandlerTests { - private readonly IFixture _fixture; private readonly IDriveService _mockDriveService; private readonly IDirectoryService _mockDirectoryService; private readonly IFileService _mockFileService; private readonly IPathService _mockPathService; private readonly GetDirectoryTreeQueryHandler _sut; - private readonly GetDirectoryTreeQueryFixture _getDirectoryTreeQueryFixture; private readonly DirectoryFixture _directoryFixture; private readonly PathSegmentFixture _pathSegmentFixture; private readonly FileFixture _fileFixture; @@ -45,13 +41,11 @@ public class GetDirectoryTreeQueryHandlerTests /// public GetDirectoryTreeQueryHandlerTests() { - _fixture = new Fixture().Customize(new AutoNSubstituteCustomization()); _mockDriveService = Substitute.For(); _mockDirectoryService = Substitute.For(); _mockFileService = Substitute.For(); _mockPathService = Substitute.For(); _sut = new GetDirectoryTreeQueryHandler(_mockDriveService, _mockDirectoryService, _mockFileService, _mockPathService); - _getDirectoryTreeQueryFixture = new GetDirectoryTreeQueryFixture(); _directoryFixture = new DirectoryFixture(); _pathSegmentFixture = new PathSegmentFixture(); _fileFixture = new FileFixture(); @@ -79,7 +73,7 @@ public class GetDirectoryTreeQueryHandlerTests IEnumerable files = _fileFixture.CreateMany(2); _mockDriveService.GetDrives().Returns(ErrorOrFactory.From(drives)); - _mockPathService.ParsePath(query.Path).Returns(ErrorOrFactory.From(pathSegments)); + _mockPathService.ParsePath(query.Path!).Returns(ErrorOrFactory.From(pathSegments)); _mockPathService.CombinePath(Arg.Is(x => true), Arg.Is(y => true)).Returns(callInfo => $"{callInfo.ArgAt(0)}\\{callInfo.ArgAt(1)}"); _mockDirectoryService.GetSubdirectories(Arg.Any(), query.IncludeHiddenElements).Returns(ErrorOrFactory.From(subdirectories)); _mockFileService.GetFiles(Arg.Any(), query.IncludeHiddenElements).Returns(ErrorOrFactory.From(files)); @@ -92,7 +86,7 @@ public class GetDirectoryTreeQueryHandlerTests result.Value.Should().NotBeEmpty(); result.Value.First().Children.Should().NotBeEmpty(); _mockDriveService.Received(1).GetDrives(); - _mockPathService.Received(1).ParsePath(query.Path); + _mockPathService.Received(1).ParsePath(query.Path!); _mockDirectoryService.Received(1).GetSubdirectories(Arg.Any(), query.IncludeHiddenElements); _mockFileService.Received(0).GetFiles(Arg.Any(), query.IncludeHiddenElements); } @@ -119,7 +113,7 @@ public class GetDirectoryTreeQueryHandlerTests IEnumerable files = _fileFixture.CreateMany(2); _mockDriveService.GetDrives().Returns(ErrorOrFactory.From(drives)); - _mockPathService.ParsePath(query.Path).Returns(ErrorOrFactory.From(pathSegments)); + _mockPathService.ParsePath(query.Path!).Returns(ErrorOrFactory.From(pathSegments)); _mockPathService.CombinePath(Arg.Is(x => true), Arg.Is(y => true)).Returns(callInfo => $"{callInfo.ArgAt(0)}\\{callInfo.ArgAt(1)}"); _mockDirectoryService.GetSubdirectories(Arg.Any(), query.IncludeHiddenElements).Returns(ErrorOrFactory.From(subdirectories)); _mockFileService.GetFiles(Arg.Any(), query.IncludeHiddenElements).Returns(ErrorOrFactory.From(files)); @@ -132,7 +126,7 @@ public class GetDirectoryTreeQueryHandlerTests result.Value.Should().NotBeEmpty(); result.Value.First().Children.Should().NotBeEmpty(); _mockDriveService.Received(1).GetDrives(); - _mockPathService.Received(1).ParsePath(query.Path); + _mockPathService.Received(1).ParsePath(query.Path!); _mockDirectoryService.Received(1).GetSubdirectories(Arg.Any(), query.IncludeHiddenElements); _mockFileService.Received(1).GetFiles(Arg.Any(), query.IncludeHiddenElements); } @@ -166,7 +160,7 @@ public class GetDirectoryTreeQueryHandlerTests Error error = Error.Failure("PathService.Error", "An error occurred"); _mockDriveService.GetDrives().Returns(ErrorOrFactory.From(drives)); - _mockPathService.ParsePath(query.Path).Returns(error); + _mockPathService.ParsePath(query.Path!).Returns(error); // Act ErrorOr> result = await _sut.Handle(query, CancellationToken.None); @@ -175,7 +169,7 @@ public class GetDirectoryTreeQueryHandlerTests result.IsError.Should().BeTrue(); result.FirstError.Should().Be(error); _mockDriveService.Received(1).GetDrives(); - _mockPathService.Received(1).ParsePath(query.Path); + _mockPathService.Received(1).ParsePath(query.Path!); } [Fact] @@ -192,7 +186,7 @@ public class GetDirectoryTreeQueryHandlerTests Error error = Error.Failure("PathService.Error", "An error occurred"); _mockDriveService.GetDrives().Returns(ErrorOrFactory.From(drives)); - _mockPathService.ParsePath(query.Path).Returns(ErrorOrFactory.From(pathSegments)); + _mockPathService.ParsePath(query.Path!).Returns(ErrorOrFactory.From(pathSegments)); _mockPathService.CombinePath(Arg.Any(), Arg.Any()).Returns(error); // Act @@ -202,7 +196,7 @@ public class GetDirectoryTreeQueryHandlerTests result.IsError.Should().BeTrue(); result.FirstError.Should().Be(error); _mockDriveService.Received(1).GetDrives(); - _mockPathService.Received(1).ParsePath(query.Path); + _mockPathService.Received(1).ParsePath(query.Path!); _mockPathService.Received(1).CombinePath(Arg.Any(), Arg.Any()); } @@ -220,7 +214,7 @@ public class GetDirectoryTreeQueryHandlerTests Error error = Error.Failure("DirectoryService.Error", "An error occurred"); _mockDriveService.GetDrives().Returns(ErrorOrFactory.From(drives)); - _mockPathService.ParsePath(query.Path).Returns(ErrorOrFactory.From(pathSegments)); + _mockPathService.ParsePath(query.Path!).Returns(ErrorOrFactory.From(pathSegments)); _mockPathService.CombinePath(Arg.Is(x => true), Arg.Is(y => true)).Returns(callInfo => $"{callInfo.ArgAt(0)}\\{callInfo.ArgAt(1)}"); _mockDirectoryService.GetSubdirectories(Arg.Any(), query.IncludeHiddenElements).Returns(error); @@ -231,7 +225,7 @@ public class GetDirectoryTreeQueryHandlerTests result.IsError.Should().BeTrue(); result.FirstError.Should().Be(error); _mockDriveService.Received(1).GetDrives(); - _mockPathService.Received(1).ParsePath(query.Path); + _mockPathService.Received(1).ParsePath(query.Path!); _mockDirectoryService.Received(1).GetSubdirectories(Arg.Any(), query.IncludeHiddenElements); } @@ -250,7 +244,7 @@ public class GetDirectoryTreeQueryHandlerTests Error error = Error.Failure("FileService.Error", "An error occurred"); _mockDriveService.GetDrives().Returns(ErrorOrFactory.From(drives)); - _mockPathService.ParsePath(query.Path).Returns(ErrorOrFactory.From(pathSegments)); + _mockPathService.ParsePath(query.Path!).Returns(ErrorOrFactory.From(pathSegments)); _mockPathService.CombinePath(Arg.Is(x => true), Arg.Is(y => true)).Returns(callInfo => $"{callInfo.ArgAt(0)}\\{callInfo.ArgAt(1)}"); _mockDirectoryService.GetSubdirectories(Arg.Any(), query.IncludeHiddenElements).Returns(ErrorOrFactory.From(subdirectories)); _mockFileService.GetFiles(Arg.Any(), query.IncludeHiddenElements).Returns(error); @@ -262,7 +256,7 @@ public class GetDirectoryTreeQueryHandlerTests result.IsError.Should().BeTrue(); result.FirstError.Should().Be(error); _mockDriveService.Received(1).GetDrives(); - _mockPathService.Received(1).ParsePath(query.Path); + _mockPathService.Received(1).ParsePath(query.Path!); _mockDirectoryService.Received(1).GetSubdirectories(Arg.Any(), query.IncludeHiddenElements); _mockFileService.Received(1).GetFiles(Arg.Any(), query.IncludeHiddenElements); } @@ -307,7 +301,7 @@ public class GetDirectoryTreeQueryHandlerTests ]; _mockDriveService.GetDrives().Returns(ErrorOrFactory.From(drives)); - _mockPathService.ParsePath(query.Path).Returns(ErrorOrFactory.From((IEnumerable)pathSegments)); + _mockPathService.ParsePath(query.Path!).Returns(ErrorOrFactory.From((IEnumerable)pathSegments)); _mockPathService.Exists(Arg.Any(), Arg.Any()).Returns(true); _mockPathService.CombinePath(Arg.Any(), Arg.Any()) .Returns(callInfo => $"{callInfo.ArgAt(0)}\\{callInfo.ArgAt(1)}"); @@ -347,7 +341,7 @@ public class GetDirectoryTreeQueryHandlerTests _mockDriveService.GetDrives().Returns(ErrorOrFactory.From(drives)); _mockPathService.Exists(Arg.Any(), Arg.Any()).Returns(true); - _mockPathService.ParsePath(query.Path).Returns(ErrorOrFactory.From((IEnumerable)pathSegments)); + _mockPathService.ParsePath(query.Path!).Returns(ErrorOrFactory.From((IEnumerable)pathSegments)); _mockPathService.CombinePath(Arg.Any(), Arg.Any()) .Returns(callInfo => $"{callInfo.ArgAt(0)}\\{callInfo.ArgAt(1)}"); _mockDirectoryService.GetSubdirectories(Arg.Any(), Arg.Any()) @@ -373,7 +367,7 @@ public class GetDirectoryTreeQueryHandlerTests PathSegment rootSegment = _pathSegmentFixture.CreatePathSegment(name: "C:", isDrive: true); _mockDriveService.GetDrives().Returns(ErrorOrFactory.From(drives)); - _mockPathService.ParsePath(query.Path).Returns(ErrorOrFactory.From((IEnumerable)[rootSegment])); + _mockPathService.ParsePath(query.Path!).Returns(ErrorOrFactory.From((IEnumerable)[rootSegment])); IEnumerable visibleDirectories = _directoryFixture.CreateMany(2); _mockDirectoryService.GetSubdirectories(Arg.Any(), false).Returns(ErrorOrFactory.From(visibleDirectories)); diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/FileManagement/Directories/Queries/GetDirectoryTree/GetDirectoryTreeQueryValidatorTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Directories/Queries/GetDirectoryTree/GetDirectoryTreeQueryValidatorTests.cs similarity index 88% rename from tests/UnitTests/Lumina.Application.UnitTests/Core/FileManagement/Directories/Queries/GetDirectoryTree/GetDirectoryTreeQueryValidatorTests.cs rename to tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Directories/Queries/GetDirectoryTree/GetDirectoryTreeQueryValidatorTests.cs index 10bc83e1..f5743282 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/FileManagement/Directories/Queries/GetDirectoryTree/GetDirectoryTreeQueryValidatorTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Directories/Queries/GetDirectoryTree/GetDirectoryTreeQueryValidatorTests.cs @@ -1,12 +1,12 @@ #region ========================================================================= USING ===================================================================================== using FluentValidation.TestHelper; -using Lumina.Application.Core.FileManagement.Directories.Queries.GetDirectoryTree; -using Lumina.Application.UnitTests.Core.FileManagement.Directories.Queries.GetDirectoryTree.Fixtures; +using Lumina.Application.Core.FileSystemManagement.Directories.Queries.GetDirectoryTree; +using Lumina.Application.UnitTests.Core.FileSystemManagement.Directories.Queries.GetDirectoryTree.Fixtures; using Lumina.Domain.Common.Errors; using System.Diagnostics.CodeAnalysis; #endregion -namespace Lumina.Application.UnitTests.Core.FileManagement.Directories.Queries.GetDirectoryTree; +namespace Lumina.Application.UnitTests.Core.FileSystemManagement.Directories.Queries.GetDirectoryTree; /// /// Contains unit tests for the class. @@ -36,7 +36,7 @@ public class GetDirectoryTreeQueryValidatorTests // Assert result.ShouldHaveValidationErrorFor(x => x.Path) - .WithErrorMessage(Errors.FileManagement.PathCannotBeEmpty.Code); + .WithErrorMessage(Errors.FileSystemManagement.PathCannotBeEmpty.Description); } [Fact] @@ -51,7 +51,7 @@ public class GetDirectoryTreeQueryValidatorTests // Assert result.ShouldHaveValidationErrorFor(x => x.Path) - .WithErrorMessage(Errors.FileManagement.PathCannotBeEmpty.Code); + .WithErrorMessage(Errors.FileSystemManagement.PathCannotBeEmpty.Description); } [Fact] @@ -66,7 +66,7 @@ public class GetDirectoryTreeQueryValidatorTests // Assert result.ShouldHaveValidationErrorFor(x => x.Path) - .WithErrorMessage(Errors.FileManagement.PathCannotBeEmpty.Code); + .WithErrorMessage(Errors.FileSystemManagement.PathCannotBeEmpty.Description); } [Fact] diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/FileManagement/Directories/Queries/GetTreeDirectories/Fixtures/GetTreeDirectoriesQueryFixture.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Directories/Queries/GetTreeDirectories/Fixtures/GetTreeDirectoriesQueryFixture.cs similarity index 84% rename from tests/UnitTests/Lumina.Application.UnitTests/Core/FileManagement/Directories/Queries/GetTreeDirectories/Fixtures/GetTreeDirectoriesQueryFixture.cs rename to tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Directories/Queries/GetTreeDirectories/Fixtures/GetTreeDirectoriesQueryFixture.cs index dc54622e..d076de03 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/FileManagement/Directories/Queries/GetTreeDirectories/Fixtures/GetTreeDirectoriesQueryFixture.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Directories/Queries/GetTreeDirectories/Fixtures/GetTreeDirectoriesQueryFixture.cs @@ -1,10 +1,10 @@ #region ========================================================================= USING ===================================================================================== using Bogus; -using Lumina.Application.Core.FileManagement.Directories.Queries.GetTreeDirectories; +using Lumina.Application.Core.FileSystemManagement.Directories.Queries.GetTreeDirectories; using System.Diagnostics.CodeAnalysis; #endregion -namespace Lumina.Application.UnitTests.Core.FileManagement.Directories.Queries.GetTreeDirectories.Fixtures; +namespace Lumina.Application.UnitTests.Core.FileSystemManagement.Directories.Queries.GetTreeDirectories.Fixtures; /// /// Fixture class for the class. diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Directories/Queries/GetTreeDirectories/GetTreeDirectoriesQueryHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Directories/Queries/GetTreeDirectories/GetTreeDirectoriesQueryHandlerTests.cs new file mode 100644 index 00000000..be9b61c5 --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Directories/Queries/GetTreeDirectories/GetTreeDirectoriesQueryHandlerTests.cs @@ -0,0 +1,232 @@ +#region ========================================================================= USING ===================================================================================== +using AutoFixture; +using AutoFixture.AutoNSubstitute; +using ErrorOr; +using FluentAssertions; +using Lumina.Application.Core.FileSystemManagement.Directories.Queries.GetTreeDirectories; +using Lumina.Application.UnitTests.Core.FileSystemManagement.Directories.Fixtures; +using Lumina.Application.UnitTests.Core.FileSystemManagement.Directories.Queries.GetTreeDirectories.Fixtures; +using Lumina.Contracts.Enums.FileSystem; +using Lumina.Contracts.Responses.FileSystemManagement.Common; +using Lumina.Domain.Core.Aggregates.FileSystemManagement.FileSystemManagementAggregate; +using Lumina.Domain.Core.Aggregates.FileSystemManagement.FileSystemManagementAggregate.Entities; +using Lumina.Domain.Core.Aggregates.FileSystemManagement.FileSystemManagementAggregate.Services; +using NSubstitute; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Application.UnitTests.Core.FileSystemManagement.Directories.Queries.GetTreeDirectories; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class GetTreeDirectoriesQueryHandlerTests +{ + private readonly IFixture _fixture; + private readonly IDirectoryService _mockDirectoryService; + private readonly GetTreeDirectoriesQueryHandler _sut; + private readonly DirectoryFixture _directoryFixture; + + /// + /// Initializes a new instance of the class. + /// + public GetTreeDirectoriesQueryHandlerTests() + { + _fixture = new Fixture().Customize(new AutoNSubstituteCustomization()); + _mockDirectoryService = Substitute.For(); + _sut = new GetTreeDirectoriesQueryHandler(_mockDirectoryService); + _directoryFixture = new DirectoryFixture(); + } + + [Fact] + public async Task Handle_WhenCalledWithValidQueryWithoutFilesIncluded_ShouldReturnSuccessResult() + { + // Arrange + GetTreeDirectoriesQuery getDirectoriesQuery = GetTreeDirectoriesQueryFixture.CreateGetTreeDirectoryQuery(false); + + IEnumerable directories = _directoryFixture.CreateMany(); + + _mockDirectoryService.GetSubdirectories(getDirectoriesQuery.Path!, getDirectoriesQuery.IncludeHiddenElements) + .Returns(ErrorOrFactory.From(directories)); + + // Act + ErrorOr> result = await _sut.Handle(getDirectoriesQuery, CancellationToken.None); + + // Assert + result.IsError.Should().BeFalse(); + result.Value.Should().BeAssignableTo>(); + result.Value.Should().HaveCount(directories.Count()); + + List resultList = result.Value.ToList(); + List directoriesList = directories.ToList(); + + for (int i = 0; i < resultList.Count; i++) + { + resultList[i].Path.Should().Be(directoriesList[i].Id.Path); + resultList[i].Name.Should().Be(directoriesList[i].Name); + resultList[i].ItemType.Should().Be(FileSystemItemType.Directory); + resultList[i].IsExpanded.Should().BeFalse(); + resultList[i].ChildrenLoaded.Should().BeFalse(); + resultList[i].Children.Should().BeEmpty(); + } + + _mockDirectoryService.Received(1).GetSubdirectories(getDirectoriesQuery.Path!, getDirectoriesQuery.IncludeHiddenElements); + } + + [Fact] + public async Task Handle_WhenCalledWithValidQueryWithFilesIncluded_ShouldReturnSuccessResult() + { + // Arrange + GetTreeDirectoriesQuery getDirectoriesQuery = GetTreeDirectoriesQueryFixture.CreateGetTreeDirectoryQuery(true); + + IEnumerable directories = _directoryFixture.CreateManyNested(); + + _mockDirectoryService.GetSubdirectories(getDirectoriesQuery.Path!, getDirectoriesQuery.IncludeHiddenElements) + .Returns(ErrorOrFactory.From(directories)); + + // Act + ErrorOr> result = await _sut.Handle(getDirectoriesQuery, CancellationToken.None); + + // Assert + result.IsError.Should().BeFalse(); + result.Value.Should().BeAssignableTo>(); + result.Value.Should().HaveCount(directories.Count()); + + List resultList = result.Value.ToList(); + List directoriesList = directories.ToList(); + + for (int i = 0; i < resultList.Count; i++) + { + FileSystemTreeNodeResponse response = resultList[i]; + Directory directory = directoriesList[i]; + + response.Path.Should().Be(directory.Id.Path); + response.Name.Should().Be(directory.Name); + response.ItemType.Should().Be(FileSystemItemType.Directory); + response.IsExpanded.Should().BeFalse(); + response.ChildrenLoaded.Should().BeFalse(); + response.Children.Should().HaveCount(directory.Items.Count); + + List childResponses = [.. response.Children]; + List directoryItems = [.. directory.Items]; + + for (int j = 0; j < childResponses.Count; j++) + { + FileSystemTreeNodeResponse childResponse = childResponses[j]; + FileSystemItem item = directoryItems[j]; + + childResponse.Path.Should().Be(item.Id.Path); + childResponse.Name.Should().Be(item.Name); + childResponse.ItemType.Should().Be(item.Type); + childResponse.IsExpanded.Should().BeFalse(); + childResponse.ChildrenLoaded.Should().BeFalse(); + + if (item is Directory) + childResponse.Children.Should().NotBeNull(); + else + childResponse.Children.Should().BeEmpty(); + } + } + _mockDirectoryService.Received(1).GetSubdirectories(getDirectoriesQuery.Path!, getDirectoriesQuery.IncludeHiddenElements); + } + + [Fact] + public async Task Handle_WhenDirectoryServiceReturnsError_ShouldReturnFailureResult() + { + // Arrange + GetTreeDirectoriesQuery query = GetTreeDirectoriesQueryFixture.CreateGetTreeDirectoryQuery(); + Error error = Error.Failure("DirectoryService.Error", "An error occurred"); + _mockDirectoryService.GetSubdirectories(query.Path!, query.IncludeHiddenElements) + .Returns(error); + + // Act + ErrorOr> result = await _sut.Handle(query, CancellationToken.None); + + // Assert + result.IsError.Should().BeTrue(); + result.FirstError.Should().Be(error); + _mockDirectoryService.Received(1).GetSubdirectories(query.Path!, query.IncludeHiddenElements); + } + + [Fact] + public async Task Handle_WhenDirectoryServiceReturnsEmptyList_ShouldReturnEmptySuccessResult() + { + // Arrange + GetTreeDirectoriesQuery query = _fixture.Create(); + ErrorOr> emptyList = ErrorOrFactory.From(Enumerable.Empty()); + _mockDirectoryService.GetSubdirectories(query.Path!, query.IncludeHiddenElements) + .Returns(emptyList); + + // Act + ErrorOr> result = await _sut.Handle(query, CancellationToken.None); + + // Assert + result.IsError.Should().BeFalse(); + result.Value.Should().BeEmpty(); + _mockDirectoryService.Received(1).GetSubdirectories(query.Path!, query.IncludeHiddenElements); + } + + [Fact] + public async Task Handle_WhenCalledWithNestedDirectories_ShouldReturnCorrectlyNestedResponse() + { + // Arrange + GetTreeDirectoriesQuery query = GetTreeDirectoriesQueryFixture.CreateGetTreeDirectoryQuery(true); + IEnumerable nestedDirectories = _directoryFixture.CreateManyNested(2, 2, 2); + + _mockDirectoryService.GetSubdirectories(query.Path!, query.IncludeHiddenElements) + .Returns(ErrorOrFactory.From(nestedDirectories)); + + // Act + ErrorOr> result = await _sut.Handle(query, CancellationToken.None); + + // Assert + result.IsError.Should().BeFalse(); + result.Value.Should().BeAssignableTo>(); + result.Value.Should().HaveCount(2); // top level directories + + List resultList = result.Value.ToList(); + List directoriesList = nestedDirectories.ToList(); + + for (int i = 0; i < resultList.Count; i++) + { + FileSystemTreeNodeResponse response = resultList[i]; + Directory directory = directoriesList[i]; + + response.Path.Should().Be(directory.Id.Path); + response.Name.Should().Be(directory.Name); + response.ItemType.Should().Be(FileSystemItemType.Directory); + response.IsExpanded.Should().BeFalse(); + response.ChildrenLoaded.Should().BeFalse(); + response.Children.Should().HaveCount(directory.Items.Count); + + // check first level of children + for (int j = 0; j < response.Children.Count; j++) + { + FileSystemTreeNodeResponse childResponse = response.Children[j]; + FileSystemItem childItem = directory.Items.ElementAt(j); + + childResponse.Path.Should().Be(childItem.Id.Path); + childResponse.Name.Should().Be(childItem.Name); + childResponse.ItemType.Should().Be(childItem.Type); + childResponse.IsExpanded.Should().BeFalse(); + childResponse.ChildrenLoaded.Should().BeFalse(); + + if (childItem is Directory dir) + { + childResponse.Children.Should().NotBeNull(); + childResponse.Children.Should().HaveCount(dir.Items.Count); + } + else + childResponse.Children.Should().BeEmpty(); + } + } + + result.Value.Any(r => r.Children.Count != 0).Should().BeTrue(); + _mockDirectoryService.Received(1).GetSubdirectories(query.Path!, query.IncludeHiddenElements); + } +} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/FileManagement/Directories/Queries/GetTreeDirectories/GetTreeDirectoriesQueryValidatorTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Directories/Queries/GetTreeDirectories/GetTreeDirectoriesQueryValidatorTests.cs similarity index 86% rename from tests/UnitTests/Lumina.Application.UnitTests/Core/FileManagement/Directories/Queries/GetTreeDirectories/GetTreeDirectoriesQueryValidatorTests.cs rename to tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Directories/Queries/GetTreeDirectories/GetTreeDirectoriesQueryValidatorTests.cs index 805bc0a7..e421513d 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/FileManagement/Directories/Queries/GetTreeDirectories/GetTreeDirectoriesQueryValidatorTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Directories/Queries/GetTreeDirectories/GetTreeDirectoriesQueryValidatorTests.cs @@ -1,12 +1,12 @@ #region ========================================================================= USING ===================================================================================== using FluentValidation.TestHelper; -using Lumina.Application.Core.FileManagement.Directories.Queries.GetTreeDirectories; -using Lumina.Application.UnitTests.Core.FileManagement.Directories.Queries.GetTreeDirectories.Fixtures; +using Lumina.Application.Core.FileSystemManagement.Directories.Queries.GetTreeDirectories; +using Lumina.Application.UnitTests.Core.FileSystemManagement.Directories.Queries.GetTreeDirectories.Fixtures; using Lumina.Domain.Common.Errors; using System.Diagnostics.CodeAnalysis; #endregion -namespace Lumina.Application.UnitTests.Core.FileManagement.Directories.Queries.GetTreeDirectories; +namespace Lumina.Application.UnitTests.Core.FileSystemManagement.Directories.Queries.GetTreeDirectories; /// /// Contains unit tests for the class. @@ -36,7 +36,7 @@ public class GetTreeDirectoriesQueryValidatorTests // Assert result.ShouldHaveValidationErrorFor(x => x.Path) - .WithErrorMessage(Errors.FileManagement.PathCannotBeEmpty.Code); + .WithErrorMessage(Errors.FileSystemManagement.PathCannotBeEmpty.Description); } [Fact] @@ -51,7 +51,7 @@ public class GetTreeDirectoriesQueryValidatorTests // Assert result.ShouldHaveValidationErrorFor(x => x.Path) - .WithErrorMessage(Errors.FileManagement.PathCannotBeEmpty.Code); + .WithErrorMessage(Errors.FileSystemManagement.PathCannotBeEmpty.Description); } [Fact] @@ -66,7 +66,7 @@ public class GetTreeDirectoriesQueryValidatorTests // Assert result.ShouldHaveValidationErrorFor(x => x.Path) - .WithErrorMessage(Errors.FileManagement.PathCannotBeEmpty.Code); + .WithErrorMessage(Errors.FileSystemManagement.PathCannotBeEmpty.Description); } [Fact] diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/FileManagement/Drives/Queries/GetDrives/Fixtures/GetDrivesQueryFixture.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Drives/Queries/GetDrives/Fixtures/GetDrivesQueryFixture.cs similarity index 94% rename from tests/UnitTests/Lumina.Application.UnitTests/Core/FileManagement/Drives/Queries/GetDrives/Fixtures/GetDrivesQueryFixture.cs rename to tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Drives/Queries/GetDrives/Fixtures/GetDrivesQueryFixture.cs index 321644bf..c5816889 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/FileManagement/Drives/Queries/GetDrives/Fixtures/GetDrivesQueryFixture.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Drives/Queries/GetDrives/Fixtures/GetDrivesQueryFixture.cs @@ -1,13 +1,13 @@ #region ========================================================================= USING ===================================================================================== using Bogus; using Lumina.Contracts.Enums.FileSystem; -using Lumina.Contracts.Responses.FileManagement; +using Lumina.Contracts.Responses.FileSystemManagement.Common; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Linq; #endregion -namespace Lumina.Application.UnitTests.Core.FileManagement.Drives.Queries.GetDrives.Fixtures; +namespace Lumina.Application.UnitTests.Core.FileSystemManagement.Drives.Queries.GetDrives.Fixtures; /// /// Fixture class for the class. diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/FileManagement/Drives/Queries/GetDrives/GetDrivesQueryHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Drives/Queries/GetDrives/GetDrivesQueryHandlerTests.cs similarity index 67% rename from tests/UnitTests/Lumina.Application.UnitTests/Core/FileManagement/Drives/Queries/GetDrives/GetDrivesQueryHandlerTests.cs rename to tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Drives/Queries/GetDrives/GetDrivesQueryHandlerTests.cs index b741946f..bee40c40 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/FileManagement/Drives/Queries/GetDrives/GetDrivesQueryHandlerTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Drives/Queries/GetDrives/GetDrivesQueryHandlerTests.cs @@ -3,13 +3,12 @@ using AutoFixture; using AutoFixture.AutoNSubstitute; using ErrorOr; using FluentAssertions; -using Lumina.Application.Core.FileManagement.Drives.Queries.GetDrives; -using Lumina.Application.UnitTests.Core.FileManagement.Drives.Queries.GetDrives.Fixtures; -using Lumina.Contracts.Responses.FileManagement; -using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate; -using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.Entities; -using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.Services; -using MapsterMapper; +using Lumina.Application.Core.FileSystemManagement.Drives.Queries.GetDrives; +using Lumina.Contracts.Enums.FileSystem; +using Lumina.Contracts.Responses.FileSystemManagement.Common; +using Lumina.Domain.Core.Aggregates.FileSystemManagement.FileSystemManagementAggregate; +using Lumina.Domain.Core.Aggregates.FileSystemManagement.FileSystemManagementAggregate.Entities; +using Lumina.Domain.Core.Aggregates.FileSystemManagement.FileSystemManagementAggregate.Services; using NSubstitute; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; @@ -18,7 +17,7 @@ using System.Threading; using System.Threading.Tasks; #endregion -namespace Lumina.Application.UnitTests.Core.FileManagement.Drives.Queries.GetDrives; +namespace Lumina.Application.UnitTests.Core.FileSystemManagement.Drives.Queries.GetDrives; /// /// Contains unit tests for the class. @@ -27,10 +26,8 @@ namespace Lumina.Application.UnitTests.Core.FileManagement.Drives.Queries.GetDri public class GetDrivesQueryHandlerTests { private readonly IFixture _fixture; - private readonly IMapper _mockMapper; private readonly IDriveService _mockDriveService; private readonly GetDrivesQueryHandler _sut; - private readonly GetDrivesQueryFixture _getDrivesQueryFixture; /// /// Initializes a new instance of the class. @@ -39,9 +36,7 @@ public class GetDrivesQueryHandlerTests { _fixture = new Fixture().Customize(new AutoNSubstituteCustomization()); _mockDriveService = Substitute.For(); - _mockMapper = Substitute.For(); - _sut = new GetDrivesQueryHandler(_mockDriveService, _mockMapper); - _getDrivesQueryFixture = new GetDrivesQueryFixture(); + _sut = new GetDrivesQueryHandler(_mockDriveService); } [Fact] @@ -56,23 +51,34 @@ public class GetDrivesQueryHandlerTests WindowsRootItem.Create("D:\\", "D:").Value ]; - List driveResponses = _getDrivesQueryFixture.CreateMany(); - _mockDriveService.GetDrives() .Returns(ErrorOrFactory.From(drives)); - _mockMapper.Map>(Arg.Is>(d => d == drives)) - .Returns(driveResponses); - // Act ErrorOr> result = await _sut.Handle(getDrivesQuery, CancellationToken.None); // Assert result.IsError.Should().BeFalse(); result.Value.Should().BeAssignableTo>(); - result.Value.Should().BeEquivalentTo(driveResponses); + result.Value.Should().HaveCount(drives.Count()); + + List resultList = result.Value.ToList(); + List drivesList = drives.ToList(); + + for (int i = 0; i < resultList.Count; i++) + { + FileSystemTreeNodeResponse response = resultList[i]; + WindowsRootItem drive = (WindowsRootItem)drivesList[i]; + + response.Path.Should().Be(drive.Id.Path); + response.Name.Should().Be(drive.Name); + response.ItemType.Should().Be(FileSystemItemType.Root); + response.IsExpanded.Should().BeFalse(); + response.ChildrenLoaded.Should().BeFalse(); + response.Children.Should().BeEmpty(); + } + _mockDriveService.Received(1).GetDrives(); - _mockMapper.Received(1).Map>(Arg.Is>(d => d == drives)); } [Fact] @@ -102,9 +108,6 @@ public class GetDrivesQueryHandlerTests _mockDriveService.GetDrives() .Returns(emptyList); - _mockMapper.Map>(Arg.Any>()) - .Returns([]); - // Act ErrorOr> result = await _sut.Handle(query, CancellationToken.None); @@ -112,6 +115,5 @@ public class GetDrivesQueryHandlerTests result.IsError.Should().BeFalse(); result.Value.Should().BeEmpty(); _mockDriveService.Received(1).GetDrives(); - _mockMapper.Received(1).Map>(Arg.Any>()); } } diff --git a/tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/FileManagementAggregate/Entities/Fixtures/UnixRootItemFixture.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/FileSystem/Fixtures/UnixRootItemFixture.cs similarity index 65% rename from tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/FileManagementAggregate/Entities/Fixtures/UnixRootItemFixture.cs rename to tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/FileSystem/Fixtures/UnixRootItemFixture.cs index 02e4e5b1..0e80cca9 100644 --- a/tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/FileManagementAggregate/Entities/Fixtures/UnixRootItemFixture.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/FileSystem/Fixtures/UnixRootItemFixture.cs @@ -2,12 +2,12 @@ using Bogus; using ErrorOr; using Lumina.Contracts.Enums.FileSystem; -using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.Entities; +using Lumina.Domain.Core.Aggregates.FileSystemManagement.FileSystemManagementAggregate.Entities; using System; using System.Diagnostics.CodeAnalysis; #endregion -namespace Lumina.Domain.UnitTests.Core.Aggregates.FileManagementAggregate.Entities.Fixtures; +namespace Lumina.Application.UnitTests.Core.FileSystemManagement.FileSystem.Fixtures; /// /// Fixture class for the class. @@ -15,17 +15,19 @@ namespace Lumina.Domain.UnitTests.Core.Aggregates.FileManagementAggregate.Entiti [ExcludeFromCodeCoverage] public class UnixRootItemFixture { + private readonly Faker _faker = new(); + /// /// Creates a random valid . /// - /// The status of the UNIX root item. /// The created . - public UnixRootItem CreateUnixRootItem(FileSystemItemStatus status = FileSystemItemStatus.Accessible) + public UnixRootItem Create() { - ErrorOr unixRootItemResult = UnixRootItem.Create(status); - + ErrorOr unixRootItemResult = UnixRootItem.Create( + _faker.PickRandom() + ); if (unixRootItemResult.IsError) - throw new InvalidOperationException("Failed to create UnixRootItem: " + string.Join(", ", unixRootItemResult.Errors)); + throw new InvalidOperationException("Failed to create File: " + string.Join(", ", unixRootItemResult.Errors)); return unixRootItemResult.Value; } } diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/FileSystem/Fixtures/WindowsRootItemFixture.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/FileSystem/Fixtures/WindowsRootItemFixture.cs new file mode 100644 index 00000000..d1b4fd30 --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/FileSystem/Fixtures/WindowsRootItemFixture.cs @@ -0,0 +1,35 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using ErrorOr; +using Lumina.Contracts.Enums.FileSystem; +using Lumina.Domain.Core.Aggregates.FileSystemManagement.FileSystemManagementAggregate.Entities; +using System; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Application.UnitTests.Core.FileSystemManagement.FileSystem.Fixtures; + +/// +/// Fixture class for the class. +/// +[ExcludeFromCodeCoverage] +public class WindowsRootItemFixture +{ + private readonly Faker _faker = new(); + + /// + /// Creates a random valid . + /// + /// The created . + public WindowsRootItem Create() + { + ErrorOr windowsRootItemResult = WindowsRootItem.Create( + _faker.System.FilePath(), + _faker.System.FileName(), + _faker.PickRandom() + ); + if (windowsRootItemResult.IsError) + throw new InvalidOperationException("Failed to create File: " + string.Join(", ", windowsRootItemResult.Errors)); + return windowsRootItemResult.Value; + } +} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/FileManagement/FileSystem/Queries/GetFileSystem/GetFileSystemQueryHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/FileSystem/Queries/GetFileSystem/GetFileSystemQueryHandlerTests.cs similarity index 91% rename from tests/UnitTests/Lumina.Application.UnitTests/Core/FileManagement/FileSystem/Queries/GetFileSystem/GetFileSystemQueryHandlerTests.cs rename to tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/FileSystem/Queries/GetFileSystem/GetFileSystemQueryHandlerTests.cs index 40d13ad3..e73ab97b 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/FileManagement/FileSystem/Queries/GetFileSystem/GetFileSystemQueryHandlerTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/FileSystem/Queries/GetFileSystem/GetFileSystemQueryHandlerTests.cs @@ -2,10 +2,10 @@ using AutoFixture; using AutoFixture.AutoNSubstitute; using FluentAssertions; -using Lumina.Application.Core.FileManagement.FileSystem.Queries.GetFileSystem; +using Lumina.Application.Core.FileSystemManagement.FileSystem.Queries.GetFileSystem; using Lumina.Contracts.Enums.FileSystem; -using Lumina.Contracts.Responses.FileManagement; -using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.Strategies.Platform; +using Lumina.Contracts.Responses.FileSystemManagement.FileSystem; +using Lumina.Domain.Core.Aggregates.FileSystemManagement.FileSystemManagementAggregate.Strategies.Platform; using NSubstitute; using System; using System.Diagnostics.CodeAnalysis; @@ -13,7 +13,7 @@ using System.Threading; using System.Threading.Tasks; #endregion -namespace Lumina.Application.UnitTests.Core.FileManagement.FileSystem.Queries.GetFileSystem; +namespace Lumina.Application.UnitTests.Core.FileSystemManagement.FileSystem.Queries.GetFileSystem; /// /// Contains unit tests for the class. diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/FileManagement/Files/Fixtures/FileFixture.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Files/Fixtures/FileFixture.cs similarity index 93% rename from tests/UnitTests/Lumina.Application.UnitTests/Core/FileManagement/Files/Fixtures/FileFixture.cs rename to tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Files/Fixtures/FileFixture.cs index f281f67a..e8a0203c 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/FileManagement/Files/Fixtures/FileFixture.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Files/Fixtures/FileFixture.cs @@ -3,14 +3,14 @@ using Bogus; using ErrorOr; using Lumina.Contracts.Enums.FileSystem; using Lumina.Domain.Common.Primitives; -using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.Entities; +using Lumina.Domain.Core.Aggregates.FileSystemManagement.FileSystemManagementAggregate.Entities; using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Linq; #endregion -namespace Lumina.Application.UnitTests.Core.FileManagement.Files.Fixtures; +namespace Lumina.Application.UnitTests.Core.FileSystemManagement.Files.Fixtures; /// /// Fixture class for the class. diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/FileManagement/Files/Fixtures/FileResponseFixture.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Files/Fixtures/FileResponseFixture.cs similarity index 89% rename from tests/UnitTests/Lumina.Application.UnitTests/Core/FileManagement/Files/Fixtures/FileResponseFixture.cs rename to tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Files/Fixtures/FileResponseFixture.cs index 9743f5f3..beb6f76c 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/FileManagement/Files/Fixtures/FileResponseFixture.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Files/Fixtures/FileResponseFixture.cs @@ -1,12 +1,12 @@ #region ========================================================================= USING ===================================================================================== using Bogus; -using Lumina.Contracts.Responses.FileManagement; +using Lumina.Contracts.Responses.FileSystemManagement.Files; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Linq; #endregion -namespace Lumina.Application.UnitTests.Core.FileManagement.Files.Fixtures; +namespace Lumina.Application.UnitTests.Core.FileSystemManagement.Files.Fixtures; /// /// Fixture class for the class. diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/FileManagement/Files/Queries/GetFiles/Fixtures/GetFilesQueryFixture.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Files/Queries/GetFiles/Fixtures/GetFilesQueryFixture.cs similarity index 85% rename from tests/UnitTests/Lumina.Application.UnitTests/Core/FileManagement/Files/Queries/GetFiles/Fixtures/GetFilesQueryFixture.cs rename to tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Files/Queries/GetFiles/Fixtures/GetFilesQueryFixture.cs index 754f5ca2..9783412f 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/FileManagement/Files/Queries/GetFiles/Fixtures/GetFilesQueryFixture.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Files/Queries/GetFiles/Fixtures/GetFilesQueryFixture.cs @@ -1,10 +1,10 @@ #region ========================================================================= USING ===================================================================================== using Bogus; -using Lumina.Application.Core.FileManagement.Files.Queries.GetFiles; +using Lumina.Application.Core.FileSystemManagement.Files.Queries.GetFiles; using System.Diagnostics.CodeAnalysis; #endregion -namespace Lumina.Application.UnitTests.Core.FileManagement.Files.Queries.GetFiles.Fixtures; +namespace Lumina.Application.UnitTests.Core.FileSystemManagement.Files.Queries.GetFiles.Fixtures; /// /// Fixture class for the class. diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/FileManagement/Files/Queries/GetFiles/GetFilesQueryHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Files/Queries/GetFiles/GetFilesQueryHandlerTests.cs similarity index 58% rename from tests/UnitTests/Lumina.Application.UnitTests/Core/FileManagement/Files/Queries/GetFiles/GetFilesQueryHandlerTests.cs rename to tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Files/Queries/GetFiles/GetFilesQueryHandlerTests.cs index 0f191856..750f0225 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/FileManagement/Files/Queries/GetFiles/GetFilesQueryHandlerTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Files/Queries/GetFiles/GetFilesQueryHandlerTests.cs @@ -3,13 +3,12 @@ using AutoFixture; using AutoFixture.AutoNSubstitute; using ErrorOr; using FluentAssertions; -using Lumina.Application.Core.FileManagement.Files.Queries.GetFiles; -using Lumina.Application.UnitTests.Core.FileManagement.Files.Fixtures; -using Lumina.Application.UnitTests.Core.FileManagement.Files.Queries.GetFiles.Fixtures; -using Lumina.Contracts.Responses.FileManagement; -using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.Entities; -using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.Services; -using MapsterMapper; +using Lumina.Application.Core.FileSystemManagement.Files.Queries.GetFiles; +using Lumina.Application.UnitTests.Core.FileSystemManagement.Files.Fixtures; +using Lumina.Application.UnitTests.Core.FileSystemManagement.Files.Queries.GetFiles.Fixtures; +using Lumina.Contracts.Responses.FileSystemManagement.Files; +using Lumina.Domain.Core.Aggregates.FileSystemManagement.FileSystemManagementAggregate.Entities; +using Lumina.Domain.Core.Aggregates.FileSystemManagement.FileSystemManagementAggregate.Services; using NSubstitute; using System; using System.Collections.Generic; @@ -19,7 +18,7 @@ using System.Threading; using System.Threading.Tasks; #endregion -namespace Lumina.Application.UnitTests.Core.FileManagement.Files.Queries.GetFiles; +namespace Lumina.Application.UnitTests.Core.FileSystemManagement.Files.Queries.GetFiles; /// @@ -29,11 +28,9 @@ namespace Lumina.Application.UnitTests.Core.FileManagement.Files.Queries.GetFile public class GetFilesQueryHandlerTests { private readonly IFixture _fixture; - private readonly IMapper _mockMapper; private readonly IFileService _mockFileService; private readonly GetFilesQueryHandler _sut; private readonly FileFixture _fileFixture; - private readonly FileResponseFixture _fileResponseFixture; /// /// Initializes a new instance of the class. @@ -42,10 +39,8 @@ public class GetFilesQueryHandlerTests { _fixture = new Fixture().Customize(new AutoNSubstituteCustomization()); _mockFileService = Substitute.For(); - _mockMapper = Substitute.For(); - _sut = new GetFilesQueryHandler(_mockFileService, _mockMapper); + _sut = new GetFilesQueryHandler(_mockFileService); _fileFixture = new FileFixture(); - _fileResponseFixture = new FileResponseFixture(); } [Fact] @@ -55,23 +50,31 @@ public class GetFilesQueryHandlerTests GetFilesQuery getFilesQuery = GetFilesQueryFixture.CreateGetFilesQuery(false); IEnumerable files = _fileFixture.CreateMany(); - IEnumerable fileResponses = _fileResponseFixture.CreateMany(files.Count()); - _mockFileService.GetFiles(getFilesQuery.Path, getFilesQuery.IncludeHiddenElements) + _mockFileService.GetFiles(getFilesQuery.Path!, getFilesQuery.IncludeHiddenElements) .Returns(ErrorOrFactory.From(files)); - _mockMapper.Map>(Arg.Is>(f => f == files)) - .Returns(fileResponses); - // Act ErrorOr> result = await _sut.Handle(getFilesQuery, CancellationToken.None); // Assert result.IsError.Should().BeFalse(); result.Value.Should().BeAssignableTo>(); - result.Value.Should().BeEquivalentTo(fileResponses); - _mockFileService.Received(1).GetFiles(getFilesQuery.Path, getFilesQuery.IncludeHiddenElements); - _mockMapper.Received(1).Map>(Arg.Is>(f => f == files)); + result.Value.Should().HaveCount(files.Count()); + + List resultList = result.Value.ToList(); + List filesList = files.ToList(); + + for (int i = 0; i < resultList.Count; i++) + { + resultList[i].Path.Should().Be(filesList[i].Id.Path); + resultList[i].Name.Should().Be(filesList[i].Name); + resultList[i].DateCreated.Should().Be(filesList[i].DateCreated.Value); + resultList[i].DateModified.Should().Be(filesList[i].DateModified.Value); + resultList[i].Size.Should().Be(filesList[i].Size); + } + + _mockFileService.Received(1).GetFiles(getFilesQuery.Path!, getFilesQuery.IncludeHiddenElements); } [Fact] @@ -81,23 +84,31 @@ public class GetFilesQueryHandlerTests GetFilesQuery getFilesQuery = GetFilesQueryFixture.CreateGetFilesQuery(true); IEnumerable files = _fileFixture.CreateMany(); - IEnumerable fileResponses = _fileResponseFixture.CreateMany(files.Count()); - _mockFileService.GetFiles(getFilesQuery.Path, getFilesQuery.IncludeHiddenElements) + _mockFileService.GetFiles(getFilesQuery.Path!, getFilesQuery.IncludeHiddenElements) .Returns(ErrorOrFactory.From(files)); - _mockMapper.Map>(Arg.Is>(f => f == files)) - .Returns(fileResponses); - // Act ErrorOr> result = await _sut.Handle(getFilesQuery, CancellationToken.None); // Assert result.IsError.Should().BeFalse(); result.Value.Should().BeAssignableTo>(); - result.Value.Should().BeEquivalentTo(fileResponses); - _mockFileService.Received(1).GetFiles(getFilesQuery.Path, getFilesQuery.IncludeHiddenElements); - _mockMapper.Received(1).Map>(Arg.Is>(f => f == files)); + result.Value.Should().HaveCount(files.Count()); + + List resultList = result.Value.ToList(); + List filesList = files.ToList(); + + for (int i = 0; i < resultList.Count; i++) + { + resultList[i].Path.Should().Be(filesList[i].Id.Path); + resultList[i].Name.Should().Be(filesList[i].Name); + resultList[i].DateCreated.Should().Be(filesList[i].DateCreated.Value); + resultList[i].DateModified.Should().Be(filesList[i].DateModified.Value); + resultList[i].Size.Should().Be(filesList[i].Size); + } + + _mockFileService.Received(1).GetFiles(getFilesQuery.Path!, getFilesQuery.IncludeHiddenElements); } [Fact] @@ -106,7 +117,7 @@ public class GetFilesQueryHandlerTests // Arrange GetFilesQuery query = _fixture.Create(); Error error = Error.Failure("FileService.Error", "An error occurred"); - _mockFileService.GetFiles(query.Path, query.IncludeHiddenElements) + _mockFileService.GetFiles(query.Path!, query.IncludeHiddenElements) .Returns(error); // Act @@ -115,8 +126,7 @@ public class GetFilesQueryHandlerTests // Assert result.IsError.Should().BeTrue(); result.FirstError.Should().Be(error); - _mockFileService.Received(1).GetFiles(query.Path, query.IncludeHiddenElements); - _mockMapper.DidNotReceive().Map>(Arg.Any>()); + _mockFileService.Received(1).GetFiles(query.Path!, query.IncludeHiddenElements); } [Fact] @@ -125,19 +135,15 @@ public class GetFilesQueryHandlerTests // Arrange GetFilesQuery query = _fixture.Create(); ErrorOr> emptyList = ErrorOrFactory.From(Enumerable.Empty()); - _mockFileService.GetFiles(query.Path, query.IncludeHiddenElements) + _mockFileService.GetFiles(query.Path!, query.IncludeHiddenElements) .Returns(emptyList); - _mockMapper.Map>(Arg.Is>(f => !f.Any())) - .Returns([]); - // Act ErrorOr> result = await _sut.Handle(query, CancellationToken.None); // Assert result.IsError.Should().BeFalse(); result.Value.Should().BeEmpty(); - _mockFileService.Received(1).GetFiles(query.Path, query.IncludeHiddenElements); - _mockMapper.Received(1).Map>(Arg.Is>(f => !f.Any())); + _mockFileService.Received(1).GetFiles(query.Path!, query.IncludeHiddenElements); } } diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/FileManagement/Files/Queries/GetFiles/GetFilesQueryValidatorTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Files/Queries/GetFiles/GetFilesQueryValidatorTests.cs similarity index 86% rename from tests/UnitTests/Lumina.Application.UnitTests/Core/FileManagement/Files/Queries/GetFiles/GetFilesQueryValidatorTests.cs rename to tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Files/Queries/GetFiles/GetFilesQueryValidatorTests.cs index 22e7bebb..3c76e7d1 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/FileManagement/Files/Queries/GetFiles/GetFilesQueryValidatorTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Files/Queries/GetFiles/GetFilesQueryValidatorTests.cs @@ -1,12 +1,12 @@ #region ========================================================================= USING ===================================================================================== using FluentValidation.TestHelper; -using Lumina.Application.Core.FileManagement.Files.Queries.GetFiles; -using Lumina.Application.UnitTests.Core.FileManagement.Files.Queries.GetFiles.Fixtures; +using Lumina.Application.Core.FileSystemManagement.Files.Queries.GetFiles; +using Lumina.Application.UnitTests.Core.FileSystemManagement.Files.Queries.GetFiles.Fixtures; using Lumina.Domain.Common.Errors; using System.Diagnostics.CodeAnalysis; #endregion -namespace Lumina.Application.UnitTests.Core.FileManagement.Files.Queries.GetFiles; +namespace Lumina.Application.UnitTests.Core.FileSystemManagement.Files.Queries.GetFiles; /// /// Contains unit tests for the class. @@ -36,7 +36,7 @@ public class GetFilesQueryValidatorTests // Assert result.ShouldHaveValidationErrorFor(x => x.Path) - .WithErrorMessage(Errors.FileManagement.PathCannotBeEmpty.Code); + .WithErrorMessage(Errors.FileSystemManagement.PathCannotBeEmpty.Description); } [Fact] @@ -51,7 +51,7 @@ public class GetFilesQueryValidatorTests // Assert result.ShouldHaveValidationErrorFor(x => x.Path) - .WithErrorMessage(Errors.FileManagement.PathCannotBeEmpty.Code); + .WithErrorMessage(Errors.FileSystemManagement.PathCannotBeEmpty.Description); } [Fact] @@ -66,7 +66,7 @@ public class GetFilesQueryValidatorTests // Assert result.ShouldHaveValidationErrorFor(x => x.Path) - .WithErrorMessage(Errors.FileManagement.PathCannotBeEmpty.Code); + .WithErrorMessage(Errors.FileSystemManagement.PathCannotBeEmpty.Description); } [Fact] diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/FileManagement/Files/Queries/GetTreeFiles/Fixtures/GetTreeFilesQueryFixture.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Files/Queries/GetTreeFiles/Fixtures/GetTreeFilesQueryFixture.cs similarity index 85% rename from tests/UnitTests/Lumina.Application.UnitTests/Core/FileManagement/Files/Queries/GetTreeFiles/Fixtures/GetTreeFilesQueryFixture.cs rename to tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Files/Queries/GetTreeFiles/Fixtures/GetTreeFilesQueryFixture.cs index f069cc5b..f9765f3d 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/FileManagement/Files/Queries/GetTreeFiles/Fixtures/GetTreeFilesQueryFixture.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Files/Queries/GetTreeFiles/Fixtures/GetTreeFilesQueryFixture.cs @@ -1,10 +1,10 @@ #region ========================================================================= USING ===================================================================================== using Bogus; -using Lumina.Application.Core.FileManagement.Files.Queries.GetTreeFiles; +using Lumina.Application.Core.FileSystemManagement.Files.Queries.GetTreeFiles; using System.Diagnostics.CodeAnalysis; #endregion -namespace Lumina.Application.UnitTests.Core.FileManagement.Files.Queries.GetTreeFiles.Fixtures; +namespace Lumina.Application.UnitTests.Core.FileSystemManagement.Files.Queries.GetTreeFiles.Fixtures; /// /// Fixture class for the class. diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/FileManagement/Files/Queries/GetTreeFiles/GetTreeFilesQueryHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Files/Queries/GetTreeFiles/GetTreeFilesQueryHandlerTests.cs similarity index 59% rename from tests/UnitTests/Lumina.Application.UnitTests/Core/FileManagement/Files/Queries/GetTreeFiles/GetTreeFilesQueryHandlerTests.cs rename to tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Files/Queries/GetTreeFiles/GetTreeFilesQueryHandlerTests.cs index 349c0da8..8c181349 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/FileManagement/Files/Queries/GetTreeFiles/GetTreeFilesQueryHandlerTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Files/Queries/GetTreeFiles/GetTreeFilesQueryHandlerTests.cs @@ -3,14 +3,13 @@ using AutoFixture; using AutoFixture.AutoNSubstitute; using ErrorOr; using FluentAssertions; -using Lumina.Application.Core.FileManagement.Files.Queries.GetTreeFiles; -using Lumina.Application.UnitTests.Core.FileManagement.Directories.Fixtures; -using Lumina.Application.UnitTests.Core.FileManagement.Files.Fixtures; -using Lumina.Application.UnitTests.Core.FileManagement.Files.Queries.GetTreeFiles.Fixtures; -using Lumina.Contracts.Responses.FileManagement; -using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.Entities; -using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.Services; -using MapsterMapper; +using Lumina.Application.Core.FileSystemManagement.Files.Queries.GetTreeFiles; +using Lumina.Application.UnitTests.Core.FileSystemManagement.Files.Fixtures; +using Lumina.Application.UnitTests.Core.FileSystemManagement.Files.Queries.GetTreeFiles.Fixtures; +using Lumina.Contracts.Enums.FileSystem; +using Lumina.Contracts.Responses.FileSystemManagement.Common; +using Lumina.Domain.Core.Aggregates.FileSystemManagement.FileSystemManagementAggregate.Entities; +using Lumina.Domain.Core.Aggregates.FileSystemManagement.FileSystemManagementAggregate.Services; using NSubstitute; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; @@ -19,7 +18,7 @@ using System.Threading; using System.Threading.Tasks; #endregion -namespace Lumina.Application.UnitTests.Core.FileManagement.Files.Queries.GetTreeFiles; +namespace Lumina.Application.UnitTests.Core.FileSystemManagement.Files.Queries.GetTreeFiles; /// /// Contains unit tests for the class. @@ -28,11 +27,9 @@ namespace Lumina.Application.UnitTests.Core.FileManagement.Files.Queries.GetTree public class GetTreeFilesQueryHandlerTests { private readonly IFixture _fixture; - private readonly IMapper _mockMapper; private readonly IFileService _mockFileService; private readonly GetTreeFilesQueryHandler _sut; private readonly FileFixture _fileFixture; - private readonly FileSystemTreeNodeResponseFixture _fileSystemTreeNodeResponseFixture; /// /// Initializes a new instance of the class. @@ -41,10 +38,8 @@ public class GetTreeFilesQueryHandlerTests { _fixture = new Fixture().Customize(new AutoNSubstituteCustomization()); _mockFileService = Substitute.For(); - _mockMapper = Substitute.For(); - _sut = new GetTreeFilesQueryHandler(_mockFileService, _mockMapper); + _sut = new GetTreeFilesQueryHandler(_mockFileService); _fileFixture = new FileFixture(); - _fileSystemTreeNodeResponseFixture = new FileSystemTreeNodeResponseFixture(); } [Fact] @@ -54,23 +49,32 @@ public class GetTreeFilesQueryHandlerTests GetTreeFilesQuery getFilesQuery = GetTreeFilesQueryFixture.CreateGetFilesQuery(false); IEnumerable files = _fileFixture.CreateMany(); - IEnumerable fileResponses = _fileSystemTreeNodeResponseFixture.CreateMany(files.Count()); - _mockFileService.GetFiles(getFilesQuery.Path, getFilesQuery.IncludeHiddenElements) + _mockFileService.GetFiles(getFilesQuery.Path!, getFilesQuery.IncludeHiddenElements) .Returns(ErrorOrFactory.From(files)); - _mockMapper.Map>(Arg.Is>(f => f == files)) - .Returns(fileResponses); - // Act ErrorOr> result = await _sut.Handle(getFilesQuery, CancellationToken.None); // Assert result.IsError.Should().BeFalse(); result.Value.Should().BeAssignableTo>(); - result.Value.Should().BeEquivalentTo(fileResponses); - _mockFileService.Received(1).GetFiles(getFilesQuery.Path, getFilesQuery.IncludeHiddenElements); - _mockMapper.Received(1).Map>(Arg.Is>(f => f == files)); + result.Value.Should().HaveCount(files.Count()); + + List resultList = result.Value.ToList(); + List filesList = files.ToList(); + + for (int i = 0; i < resultList.Count; i++) + { + resultList[i].Path.Should().Be(filesList[i].Id.Path); + resultList[i].Name.Should().Be(filesList[i].Name); + resultList[i].ItemType.Should().Be(FileSystemItemType.File); + resultList[i].IsExpanded.Should().BeFalse(); + resultList[i].ChildrenLoaded.Should().BeFalse(); + resultList[i].Children.Should().BeEmpty(); + } + + _mockFileService.Received(1).GetFiles(getFilesQuery.Path!, getFilesQuery.IncludeHiddenElements); } [Fact] @@ -80,23 +84,32 @@ public class GetTreeFilesQueryHandlerTests GetTreeFilesQuery getFilesQuery = GetTreeFilesQueryFixture.CreateGetFilesQuery(true); IEnumerable files = _fileFixture.CreateMany(); - IEnumerable fileResponses = _fileSystemTreeNodeResponseFixture.CreateMany(files.Count()); - _mockFileService.GetFiles(getFilesQuery.Path, getFilesQuery.IncludeHiddenElements) + _mockFileService.GetFiles(getFilesQuery.Path!, getFilesQuery.IncludeHiddenElements) .Returns(ErrorOrFactory.From(files)); - _mockMapper.Map>(Arg.Is>(f => f == files)) - .Returns(fileResponses); - // Act ErrorOr> result = await _sut.Handle(getFilesQuery, CancellationToken.None); // Assert result.IsError.Should().BeFalse(); result.Value.Should().BeAssignableTo>(); - result.Value.Should().BeEquivalentTo(fileResponses); - _mockFileService.Received(1).GetFiles(getFilesQuery.Path, getFilesQuery.IncludeHiddenElements); - _mockMapper.Received(1).Map>(Arg.Is>(f => f == files)); + result.Value.Should().HaveCount(files.Count()); + + List resultList = result.Value.ToList(); + List filesList = files.ToList(); + + for (int i = 0; i < resultList.Count; i++) + { + resultList[i].Path.Should().Be(filesList[i].Id.Path); + resultList[i].Name.Should().Be(filesList[i].Name); + resultList[i].ItemType.Should().Be(FileSystemItemType.File); + resultList[i].IsExpanded.Should().BeFalse(); + resultList[i].ChildrenLoaded.Should().BeFalse(); + resultList[i].Children.Should().BeEmpty(); + } + + _mockFileService.Received(1).GetFiles(getFilesQuery.Path!, getFilesQuery.IncludeHiddenElements); } [Fact] @@ -105,7 +118,7 @@ public class GetTreeFilesQueryHandlerTests // Arrange GetTreeFilesQuery query = _fixture.Create(); Error error = Error.Failure("FileService.Error", "An error occurred"); - _mockFileService.GetFiles(query.Path, query.IncludeHiddenElements) + _mockFileService.GetFiles(query.Path!, query.IncludeHiddenElements) .Returns(error); // Act @@ -114,7 +127,7 @@ public class GetTreeFilesQueryHandlerTests // Assert result.IsError.Should().BeTrue(); result.FirstError.Should().Be(error); - _mockFileService.Received(1).GetFiles(query.Path, query.IncludeHiddenElements); + _mockFileService.Received(1).GetFiles(query.Path!, query.IncludeHiddenElements); } [Fact] @@ -123,7 +136,7 @@ public class GetTreeFilesQueryHandlerTests // Arrange GetTreeFilesQuery query = _fixture.Create(); ErrorOr> emptyList = ErrorOrFactory.From(Enumerable.Empty()); - _mockFileService.GetFiles(query.Path, query.IncludeHiddenElements) + _mockFileService.GetFiles(query.Path!, query.IncludeHiddenElements) .Returns(emptyList); // Act @@ -132,6 +145,6 @@ public class GetTreeFilesQueryHandlerTests // Assert result.IsError.Should().BeFalse(); result.Value.Should().BeEmpty(); - _mockFileService.Received(1).GetFiles(query.Path, query.IncludeHiddenElements); + _mockFileService.Received(1).GetFiles(query.Path!, query.IncludeHiddenElements); } } diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/FileManagement/Files/Queries/GetTreeFiles/GetTreeFilesQueryValidatorTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Files/Queries/GetTreeFiles/GetTreeFilesQueryValidatorTests.cs similarity index 86% rename from tests/UnitTests/Lumina.Application.UnitTests/Core/FileManagement/Files/Queries/GetTreeFiles/GetTreeFilesQueryValidatorTests.cs rename to tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Files/Queries/GetTreeFiles/GetTreeFilesQueryValidatorTests.cs index af531af1..c56eb675 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/FileManagement/Files/Queries/GetTreeFiles/GetTreeFilesQueryValidatorTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Files/Queries/GetTreeFiles/GetTreeFilesQueryValidatorTests.cs @@ -1,12 +1,12 @@ #region ========================================================================= USING ===================================================================================== using FluentValidation.TestHelper; -using Lumina.Application.Core.FileManagement.Files.Queries.GetTreeFiles; -using Lumina.Application.UnitTests.Core.FileManagement.Files.Queries.GetTreeFiles.Fixtures; +using Lumina.Application.Core.FileSystemManagement.Files.Queries.GetTreeFiles; +using Lumina.Application.UnitTests.Core.FileSystemManagement.Files.Queries.GetTreeFiles.Fixtures; using Lumina.Domain.Common.Errors; using System.Diagnostics.CodeAnalysis; #endregion -namespace Lumina.Application.UnitTests.Core.FileManagement.Files.Queries.GetTreeFiles; +namespace Lumina.Application.UnitTests.Core.FileSystemManagement.Files.Queries.GetTreeFiles; /// /// Contains unit tests for the class. @@ -36,7 +36,7 @@ public class GetTreeFilesQueryValidatorTests // Assert result.ShouldHaveValidationErrorFor(x => x.Path) - .WithErrorMessage(Errors.FileManagement.PathCannotBeEmpty.Code); + .WithErrorMessage(Errors.FileSystemManagement.PathCannotBeEmpty.Description); } [Fact] @@ -51,7 +51,7 @@ public class GetTreeFilesQueryValidatorTests // Assert result.ShouldHaveValidationErrorFor(x => x.Path) - .WithErrorMessage(Errors.FileManagement.PathCannotBeEmpty.Code); + .WithErrorMessage(Errors.FileSystemManagement.PathCannotBeEmpty.Description); } [Fact] @@ -66,7 +66,7 @@ public class GetTreeFilesQueryValidatorTests // Assert result.ShouldHaveValidationErrorFor(x => x.Path) - .WithErrorMessage(Errors.FileManagement.PathCannotBeEmpty.Code); + .WithErrorMessage(Errors.FileSystemManagement.PathCannotBeEmpty.Description); } [Fact] diff --git a/tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/FileManagementAggregate/ValueObjects/Fixtures/FileSystemPathIdFixture.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Fixtures/FileSystemPathIdFixture.cs similarity index 87% rename from tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/FileManagementAggregate/ValueObjects/Fixtures/FileSystemPathIdFixture.cs rename to tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Fixtures/FileSystemPathIdFixture.cs index 06cdabe8..b284378c 100644 --- a/tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/FileManagementAggregate/ValueObjects/Fixtures/FileSystemPathIdFixture.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Fixtures/FileSystemPathIdFixture.cs @@ -1,12 +1,12 @@ #region ========================================================================= USING ===================================================================================== using Bogus; using ErrorOr; -using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.ValueObjects; +using Lumina.Domain.Core.Aggregates.FileSystemManagement.FileSystemManagementAggregate.ValueObjects; using System; using System.Diagnostics.CodeAnalysis; #endregion -namespace Lumina.Domain.UnitTests.Core.Aggregates.FileManagementAggregate.ValueObjects.Fixtures; +namespace Lumina.Application.UnitTests.Core.FileSystemManagement.Fixtures; /// /// Fixture class for the class. diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/FileManagement/Pahs/Commands/CombinePath/CombinePathCommandHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Pahs/Commands/CombinePath/CombinePathCommandHandlerTests.cs similarity index 80% rename from tests/UnitTests/Lumina.Application.UnitTests/Core/FileManagement/Pahs/Commands/CombinePath/CombinePathCommandHandlerTests.cs rename to tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Pahs/Commands/CombinePath/CombinePathCommandHandlerTests.cs index 6ce39db9..f1bc59ad 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/FileManagement/Pahs/Commands/CombinePath/CombinePathCommandHandlerTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Pahs/Commands/CombinePath/CombinePathCommandHandlerTests.cs @@ -3,17 +3,17 @@ using AutoFixture; using AutoFixture.AutoNSubstitute; using ErrorOr; using FluentAssertions; -using Lumina.Application.Core.FileManagement.Paths.Commands.CombinePath; -using Lumina.Application.UnitTests.Core.FileManagement.Pahs.Commands.CombinePath.Fixtures; -using Lumina.Contracts.Responses.FileManagement; -using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.Services; +using Lumina.Application.Core.FileSystemManagement.Paths.Commands.CombinePath; +using Lumina.Application.UnitTests.Core.FileSystemManagement.Pahs.Commands.CombinePath.Fixtures; +using Lumina.Contracts.Responses.FileSystemManagement.Path; +using Lumina.Domain.Core.Aggregates.FileSystemManagement.FileSystemManagementAggregate.Services; using NSubstitute; using System.Diagnostics.CodeAnalysis; using System.Threading; using System.Threading.Tasks; #endregion -namespace Lumina.Application.UnitTests.Core.FileManagement.Pahs.Commands.CombinePath; +namespace Lumina.Application.UnitTests.Core.FileSystemManagement.Pahs.Commands.CombinePath; /// /// Contains unit tests for the class. @@ -40,9 +40,9 @@ public class CombinePathCommandHandlerTests { // Arrange CombinePathCommand combinePathCommand = CombinePathCommandFixture.CreateCombinePathCommand(); - string combinedPath = System.IO.Path.Combine(combinePathCommand.OriginalPath, combinePathCommand.NewPath); + string combinedPath = System.IO.Path.Combine(combinePathCommand.OriginalPath!, combinePathCommand.NewPath!); - _mockPathService.CombinePath(combinePathCommand.OriginalPath, combinePathCommand.NewPath) + _mockPathService.CombinePath(combinePathCommand.OriginalPath!, combinePathCommand.NewPath!) .Returns(ErrorOrFactory.From(combinedPath)); // Act @@ -52,7 +52,7 @@ public class CombinePathCommandHandlerTests result.IsError.Should().BeFalse(); result.Value.Should().BeOfType(); result.Value.Path.Should().Be(combinedPath); - _mockPathService.Received(1).CombinePath(combinePathCommand.OriginalPath, combinePathCommand.NewPath); + _mockPathService.Received(1).CombinePath(combinePathCommand.OriginalPath!, combinePathCommand.NewPath!); } [Fact] @@ -61,7 +61,7 @@ public class CombinePathCommandHandlerTests // Arrange CombinePathCommand command = _fixture.Create(); Error error = Error.Failure("PathService.Error", "An error occurred"); - _mockPathService.CombinePath(command.OriginalPath, command.NewPath) + _mockPathService.CombinePath(command.OriginalPath!, command.NewPath!) .Returns(error); // Act @@ -70,7 +70,7 @@ public class CombinePathCommandHandlerTests // Assert result.IsError.Should().BeTrue(); result.FirstError.Should().Be(error); - _mockPathService.Received(1).CombinePath(command.OriginalPath, command.NewPath); + _mockPathService.Received(1).CombinePath(command.OriginalPath!, command.NewPath!); } [Fact] @@ -78,7 +78,7 @@ public class CombinePathCommandHandlerTests { // Arrange CombinePathCommand command = _fixture.Create(); - _mockPathService.CombinePath(command.OriginalPath, command.NewPath) + _mockPathService.CombinePath(command.OriginalPath!, command.NewPath!) .Returns(ErrorOrFactory.From(string.Empty)); // Act @@ -88,6 +88,6 @@ public class CombinePathCommandHandlerTests result.IsError.Should().BeFalse(); result.Value.Should().BeOfType(); result.Value.Path.Should().BeEmpty(); - _mockPathService.Received(1).CombinePath(command.OriginalPath, command.NewPath); + _mockPathService.Received(1).CombinePath(command.OriginalPath!, command.NewPath!); } } diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/FileManagement/Pahs/Commands/CombinePath/CombinePathCommandValidatorTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Pahs/Commands/CombinePath/CombinePathCommandValidatorTests.cs similarity index 83% rename from tests/UnitTests/Lumina.Application.UnitTests/Core/FileManagement/Pahs/Commands/CombinePath/CombinePathCommandValidatorTests.cs rename to tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Pahs/Commands/CombinePath/CombinePathCommandValidatorTests.cs index 9855fa10..277340d6 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/FileManagement/Pahs/Commands/CombinePath/CombinePathCommandValidatorTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Pahs/Commands/CombinePath/CombinePathCommandValidatorTests.cs @@ -1,12 +1,12 @@ #region ========================================================================= USING ===================================================================================== using FluentValidation.TestHelper; -using Lumina.Application.Core.FileManagement.Paths.Commands.CombinePath; -using Lumina.Application.UnitTests.Core.FileManagement.Pahs.Commands.CombinePath.Fixtures; +using Lumina.Application.Core.FileSystemManagement.Paths.Commands.CombinePath; +using Lumina.Application.UnitTests.Core.FileSystemManagement.Pahs.Commands.CombinePath.Fixtures; using Lumina.Domain.Common.Errors; using System.Diagnostics.CodeAnalysis; #endregion -namespace Lumina.Application.UnitTests.Core.FileManagement.Pahs.Commands.CombinePath; +namespace Lumina.Application.UnitTests.Core.FileSystemManagement.Pahs.Commands.CombinePath; /// /// Contains unit tests for the class. @@ -36,7 +36,7 @@ public class CombinePathCommandValidatorTests // Assert result.ShouldHaveValidationErrorFor(x => x.OriginalPath) - .WithErrorMessage(Errors.FileManagement.PathCannotBeEmpty.Code); + .WithErrorMessage(Errors.FileSystemManagement.PathCannotBeEmpty.Description); } [Fact] @@ -51,7 +51,7 @@ public class CombinePathCommandValidatorTests // Assert result.ShouldHaveValidationErrorFor(x => x.OriginalPath) - .WithErrorMessage(Errors.FileManagement.PathCannotBeEmpty.Code); + .WithErrorMessage(Errors.FileSystemManagement.PathCannotBeEmpty.Description); } [Fact] @@ -66,7 +66,7 @@ public class CombinePathCommandValidatorTests // Assert result.ShouldHaveValidationErrorFor(x => x.OriginalPath) - .WithErrorMessage(Errors.FileManagement.PathCannotBeEmpty.Code); + .WithErrorMessage(Errors.FileSystemManagement.PathCannotBeEmpty.Description); } [Fact] @@ -81,7 +81,7 @@ public class CombinePathCommandValidatorTests // Assert result.ShouldHaveValidationErrorFor(x => x.NewPath) - .WithErrorMessage(Errors.FileManagement.PathCannotBeEmpty.Code); + .WithErrorMessage(Errors.FileSystemManagement.PathCannotBeEmpty.Description); } [Fact] @@ -96,7 +96,7 @@ public class CombinePathCommandValidatorTests // Assert result.ShouldHaveValidationErrorFor(x => x.NewPath) - .WithErrorMessage(Errors.FileManagement.PathCannotBeEmpty.Code); + .WithErrorMessage(Errors.FileSystemManagement.PathCannotBeEmpty.Description); } [Fact] @@ -111,7 +111,7 @@ public class CombinePathCommandValidatorTests // Assert result.ShouldHaveValidationErrorFor(x => x.NewPath) - .WithErrorMessage(Errors.FileManagement.PathCannotBeEmpty.Code); + .WithErrorMessage(Errors.FileSystemManagement.PathCannotBeEmpty.Description); } [Fact] diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/FileManagement/Pahs/Commands/CombinePath/Fixtures/CombinePathCommandFixture.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Pahs/Commands/CombinePath/Fixtures/CombinePathCommandFixture.cs similarity index 83% rename from tests/UnitTests/Lumina.Application.UnitTests/Core/FileManagement/Pahs/Commands/CombinePath/Fixtures/CombinePathCommandFixture.cs rename to tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Pahs/Commands/CombinePath/Fixtures/CombinePathCommandFixture.cs index 3a5bb917..99869197 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/FileManagement/Pahs/Commands/CombinePath/Fixtures/CombinePathCommandFixture.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Pahs/Commands/CombinePath/Fixtures/CombinePathCommandFixture.cs @@ -1,10 +1,10 @@ #region ========================================================================= USING ===================================================================================== using Bogus; -using Lumina.Application.Core.FileManagement.Paths.Commands.CombinePath; +using Lumina.Application.Core.FileSystemManagement.Paths.Commands.CombinePath; using System.Diagnostics.CodeAnalysis; #endregion -namespace Lumina.Application.UnitTests.Core.FileManagement.Pahs.Commands.CombinePath.Fixtures; +namespace Lumina.Application.UnitTests.Core.FileSystemManagement.Pahs.Commands.CombinePath.Fixtures; /// /// Fixture class for the class. diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/FileManagement/Pahs/Commands/SplitPath/Fixtures/SplitPathCommandFixture.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Pahs/Commands/SplitPath/Fixtures/SplitPathCommandFixture.cs similarity index 82% rename from tests/UnitTests/Lumina.Application.UnitTests/Core/FileManagement/Pahs/Commands/SplitPath/Fixtures/SplitPathCommandFixture.cs rename to tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Pahs/Commands/SplitPath/Fixtures/SplitPathCommandFixture.cs index e20d8d26..f502bd49 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/FileManagement/Pahs/Commands/SplitPath/Fixtures/SplitPathCommandFixture.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Pahs/Commands/SplitPath/Fixtures/SplitPathCommandFixture.cs @@ -1,10 +1,10 @@ #region ========================================================================= USING ===================================================================================== using Bogus; -using Lumina.Application.Core.FileManagement.Paths.Commands.SplitPath; +using Lumina.Application.Core.FileSystemManagement.Paths.Commands.SplitPath; using System.Diagnostics.CodeAnalysis; #endregion -namespace Lumina.Application.UnitTests.Core.FileManagement.Pahs.Commands.SplitPath.Fixtures; +namespace Lumina.Application.UnitTests.Core.FileSystemManagement.Pahs.Commands.SplitPath.Fixtures; /// /// Fixture class for the class. diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/FileManagement/Pahs/Commands/SplitPath/SplitPathCommandHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Pahs/Commands/SplitPath/SplitPathCommandHandlerTests.cs similarity index 56% rename from tests/UnitTests/Lumina.Application.UnitTests/Core/FileManagement/Pahs/Commands/SplitPath/SplitPathCommandHandlerTests.cs rename to tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Pahs/Commands/SplitPath/SplitPathCommandHandlerTests.cs index 4b4cc870..9dba7b29 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/FileManagement/Pahs/Commands/SplitPath/SplitPathCommandHandlerTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Pahs/Commands/SplitPath/SplitPathCommandHandlerTests.cs @@ -3,15 +3,12 @@ using AutoFixture; using AutoFixture.AutoNSubstitute; using ErrorOr; using FluentAssertions; -using Lumina.Application.Common.Mapping.FileManagement; -using Lumina.Application.Core.FileManagement.Paths.Commands.SplitPath; -using Lumina.Application.UnitTests.Core.FileManagement.Pahs.Commands.SplitPath.Fixtures; -using Lumina.Application.UnitTests.Core.FileManagement.Pahs.Fixtures; -using Lumina.Contracts.Responses.FileManagement; -using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.Services; -using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.ValueObjects; -using Mapster; -using MapsterMapper; +using Lumina.Application.Core.FileSystemManagement.Paths.Commands.SplitPath; +using Lumina.Application.UnitTests.Core.FileSystemManagement.Pahs.Commands.SplitPath.Fixtures; +using Lumina.Application.UnitTests.Core.FileSystemManagement.Pahs.Fixtures; +using Lumina.Contracts.Responses.FileSystemManagement.Path; +using Lumina.Domain.Core.Aggregates.FileSystemManagement.FileSystemManagementAggregate.Services; +using Lumina.Domain.Core.Aggregates.FileSystemManagement.FileSystemManagementAggregate.ValueObjects; using NSubstitute; using System; using System.Collections.Generic; @@ -21,7 +18,7 @@ using System.Threading; using System.Threading.Tasks; #endregion -namespace Lumina.Application.UnitTests.Core.FileManagement.Pahs.Commands.SplitPath; +namespace Lumina.Application.UnitTests.Core.FileSystemManagement.Pahs.Commands.SplitPath; /// /// Contains unit tests for the class. @@ -30,13 +27,9 @@ namespace Lumina.Application.UnitTests.Core.FileManagement.Pahs.Commands.SplitPa public class SplitPathCommandHandlerTests { private readonly IFixture _fixture; - private readonly IMapper _mockMapper; private readonly IPathService _mockPathService; private readonly SplitPathCommandHandler _sut; private readonly PathSegmentFixture _pathSegmentFixture; - private readonly PathSegmentResponseFixture _pathSegmentResponseFixture; - private readonly PathSegmentMappingConfig _pathSegmentMappingConfig; - private readonly TypeAdapterConfig _config; /// /// Initializes a new instance of the class. @@ -45,14 +38,8 @@ public class SplitPathCommandHandlerTests { _fixture = new Fixture().Customize(new AutoNSubstituteCustomization()); _mockPathService = Substitute.For(); - _mockMapper = Substitute.For(); - _sut = new SplitPathCommandHandler(_mockPathService, _mockMapper); + _sut = new SplitPathCommandHandler(_mockPathService); _pathSegmentFixture = new PathSegmentFixture(); - _pathSegmentResponseFixture = new PathSegmentResponseFixture(); - - _config = new TypeAdapterConfig(); - _pathSegmentMappingConfig = new PathSegmentMappingConfig(); - _pathSegmentMappingConfig.Register(_config); } [Fact] @@ -62,23 +49,24 @@ public class SplitPathCommandHandlerTests SplitPathCommand splitPathCommand = SplitPathCommandFixture.CreateSplitPathCommand(); IEnumerable pathSegments = _pathSegmentFixture.CreateMany(); - IEnumerable pathSegmentResponses = _pathSegmentResponseFixture.CreateMany(pathSegments.Count()); - _mockPathService.ParsePath(splitPathCommand.Path) + _mockPathService.ParsePath(splitPathCommand.Path!) .Returns(ErrorOrFactory.From(pathSegments)); - _mockMapper.Map>(Arg.Any>()) - .Returns(pathSegmentResponses); - // Act ErrorOr> result = await _sut.Handle(splitPathCommand, CancellationToken.None); // Assert result.IsError.Should().BeFalse(); result.Value.Should().BeAssignableTo>(); - result.Value.Should().BeEquivalentTo(pathSegmentResponses); - _mockPathService.Received(1).ParsePath(splitPathCommand.Path); - _mockMapper.Received(1).Map>(Arg.Any>()); + result.Value.Should().HaveCount(pathSegments.Count()); + + List resultList = result.Value.ToList(); + List segmentsList = pathSegments.ToList(); + + for (int i = 0; i < resultList.Count; i++) + resultList[i].Path.Should().Be(segmentsList[i].Name); + _mockPathService.Received(1).ParsePath(splitPathCommand.Path!); } [Fact] @@ -87,7 +75,7 @@ public class SplitPathCommandHandlerTests // Arrange SplitPathCommand command = _fixture.Create(); Error error = Error.Failure("PathService.Error", "An error occurred"); - _mockPathService.ParsePath(command.Path) + _mockPathService.ParsePath(command.Path!) .Returns(error); // Act @@ -96,8 +84,7 @@ public class SplitPathCommandHandlerTests // Assert result.IsError.Should().BeTrue(); result.FirstError.Should().Be(error); - _mockPathService.Received(1).ParsePath(command.Path); - _mockMapper.DidNotReceive().Map>(Arg.Any>>()); + _mockPathService.Received(1).ParsePath(command.Path!); } [Fact] @@ -106,19 +93,15 @@ public class SplitPathCommandHandlerTests // Arrange SplitPathCommand command = _fixture.Create(); ErrorOr> emptyList = ErrorOrFactory.From(Enumerable.Empty()); - _mockPathService.ParsePath(command.Path) + _mockPathService.ParsePath(command.Path!) .Returns(emptyList); - _mockMapper.Map>(Arg.Any>()) - .Returns([]); - // Act ErrorOr> result = await _sut.Handle(command, CancellationToken.None); // Assert result.IsError.Should().BeFalse(); result.Value.Should().BeEmpty(); - _mockPathService.Received(1).ParsePath(command.Path); - _mockMapper.Received(1).Map>(Arg.Any>()); + _mockPathService.Received(1).ParsePath(command.Path!); } } diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/FileManagement/Pahs/Commands/SplitPath/SplitPathCommandValidatorTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Pahs/Commands/SplitPath/SplitPathCommandValidatorTests.cs similarity index 82% rename from tests/UnitTests/Lumina.Application.UnitTests/Core/FileManagement/Pahs/Commands/SplitPath/SplitPathCommandValidatorTests.cs rename to tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Pahs/Commands/SplitPath/SplitPathCommandValidatorTests.cs index 52853e6a..9df7b608 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/FileManagement/Pahs/Commands/SplitPath/SplitPathCommandValidatorTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Pahs/Commands/SplitPath/SplitPathCommandValidatorTests.cs @@ -1,12 +1,12 @@ #region ========================================================================= USING ===================================================================================== using FluentValidation.TestHelper; -using Lumina.Application.Core.FileManagement.Paths.Commands.SplitPath; -using Lumina.Application.UnitTests.Core.FileManagement.Pahs.Commands.SplitPath.Fixtures; +using Lumina.Application.Core.FileSystemManagement.Paths.Commands.SplitPath; +using Lumina.Application.UnitTests.Core.FileSystemManagement.Pahs.Commands.SplitPath.Fixtures; using Lumina.Domain.Common.Errors; using System.Diagnostics.CodeAnalysis; #endregion -namespace Lumina.Application.UnitTests.Core.FileManagement.Pahs.Commands.SplitPath; +namespace Lumina.Application.UnitTests.Core.FileSystemManagement.Pahs.Commands.SplitPath; /// /// Contains unit tests for the class. @@ -36,7 +36,7 @@ public class SplitPathCommandValidatorTests // Assert result.ShouldHaveValidationErrorFor(x => x.Path) - .WithErrorMessage(Errors.FileManagement.PathCannotBeEmpty.Code); + .WithErrorMessage(Errors.FileSystemManagement.PathCannotBeEmpty.Description); } [Fact] @@ -51,7 +51,7 @@ public class SplitPathCommandValidatorTests // Assert result.ShouldHaveValidationErrorFor(x => x.Path) - .WithErrorMessage(Errors.FileManagement.PathCannotBeEmpty.Code); + .WithErrorMessage(Errors.FileSystemManagement.PathCannotBeEmpty.Description); } [Fact] @@ -66,7 +66,7 @@ public class SplitPathCommandValidatorTests // Assert result.ShouldHaveValidationErrorFor(x => x.Path) - .WithErrorMessage(Errors.FileManagement.PathCannotBeEmpty.Code); + .WithErrorMessage(Errors.FileSystemManagement.PathCannotBeEmpty.Description); } [Fact] diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/FileManagement/Pahs/Fixtures/PathSegmentFixture.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Pahs/Fixtures/PathSegmentFixture.cs similarity index 90% rename from tests/UnitTests/Lumina.Application.UnitTests/Core/FileManagement/Pahs/Fixtures/PathSegmentFixture.cs rename to tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Pahs/Fixtures/PathSegmentFixture.cs index 00cb640b..ad424e86 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/FileManagement/Pahs/Fixtures/PathSegmentFixture.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Pahs/Fixtures/PathSegmentFixture.cs @@ -1,14 +1,14 @@ #region ========================================================================= USING ===================================================================================== using Bogus; using ErrorOr; -using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.ValueObjects; +using Lumina.Domain.Core.Aggregates.FileSystemManagement.FileSystemManagementAggregate.ValueObjects; using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Linq; #endregion -namespace Lumina.Application.UnitTests.Core.FileManagement.Pahs.Fixtures; +namespace Lumina.Application.UnitTests.Core.FileSystemManagement.Pahs.Fixtures; /// /// Fixture class for the class. diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/FileManagement/Pahs/Fixtures/PathSegmentResponseFixture.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Pahs/Fixtures/PathSegmentResponseFixture.cs similarity index 89% rename from tests/UnitTests/Lumina.Application.UnitTests/Core/FileManagement/Pahs/Fixtures/PathSegmentResponseFixture.cs rename to tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Pahs/Fixtures/PathSegmentResponseFixture.cs index 76b51de5..cd0904e5 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/FileManagement/Pahs/Fixtures/PathSegmentResponseFixture.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Pahs/Fixtures/PathSegmentResponseFixture.cs @@ -1,12 +1,12 @@ #region ========================================================================= USING ===================================================================================== using Bogus; -using Lumina.Contracts.Responses.FileManagement; +using Lumina.Contracts.Responses.FileSystemManagement.Path; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Linq; #endregion -namespace Lumina.Application.UnitTests.Core.FileManagement.Pahs.Fixtures; +namespace Lumina.Application.UnitTests.Core.FileSystemManagement.Pahs.Fixtures; /// /// Fixture class for the class. diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/FileManagement/Pahs/Fixtures/PathSeparatorResponseFixture.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Pahs/Fixtures/PathSeparatorResponseFixture.cs similarity index 89% rename from tests/UnitTests/Lumina.Application.UnitTests/Core/FileManagement/Pahs/Fixtures/PathSeparatorResponseFixture.cs rename to tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Pahs/Fixtures/PathSeparatorResponseFixture.cs index 806a6237..a23d6c4b 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/FileManagement/Pahs/Fixtures/PathSeparatorResponseFixture.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Pahs/Fixtures/PathSeparatorResponseFixture.cs @@ -1,12 +1,12 @@ #region ========================================================================= USING ===================================================================================== using Bogus; -using Lumina.Contracts.Responses.FileManagement; +using Lumina.Contracts.Responses.FileSystemManagement.Path; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Linq; #endregion -namespace Lumina.Application.UnitTests.Core.FileManagement.Pahs.Fixtures; +namespace Lumina.Application.UnitTests.Core.FileSystemManagement.Pahs.Fixtures; /// /// Fixture class for the class. diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/FileManagement/Pahs/Queries/CheckPathExists/CheckPathExistsQueryHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Pahs/Queries/CheckPathExists/CheckPathExistsQueryHandlerTests.cs similarity index 76% rename from tests/UnitTests/Lumina.Application.UnitTests/Core/FileManagement/Pahs/Queries/CheckPathExists/CheckPathExistsQueryHandlerTests.cs rename to tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Pahs/Queries/CheckPathExists/CheckPathExistsQueryHandlerTests.cs index 79c47409..eda2cd4c 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/FileManagement/Pahs/Queries/CheckPathExists/CheckPathExistsQueryHandlerTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Pahs/Queries/CheckPathExists/CheckPathExistsQueryHandlerTests.cs @@ -1,16 +1,16 @@ #region ========================================================================= USING ===================================================================================== using FluentAssertions; -using Lumina.Application.Core.FileManagement.Paths.Queries.CheckPathExists; -using Lumina.Application.UnitTests.Core.FileManagement.Pahs.Queries.CheckPathExists.Fixtures; -using Lumina.Contracts.Responses.FileManagement; -using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.Services; +using Lumina.Application.Core.FileSystemManagement.Paths.Queries.CheckPathExists; +using Lumina.Application.UnitTests.Core.FileSystemManagement.Pahs.Queries.CheckPathExists.Fixtures; +using Lumina.Contracts.Responses.FileSystemManagement.Path; +using Lumina.Domain.Core.Aggregates.FileSystemManagement.FileSystemManagementAggregate.Services; using NSubstitute; using System.Diagnostics.CodeAnalysis; using System.Threading; using System.Threading.Tasks; #endregion -namespace Lumina.Application.UnitTests.Core.FileManagement.Pahs.Queries.CheckPathExists; +namespace Lumina.Application.UnitTests.Core.FileSystemManagement.Pahs.Queries.CheckPathExists; /// /// Contains unit tests for the class. @@ -35,14 +35,14 @@ public class CheckPathExistsQueryHandlerTests { // Arrange CheckPathExistsQuery query = CheckPathExistsQueryFixture.CreateCheckPathExistsQuery(); - _mockPathService.Exists(query.Path).Returns(true); + _mockPathService.Exists(query.Path!).Returns(true); // Act PathExistsResponse result = await _sut.Handle(query, CancellationToken.None); // Assert result.Exists.Should().BeTrue(); - _mockPathService.Received(1).Exists(query.Path); + _mockPathService.Received(1).Exists(query.Path!); } [Fact] @@ -50,14 +50,14 @@ public class CheckPathExistsQueryHandlerTests { // Arrange CheckPathExistsQuery query = CheckPathExistsQueryFixture.CreateCheckPathExistsQuery(true); - _mockPathService.Exists(query.Path).Returns(true); + _mockPathService.Exists(query.Path!).Returns(true); // Act PathExistsResponse result = await _sut.Handle(query, CancellationToken.None); // Assert result.Exists.Should().BeTrue(); - _mockPathService.Received(1).Exists(query.Path); + _mockPathService.Received(1).Exists(query.Path!); } [Fact] @@ -65,14 +65,14 @@ public class CheckPathExistsQueryHandlerTests { // Arrange CheckPathExistsQuery query = CheckPathExistsQueryFixture.CreateCheckPathExistsQuery(false); - _mockPathService.Exists(query.Path, false).Returns(false); + _mockPathService.Exists(query.Path!, false).Returns(false); // Act PathExistsResponse result = await _sut.Handle(query, CancellationToken.None); // Assert result.Exists.Should().BeFalse(); - _mockPathService.Received(1).Exists(query.Path, false); + _mockPathService.Received(1).Exists(query.Path!, false); } [Fact] @@ -80,14 +80,14 @@ public class CheckPathExistsQueryHandlerTests { // Arrange CheckPathExistsQuery query = CheckPathExistsQueryFixture.CreateCheckPathExistsQuery(); - _mockPathService.Exists(query.Path).Returns(false); + _mockPathService.Exists(query.Path!).Returns(false); // Act PathExistsResponse result = await _sut.Handle(query, CancellationToken.None); // Assert result.Exists.Should().BeFalse(); - _mockPathService.Received(1).Exists(query.Path); + _mockPathService.Received(1).Exists(query.Path!); } [Fact] @@ -110,7 +110,7 @@ public class CheckPathExistsQueryHandlerTests { // Arrange CheckPathExistsQuery query = CheckPathExistsQueryFixture.CreateCheckPathExistsQuery(); - _mockPathService.Exists(query.Path).Returns(true); + _mockPathService.Exists(query.Path!).Returns(true); CancellationToken cancellationToken = new(true); // Act @@ -118,6 +118,6 @@ public class CheckPathExistsQueryHandlerTests // Assert result.Exists.Should().BeTrue(); - _mockPathService.Received(1).Exists(query.Path); + _mockPathService.Received(1).Exists(query.Path!); } } diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/FileManagement/Pahs/Queries/CheckPathExists/CheckPathExistsQueryValidatorTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Pahs/Queries/CheckPathExists/CheckPathExistsQueryValidatorTests.cs similarity index 82% rename from tests/UnitTests/Lumina.Application.UnitTests/Core/FileManagement/Pahs/Queries/CheckPathExists/CheckPathExistsQueryValidatorTests.cs rename to tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Pahs/Queries/CheckPathExists/CheckPathExistsQueryValidatorTests.cs index 9eb7ea10..9a392b43 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/FileManagement/Pahs/Queries/CheckPathExists/CheckPathExistsQueryValidatorTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Pahs/Queries/CheckPathExists/CheckPathExistsQueryValidatorTests.cs @@ -1,12 +1,12 @@ #region ========================================================================= USING ===================================================================================== using FluentValidation.TestHelper; -using Lumina.Application.Core.FileManagement.Paths.Queries.CheckPathExists; -using Lumina.Application.UnitTests.Core.FileManagement.Pahs.Queries.CheckPathExists.Fixtures; +using Lumina.Application.Core.FileSystemManagement.Paths.Queries.CheckPathExists; +using Lumina.Application.UnitTests.Core.FileSystemManagement.Pahs.Queries.CheckPathExists.Fixtures; using Lumina.Domain.Common.Errors; using System.Diagnostics.CodeAnalysis; #endregion -namespace Lumina.Application.UnitTests.Core.FileManagement.Pahs.Queries.CheckPathExists; +namespace Lumina.Application.UnitTests.Core.FileSystemManagement.Pahs.Queries.CheckPathExists; /// /// Contains unit tests for the class. @@ -36,7 +36,7 @@ public class CheckPathExistsQueryValidatorTests // Assert result.ShouldHaveValidationErrorFor(x => x.Path) - .WithErrorMessage(Errors.FileManagement.PathCannotBeEmpty.Code); + .WithErrorMessage(Errors.FileSystemManagement.PathCannotBeEmpty.Description); } [Fact] @@ -51,7 +51,7 @@ public class CheckPathExistsQueryValidatorTests // Assert result.ShouldHaveValidationErrorFor(x => x.Path) - .WithErrorMessage(Errors.FileManagement.PathCannotBeEmpty.Code); + .WithErrorMessage(Errors.FileSystemManagement.PathCannotBeEmpty.Description); } [Fact] @@ -66,7 +66,7 @@ public class CheckPathExistsQueryValidatorTests // Assert result.ShouldHaveValidationErrorFor(x => x.Path) - .WithErrorMessage(Errors.FileManagement.PathCannotBeEmpty.Code); + .WithErrorMessage(Errors.FileSystemManagement.PathCannotBeEmpty.Description); } [Fact] diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/FileManagement/Pahs/Queries/CheckPathExists/Fixtures/CheckPathExistsQueryFixture.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Pahs/Queries/CheckPathExists/Fixtures/CheckPathExistsQueryFixture.cs similarity index 85% rename from tests/UnitTests/Lumina.Application.UnitTests/Core/FileManagement/Pahs/Queries/CheckPathExists/Fixtures/CheckPathExistsQueryFixture.cs rename to tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Pahs/Queries/CheckPathExists/Fixtures/CheckPathExistsQueryFixture.cs index 645b84d3..7fd2a819 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/FileManagement/Pahs/Queries/CheckPathExists/Fixtures/CheckPathExistsQueryFixture.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Pahs/Queries/CheckPathExists/Fixtures/CheckPathExistsQueryFixture.cs @@ -1,10 +1,10 @@ #region ========================================================================= USING ===================================================================================== using Bogus; -using Lumina.Application.Core.FileManagement.Paths.Queries.CheckPathExists; +using Lumina.Application.Core.FileSystemManagement.Paths.Queries.CheckPathExists; using System.Diagnostics.CodeAnalysis; #endregion -namespace Lumina.Application.UnitTests.Core.FileManagement.Pahs.Queries.CheckPathExists.Fixtures; +namespace Lumina.Application.UnitTests.Core.FileSystemManagement.Pahs.Queries.CheckPathExists.Fixtures; /// /// Fixture class for the class. diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/FileManagement/Pahs/Queries/GetPathParent/Fixtures/GetPathParentQueryFixture.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Pahs/Queries/GetPathParent/Fixtures/GetPathParentQueryFixture.cs similarity index 82% rename from tests/UnitTests/Lumina.Application.UnitTests/Core/FileManagement/Pahs/Queries/GetPathParent/Fixtures/GetPathParentQueryFixture.cs rename to tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Pahs/Queries/GetPathParent/Fixtures/GetPathParentQueryFixture.cs index 63ea1131..21529dff 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/FileManagement/Pahs/Queries/GetPathParent/Fixtures/GetPathParentQueryFixture.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Pahs/Queries/GetPathParent/Fixtures/GetPathParentQueryFixture.cs @@ -1,10 +1,10 @@ #region ========================================================================= USING ===================================================================================== using Bogus; -using Lumina.Application.Core.FileManagement.Paths.Queries.GetPathParent; +using Lumina.Application.Core.FileSystemManagement.Paths.Queries.GetPathParent; using System.Diagnostics.CodeAnalysis; #endregion -namespace Lumina.Application.UnitTests.Core.FileManagement.Pahs.Queries.GetPathParent.Fixtures; +namespace Lumina.Application.UnitTests.Core.FileSystemManagement.Pahs.Queries.GetPathParent.Fixtures; /// /// Fixture class for the class. diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/FileManagement/Pahs/Queries/GetPathParent/GetPathParentQueryHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Pahs/Queries/GetPathParent/GetPathParentQueryHandlerTests.cs similarity index 60% rename from tests/UnitTests/Lumina.Application.UnitTests/Core/FileManagement/Pahs/Queries/GetPathParent/GetPathParentQueryHandlerTests.cs rename to tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Pahs/Queries/GetPathParent/GetPathParentQueryHandlerTests.cs index fe5c43bc..04096777 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/FileManagement/Pahs/Queries/GetPathParent/GetPathParentQueryHandlerTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Pahs/Queries/GetPathParent/GetPathParentQueryHandlerTests.cs @@ -3,13 +3,12 @@ using AutoFixture; using AutoFixture.AutoNSubstitute; using ErrorOr; using FluentAssertions; -using Lumina.Application.Core.FileManagement.Paths.Queries.GetPathParent; -using Lumina.Application.UnitTests.Core.FileManagement.Pahs.Fixtures; -using Lumina.Application.UnitTests.Core.FileManagement.Pahs.Queries.GetPathParent.Fixtures; -using Lumina.Contracts.Responses.FileManagement; -using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.Services; -using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.ValueObjects; -using MapsterMapper; +using Lumina.Application.Core.FileSystemManagement.Paths.Queries.GetPathParent; +using Lumina.Application.UnitTests.Core.FileSystemManagement.Pahs.Fixtures; +using Lumina.Application.UnitTests.Core.FileSystemManagement.Pahs.Queries.GetPathParent.Fixtures; +using Lumina.Contracts.Responses.FileSystemManagement.Path; +using Lumina.Domain.Core.Aggregates.FileSystemManagement.FileSystemManagementAggregate.Services; +using Lumina.Domain.Core.Aggregates.FileSystemManagement.FileSystemManagementAggregate.ValueObjects; using NSubstitute; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; @@ -18,7 +17,7 @@ using System.Threading; using System.Threading.Tasks; #endregion -namespace Lumina.Application.UnitTests.Core.FileManagement.Pahs.Queries.GetPathParent; +namespace Lumina.Application.UnitTests.Core.FileSystemManagement.Pahs.Queries.GetPathParent; /// /// Contains unit tests for the class. @@ -27,20 +26,16 @@ namespace Lumina.Application.UnitTests.Core.FileManagement.Pahs.Queries.GetPathP public class GetPathParentQueryHandlerTests { private readonly IFixture _fixture; - private readonly IMapper _mockMapper; private readonly IPathService _mockPathService; private readonly GetPathParentQueryHandler _sut; private readonly PathSegmentFixture _pathSegmentFixture; - private readonly PathSegmentResponseFixture _pathSegmentResponseFixture; public GetPathParentQueryHandlerTests() { _fixture = new Fixture().Customize(new AutoNSubstituteCustomization()); _mockPathService = Substitute.For(); - _mockMapper = Substitute.For(); - _sut = new GetPathParentQueryHandler(_mockPathService, _mockMapper); + _sut = new GetPathParentQueryHandler(_mockPathService); _pathSegmentFixture = new PathSegmentFixture(); - _pathSegmentResponseFixture = new PathSegmentResponseFixture(); } [Fact] @@ -50,14 +45,13 @@ public class GetPathParentQueryHandlerTests GetPathParentQuery query = GetPathParentQueryFixture.CreateGetPathParentQuery(); IEnumerable pathSegments = _pathSegmentFixture.CreateMany(); - IEnumerable pathSegmentResponses = _pathSegmentResponseFixture.CreateMany(pathSegments.Count()); - _mockPathService.GoUpOneLevel(query.Path) + // Create PathSegmentResponses based on the PathSegments + IEnumerable pathSegmentResponses = pathSegments.Select(segment => new PathSegmentResponse(segment.Name)); + + _mockPathService.GoUpOneLevel(query.Path!) .Returns(ErrorOrFactory.From(pathSegments)); - _mockMapper.Map>(Arg.Is>(p => p == pathSegments)) - .Returns(pathSegmentResponses); - // Act ErrorOr> result = await _sut.Handle(query, CancellationToken.None); @@ -65,8 +59,7 @@ public class GetPathParentQueryHandlerTests result.IsError.Should().BeFalse(); result.Value.Should().BeAssignableTo>(); result.Value.Should().BeEquivalentTo(pathSegmentResponses); - _mockPathService.Received(1).GoUpOneLevel(query.Path); - _mockMapper.Received(1).Map>(Arg.Is>(p => p == pathSegments)); + _mockPathService.Received(1).GoUpOneLevel(query.Path!); } [Fact] @@ -75,7 +68,7 @@ public class GetPathParentQueryHandlerTests // Arrange GetPathParentQuery query = _fixture.Create(); Error error = Error.Failure("PathService.Error", "An error occurred"); - _mockPathService.GoUpOneLevel(query.Path) + _mockPathService.GoUpOneLevel(query.Path!) .Returns(error); // Act @@ -84,8 +77,7 @@ public class GetPathParentQueryHandlerTests // Assert result.IsError.Should().BeTrue(); result.FirstError.Should().Be(error); - _mockPathService.Received(1).GoUpOneLevel(query.Path); - _mockMapper.DidNotReceive().Map>(Arg.Any>()); + _mockPathService.Received(1).GoUpOneLevel(query.Path!); } [Fact] @@ -94,19 +86,15 @@ public class GetPathParentQueryHandlerTests // Arrange GetPathParentQuery query = _fixture.Create(); ErrorOr> emptyList = ErrorOrFactory.From(Enumerable.Empty()); - _mockPathService.GoUpOneLevel(query.Path) + _mockPathService.GoUpOneLevel(query.Path!) .Returns(emptyList); - _mockMapper.Map>(Arg.Is>(p => !p.Any())) - .Returns([]); - // Act ErrorOr> result = await _sut.Handle(query, CancellationToken.None); // Assert result.IsError.Should().BeFalse(); result.Value.Should().BeEmpty(); - _mockPathService.Received(1).GoUpOneLevel(query.Path); - _mockMapper.Received(1).Map>(Arg.Is>(p => !p.Any())); + _mockPathService.Received(1).GoUpOneLevel(query.Path!); } } diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/FileManagement/Pahs/Queries/GetPathParent/GetPathParentQueryValidatorTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Pahs/Queries/GetPathParent/GetPathParentQueryValidatorTests.cs similarity index 82% rename from tests/UnitTests/Lumina.Application.UnitTests/Core/FileManagement/Pahs/Queries/GetPathParent/GetPathParentQueryValidatorTests.cs rename to tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Pahs/Queries/GetPathParent/GetPathParentQueryValidatorTests.cs index a65398b2..c8a06aa7 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/FileManagement/Pahs/Queries/GetPathParent/GetPathParentQueryValidatorTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Pahs/Queries/GetPathParent/GetPathParentQueryValidatorTests.cs @@ -1,12 +1,12 @@ #region ========================================================================= USING ===================================================================================== using FluentValidation.TestHelper; -using Lumina.Application.Core.FileManagement.Paths.Queries.GetPathParent; -using Lumina.Application.UnitTests.Core.FileManagement.Pahs.Queries.GetPathParent.Fixtures; +using Lumina.Application.Core.FileSystemManagement.Paths.Queries.GetPathParent; +using Lumina.Application.UnitTests.Core.FileSystemManagement.Pahs.Queries.GetPathParent.Fixtures; using Lumina.Domain.Common.Errors; using System.Diagnostics.CodeAnalysis; #endregion -namespace Lumina.Application.UnitTests.Core.FileManagement.Pahs.Queries.GetPathParent; +namespace Lumina.Application.UnitTests.Core.FileSystemManagement.Pahs.Queries.GetPathParent; /// /// Contains unit tests for the class. @@ -36,7 +36,7 @@ public class GetPathParentQueryValidatorTests // Assert result.ShouldHaveValidationErrorFor(x => x.Path) - .WithErrorMessage(Errors.FileManagement.PathCannotBeEmpty.Code); + .WithErrorMessage(Errors.FileSystemManagement.PathCannotBeEmpty.Description); } [Fact] @@ -51,7 +51,7 @@ public class GetPathParentQueryValidatorTests // Assert result.ShouldHaveValidationErrorFor(x => x.Path) - .WithErrorMessage(Errors.FileManagement.PathCannotBeEmpty.Code); + .WithErrorMessage(Errors.FileSystemManagement.PathCannotBeEmpty.Description); } [Fact] @@ -66,7 +66,7 @@ public class GetPathParentQueryValidatorTests // Assert result.ShouldHaveValidationErrorFor(x => x.Path) - .WithErrorMessage(Errors.FileManagement.PathCannotBeEmpty.Code); + .WithErrorMessage(Errors.FileSystemManagement.PathCannotBeEmpty.Description); } [Fact] diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/FileManagement/Pahs/Queries/GetPathRoot/Fixtures/GetPathRootQueryFixture.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Pahs/Queries/GetPathRoot/Fixtures/GetPathRootQueryFixture.cs similarity index 82% rename from tests/UnitTests/Lumina.Application.UnitTests/Core/FileManagement/Pahs/Queries/GetPathRoot/Fixtures/GetPathRootQueryFixture.cs rename to tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Pahs/Queries/GetPathRoot/Fixtures/GetPathRootQueryFixture.cs index 5aaa6714..6f19dc55 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/FileManagement/Pahs/Queries/GetPathRoot/Fixtures/GetPathRootQueryFixture.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Pahs/Queries/GetPathRoot/Fixtures/GetPathRootQueryFixture.cs @@ -1,10 +1,10 @@ #region ========================================================================= USING ===================================================================================== using Bogus; -using Lumina.Application.Core.FileManagement.Paths.Queries.GetPathRoot; +using Lumina.Application.Core.FileSystemManagement.Paths.Queries.GetPathRoot; using System.Diagnostics.CodeAnalysis; #endregion -namespace Lumina.Application.UnitTests.Core.FileManagement.Pahs.Queries.GetPathRoot.Fixtures; +namespace Lumina.Application.UnitTests.Core.FileSystemManagement.Pahs.Queries.GetPathRoot.Fixtures; /// /// Fixture class for the class. diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/FileManagement/Pahs/Queries/GetPathRoot/GetPathRootQueryHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Pahs/Queries/GetPathRoot/GetPathRootQueryHandlerTests.cs similarity index 54% rename from tests/UnitTests/Lumina.Application.UnitTests/Core/FileManagement/Pahs/Queries/GetPathRoot/GetPathRootQueryHandlerTests.cs rename to tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Pahs/Queries/GetPathRoot/GetPathRootQueryHandlerTests.cs index 17473562..10847ee8 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/FileManagement/Pahs/Queries/GetPathRoot/GetPathRootQueryHandlerTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Pahs/Queries/GetPathRoot/GetPathRootQueryHandlerTests.cs @@ -1,22 +1,19 @@ #region ========================================================================= USING ===================================================================================== -using AutoFixture; -using AutoFixture.AutoNSubstitute; using ErrorOr; using FluentAssertions; -using Lumina.Application.Core.FileManagement.Paths.Queries.GetPathRoot; -using Lumina.Application.UnitTests.Core.FileManagement.Pahs.Fixtures; -using Lumina.Application.UnitTests.Core.FileManagement.Pahs.Queries.GetPathRoot.Fixtures; -using Lumina.Contracts.Responses.FileManagement; -using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.Services; -using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.ValueObjects; -using MapsterMapper; +using Lumina.Application.Core.FileSystemManagement.Paths.Queries.GetPathRoot; +using Lumina.Application.UnitTests.Core.FileSystemManagement.Pahs.Fixtures; +using Lumina.Application.UnitTests.Core.FileSystemManagement.Pahs.Queries.GetPathRoot.Fixtures; +using Lumina.Contracts.Responses.FileSystemManagement.Path; +using Lumina.Domain.Core.Aggregates.FileSystemManagement.FileSystemManagementAggregate.Services; +using Lumina.Domain.Core.Aggregates.FileSystemManagement.FileSystemManagementAggregate.ValueObjects; using NSubstitute; using System.Diagnostics.CodeAnalysis; using System.Threading; using System.Threading.Tasks; #endregion -namespace Lumina.Application.UnitTests.Core.FileManagement.Pahs.Queries.GetPathRoot; +namespace Lumina.Application.UnitTests.Core.FileSystemManagement.Pahs.Queries.GetPathRoot; /// /// Contains unit tests for the class. @@ -24,24 +21,18 @@ namespace Lumina.Application.UnitTests.Core.FileManagement.Pahs.Queries.GetPathR [ExcludeFromCodeCoverage] public class GetPathRootQueryHandlerTests { - private readonly IFixture _fixture; - private readonly IMapper _mockMapper; private readonly IPathService _mockPathService; private readonly GetPathRootQueryHandler _sut; private readonly PathSegmentFixture _pathSegmentFixture; - private readonly PathSegmentResponseFixture _pathSegmentResponseFixture; /// /// Initializes a new instance of the class. /// public GetPathRootQueryHandlerTests() { - _fixture = new Fixture().Customize(new AutoNSubstituteCustomization()); _mockPathService = Substitute.For(); - _mockMapper = Substitute.For(); - _sut = new GetPathRootQueryHandler(_mockPathService, _mockMapper); + _sut = new GetPathRootQueryHandler(_mockPathService); _pathSegmentFixture = new PathSegmentFixture(); - _pathSegmentResponseFixture = new PathSegmentResponseFixture(); } [Fact] @@ -50,22 +41,18 @@ public class GetPathRootQueryHandlerTests // Arrange GetPathRootQuery query = GetPathRootQueryFixture.CreateGetPathRootQuery(); PathSegment pathSegment = _pathSegmentFixture.CreatePathSegment(isDrive: true); - PathSegmentResponse pathSegmentResponse = _pathSegmentResponseFixture.Create(); - _mockPathService.GetPathRoot(query.Path) + _mockPathService.GetPathRoot(query.Path!) .Returns(ErrorOrFactory.From(pathSegment)); - _mockMapper.Map(Arg.Is(p => p == pathSegment)) - .Returns(pathSegmentResponse); - // Act ErrorOr result = await _sut.Handle(query, CancellationToken.None); // Assert result.IsError.Should().BeFalse(); - result.Value.Should().BeEquivalentTo(pathSegmentResponse); - _mockPathService.Received(1).GetPathRoot(query.Path); - _mockMapper.Received(1).Map(Arg.Is(p => p == pathSegment)); + result.Value.Should().NotBeNull(); + result.Value.Path.Should().Be(pathSegment.Name); + _mockPathService.Received(1).GetPathRoot(query.Path!); } [Fact] @@ -74,7 +61,7 @@ public class GetPathRootQueryHandlerTests // Arrange GetPathRootQuery query = GetPathRootQueryFixture.CreateGetPathRootQuery(); Error error = Error.Failure("PathService.Error", "An error occurred"); - _mockPathService.GetPathRoot(query.Path) + _mockPathService.GetPathRoot(query.Path!) .Returns(error); // Act @@ -83,8 +70,7 @@ public class GetPathRootQueryHandlerTests // Assert result.IsError.Should().BeTrue(); result.FirstError.Should().Be(error); - _mockPathService.Received(1).GetPathRoot(query.Path); - _mockMapper.DidNotReceive().Map(Arg.Any()); + _mockPathService.Received(1).GetPathRoot(query.Path!); } [Fact] @@ -93,21 +79,17 @@ public class GetPathRootQueryHandlerTests // Arrange GetPathRootQuery query = GetPathRootQueryFixture.CreateGetPathRootQuery(); PathSegment rootPathSegment = _pathSegmentFixture.CreatePathSegment(name: "/", isDirectory: true, isDrive: true); - PathSegmentResponse rootResponse = _pathSegmentResponseFixture.Create(); - _mockPathService.GetPathRoot(query.Path) + _mockPathService.GetPathRoot(query.Path!) .Returns(ErrorOrFactory.From(rootPathSegment)); - _mockMapper.Map(Arg.Is(p => p == rootPathSegment)) - .Returns(rootResponse); - // Act ErrorOr result = await _sut.Handle(query, CancellationToken.None); // Assert result.IsError.Should().BeFalse(); - result.Value.Should().BeEquivalentTo(rootResponse); - _mockPathService.Received(1).GetPathRoot(query.Path); - _mockMapper.Received(1).Map(Arg.Is(p => p == rootPathSegment)); + result.Value.Should().NotBeNull(); + result.Value.Path.Should().Be("/"); + _mockPathService.Received(1).GetPathRoot(query.Path!); } } diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/FileManagement/Pahs/Queries/GetPathRoot/GetPathRootQueryValidatorTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Pahs/Queries/GetPathRoot/GetPathRootQueryValidatorTests.cs similarity index 82% rename from tests/UnitTests/Lumina.Application.UnitTests/Core/FileManagement/Pahs/Queries/GetPathRoot/GetPathRootQueryValidatorTests.cs rename to tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Pahs/Queries/GetPathRoot/GetPathRootQueryValidatorTests.cs index 1ceea673..0b4726bf 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/FileManagement/Pahs/Queries/GetPathRoot/GetPathRootQueryValidatorTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Pahs/Queries/GetPathRoot/GetPathRootQueryValidatorTests.cs @@ -1,12 +1,12 @@ #region ========================================================================= USING ===================================================================================== using FluentValidation.TestHelper; -using Lumina.Application.Core.FileManagement.Paths.Queries.GetPathRoot; -using Lumina.Application.UnitTests.Core.FileManagement.Pahs.Queries.GetPathRoot.Fixtures; +using Lumina.Application.Core.FileSystemManagement.Paths.Queries.GetPathRoot; +using Lumina.Application.UnitTests.Core.FileSystemManagement.Pahs.Queries.GetPathRoot.Fixtures; using Lumina.Domain.Common.Errors; using System.Diagnostics.CodeAnalysis; #endregion -namespace Lumina.Application.UnitTests.Core.FileManagement.Pahs.Queries.GetPathRoot; +namespace Lumina.Application.UnitTests.Core.FileSystemManagement.Pahs.Queries.GetPathRoot; /// /// Contains unit tests for the class. @@ -36,7 +36,7 @@ public class GetPathRootQueryValidatorTests // Assert result.ShouldHaveValidationErrorFor(x => x.Path) - .WithErrorMessage(Errors.FileManagement.PathCannotBeEmpty.Code); + .WithErrorMessage(Errors.FileSystemManagement.PathCannotBeEmpty.Description); } [Fact] @@ -51,7 +51,7 @@ public class GetPathRootQueryValidatorTests // Assert result.ShouldHaveValidationErrorFor(x => x.Path) - .WithErrorMessage(Errors.FileManagement.PathCannotBeEmpty.Code); + .WithErrorMessage(Errors.FileSystemManagement.PathCannotBeEmpty.Description); } [Fact] @@ -66,7 +66,7 @@ public class GetPathRootQueryValidatorTests // Assert result.ShouldHaveValidationErrorFor(x => x.Path) - .WithErrorMessage(Errors.FileManagement.PathCannotBeEmpty.Code); + .WithErrorMessage(Errors.FileSystemManagement.PathCannotBeEmpty.Description); } [Fact] diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/FileManagement/Pahs/Queries/GetPathSeparator/GetPathSeparatorQueryHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Pahs/Queries/GetPathSeparator/GetPathSeparatorQueryHandlerTests.cs similarity index 90% rename from tests/UnitTests/Lumina.Application.UnitTests/Core/FileManagement/Pahs/Queries/GetPathSeparator/GetPathSeparatorQueryHandlerTests.cs rename to tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Pahs/Queries/GetPathSeparator/GetPathSeparatorQueryHandlerTests.cs index 34e86458..d8b783f0 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/FileManagement/Pahs/Queries/GetPathSeparator/GetPathSeparatorQueryHandlerTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Pahs/Queries/GetPathSeparator/GetPathSeparatorQueryHandlerTests.cs @@ -1,8 +1,8 @@ #region ========================================================================= USING ===================================================================================== using FluentAssertions; -using Lumina.Application.Core.FileManagement.Paths.Queries.GetPathSeparator; -using Lumina.Contracts.Responses.FileManagement; -using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.Services; +using Lumina.Application.Core.FileSystemManagement.Paths.Queries.GetPathSeparator; +using Lumina.Contracts.Responses.FileSystemManagement.Path; +using Lumina.Domain.Core.Aggregates.FileSystemManagement.FileSystemManagementAggregate.Services; using NSubstitute; using System; using System.Diagnostics.CodeAnalysis; @@ -10,7 +10,7 @@ using System.Threading; using System.Threading.Tasks; #endregion -namespace Lumina.Application.UnitTests.Core.FileManagement.Pahs.Queries.GetPathSeparator; +namespace Lumina.Application.UnitTests.Core.FileSystemManagement.Pahs.Queries.GetPathSeparator; /// /// Contains unit tests for the class. diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/FileManagement/Pahs/Queries/ValidatePath/Fixtures/ValidatePathQueryFixure.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Pahs/Queries/ValidatePath/Fixtures/ValidatePathQueryFixure.cs similarity index 82% rename from tests/UnitTests/Lumina.Application.UnitTests/Core/FileManagement/Pahs/Queries/ValidatePath/Fixtures/ValidatePathQueryFixure.cs rename to tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Pahs/Queries/ValidatePath/Fixtures/ValidatePathQueryFixure.cs index e7ecd5f3..82667104 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/FileManagement/Pahs/Queries/ValidatePath/Fixtures/ValidatePathQueryFixure.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Pahs/Queries/ValidatePath/Fixtures/ValidatePathQueryFixure.cs @@ -1,10 +1,10 @@ #region ========================================================================= USING ===================================================================================== using Bogus; -using Lumina.Application.Core.FileManagement.Paths.Queries.ValidatePath; +using Lumina.Application.Core.FileSystemManagement.Paths.Queries.ValidatePath; using System.Diagnostics.CodeAnalysis; #endregion -namespace Lumina.Application.UnitTests.Core.FileManagement.Pahs.Queries.ValidatePath.Fixtures; +namespace Lumina.Application.UnitTests.Core.FileSystemManagement.Pahs.Queries.ValidatePath.Fixtures; /// /// Fixture class for the class. diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/FileManagement/Pahs/Queries/ValidatePath/ValidatePathQueryHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Pahs/Queries/ValidatePath/ValidatePathQueryHandlerTests.cs similarity index 79% rename from tests/UnitTests/Lumina.Application.UnitTests/Core/FileManagement/Pahs/Queries/ValidatePath/ValidatePathQueryHandlerTests.cs rename to tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Pahs/Queries/ValidatePath/ValidatePathQueryHandlerTests.cs index f43c085a..9d08c561 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/FileManagement/Pahs/Queries/ValidatePath/ValidatePathQueryHandlerTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Pahs/Queries/ValidatePath/ValidatePathQueryHandlerTests.cs @@ -1,16 +1,16 @@ #region ========================================================================= USING ===================================================================================== using FluentAssertions; -using Lumina.Application.Core.FileManagement.Paths.Queries.ValidatePath; -using Lumina.Application.UnitTests.Core.FileManagement.Pahs.Queries.ValidatePath.Fixtures; -using Lumina.Contracts.Responses.FileManagement; -using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.Services; +using Lumina.Application.Core.FileSystemManagement.Paths.Queries.ValidatePath; +using Lumina.Application.UnitTests.Core.FileSystemManagement.Pahs.Queries.ValidatePath.Fixtures; +using Lumina.Contracts.Responses.FileSystemManagement.Path; +using Lumina.Domain.Core.Aggregates.FileSystemManagement.FileSystemManagementAggregate.Services; using NSubstitute; using System.Diagnostics.CodeAnalysis; using System.Threading; using System.Threading.Tasks; #endregion -namespace Lumina.Application.UnitTests.Core.FileManagement.Pahs.Queries.ValidatePath; +namespace Lumina.Application.UnitTests.Core.FileSystemManagement.Pahs.Queries.ValidatePath; /// /// Contains unit tests for the class. @@ -35,14 +35,14 @@ public class ValidatePathQueryHandlerTests { // Arrange ValidatePathQuery query = ValidatePathQueryFixure.CreateValidatePathQuery(); - _mockPathService.IsValidPath(query.Path).Returns(true); + _mockPathService.IsValidPath(query.Path!).Returns(true); // Act PathValidResponse result = await _sut.Handle(query, CancellationToken.None); // Assert result.IsValid.Should().BeTrue(); - _mockPathService.Received(1).IsValidPath(query.Path); + _mockPathService.Received(1).IsValidPath(query.Path!); } [Fact] @@ -50,14 +50,14 @@ public class ValidatePathQueryHandlerTests { // Arrange ValidatePathQuery query = ValidatePathQueryFixure.CreateValidatePathQuery(); - _mockPathService.IsValidPath(query.Path).Returns(false); + _mockPathService.IsValidPath(query.Path!).Returns(false); // Act PathValidResponse result = await _sut.Handle(query, CancellationToken.None); // Assert result.IsValid.Should().BeFalse(); - _mockPathService.Received(1).IsValidPath(query.Path); + _mockPathService.Received(1).IsValidPath(query.Path!); } [Fact] diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/FileManagement/Pahs/Queries/ValidatePath/ValidatePathQueryValidatorTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Pahs/Queries/ValidatePath/ValidatePathQueryValidatorTests.cs similarity index 82% rename from tests/UnitTests/Lumina.Application.UnitTests/Core/FileManagement/Pahs/Queries/ValidatePath/ValidatePathQueryValidatorTests.cs rename to tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Pahs/Queries/ValidatePath/ValidatePathQueryValidatorTests.cs index 710b061b..6d4369c2 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/FileManagement/Pahs/Queries/ValidatePath/ValidatePathQueryValidatorTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Pahs/Queries/ValidatePath/ValidatePathQueryValidatorTests.cs @@ -1,12 +1,12 @@ #region ========================================================================= USING ===================================================================================== using FluentValidation.TestHelper; -using Lumina.Application.Core.FileManagement.Paths.Queries.ValidatePath; -using Lumina.Application.UnitTests.Core.FileManagement.Pahs.Queries.ValidatePath.Fixtures; +using Lumina.Application.Core.FileSystemManagement.Paths.Queries.ValidatePath; +using Lumina.Application.UnitTests.Core.FileSystemManagement.Pahs.Queries.ValidatePath.Fixtures; using Lumina.Domain.Common.Errors; using System.Diagnostics.CodeAnalysis; #endregion -namespace Lumina.Application.UnitTests.Core.FileManagement.Pahs.Queries.ValidatePath; +namespace Lumina.Application.UnitTests.Core.FileSystemManagement.Pahs.Queries.ValidatePath; /// /// Contains unit tests for the class. @@ -36,7 +36,7 @@ public class ValidatePathQueryValidatorTests // Assert result.ShouldHaveValidationErrorFor(x => x.Path) - .WithErrorMessage(Errors.FileManagement.PathCannotBeEmpty.Code); + .WithErrorMessage(Errors.FileSystemManagement.PathCannotBeEmpty.Description); } [Fact] @@ -51,7 +51,7 @@ public class ValidatePathQueryValidatorTests // Assert result.ShouldHaveValidationErrorFor(x => x.Path) - .WithErrorMessage(Errors.FileManagement.PathCannotBeEmpty.Code); + .WithErrorMessage(Errors.FileSystemManagement.PathCannotBeEmpty.Description); } [Fact] @@ -66,7 +66,7 @@ public class ValidatePathQueryValidatorTests // Assert result.ShouldHaveValidationErrorFor(x => x.Path) - .WithErrorMessage(Errors.FileManagement.PathCannotBeEmpty.Code); + .WithErrorMessage(Errors.FileSystemManagement.PathCannotBeEmpty.Description); } [Fact] diff --git a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Controllers/FileManagement/Fixtures/ThumbnailResponseFixture.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Thumbnails/Fixtures/ThumbnailResponseFixture.cs similarity index 86% rename from tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Controllers/FileManagement/Fixtures/ThumbnailResponseFixture.cs rename to tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Thumbnails/Fixtures/ThumbnailResponseFixture.cs index 0e27a212..455af320 100644 --- a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Controllers/FileManagement/Fixtures/ThumbnailResponseFixture.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Thumbnails/Fixtures/ThumbnailResponseFixture.cs @@ -1,11 +1,11 @@ #region ========================================================================= USING ===================================================================================== using Bogus; using Lumina.Contracts.Enums.PhotoLibrary; -using Lumina.Contracts.Responses.FileManagement; +using Lumina.Contracts.Responses.FileSystemManagement.Thumbnails; using System.Diagnostics.CodeAnalysis; #endregion -namespace Lumina.Presentation.Api.UnitTests.Core.Controllers.FileManagement.Fixtures; +namespace Lumina.Application.UnitTests.Core.FileSystemManagement.Thumbnails.Fixtures; /// /// Fixture class for the class. diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/FileManagement/Thumbnails/Queries/GetThumbnail/Fixtures/GetThumbnailQueryFixture.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Thumbnails/Queries/GetThumbnail/Fixtures/GetThumbnailQueryFixture.cs similarity index 82% rename from tests/UnitTests/Lumina.Application.UnitTests/Core/FileManagement/Thumbnails/Queries/GetThumbnail/Fixtures/GetThumbnailQueryFixture.cs rename to tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Thumbnails/Queries/GetThumbnail/Fixtures/GetThumbnailQueryFixture.cs index eb25fd9a..3481ddcb 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/FileManagement/Thumbnails/Queries/GetThumbnail/Fixtures/GetThumbnailQueryFixture.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Thumbnails/Queries/GetThumbnail/Fixtures/GetThumbnailQueryFixture.cs @@ -1,10 +1,10 @@ #region ========================================================================= USING ===================================================================================== using Bogus; -using Lumina.Application.Core.FileManagement.Thumbnails.Queries.GetThumbnail; +using Lumina.Application.Core.FileSystemManagement.Thumbnails.Queries.GetThumbnail; using System.Diagnostics.CodeAnalysis; #endregion -namespace Lumina.Application.UnitTests.Core.FileManagement.Thumbnails.Queries.GetThumbnail.Fixtures; +namespace Lumina.Application.UnitTests.Core.FileSystemManagement.Thumbnails.Queries.GetThumbnail.Fixtures; /// /// Fixture class for the class. diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/FileManagement/Thumbnails/Queries/GetThumbnail/GetThumbnailQueryHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Thumbnails/Queries/GetThumbnail/GetThumbnailQueryHandlerTests.cs similarity index 62% rename from tests/UnitTests/Lumina.Application.UnitTests/Core/FileManagement/Thumbnails/Queries/GetThumbnail/GetThumbnailQueryHandlerTests.cs rename to tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Thumbnails/Queries/GetThumbnail/GetThumbnailQueryHandlerTests.cs index 4e9a1637..01a03462 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/FileManagement/Thumbnails/Queries/GetThumbnail/GetThumbnailQueryHandlerTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Thumbnails/Queries/GetThumbnail/GetThumbnailQueryHandlerTests.cs @@ -3,19 +3,18 @@ using AutoFixture; using AutoFixture.AutoNSubstitute; using ErrorOr; using FluentAssertions; -using Lumina.Application.Core.FileManagement.Thumbnails.Queries.GetThumbnail; -using Lumina.Application.UnitTests.Core.FileManagement.Thumbnails.Fixtures; -using Lumina.Contracts.Responses.FileManagement; -using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.Services; -using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.ValueObjects; -using MapsterMapper; +using Lumina.Application.Core.FileSystemManagement.Thumbnails.Queries.GetThumbnail; +using Lumina.Application.UnitTests.Core.FileSystemManagement.Thumbnails.Fixtures; +using Lumina.Contracts.Responses.FileSystemManagement.Thumbnails; +using Lumina.Domain.Core.Aggregates.FileSystemManagement.FileSystemManagementAggregate.Services; +using Lumina.Domain.Core.Aggregates.FileSystemManagement.FileSystemManagementAggregate.ValueObjects; using NSubstitute; using System.Diagnostics.CodeAnalysis; using System.Threading; using System.Threading.Tasks; #endregion -namespace Lumina.Application.UnitTests.Core.FileManagement.Thumbnails.Queries.GetThumbnail; +namespace Lumina.Application.UnitTests.Core.FileSystemManagement.Thumbnails.Queries.GetThumbnail; /// /// Contains unit tests for the class. @@ -25,15 +24,13 @@ public class GetThumbnailQueryHandlerTests { private readonly IFixture _fixture; private readonly IThumbnailService _mockThumbnailService; - private readonly IMapper _mockMapper; private readonly GetThumbnailQueryHandler _sut; public GetThumbnailQueryHandlerTests() { _fixture = new Fixture().Customize(new AutoNSubstituteCustomization()); _mockThumbnailService = Substitute.For(); - _mockMapper = Substitute.For(); - _sut = new GetThumbnailQueryHandler(_mockThumbnailService, _mockMapper); + _sut = new GetThumbnailQueryHandler(_mockThumbnailService); } [Fact] @@ -42,22 +39,19 @@ public class GetThumbnailQueryHandlerTests // Arrange GetThumbnailQuery query = _fixture.Create(); Thumbnail thumbnail = _fixture.Create(); - ThumbnailResponse thumbnailResponse = ThumbnailResponseFixture.CreateThumbnailResponse(); - _mockThumbnailService.GetThumbnailAsync(query.Path, query.Quality, Arg.Any()) + _mockThumbnailService.GetThumbnailAsync(query.Path!, query.Quality, Arg.Any()) .Returns(ErrorOrFactory.From(thumbnail)); - _mockMapper.Map(Arg.Is(t => t == thumbnail)) - .Returns(thumbnailResponse); - // Act ErrorOr result = await _sut.Handle(query, CancellationToken.None); // Assert result.IsError.Should().BeFalse(); - result.Value.Should().BeEquivalentTo(thumbnailResponse); - await _mockThumbnailService.Received(1).GetThumbnailAsync(query.Path, query.Quality, Arg.Any()); - _mockMapper.Received(1).Map(Arg.Is(t => t == thumbnail)); + result.Value.Should().NotBeNull(); + result.Value.Type.Should().Be(thumbnail.Type); + result.Value.Bytes.Should().BeEquivalentTo(thumbnail.Bytes); + await _mockThumbnailService.Received(1).GetThumbnailAsync(query.Path!, query.Quality, Arg.Any()); } [Fact] @@ -66,7 +60,7 @@ public class GetThumbnailQueryHandlerTests // Arrange GetThumbnailQuery query = _fixture.Create(); Error error = Error.Failure("ThumbnailService.Error", "An error occurred"); - _mockThumbnailService.GetThumbnailAsync(query.Path, query.Quality, Arg.Any()) + _mockThumbnailService.GetThumbnailAsync(query.Path!, query.Quality, Arg.Any()) .Returns(error); // Act @@ -75,8 +69,7 @@ public class GetThumbnailQueryHandlerTests // Assert result.IsError.Should().BeTrue(); result.FirstError.Should().Be(error); - await _mockThumbnailService.Received(1).GetThumbnailAsync(query.Path, query.Quality, Arg.Any()); - _mockMapper.DidNotReceive().Map(Arg.Any()); + await _mockThumbnailService.Received(1).GetThumbnailAsync(query.Path!, query.Quality, Arg.Any()); } [Fact] @@ -87,12 +80,11 @@ public class GetThumbnailQueryHandlerTests CancellationTokenSource cts = new(); cts.Cancel(); - _mockThumbnailService.GetThumbnailAsync(query.Path, query.Quality, cts.Token) + _mockThumbnailService.GetThumbnailAsync(query.Path!, query.Quality, cts.Token) .Returns(Task.FromCanceled>(cts.Token)); // Act & Assert await Assert.ThrowsAsync(() => _sut.Handle(query, cts.Token).AsTask()); - await _mockThumbnailService.Received(1).GetThumbnailAsync(query.Path, query.Quality, cts.Token); - _mockMapper.DidNotReceive().Map(Arg.Any()); + await _mockThumbnailService.Received(1).GetThumbnailAsync(query.Path!, query.Quality, cts.Token); } } diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/FileManagement/Thumbnails/Queries/GetThumbnail/GetThumbnailQueryValidatorTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Thumbnails/Queries/GetThumbnail/GetThumbnailQueryValidatorTests.cs similarity index 89% rename from tests/UnitTests/Lumina.Application.UnitTests/Core/FileManagement/Thumbnails/Queries/GetThumbnail/GetThumbnailQueryValidatorTests.cs rename to tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Thumbnails/Queries/GetThumbnail/GetThumbnailQueryValidatorTests.cs index 9c3c0780..afe45770 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/FileManagement/Thumbnails/Queries/GetThumbnail/GetThumbnailQueryValidatorTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Thumbnails/Queries/GetThumbnail/GetThumbnailQueryValidatorTests.cs @@ -1,11 +1,11 @@ #region ========================================================================= USING ===================================================================================== using FluentValidation.TestHelper; -using Lumina.Application.Core.FileManagement.Thumbnails.Queries.GetThumbnail; +using Lumina.Application.Core.FileSystemManagement.Thumbnails.Queries.GetThumbnail; using Lumina.Domain.Common.Errors; using System.Diagnostics.CodeAnalysis; #endregion -namespace Lumina.Application.UnitTests.Core.FileManagement.Thumbnails.Queries.GetThumbnail; +namespace Lumina.Application.UnitTests.Core.FileSystemManagement.Thumbnails.Queries.GetThumbnail; /// /// Contains unit tests for the class. @@ -33,7 +33,7 @@ public class GetThumbnailQueryValidatorTests TestValidationResult result = _validator.TestValidate(query); // Assert - result.ShouldHaveValidationErrorFor(x => x.Path).WithErrorMessage(Errors.FileManagement.PathCannotBeEmpty.Code); + result.ShouldHaveValidationErrorFor(x => x.Path).WithErrorMessage(Errors.FileSystemManagement.PathCannotBeEmpty.Description); } [Fact] @@ -46,7 +46,7 @@ public class GetThumbnailQueryValidatorTests TestValidationResult result = _validator.TestValidate(query); // Assert - result.ShouldHaveValidationErrorFor(x => x.Path).WithErrorMessage(Errors.FileManagement.PathCannotBeEmpty.Code); + result.ShouldHaveValidationErrorFor(x => x.Path).WithErrorMessage(Errors.FileSystemManagement.PathCannotBeEmpty.Description); } [Fact] @@ -72,7 +72,7 @@ public class GetThumbnailQueryValidatorTests TestValidationResult result = _validator.TestValidate(query); // Assert - result.ShouldHaveValidationErrorFor(x => x.Quality).WithErrorMessage(Errors.Thumbnails.ImageQaulityMustBeBetweenZeroAndOneHundred.Code); + result.ShouldHaveValidationErrorFor(x => x.Quality).WithErrorMessage(Errors.Thumbnails.ImageQaulityMustBeBetweenZeroAndOneHundred.Description); } [Fact] @@ -85,7 +85,7 @@ public class GetThumbnailQueryValidatorTests TestValidationResult result = _validator.TestValidate(query); // Assert - result.ShouldHaveValidationErrorFor(x => x.Quality).WithErrorMessage(Errors.Thumbnails.ImageQaulityMustBeBetweenZeroAndOneHundred.Code); + result.ShouldHaveValidationErrorFor(x => x.Quality).WithErrorMessage(Errors.Thumbnails.ImageQaulityMustBeBetweenZeroAndOneHundred.Description); } [Fact] diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/WrittenContentLibrary/BooksLibrary/Books/Commands/AddBook/AddBookCommandHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/WrittenContentLibrary/BooksLibrary/Books/Commands/AddBook/AddBookCommandHandlerTests.cs index 1b31b0e5..46845488 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/WrittenContentLibrary/BooksLibrary/Books/Commands/AddBook/AddBookCommandHandlerTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/WrittenContentLibrary/BooksLibrary/Books/Commands/AddBook/AddBookCommandHandlerTests.cs @@ -1,4 +1,4 @@ -#region ========================================================================= USING ===================================================================================== +#region ========================================================================= USING ===================================================================================== using AutoFixture; using AutoFixture.AutoNSubstitute; using ErrorOr; @@ -8,12 +8,11 @@ using Lumina.Application.Common.DataAccess.UoW; using Lumina.Application.Core.WrittenContentLibrary.BooksLibrary.Books.Commands.AddBook; using Lumina.Application.UnitTests.Common.Setup; using Lumina.Application.UnitTests.Core.WrittenContentLibrary.BooksLibrary.Books.Commands.AddBook.Fixtures; +using Lumina.Contracts.Entities.Common; +using Lumina.Contracts.Entities.WrittenContentLibrary.BookLibrary; using Lumina.Contracts.Enums.BookLibrary; -using Lumina.Contracts.Models.Common; -using Lumina.Contracts.Models.WrittenContentLibrary.BookLibrary; +using Lumina.Contracts.Responses.WrittenContentLibrary.BookLibrary.Books; using Lumina.Domain.Common.Errors; -using Lumina.Domain.Core.Aggregates.WrittenContentLibrary.BookLibraryAggregate; -using MapsterMapper; using NSubstitute; using System; using System.Diagnostics.CodeAnalysis; @@ -31,7 +30,6 @@ public class AddBookCommandHandlerTests { private readonly IFixture _fixture; private readonly IUnitOfWork _mockUnitOfWork; - private readonly IMapper _mockMapper; private readonly IBookRepository _mockBookRepository; private readonly AddBookCommandHandler _sut; private readonly AddBookCommandFixture _commandBookFixture; @@ -46,12 +44,11 @@ public class AddBookCommandHandlerTests _fixture.Customizations.Add(new NullableDateOnlySpecimenBuilder()); _mockUnitOfWork = Substitute.For(); - _mockMapper = Substitute.For(); _mockBookRepository = Substitute.For(); _mockUnitOfWork.GetRepository().Returns(_mockBookRepository); - _sut = new AddBookCommandHandler(_mockUnitOfWork, _mockMapper); + _sut = new AddBookCommandHandler(_mockUnitOfWork); _commandBookFixture = new AddBookCommandFixture(); } @@ -60,19 +57,17 @@ public class AddBookCommandHandlerTests { // Arrange AddBookCommand bookCommand = _commandBookFixture.CreateCommandBook(); - BookModel bookModel = _fixture.Create(); - _mockMapper.Map(Arg.Any()).Returns(bookModel); - _mockBookRepository.InsertAsync(Arg.Any(), Arg.Any()) + _mockBookRepository.InsertAsync(Arg.Any(), Arg.Any()) .Returns(Result.Created); // Act - ErrorOr result = await _sut.Handle(bookCommand, CancellationToken.None); + ErrorOr result = await _sut.Handle(bookCommand, CancellationToken.None); // Assert result.IsError.Should().BeFalse(); - result.Value.Should().BeOfType(); - await _mockBookRepository.Received(1).InsertAsync(Arg.Any(), Arg.Any()); + result.Value.Should().BeOfType(); + await _mockBookRepository.Received(1).InsertAsync(Arg.Any(), Arg.Any()); await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any()); } @@ -81,15 +76,15 @@ public class AddBookCommandHandlerTests { // Arrange AddBookCommand bookCommand = _commandBookFixture.CreateCommandBook(); - bookCommand = bookCommand with { Metadata = bookCommand.Metadata with { Title = null } }; + bookCommand = bookCommand with { Metadata = bookCommand.Metadata! with { Title = null } }; // Act - ErrorOr result = await _sut.Handle(bookCommand, CancellationToken.None); + ErrorOr result = await _sut.Handle(bookCommand, CancellationToken.None); // Assert result.IsError.Should().BeTrue(); - result.Errors.Should().Contain(e => e.Code == Errors.Metadata.TitleCannotBeEmpty.Code); - await _mockBookRepository.DidNotReceive().InsertAsync(Arg.Any(), Arg.Any()); + result.Errors.Should().Contain(e => e.Description == Errors.Metadata.TitleCannotBeEmpty.Description); + await _mockBookRepository.DidNotReceive().InsertAsync(Arg.Any(), Arg.Any()); await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); } @@ -98,19 +93,17 @@ public class AddBookCommandHandlerTests { // Arrange AddBookCommand bookCommand = _commandBookFixture.CreateCommandBook(); - BookModel bookModel = _fixture.Create(); - _mockMapper.Map(Arg.Any()).Returns(bookModel); - _mockBookRepository.InsertAsync(Arg.Any(), Arg.Any()) + _mockBookRepository.InsertAsync(Arg.Any(), Arg.Any()) .Returns(Errors.WrittenContent.BookAlreadyExists); // Act - ErrorOr result = await _sut.Handle(bookCommand, CancellationToken.None); + ErrorOr result = await _sut.Handle(bookCommand, CancellationToken.None); // Assert result.IsError.Should().BeTrue(); result.Errors.Should().Contain(Errors.WrittenContent.BookAlreadyExists); - await _mockBookRepository.Received(1).InsertAsync(Arg.Any(), Arg.Any()); + await _mockBookRepository.Received(1).InsertAsync(Arg.Any(), Arg.Any()); await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); } @@ -119,15 +112,15 @@ public class AddBookCommandHandlerTests { // Arrange AddBookCommand bookCommand = _commandBookFixture.CreateCommandBook(); - bookCommand = bookCommand with { ISBNs = [new IsbnModel("invalid", IsbnFormat.Isbn13)] }; + bookCommand = bookCommand with { ISBNs = [new IsbnEntity("invalid", IsbnFormat.Isbn13)] }; // Act - ErrorOr result = await _sut.Handle(bookCommand, CancellationToken.None); + ErrorOr result = await _sut.Handle(bookCommand, CancellationToken.None); // Assert result.IsError.Should().BeTrue(); - result.Errors.Should().Contain(e => e.Code == Errors.WrittenContent.InvalidIsbn13Format.Code); - await _mockBookRepository.DidNotReceive().InsertAsync(Arg.Any(), Arg.Any()); + result.Errors.Should().Contain(e => e.Description == Errors.WrittenContent.InvalidIsbn13Format.Description); + await _mockBookRepository.DidNotReceive().InsertAsync(Arg.Any(), Arg.Any()); await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); } @@ -136,15 +129,15 @@ public class AddBookCommandHandlerTests { // Arrange AddBookCommand bookCommand = _commandBookFixture.CreateCommandBook(); - bookCommand = bookCommand with { Ratings = [new BookRatingModel(-1, 5, null, null)] }; + bookCommand = bookCommand with { Ratings = [new BookRatingEntity(-1, 5, null, null)] }; // Act - ErrorOr result = await _sut.Handle(bookCommand, CancellationToken.None); + ErrorOr result = await _sut.Handle(bookCommand, CancellationToken.None); // Assert result.IsError.Should().BeTrue(); - result.Errors.Should().Contain(e => e.Code == Errors.Metadata.RatingValueMustBePositive.Code); - await _mockBookRepository.DidNotReceive().InsertAsync(Arg.Any(), Arg.Any()); + result.Errors.Should().Contain(e => e.Description == Errors.Metadata.RatingValueMustBePositive.Description); + await _mockBookRepository.DidNotReceive().InsertAsync(Arg.Any(), Arg.Any()); await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); } @@ -155,19 +148,19 @@ public class AddBookCommandHandlerTests AddBookCommand bookCommand = _commandBookFixture.CreateCommandBook(); bookCommand = bookCommand with { - Metadata = bookCommand.Metadata with + Metadata = bookCommand.Metadata! with { - Genres = [new GenreModel("")] + Genres = [new GenreEntity("")] } }; // Act - ErrorOr result = await _sut.Handle(bookCommand, CancellationToken.None); + ErrorOr result = await _sut.Handle(bookCommand, CancellationToken.None); // Assert result.IsError.Should().BeTrue(); - result.Errors.Should().Contain(e => e.Code == Errors.Metadata.GenreNameCannotBeEmpty.Code); - await _mockBookRepository.DidNotReceive().InsertAsync(Arg.Any(), Arg.Any()); + result.Errors.Should().Contain(e => e.Description == Errors.Metadata.GenreNameCannotBeEmpty.Description); + await _mockBookRepository.DidNotReceive().InsertAsync(Arg.Any(), Arg.Any()); await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); } @@ -178,19 +171,19 @@ public class AddBookCommandHandlerTests AddBookCommand bookCommand = _commandBookFixture.CreateCommandBook(); bookCommand = bookCommand with { - Metadata = bookCommand.Metadata with + Metadata = bookCommand.Metadata! with { - Tags = [new TagModel("")] + Tags = [new TagEntity("")] } }; // Act - ErrorOr result = await _sut.Handle(bookCommand, CancellationToken.None); + ErrorOr result = await _sut.Handle(bookCommand, CancellationToken.None); // Assert result.IsError.Should().BeTrue(); - result.Errors.Should().Contain(e => e.Code == Errors.Metadata.TagNameCannotBeEmpty.Code); - await _mockBookRepository.DidNotReceive().InsertAsync(Arg.Any(), Arg.Any()); + result.Errors.Should().Contain(e => e.Description == Errors.Metadata.TagNameCannotBeEmpty.Description); + await _mockBookRepository.DidNotReceive().InsertAsync(Arg.Any(), Arg.Any()); await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); } @@ -201,9 +194,9 @@ public class AddBookCommandHandlerTests AddBookCommand bookCommand = _commandBookFixture.CreateCommandBook(); bookCommand = bookCommand with { - Metadata = bookCommand.Metadata with + Metadata = bookCommand.Metadata! with { - ReleaseInfo = new ReleaseInfoModel( + ReleaseInfo = new ReleaseInfoEntity( OriginalReleaseDate: new DateOnly(2025, 1, 1), ReReleaseDate: new DateOnly(2024, 1, 1), OriginalReleaseYear: null, @@ -215,12 +208,12 @@ public class AddBookCommandHandlerTests }; // Act - ErrorOr result = await _sut.Handle(bookCommand, CancellationToken.None); + ErrorOr result = await _sut.Handle(bookCommand, CancellationToken.None); // Assert result.IsError.Should().BeTrue(); - result.Errors.Should().Contain(e => e.Code == Errors.Metadata.ReReleaseDateCannotBeEarlierThanOriginalReleaseDate.Code); - await _mockBookRepository.DidNotReceive().InsertAsync(Arg.Any(), Arg.Any()); + result.Errors.Should().Contain(e => e.Description == Errors.Metadata.ReReleaseDateCannotBeEarlierThanOriginalReleaseDate.Description); + await _mockBookRepository.DidNotReceive().InsertAsync(Arg.Any(), Arg.Any()); await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); } @@ -231,19 +224,19 @@ public class AddBookCommandHandlerTests AddBookCommand bookCommand = _commandBookFixture.CreateCommandBook(); bookCommand = bookCommand with { - Metadata = bookCommand.Metadata with + Metadata = bookCommand.Metadata! with { - Language = new LanguageInfoModel("", "English", null) + Language = new LanguageInfoEntity("", "English", null) } }; // Act - ErrorOr result = await _sut.Handle(bookCommand, CancellationToken.None); + ErrorOr result = await _sut.Handle(bookCommand, CancellationToken.None); // Assert result.IsError.Should().BeTrue(); - result.Errors.Should().Contain(e => e.Code == Errors.Metadata.LanguageCodeCannotBeEmpty.Code); - await _mockBookRepository.DidNotReceive().InsertAsync(Arg.Any(), Arg.Any()); + result.Errors.Should().Contain(e => e.Description == Errors.Metadata.LanguageCodeCannotBeEmpty.Description); + await _mockBookRepository.DidNotReceive().InsertAsync(Arg.Any(), Arg.Any()); await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); } @@ -254,19 +247,19 @@ public class AddBookCommandHandlerTests AddBookCommand bookCommand = _commandBookFixture.CreateCommandBook(); bookCommand = bookCommand with { - Metadata = bookCommand.Metadata with + Metadata = bookCommand.Metadata! with { - OriginalLanguage = new LanguageInfoModel("", "English", null) + OriginalLanguage = new LanguageInfoEntity("", "English", null) } }; // Act - ErrorOr result = await _sut.Handle(bookCommand, CancellationToken.None); + ErrorOr result = await _sut.Handle(bookCommand, CancellationToken.None); // Assert result.IsError.Should().BeTrue(); - result.Errors.Should().Contain(e => e.Code == Errors.Metadata.LanguageCodeCannotBeEmpty.Code); - await _mockBookRepository.DidNotReceive().InsertAsync(Arg.Any(), Arg.Any()); + result.Errors.Should().Contain(e => e.Description == Errors.Metadata.LanguageCodeCannotBeEmpty.Description); + await _mockBookRepository.DidNotReceive().InsertAsync(Arg.Any(), Arg.Any()); await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); } -} \ No newline at end of file +} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/WrittenContentLibrary/BooksLibrary/Books/Commands/AddBook/AddBookCommandValidatorTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/WrittenContentLibrary/BooksLibrary/Books/Commands/AddBook/AddBookCommandValidatorTests.cs index f7636d20..5aa0d855 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/WrittenContentLibrary/BooksLibrary/Books/Commands/AddBook/AddBookCommandValidatorTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/WrittenContentLibrary/BooksLibrary/Books/Commands/AddBook/AddBookCommandValidatorTests.cs @@ -41,7 +41,7 @@ public class AddBookCommandValidatorTests TestValidationResult result = _validator.TestValidate(bookCommand); // Assert - result.ShouldHaveValidationErrorFor(x => x.Metadata.Title).WithErrorMessage(Errors.Metadata.TitleCannotBeEmpty.Code); + result.ShouldHaveValidationErrorFor(x => x.Metadata!.Title).WithErrorMessage(Errors.Metadata.TitleCannotBeEmpty.Description); } [Fact] @@ -55,7 +55,7 @@ public class AddBookCommandValidatorTests TestValidationResult result = _validator.TestValidate(bookCommand); // Assert - result.ShouldHaveValidationErrorFor(x => x.Metadata.Title).WithErrorMessage(Errors.Metadata.TitleMustBeMaximum255CharactersLong.Code); + result.ShouldHaveValidationErrorFor(x => x.Metadata!.Title).WithErrorMessage(Errors.Metadata.TitleMustBeMaximum255CharactersLong.Description); } [Fact] @@ -69,7 +69,7 @@ public class AddBookCommandValidatorTests TestValidationResult result = _validator.TestValidate(bookCommand); // Assert - result.ShouldNotHaveValidationErrorFor(x => x.Metadata.Title); + result.ShouldNotHaveValidationErrorFor(x => x.Metadata!.Title); } [Fact] @@ -83,7 +83,7 @@ public class AddBookCommandValidatorTests TestValidationResult result = _validator.TestValidate(bookCommand); // Assert - result.ShouldHaveValidationErrorFor(x => x.Metadata.OriginalTitle).WithErrorMessage(Errors.Metadata.OriginalTitleMustBeMaximum255CharactersLong.Code); + result.ShouldHaveValidationErrorFor(x => x.Metadata!.OriginalTitle).WithErrorMessage(Errors.Metadata.OriginalTitleMustBeMaximum255CharactersLong.Description); } [Fact] @@ -97,7 +97,7 @@ public class AddBookCommandValidatorTests TestValidationResult result = _validator.TestValidate(bookCommand); // Assert - result.ShouldNotHaveValidationErrorFor(x => x.Metadata.OriginalTitle); + result.ShouldNotHaveValidationErrorFor(x => x.Metadata!.OriginalTitle); } [Fact] @@ -111,7 +111,7 @@ public class AddBookCommandValidatorTests TestValidationResult result = _validator.TestValidate(bookCommand); // Assert - result.ShouldNotHaveValidationErrorFor(x => x.Metadata.OriginalTitle); + result.ShouldNotHaveValidationErrorFor(x => x.Metadata!.OriginalTitle); } [Fact] @@ -125,7 +125,7 @@ public class AddBookCommandValidatorTests TestValidationResult result = _validator.TestValidate(bookCommand); // Assert - result.ShouldHaveValidationErrorFor(x => x.Metadata.Description).WithErrorMessage(Errors.Metadata.DescriptionMustBeMaximum2000CharactersLong.Code); + result.ShouldHaveValidationErrorFor(x => x.Metadata!.Description).WithErrorMessage(Errors.Metadata.DescriptionMustBeMaximum2000CharactersLong.Description); } [Fact] @@ -139,7 +139,7 @@ public class AddBookCommandValidatorTests TestValidationResult result = _validator.TestValidate(bookCommand); // Assert - result.ShouldNotHaveValidationErrorFor(x => x.Metadata.Description); + result.ShouldNotHaveValidationErrorFor(x => x.Metadata!.Description); } [Fact] @@ -153,7 +153,7 @@ public class AddBookCommandValidatorTests TestValidationResult result = _validator.TestValidate(bookCommand); // Assert - result.ShouldNotHaveValidationErrorFor(x => x.Metadata.Description); + result.ShouldNotHaveValidationErrorFor(x => x.Metadata!.Description); } [Fact] @@ -167,7 +167,7 @@ public class AddBookCommandValidatorTests TestValidationResult result = _validator.TestValidate(bookCommand); // Assert - result.ShouldNotHaveValidationErrorFor(x => x.Metadata.Description); + result.ShouldNotHaveValidationErrorFor(x => x.Metadata!.Description); } [Fact] @@ -181,7 +181,7 @@ public class AddBookCommandValidatorTests TestValidationResult result = _validator.TestValidate(bookCommand); // Assert - result.ShouldHaveValidationErrorFor(x => x.Metadata.ReleaseInfo).WithErrorMessage(Errors.Metadata.ReleaseInfoCannotBeNull.Code); + result.ShouldHaveValidationErrorFor(x => x.Metadata!.ReleaseInfo).WithErrorMessage(Errors.Metadata.ReleaseInfoCannotBeNull.Description); } [Fact] @@ -189,13 +189,13 @@ public class AddBookCommandValidatorTests { // Arrange AddBookCommand bookCommand = _commandBookFixture.CreateCommandBook(); - bookCommand = bookCommand with { Metadata = bookCommand.Metadata! with { ReleaseInfo = bookCommand.Metadata.ReleaseInfo! with { OriginalReleaseYear = new Faker().Random.Int(2000, 2005), ReReleaseYear = new Faker().Random.Int(2005, 2010) } } }; + bookCommand = bookCommand with { Metadata = bookCommand.Metadata! with { ReleaseInfo = bookCommand.Metadata.ReleaseInfo! with { OriginalReleaseDate = null!, OriginalReleaseYear = new Faker().Random.Int(2000, 2005), ReReleaseYear = new Faker().Random.Int(2005, 2010), ReReleaseDate = null! } } }; // Act TestValidationResult result = _validator.TestValidate(bookCommand); // Assert - result.ShouldNotHaveValidationErrorFor(x => x.Metadata.ReleaseInfo!.OriginalReleaseYear); + result.ShouldNotHaveValidationErrorFor(x => x.Metadata!.ReleaseInfo!.OriginalReleaseYear); } [Fact] @@ -209,7 +209,7 @@ public class AddBookCommandValidatorTests TestValidationResult result = _validator.TestValidate(bookCommand); // Assert - result.ShouldHaveValidationErrorFor(x => x.Metadata.ReleaseInfo!.OriginalReleaseYear).WithErrorMessage(Errors.Metadata.OriginalReleaseYearMustBeBetween1And9999.Code); + result.ShouldHaveValidationErrorFor(x => x.Metadata!.ReleaseInfo!.OriginalReleaseYear).WithErrorMessage(Errors.Metadata.OriginalReleaseYearMustBeBetween1And9999.Description); } [Fact] @@ -223,7 +223,7 @@ public class AddBookCommandValidatorTests TestValidationResult result = _validator.TestValidate(bookCommand); // Assert - result.ShouldHaveValidationErrorFor(x => x.Metadata.ReleaseInfo!.OriginalReleaseYear).WithErrorMessage(Errors.Metadata.OriginalReleaseYearMustBeBetween1And9999.Code); + result.ShouldHaveValidationErrorFor(x => x.Metadata!.ReleaseInfo!.OriginalReleaseYear).WithErrorMessage(Errors.Metadata.OriginalReleaseYearMustBeBetween1And9999.Description); } [Fact] @@ -237,7 +237,7 @@ public class AddBookCommandValidatorTests { ReleaseInfo = bookCommand.Metadata.ReleaseInfo! with - { OriginalReleaseYear = new Faker().Random.Int(2000, 2005), ReReleaseYear = new Faker().Random.Int(2005, 2010) } + { OriginalReleaseYear = new Faker().Random.Int(2000, 2005), ReReleaseYear = new Faker().Random.Int(2005, 2010), ReReleaseDate = null! } } }; @@ -245,7 +245,7 @@ public class AddBookCommandValidatorTests TestValidationResult result = _validator.TestValidate(bookCommand); // Assert - result.ShouldNotHaveValidationErrorFor(x => x.Metadata.ReleaseInfo!.ReReleaseYear); + result.ShouldNotHaveValidationErrorFor(x => x.Metadata!.ReleaseInfo!.ReReleaseYear); } [Fact] @@ -259,7 +259,7 @@ public class AddBookCommandValidatorTests TestValidationResult result = _validator.TestValidate(bookCommand); // Assert - result.ShouldHaveValidationErrorFor(x => x.Metadata.ReleaseInfo!.ReReleaseYear).WithErrorMessage(Errors.Metadata.ReReleaseYearMustBeBetween1And9999.Code); + result.ShouldHaveValidationErrorFor(x => x.Metadata!.ReleaseInfo!.ReReleaseYear).WithErrorMessage(Errors.Metadata.ReReleaseYearMustBeBetween1And9999.Description); } [Fact] @@ -273,7 +273,7 @@ public class AddBookCommandValidatorTests TestValidationResult result = _validator.TestValidate(bookCommand); // Assert - result.ShouldHaveValidationErrorFor(x => x.Metadata.ReleaseInfo!.ReReleaseYear).WithErrorMessage(Errors.Metadata.ReReleaseYearMustBeBetween1And9999.Code); + result.ShouldHaveValidationErrorFor(x => x.Metadata!.ReleaseInfo!.ReReleaseYear).WithErrorMessage(Errors.Metadata.ReReleaseYearMustBeBetween1And9999.Description); } [Fact] @@ -287,7 +287,7 @@ public class AddBookCommandValidatorTests TestValidationResult result = _validator.TestValidate(bookCommand); // Assert - result.ShouldNotHaveValidationErrorFor(x => x.Metadata.ReleaseInfo!.ReleaseCountry); + result.ShouldNotHaveValidationErrorFor(x => x.Metadata!.ReleaseInfo!.ReleaseCountry); } [Fact] @@ -301,7 +301,7 @@ public class AddBookCommandValidatorTests TestValidationResult result = _validator.TestValidate(bookCommand); // Assert - result.ShouldHaveValidationErrorFor(x => x.Metadata.ReleaseInfo!.ReleaseCountry).WithErrorMessage(Errors.Metadata.CountryCodeMustBe2CharactersLong.Code); + result.ShouldHaveValidationErrorFor(x => x.Metadata!.ReleaseInfo!.ReleaseCountry).WithErrorMessage(Errors.Metadata.CountryCodeMustBe2CharactersLong.Description); } [Fact] @@ -315,7 +315,7 @@ public class AddBookCommandValidatorTests TestValidationResult result = _validator.TestValidate(bookCommand); // Assert - result.ShouldNotHaveValidationErrorFor(x => x.Metadata.ReleaseInfo!.ReleaseVersion); + result.ShouldNotHaveValidationErrorFor(x => x.Metadata!.ReleaseInfo!.ReleaseVersion); } [Fact] @@ -329,7 +329,7 @@ public class AddBookCommandValidatorTests TestValidationResult result = _validator.TestValidate(bookCommand); // Assert - result.ShouldHaveValidationErrorFor(x => x.Metadata.ReleaseInfo!.ReleaseVersion).WithErrorMessage(Errors.Metadata.ReleaseVersionMustBeMaximum50CharactersLong.Code); + result.ShouldHaveValidationErrorFor(x => x.Metadata!.ReleaseInfo!.ReleaseVersion).WithErrorMessage(Errors.Metadata.ReleaseVersionMustBeMaximum50CharactersLong.Description); } [Fact] @@ -337,13 +337,13 @@ public class AddBookCommandValidatorTests { // Arrange AddBookCommand bookCommand = _commandBookFixture.CreateCommandBook(); - bookCommand = bookCommand with { Metadata = bookCommand.Metadata! with { ReleaseInfo = bookCommand.Metadata.ReleaseInfo! with { OriginalReleaseYear = 2000, ReReleaseYear = 2001 } } }; + bookCommand = bookCommand with { Metadata = bookCommand.Metadata! with { ReleaseInfo = bookCommand.Metadata.ReleaseInfo! with { OriginalReleaseYear = 2000, ReReleaseYear = 2001, ReReleaseDate = null! } } }; // Act TestValidationResult result = _validator.TestValidate(bookCommand); // Assert - result.ShouldNotHaveValidationErrorFor(x => x.Metadata.ReleaseInfo!.ReReleaseYear); + result.ShouldNotHaveValidationErrorFor(x => x.Metadata!.ReleaseInfo!.ReReleaseYear); } [Fact] @@ -351,13 +351,13 @@ public class AddBookCommandValidatorTests { // Arrange AddBookCommand bookCommand = _commandBookFixture.CreateCommandBook(); - bookCommand = bookCommand with { Metadata = bookCommand.Metadata! with { ReleaseInfo = bookCommand.Metadata.ReleaseInfo! with { OriginalReleaseYear = 2001, ReReleaseYear = 2000 } } }; + bookCommand = bookCommand with { Metadata = bookCommand.Metadata! with { ReleaseInfo = bookCommand.Metadata.ReleaseInfo! with { OriginalReleaseYear = 2001, ReReleaseYear = 2000, ReReleaseDate = null! } } }; // Act TestValidationResult result = _validator.TestValidate(bookCommand); // Assert - result.ShouldHaveValidationErrorFor(x => x.Metadata.ReleaseInfo!.ReReleaseYear).WithErrorMessage(Errors.Metadata.ReReleaseYearCannotBeEarlierThanOriginalReleaseYear.Code); + result.ShouldHaveValidationErrorFor(x => x.Metadata!.ReleaseInfo!.ReReleaseYear).WithErrorMessage(Errors.Metadata.ReReleaseYearCannotBeEarlierThanOriginalReleaseYear.Description); } [Fact] @@ -371,7 +371,7 @@ public class AddBookCommandValidatorTests TestValidationResult result = _validator.TestValidate(bookCommand); // Assert - result.ShouldNotHaveValidationErrorFor(x => x.Metadata.ReleaseInfo!.ReReleaseDate); + result.ShouldNotHaveValidationErrorFor(x => x.Metadata!.ReleaseInfo!.ReReleaseDate); } [Fact] @@ -385,7 +385,7 @@ public class AddBookCommandValidatorTests TestValidationResult result = _validator.TestValidate(bookCommand); // Assert - result.ShouldHaveValidationErrorFor(x => x.Metadata.ReleaseInfo!.ReReleaseDate).WithErrorMessage(Errors.Metadata.ReReleaseDateCannotBeEarlierThanOriginalReleaseDate.Code); + result.ShouldHaveValidationErrorFor(x => x.Metadata!.ReleaseInfo!.ReReleaseDate).WithErrorMessage(Errors.Metadata.ReReleaseDateCannotBeEarlierThanOriginalReleaseDate.Description); } [Fact] @@ -399,7 +399,7 @@ public class AddBookCommandValidatorTests TestValidationResult result = _validator.TestValidate(bookCommand); // Assert - result.ShouldHaveValidationErrorFor(x => x.Metadata.Genres).WithErrorMessage(Errors.Metadata.GenresListCannotBeNull.Code); + result.ShouldHaveValidationErrorFor(x => x.Metadata!.Genres).WithErrorMessage(Errors.Metadata.GenresListCannotBeNull.Description); } [Fact] @@ -413,7 +413,7 @@ public class AddBookCommandValidatorTests TestValidationResult result = _validator.TestValidate(bookCommand); // Assert - result.ShouldHaveValidationErrorFor("Metadata.Genres[0].Name").WithErrorMessage(Errors.Metadata.GenreNameCannotBeEmpty.Code); + result.ShouldHaveValidationErrorFor("Metadata.Genres[0].Name").WithErrorMessage(Errors.Metadata.GenreNameCannotBeEmpty.Description); } [Fact] @@ -427,7 +427,7 @@ public class AddBookCommandValidatorTests TestValidationResult result = _validator.TestValidate(bookCommand); // Assert - result.ShouldHaveValidationErrorFor("Metadata.Genres[0].Name").WithErrorMessage(Errors.Metadata.GenreNameMustBeMaximum50CharactersLong.Code); + result.ShouldHaveValidationErrorFor("Metadata.Genres[0].Name").WithErrorMessage(Errors.Metadata.GenreNameMustBeMaximum50CharactersLong.Description); } [Fact] @@ -447,7 +447,7 @@ public class AddBookCommandValidatorTests TestValidationResult result = _validator.TestValidate(bookCommand); // Assert - result.ShouldNotHaveValidationErrorFor(x => x.Metadata.Genres); + result.ShouldNotHaveValidationErrorFor(x => x.Metadata!.Genres); } [Fact] @@ -461,7 +461,7 @@ public class AddBookCommandValidatorTests TestValidationResult result = _validator.TestValidate(bookCommand); // Assert - result.ShouldHaveValidationErrorFor(x => x.Metadata.Tags).WithErrorMessage(Errors.Metadata.TagsListCannotBeNull.Code); + result.ShouldHaveValidationErrorFor(x => x.Metadata!.Tags).WithErrorMessage(Errors.Metadata.TagsListCannotBeNull.Description); } [Fact] @@ -475,7 +475,7 @@ public class AddBookCommandValidatorTests TestValidationResult result = _validator.TestValidate(bookCommand); // Assert - result.ShouldHaveValidationErrorFor("Metadata.Tags[0].Name").WithErrorMessage(Errors.Metadata.TagNameCannotBeEmpty.Code); + result.ShouldHaveValidationErrorFor("Metadata.Tags[0].Name").WithErrorMessage(Errors.Metadata.TagNameCannotBeEmpty.Description); } [Fact] @@ -489,7 +489,7 @@ public class AddBookCommandValidatorTests TestValidationResult result = _validator.TestValidate(bookCommand); // Assert - result.ShouldHaveValidationErrorFor("Metadata.Tags[0].Name").WithErrorMessage(Errors.Metadata.TagNameMustBeMaximum50CharactersLong.Code); + result.ShouldHaveValidationErrorFor("Metadata.Tags[0].Name").WithErrorMessage(Errors.Metadata.TagNameMustBeMaximum50CharactersLong.Description); } [Fact] @@ -509,7 +509,7 @@ public class AddBookCommandValidatorTests TestValidationResult result = _validator.TestValidate(bookCommand); // Assert - result.ShouldNotHaveValidationErrorFor(x => x.Metadata.Tags); + result.ShouldNotHaveValidationErrorFor(x => x.Metadata!.Tags); } [Fact] @@ -523,7 +523,7 @@ public class AddBookCommandValidatorTests TestValidationResult result = _validator.TestValidate(bookCommand); // Assert - result.ShouldNotHaveValidationErrorFor(x => x.Metadata.Language); + result.ShouldNotHaveValidationErrorFor(x => x.Metadata!.Language); } [Fact] @@ -537,7 +537,7 @@ public class AddBookCommandValidatorTests TestValidationResult result = _validator.TestValidate(bookCommand); // Assert - result.ShouldHaveValidationErrorFor(x => x.Metadata.Language!.LanguageCode).WithErrorMessage(Errors.Metadata.LanguageCodeCannotBeEmpty.Code); + result.ShouldHaveValidationErrorFor(x => x.Metadata!.Language!.LanguageCode).WithErrorMessage(Errors.Metadata.LanguageCodeCannotBeEmpty.Description); } [Fact] @@ -551,7 +551,7 @@ public class AddBookCommandValidatorTests TestValidationResult result = _validator.TestValidate(bookCommand); // Assert - result.ShouldHaveValidationErrorFor(x => x.Metadata.Language!.LanguageCode).WithErrorMessage(Errors.Metadata.LanguageCodeMustBe2CharactersLong.Code); + result.ShouldHaveValidationErrorFor(x => x.Metadata!.Language!.LanguageCode).WithErrorMessage(Errors.Metadata.LanguageCodeMustBe2CharactersLong.Description); } [Fact] @@ -565,7 +565,7 @@ public class AddBookCommandValidatorTests TestValidationResult result = _validator.TestValidate(bookCommand); // Assert - result.ShouldHaveValidationErrorFor(x => x.Metadata.Language!.LanguageName).WithErrorMessage(Errors.Metadata.LanguageNameCannotBeEmpty.Code); + result.ShouldHaveValidationErrorFor(x => x.Metadata!.Language!.LanguageName).WithErrorMessage(Errors.Metadata.LanguageNameCannotBeEmpty.Description); } [Fact] @@ -579,7 +579,7 @@ public class AddBookCommandValidatorTests TestValidationResult result = _validator.TestValidate(bookCommand); // Assert - result.ShouldHaveValidationErrorFor(x => x.Metadata.Language!.LanguageName).WithErrorMessage(Errors.Metadata.LanguageNameMustBeMaximum50CharactersLong.Code); + result.ShouldHaveValidationErrorFor(x => x.Metadata!.Language!.LanguageName).WithErrorMessage(Errors.Metadata.LanguageNameMustBeMaximum50CharactersLong.Description); } [Fact] @@ -593,7 +593,7 @@ public class AddBookCommandValidatorTests TestValidationResult result = _validator.TestValidate(bookCommand); // Assert - result.ShouldNotHaveValidationErrorFor(x => x.Metadata.Language!.NativeName); + result.ShouldNotHaveValidationErrorFor(x => x.Metadata!.Language!.NativeName); } [Fact] @@ -607,7 +607,7 @@ public class AddBookCommandValidatorTests TestValidationResult result = _validator.TestValidate(bookCommand); // Assert - result.ShouldHaveValidationErrorFor(x => x.Metadata.Language!.NativeName).WithErrorMessage(Errors.Metadata.LanguageNativeNameMustBeMaximum50CharactersLong.Code); + result.ShouldHaveValidationErrorFor(x => x.Metadata!.Language!.NativeName).WithErrorMessage(Errors.Metadata.LanguageNativeNameMustBeMaximum50CharactersLong.Description); } [Fact] @@ -621,7 +621,7 @@ public class AddBookCommandValidatorTests TestValidationResult result = _validator.TestValidate(bookCommand); // Assert - result.ShouldNotHaveValidationErrorFor(x => x.Metadata.OriginalLanguage); + result.ShouldNotHaveValidationErrorFor(x => x.Metadata!.OriginalLanguage); } [Fact] @@ -635,7 +635,7 @@ public class AddBookCommandValidatorTests TestValidationResult result = _validator.TestValidate(bookCommand); // Assert - result.ShouldHaveValidationErrorFor(x => x.Metadata.OriginalLanguage!.LanguageCode).WithErrorMessage(Errors.Metadata.LanguageCodeCannotBeEmpty.Code); + result.ShouldHaveValidationErrorFor(x => x.Metadata!.OriginalLanguage!.LanguageCode).WithErrorMessage(Errors.Metadata.LanguageCodeCannotBeEmpty.Description); } [Fact] @@ -649,7 +649,7 @@ public class AddBookCommandValidatorTests TestValidationResult result = _validator.TestValidate(bookCommand); // Assert - result.ShouldHaveValidationErrorFor(x => x.Metadata.OriginalLanguage!.LanguageCode).WithErrorMessage(Errors.Metadata.LanguageCodeMustBe2CharactersLong.Code); + result.ShouldHaveValidationErrorFor(x => x.Metadata!.OriginalLanguage!.LanguageCode).WithErrorMessage(Errors.Metadata.LanguageCodeMustBe2CharactersLong.Description); } [Fact] @@ -663,7 +663,7 @@ public class AddBookCommandValidatorTests TestValidationResult result = _validator.TestValidate(bookCommand); // Assert - result.ShouldHaveValidationErrorFor(x => x.Metadata.OriginalLanguage!.LanguageName).WithErrorMessage(Errors.Metadata.LanguageNameCannotBeEmpty.Code); + result.ShouldHaveValidationErrorFor(x => x.Metadata!.OriginalLanguage!.LanguageName).WithErrorMessage(Errors.Metadata.LanguageNameCannotBeEmpty.Description); } [Fact] @@ -677,7 +677,7 @@ public class AddBookCommandValidatorTests TestValidationResult result = _validator.TestValidate(bookCommand); // Assert - result.ShouldHaveValidationErrorFor(x => x.Metadata.OriginalLanguage!.LanguageName).WithErrorMessage(Errors.Metadata.LanguageNameMustBeMaximum50CharactersLong.Code); + result.ShouldHaveValidationErrorFor(x => x.Metadata!.OriginalLanguage!.LanguageName).WithErrorMessage(Errors.Metadata.LanguageNameMustBeMaximum50CharactersLong.Description); } [Fact] @@ -691,7 +691,7 @@ public class AddBookCommandValidatorTests TestValidationResult result = _validator.TestValidate(bookCommand); // Assert - result.ShouldNotHaveValidationErrorFor(x => x.Metadata.OriginalLanguage!.NativeName); + result.ShouldNotHaveValidationErrorFor(x => x.Metadata!.OriginalLanguage!.NativeName); } [Fact] @@ -705,7 +705,7 @@ public class AddBookCommandValidatorTests TestValidationResult result = _validator.TestValidate(bookCommand); // Assert - result.ShouldHaveValidationErrorFor(x => x.Metadata.OriginalLanguage!.NativeName).WithErrorMessage(Errors.Metadata.LanguageNativeNameMustBeMaximum50CharactersLong.Code); + result.ShouldHaveValidationErrorFor(x => x.Metadata!.OriginalLanguage!.NativeName).WithErrorMessage(Errors.Metadata.LanguageNativeNameMustBeMaximum50CharactersLong.Description); } [Fact] @@ -719,7 +719,7 @@ public class AddBookCommandValidatorTests TestValidationResult result = _validator.TestValidate(bookCommand); // Assert - result.ShouldNotHaveValidationErrorFor(x => x.Metadata.Publisher); + result.ShouldNotHaveValidationErrorFor(x => x.Metadata!.Publisher); } [Fact] @@ -733,7 +733,7 @@ public class AddBookCommandValidatorTests TestValidationResult result = _validator.TestValidate(bookCommand); // Assert - result.ShouldNotHaveValidationErrorFor(x => x.Metadata.Publisher); + result.ShouldNotHaveValidationErrorFor(x => x.Metadata!.Publisher); } [Fact] @@ -747,7 +747,7 @@ public class AddBookCommandValidatorTests TestValidationResult result = _validator.TestValidate(bookCommand); // Assert - result.ShouldHaveValidationErrorFor(x => x.Metadata.Publisher).WithErrorMessage(Errors.WrittenContent.PublisherMustBeMaximum100CharactersLong.Code); + result.ShouldHaveValidationErrorFor(x => x.Metadata!.Publisher).WithErrorMessage(Errors.WrittenContent.PublisherMustBeMaximum100CharactersLong.Description); } [Fact] @@ -761,7 +761,7 @@ public class AddBookCommandValidatorTests TestValidationResult result = _validator.TestValidate(bookCommand); // Assert - result.ShouldNotHaveValidationErrorFor(x => x.Metadata.PageCount); + result.ShouldNotHaveValidationErrorFor(x => x.Metadata!.PageCount); } [Fact] @@ -775,7 +775,7 @@ public class AddBookCommandValidatorTests TestValidationResult result = _validator.TestValidate(bookCommand); // Assert - result.ShouldHaveValidationErrorFor(x => x.Metadata.PageCount).WithErrorMessage(Errors.WrittenContent.PageCountMustBeGreaterThanZero.Code); + result.ShouldHaveValidationErrorFor(x => x.Metadata!.PageCount).WithErrorMessage(Errors.WrittenContent.PageCountMustBeGreaterThanZero.Description); } [Fact] @@ -789,7 +789,7 @@ public class AddBookCommandValidatorTests TestValidationResult result = _validator.TestValidate(bookCommand); // Assert - result.ShouldHaveValidationErrorFor(x => x.Metadata.PageCount).WithErrorMessage(Errors.WrittenContent.PageCountMustBeGreaterThanZero.Code); + result.ShouldHaveValidationErrorFor(x => x.Metadata!.PageCount).WithErrorMessage(Errors.WrittenContent.PageCountMustBeGreaterThanZero.Description); } [Fact] @@ -803,7 +803,7 @@ public class AddBookCommandValidatorTests TestValidationResult result = _validator.TestValidate(bookCommand); // Assert - result.ShouldNotHaveValidationErrorFor(x => x.Metadata.PageCount); + result.ShouldNotHaveValidationErrorFor(x => x.Metadata!.PageCount); } [Fact] @@ -845,7 +845,7 @@ public class AddBookCommandValidatorTests TestValidationResult result = _validator.TestValidate(bookCommand); // Assert - result.ShouldHaveValidationErrorFor(x => x.Format).WithErrorMessage(Errors.WrittenContent.UnknownBookFormat.Code); + result.ShouldHaveValidationErrorFor(x => x.Format).WithErrorMessage(Errors.WrittenContent.UnknownBookFormat.Description); } [Fact] @@ -887,7 +887,7 @@ public class AddBookCommandValidatorTests TestValidationResult result = _validator.TestValidate(bookCommand); // Assert - result.ShouldHaveValidationErrorFor(x => x.Edition).WithErrorMessage(Errors.WrittenContent.EditionMustBeMaximum50CharactersLong.Code); + result.ShouldHaveValidationErrorFor(x => x.Edition).WithErrorMessage(Errors.WrittenContent.EditionMustBeMaximum50CharactersLong.Description); } [Fact] @@ -915,7 +915,7 @@ public class AddBookCommandValidatorTests TestValidationResult result = _validator.TestValidate(bookCommand); // Assert - result.ShouldHaveValidationErrorFor(x => x.VolumeNumber).WithErrorMessage(Errors.WrittenContent.VolumeNumberMustBeGreaterThanZero.Code); + result.ShouldHaveValidationErrorFor(x => x.VolumeNumber).WithErrorMessage(Errors.WrittenContent.VolumeNumberMustBeGreaterThanZero.Description); } [Fact] @@ -929,7 +929,7 @@ public class AddBookCommandValidatorTests TestValidationResult result = _validator.TestValidate(bookCommand); // Assert - result.ShouldHaveValidationErrorFor(x => x.VolumeNumber).WithErrorMessage(Errors.WrittenContent.VolumeNumberMustBeGreaterThanZero.Code); + result.ShouldHaveValidationErrorFor(x => x.VolumeNumber).WithErrorMessage(Errors.WrittenContent.VolumeNumberMustBeGreaterThanZero.Description); } [Fact] @@ -971,7 +971,7 @@ public class AddBookCommandValidatorTests // var result = _validator.TestValidate(bookCommand); // // Assert - // result.ShouldHaveValidationErrorFor(x => x.Series.Title).WithErrorMessage(Errors.Metadata.TitleCannotBeEmpty.Code); + // result.ShouldHaveValidationErrorFor(x => x.Series.Title).WithErrorMessage(Errors.Metadata.TitleCannotBeEmpty.Description); //} //[Fact] @@ -985,7 +985,7 @@ public class AddBookCommandValidatorTests // var result = _validator.TestValidate(bookCommand); // // Assert - // result.ShouldHaveValidationErrorFor(x => x.Series.Title).WithErrorMessage(Errors.Metadata.TitleMustBeMaximum255CharactersLong.Code); + // result.ShouldHaveValidationErrorFor(x => x.Series.Title).WithErrorMessage(Errors.Metadata.TitleMustBeMaximum255CharactersLong.Description); //} //[Fact] @@ -1041,7 +1041,7 @@ public class AddBookCommandValidatorTests TestValidationResult result = _validator.TestValidate(bookCommand); // Assert - result.ShouldHaveValidationErrorFor(x => x.ASIN).WithErrorMessage(Errors.WrittenContent.AsinMustBe10CharactersLong.Code); + result.ShouldHaveValidationErrorFor(x => x.ASIN).WithErrorMessage(Errors.WrittenContent.AsinMustBe10CharactersLong.Description); } [Fact] @@ -1083,7 +1083,7 @@ public class AddBookCommandValidatorTests TestValidationResult result = _validator.TestValidate(bookCommand); // Assert - result.ShouldHaveValidationErrorFor(x => x.GoodreadsId).WithErrorMessage(Errors.WrittenContent.GoodreadsIdMustBeNumeric.Code); + result.ShouldHaveValidationErrorFor(x => x.GoodreadsId).WithErrorMessage(Errors.WrittenContent.GoodreadsIdMustBeNumeric.Description); } [Fact] @@ -1097,7 +1097,7 @@ public class AddBookCommandValidatorTests TestValidationResult result = _validator.TestValidate(bookCommand); // Assert - result.ShouldHaveValidationErrorFor(x => x.GoodreadsId).WithErrorMessage(Errors.WrittenContent.GoodreadsIdMustBeNumeric.Code); + result.ShouldHaveValidationErrorFor(x => x.GoodreadsId).WithErrorMessage(Errors.WrittenContent.GoodreadsIdMustBeNumeric.Description); } [Fact] @@ -1111,7 +1111,7 @@ public class AddBookCommandValidatorTests TestValidationResult result = _validator.TestValidate(bookCommand); // Assert - result.ShouldHaveValidationErrorFor(x => x.GoodreadsId).WithErrorMessage(Errors.WrittenContent.GoodreadsIdMustBeNumeric.Code); + result.ShouldHaveValidationErrorFor(x => x.GoodreadsId).WithErrorMessage(Errors.WrittenContent.GoodreadsIdMustBeNumeric.Description); } [Fact] @@ -1153,7 +1153,7 @@ public class AddBookCommandValidatorTests TestValidationResult result = _validator.TestValidate(bookCommand); // Assert - result.ShouldHaveValidationErrorFor(x => x.LCCN).WithErrorMessage(Errors.WrittenContent.InvalidLccnFormat.Code); + result.ShouldHaveValidationErrorFor(x => x.LCCN).WithErrorMessage(Errors.WrittenContent.InvalidLccnFormat.Description); } [Fact] @@ -1167,7 +1167,7 @@ public class AddBookCommandValidatorTests TestValidationResult result = _validator.TestValidate(bookCommand); // Assert - result.ShouldHaveValidationErrorFor(x => x.LCCN).WithErrorMessage(Errors.WrittenContent.InvalidLccnFormat.Code); + result.ShouldHaveValidationErrorFor(x => x.LCCN).WithErrorMessage(Errors.WrittenContent.InvalidLccnFormat.Description); } [Fact] @@ -1181,7 +1181,7 @@ public class AddBookCommandValidatorTests TestValidationResult result = _validator.TestValidate(bookCommand); // Assert - result.ShouldHaveValidationErrorFor(x => x.LCCN).WithErrorMessage(Errors.WrittenContent.InvalidLccnFormat.Code); + result.ShouldHaveValidationErrorFor(x => x.LCCN).WithErrorMessage(Errors.WrittenContent.InvalidLccnFormat.Description); } [Fact] @@ -1279,7 +1279,7 @@ public class AddBookCommandValidatorTests TestValidationResult result = _validator.TestValidate(bookCommand); // Assert - result.ShouldHaveValidationErrorFor(x => x.OCLCNumber).WithErrorMessage(Errors.WrittenContent.InvalidOclcFormat.Code); + result.ShouldHaveValidationErrorFor(x => x.OCLCNumber).WithErrorMessage(Errors.WrittenContent.InvalidOclcFormat.Description); } [Fact] @@ -1321,7 +1321,7 @@ public class AddBookCommandValidatorTests TestValidationResult result = _validator.TestValidate(bookCommand); // Assert - result.ShouldHaveValidationErrorFor(x => x.OpenLibraryId).WithErrorMessage(Errors.WrittenContent.InvalidOpenLibraryId.Code); + result.ShouldHaveValidationErrorFor(x => x.OpenLibraryId).WithErrorMessage(Errors.WrittenContent.InvalidOpenLibraryId.Description); } [Fact] @@ -1335,7 +1335,7 @@ public class AddBookCommandValidatorTests TestValidationResult result = _validator.TestValidate(bookCommand); // Assert - result.ShouldHaveValidationErrorFor(x => x.OpenLibraryId).WithErrorMessage(Errors.WrittenContent.InvalidOpenLibraryId.Code); + result.ShouldHaveValidationErrorFor(x => x.OpenLibraryId).WithErrorMessage(Errors.WrittenContent.InvalidOpenLibraryId.Description); } [Fact] @@ -1349,7 +1349,7 @@ public class AddBookCommandValidatorTests TestValidationResult result = _validator.TestValidate(bookCommand); // Assert - result.ShouldHaveValidationErrorFor(x => x.OpenLibraryId).WithErrorMessage(Errors.WrittenContent.InvalidOpenLibraryId.Code); + result.ShouldHaveValidationErrorFor(x => x.OpenLibraryId).WithErrorMessage(Errors.WrittenContent.InvalidOpenLibraryId.Description); } [Fact] @@ -1391,7 +1391,7 @@ public class AddBookCommandValidatorTests TestValidationResult result = _validator.TestValidate(bookCommand); // Assert - result.ShouldHaveValidationErrorFor(x => x.LibraryThingId).WithErrorMessage(Errors.WrittenContent.LibraryThingIdMustBeMaximum50CharactersLong.Code); + result.ShouldHaveValidationErrorFor(x => x.LibraryThingId).WithErrorMessage(Errors.WrittenContent.LibraryThingIdMustBeMaximum50CharactersLong.Description); } [Fact] @@ -1419,7 +1419,7 @@ public class AddBookCommandValidatorTests TestValidationResult result = _validator.TestValidate(bookCommand); // Assert - result.ShouldHaveValidationErrorFor(x => x.GoogleBooksId).WithErrorMessage(Errors.WrittenContent.GoogleBooksIdMustBe12CharactersLong.Code); + result.ShouldHaveValidationErrorFor(x => x.GoogleBooksId).WithErrorMessage(Errors.WrittenContent.GoogleBooksIdMustBe12CharactersLong.Description); } [Fact] @@ -1433,7 +1433,7 @@ public class AddBookCommandValidatorTests TestValidationResult result = _validator.TestValidate(bookCommand); // Assert - result.ShouldHaveValidationErrorFor(x => x.GoogleBooksId).WithErrorMessage(Errors.WrittenContent.InvalidGoogleBooksIdFormat.Code); + result.ShouldHaveValidationErrorFor(x => x.GoogleBooksId).WithErrorMessage(Errors.WrittenContent.InvalidGoogleBooksIdFormat.Description); } [Fact] @@ -1475,7 +1475,7 @@ public class AddBookCommandValidatorTests TestValidationResult result = _validator.TestValidate(bookCommand); // Assert - result.ShouldHaveValidationErrorFor(x => x.BarnesAndNobleId).WithErrorMessage(Errors.WrittenContent.BarnesAndNoblesIdMustBe10CharactersLong.Code); + result.ShouldHaveValidationErrorFor(x => x.BarnesAndNobleId).WithErrorMessage(Errors.WrittenContent.BarnesAndNoblesIdMustBe10CharactersLong.Description); } [Fact] @@ -1489,7 +1489,7 @@ public class AddBookCommandValidatorTests TestValidationResult result = _validator.TestValidate(bookCommand); // Assert - result.ShouldHaveValidationErrorFor(x => x.BarnesAndNobleId).WithErrorMessage(Errors.WrittenContent.InvalidBarnesAndNoblesIdFormat.Code); + result.ShouldHaveValidationErrorFor(x => x.BarnesAndNobleId).WithErrorMessage(Errors.WrittenContent.InvalidBarnesAndNoblesIdFormat.Description); } [Fact] @@ -1545,7 +1545,7 @@ public class AddBookCommandValidatorTests TestValidationResult result = _validator.TestValidate(bookCommand); // Assert - result.ShouldHaveValidationErrorFor(x => x.AppleBooksId).WithErrorMessage(Errors.WrittenContent.InvalidAppleBooksIdFormat.Code); + result.ShouldHaveValidationErrorFor(x => x.AppleBooksId).WithErrorMessage(Errors.WrittenContent.InvalidAppleBooksIdFormat.Description); } [Fact] @@ -1559,7 +1559,7 @@ public class AddBookCommandValidatorTests TestValidationResult result = _validator.TestValidate(bookCommand); // Assert - result.ShouldHaveValidationErrorFor(x => x.ISBNs).WithErrorMessage(Errors.WrittenContent.IsbnListCannotBeNull.Code); + result.ShouldHaveValidationErrorFor(x => x.ISBNs).WithErrorMessage(Errors.WrittenContent.IsbnListCannotBeNull.Description); } [Fact] @@ -1573,7 +1573,7 @@ public class AddBookCommandValidatorTests TestValidationResult result = _validator.TestValidate(bookCommand); // Assert - result.ShouldHaveValidationErrorFor("ISBNs[0].Value").WithErrorMessage(Errors.WrittenContent.IsbnValueCannotBeEmpty.Code); + result.ShouldHaveValidationErrorFor("ISBNs[0].Value").WithErrorMessage(Errors.WrittenContent.IsbnValueCannotBeEmpty.Description); } [Fact] @@ -1587,7 +1587,7 @@ public class AddBookCommandValidatorTests TestValidationResult result = _validator.TestValidate(bookCommand); // Assert - result.ShouldHaveValidationErrorFor("ISBNs[0].Value").WithErrorMessage(Errors.WrittenContent.InvalidIsbn10Format.Code); + result.ShouldHaveValidationErrorFor("ISBNs[0].Value").WithErrorMessage(Errors.WrittenContent.InvalidIsbn10Format.Description); } [Fact] @@ -1601,7 +1601,7 @@ public class AddBookCommandValidatorTests TestValidationResult result = _validator.TestValidate(bookCommand); // Assert - result.ShouldHaveValidationErrorFor("ISBNs[0].Value").WithErrorMessage(Errors.WrittenContent.InvalidIsbn13Format.Code); + result.ShouldHaveValidationErrorFor("ISBNs[0].Value").WithErrorMessage(Errors.WrittenContent.InvalidIsbn13Format.Description); } [Fact] @@ -1615,7 +1615,7 @@ public class AddBookCommandValidatorTests TestValidationResult result = _validator.TestValidate(bookCommand); // Assert - result.ShouldHaveValidationErrorFor("ISBNs[0].Format").WithErrorMessage(Errors.WrittenContent.UnknownIsbnFormat.Code); + result.ShouldHaveValidationErrorFor("ISBNs[0].Format").WithErrorMessage(Errors.WrittenContent.UnknownIsbnFormat.Description); } [Fact] @@ -1629,7 +1629,7 @@ public class AddBookCommandValidatorTests TestValidationResult result = _validator.TestValidate(bookCommand); // Assert - result.ShouldNotHaveValidationErrorFor(x => x.ISBNs[0].Value); + result.ShouldNotHaveValidationErrorFor(x => x.ISBNs![0].Value); } [Fact] @@ -1643,7 +1643,7 @@ public class AddBookCommandValidatorTests TestValidationResult result = _validator.TestValidate(bookCommand); // Assert - result.ShouldNotHaveValidationErrorFor(x => x.ISBNs[0].Value); + result.ShouldNotHaveValidationErrorFor(x => x.ISBNs![0].Value); } [Fact] @@ -1657,7 +1657,7 @@ public class AddBookCommandValidatorTests TestValidationResult result = _validator.TestValidate(bookCommand); // Assert - result.ShouldHaveValidationErrorFor(x => x.Contributors).WithErrorMessage(Errors.MediaContributor.ContributorsListCannotBeNull.Code); + result.ShouldHaveValidationErrorFor(x => x.Contributors).WithErrorMessage(Errors.MediaContributor.ContributorsListCannotBeNull.Description); } [Fact] @@ -1671,7 +1671,7 @@ public class AddBookCommandValidatorTests TestValidationResult result = _validator.TestValidate(bookCommand); // Assert - result.ShouldHaveValidationErrorFor("Contributors[0].Name").WithErrorMessage(Errors.MediaContributor.ContributorNameCannotBeEmpty.Code); + result.ShouldHaveValidationErrorFor("Contributors[0].Name").WithErrorMessage(Errors.MediaContributor.ContributorNameCannotBeEmpty.Description); } [Fact] @@ -1685,7 +1685,7 @@ public class AddBookCommandValidatorTests TestValidationResult result = _validator.TestValidate(bookCommand); // Assert - result.ShouldHaveValidationErrorFor("Contributors[0].Name.DisplayName").WithErrorMessage(Errors.MediaContributor.ContributorDisplayNameMustBeMaximum100CharactersLong.Code); + result.ShouldHaveValidationErrorFor("Contributors[0].Name.DisplayName").WithErrorMessage(Errors.MediaContributor.ContributorDisplayNameMustBeMaximum100CharactersLong.Description); } [Fact] @@ -1699,7 +1699,7 @@ public class AddBookCommandValidatorTests TestValidationResult result = _validator.TestValidate(bookCommand); // Assert - result.ShouldHaveValidationErrorFor("Contributors[0].Name.DisplayName").WithErrorMessage(Errors.MediaContributor.ContributorDisplayNameCannotBeEmpty.Code); + result.ShouldHaveValidationErrorFor("Contributors[0].Name.DisplayName").WithErrorMessage(Errors.MediaContributor.ContributorDisplayNameCannotBeEmpty.Description); } [Fact] @@ -1713,7 +1713,7 @@ public class AddBookCommandValidatorTests TestValidationResult result = _validator.TestValidate(bookCommand); // Assert - result.ShouldHaveValidationErrorFor("Contributors[0].Name.LegalName").WithErrorMessage(Errors.MediaContributor.ContributorLegalNameMustBeMaximum100CharactersLong.Code); + result.ShouldHaveValidationErrorFor("Contributors[0].Name.LegalName").WithErrorMessage(Errors.MediaContributor.ContributorLegalNameMustBeMaximum100CharactersLong.Description); } [Fact] @@ -1727,7 +1727,7 @@ public class AddBookCommandValidatorTests TestValidationResult result = _validator.TestValidate(bookCommand); // Assert - result.ShouldHaveValidationErrorFor("Contributors[0].Role").WithErrorMessage(Errors.MediaContributor.ContributorRoleCannotBeNull.Code); + result.ShouldHaveValidationErrorFor("Contributors[0].Role").WithErrorMessage(Errors.MediaContributor.ContributorRoleCannotBeNull.Description); } [Fact] @@ -1741,7 +1741,7 @@ public class AddBookCommandValidatorTests TestValidationResult result = _validator.TestValidate(bookCommand); // Assert - result.ShouldHaveValidationErrorFor("Contributors[0].Role.Name").WithErrorMessage(Errors.MediaContributor.RoleNameCannotBeEmpty.Code); + result.ShouldHaveValidationErrorFor("Contributors[0].Role.Name").WithErrorMessage(Errors.MediaContributor.RoleNameCannotBeEmpty.Description); } [Fact] @@ -1755,7 +1755,7 @@ public class AddBookCommandValidatorTests TestValidationResult result = _validator.TestValidate(bookCommand); // Assert - result.ShouldHaveValidationErrorFor("Contributors[0].Role.Name").WithErrorMessage(Errors.MediaContributor.RoleNameMustBeMaximum50CharactersLong.Code); + result.ShouldHaveValidationErrorFor("Contributors[0].Role.Name").WithErrorMessage(Errors.MediaContributor.RoleNameMustBeMaximum50CharactersLong.Description); } [Fact] @@ -1769,7 +1769,7 @@ public class AddBookCommandValidatorTests TestValidationResult result = _validator.TestValidate(bookCommand); // Assert - result.ShouldHaveValidationErrorFor("Contributors[0].Role.Category").WithErrorMessage(Errors.MediaContributor.RoleCategoryCannotBeEmpty.Code); + result.ShouldHaveValidationErrorFor("Contributors[0].Role.Category").WithErrorMessage(Errors.MediaContributor.RoleCategoryCannotBeEmpty.Description); } [Fact] @@ -1783,7 +1783,7 @@ public class AddBookCommandValidatorTests TestValidationResult result = _validator.TestValidate(bookCommand); // Assert - result.ShouldHaveValidationErrorFor("Contributors[0].Role.Category").WithErrorMessage(Errors.MediaContributor.RoleCategoryMustBeMaximum50CharactersLong.Code); + result.ShouldHaveValidationErrorFor("Contributors[0].Role.Category").WithErrorMessage(Errors.MediaContributor.RoleCategoryMustBeMaximum50CharactersLong.Description); } [Fact] @@ -1797,7 +1797,7 @@ public class AddBookCommandValidatorTests TestValidationResult result = _validator.TestValidate(bookCommand); // Assert - result.ShouldHaveValidationErrorFor(x => x.Ratings).WithErrorMessage(Errors.Metadata.RatingsListCannotBeNull.Code); + result.ShouldHaveValidationErrorFor(x => x.Ratings).WithErrorMessage(Errors.Metadata.RatingsListCannotBeNull.Description); } [Fact] @@ -1811,7 +1811,7 @@ public class AddBookCommandValidatorTests TestValidationResult result = _validator.TestValidate(bookCommand); // Assert - result.ShouldHaveValidationErrorFor("Ratings[0].Value").WithErrorMessage(Errors.Metadata.RatingValueMustBePositive.Code); + result.ShouldHaveValidationErrorFor("Ratings[0].Value").WithErrorMessage(Errors.Metadata.RatingValueMustBePositive.Description); } [Fact] @@ -1825,7 +1825,7 @@ public class AddBookCommandValidatorTests TestValidationResult result = _validator.TestValidate(bookCommand); // Assert - result.ShouldHaveValidationErrorFor("Ratings[0].Value").WithErrorMessage(Errors.Metadata.RatingValueCannotBeGreaterThanMaxValue.Code); + result.ShouldHaveValidationErrorFor("Ratings[0].Value").WithErrorMessage(Errors.Metadata.RatingValueCannotBeGreaterThanMaxValue.Description); } [Fact] @@ -1839,7 +1839,7 @@ public class AddBookCommandValidatorTests TestValidationResult result = _validator.TestValidate(bookCommand); // Assert - result.ShouldHaveValidationErrorFor("Ratings[0].MaxValue").WithErrorMessage(Errors.Metadata.RatingMaxValueMustBePositive.Code); + result.ShouldHaveValidationErrorFor("Ratings[0].MaxValue").WithErrorMessage(Errors.Metadata.RatingMaxValueMustBePositive.Description); } [Fact] @@ -1853,7 +1853,7 @@ public class AddBookCommandValidatorTests TestValidationResult result = _validator.TestValidate(bookCommand); // Assert - result.ShouldHaveValidationErrorFor("Ratings[0].VoteCount").WithErrorMessage(Errors.Metadata.RatingVoteCountMustBePositive.Code); + result.ShouldHaveValidationErrorFor("Ratings[0].VoteCount").WithErrorMessage(Errors.Metadata.RatingVoteCountMustBePositive.Description); } [Fact] @@ -1886,6 +1886,6 @@ public class AddBookCommandValidatorTests TestValidationResult result = _validator.TestValidate(bookCommand); // Assert - result.ShouldNotHaveValidationErrorFor(x => x.Ratings[0].VoteCount); + result.ShouldNotHaveValidationErrorFor(x => x.Ratings![0].VoteCount); } } diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/WrittenContentLibrary/BooksLibrary/Books/Commands/AddBook/Fixtures/AddBookCommandFixture.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/WrittenContentLibrary/BooksLibrary/Books/Commands/AddBook/Fixtures/AddBookCommandFixture.cs index 31b46d05..4cf3c694 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/WrittenContentLibrary/BooksLibrary/Books/Commands/AddBook/Fixtures/AddBookCommandFixture.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/WrittenContentLibrary/BooksLibrary/Books/Commands/AddBook/Fixtures/AddBookCommandFixture.cs @@ -3,11 +3,11 @@ using AutoFixture; using Bogus; using Lumina.Application.Core.WrittenContentLibrary.BooksLibrary.Books.Commands.AddBook; using Lumina.Application.UnitTests.Common.Setup; +using Lumina.Contracts.Entities.Common; +using Lumina.Contracts.Entities.MediaContributors; +using Lumina.Contracts.Entities.WrittenContentLibrary; +using Lumina.Contracts.Entities.WrittenContentLibrary.BookLibrary; using Lumina.Contracts.Enums.BookLibrary; -using Lumina.Contracts.Models.Common; -using Lumina.Contracts.Models.MediaContributors; -using Lumina.Contracts.Models.WrittenContentLibrary; -using Lumina.Contracts.Models.WrittenContentLibrary.BookLibrary; using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; @@ -46,8 +46,8 @@ public class AddBookCommandFixture int releaseYear = _random.Next(2000, 2010); int reReleaseYear = _random.Next(2010, 2020); - ReleaseInfoModel releaseInfo = new Faker() - .CustomInstantiator(f => new ReleaseInfoModel( + ReleaseInfoEntity releaseInfo = new Faker() + .CustomInstantiator(f => new ReleaseInfoEntity( default, default, default, @@ -63,42 +63,42 @@ public class AddBookCommandFixture .RuleFor(x => x.ReleaseVersion, f => f.Random.String2(f.Random.Number(1, 50))) .Generate(); - Faker genre = new Faker() - .CustomInstantiator(f => new GenreModel( + Faker genre = new Faker() + .CustomInstantiator(f => new GenreEntity( default! )) .RuleFor(e => e.Name, f => f.Random.String2(f.Random.Number(1, 50))); - Faker tag = new Faker() - .CustomInstantiator(f => new TagModel( + Faker tag = new Faker() + .CustomInstantiator(f => new TagEntity( default! )) .RuleFor(e => e.Name, f => f.Random.String2(f.Random.Number(1, 50))); - Faker mediaContributorRole = new Faker() - .CustomInstantiator(f => new MediaContributorRoleModel( + Faker mediaContributorRole = new Faker() + .CustomInstantiator(f => new MediaContributorRoleEntity( default!, default! )) .RuleFor(e => e.Name, f => f.Random.String2(f.Random.Number(1, 50))) .RuleFor(e => e.Category, f => f.Random.String2(f.Random.Number(1, 50))); - Faker mediaContributorName = new Faker() - .CustomInstantiator(f => new MediaContributorNameModel( + Faker mediaContributorName = new Faker() + .CustomInstantiator(f => new MediaContributorNameEntity( default!, default! )) .RuleFor(e => e.DisplayName, f => f.Random.String2(f.Random.Number(1, 50))) .RuleFor(e => e.LegalName, f => f.Random.String2(f.Random.Number(1, 50))); - Faker mediaContributor = new Faker() - .CustomInstantiator(f => new MediaContributorModel( + Faker mediaContributor = new Faker() + .CustomInstantiator(f => new MediaContributorEntity( default!, default! )) .RuleFor(e => e.Name, mediaContributorName) .RuleFor(e => e.Role, mediaContributorRole); - Faker rating = new Faker() - .CustomInstantiator(f => new BookRatingModel( + Faker rating = new Faker() + .CustomInstantiator(f => new BookRatingEntity( default, default, default, @@ -109,8 +109,8 @@ public class AddBookCommandFixture .RuleFor(e => e.Source, _fixture.Create()) .RuleFor(e => e.VoteCount, _random.Next(1, 1000)); - Faker language = new Faker() - .CustomInstantiator(f => new LanguageInfoModel( + Faker language = new Faker() + .CustomInstantiator(f => new LanguageInfoEntity( default!, default!, default @@ -119,8 +119,8 @@ public class AddBookCommandFixture .RuleFor(e => e.LanguageCode, f => f.Random.String2(2)) .RuleFor(e => e.NativeName, f => f.Random.String2(f.Random.Number(1, 50))); - Faker originalLanguage = new Faker() - .CustomInstantiator(f => new LanguageInfoModel( + Faker originalLanguage = new Faker() + .CustomInstantiator(f => new LanguageInfoEntity( default!, default!, default @@ -129,8 +129,8 @@ public class AddBookCommandFixture .RuleFor(e => e.LanguageCode, f => f.Random.String2(2)) .RuleFor(e => e.NativeName, f => f.Random.String2(f.Random.Number(1, 50))); - Faker metadata = new Faker() - .CustomInstantiator(f => new WrittenContentMetadataModel( + Faker metadata = new Faker() + .CustomInstantiator(f => new WrittenContentMetadataEntity( default!, default, default, @@ -153,8 +153,8 @@ public class AddBookCommandFixture .RuleFor(x => x.Publisher, f => f.Random.String2(f.Random.Number(1, 100))) .RuleFor(x => x.PageCount, _random.Next(100, 300)); - Faker isbn = new Faker() - .CustomInstantiator(f => new IsbnModel( + Faker isbn = new Faker() + .CustomInstantiator(f => new IsbnEntity( default!, default )) @@ -171,7 +171,7 @@ public class AddBookCommandFixture int sum = 0; for (int i = 0; i < 12; i++) sum += (i % 2 == 0 ? 1 : 3) * int.Parse(isbn[i].ToString()); - int checkDigit = (10 - sum % 10) % 10; + int checkDigit = (10 - (sum % 10)) % 10; return $"{prefix}-{group[..1]}-{publisher}-{title}-{checkDigit}"; } else @@ -182,7 +182,7 @@ public class AddBookCommandFixture int sum = 0; for (int i = 0; i < 9; i++) sum += (10 - i) * digits[i]; - int checkDigit = (11 - sum % 11) % 11; + int checkDigit = (11 - (sum % 11)) % 11; string checkChar = checkDigit == 10 ? "X" : checkDigit.ToString(); return $"{digits[0]}-{digits[1]}{digits[2]}-{digits[3]}{digits[4]}{digits[5]}{digits[6]}{digits[7]}{digits[8]}-{checkChar}"; } @@ -276,7 +276,7 @@ public class AddBookCommandFixture int releaseYear = _random.Next(2000, 2010); int reReleaseYear = _random.Next(2010, 2020); - _fixture.Register(() => new ReleaseInfoModel( + _fixture.Register(() => new ReleaseInfoEntity( _faker.DateOnlyBetween(new DateOnly(releaseYear, 1, 1), new DateOnly(releaseYear, 12, 31)), releaseYear, _faker.DateOnlyBetween(new DateOnly(reReleaseYear, 1, 1), new DateOnly(reReleaseYear, 12, 31)), @@ -284,53 +284,53 @@ public class AddBookCommandFixture _fixture.Create()[2..], _fixture.Create())); - _fixture.Register(() => new GenreModel( + _fixture.Register(() => new GenreEntity( _fixture.Create() )); - _fixture.Register(() => new TagModel( + _fixture.Register(() => new TagEntity( _fixture.Create() )); - _fixture.Register(() => new LanguageInfoModel( + _fixture.Register(() => new LanguageInfoEntity( _fixture.Create(), _fixture.Create(), _fixture.Create() )); - _fixture.Register(() => new IsbnModel( + _fixture.Register(() => new IsbnEntity( _fixture.Create(), _fixture.Create() )); - _fixture.Register(() => new BookRatingModel( + _fixture.Register(() => new BookRatingEntity( _fixture.Create(), _fixture.Create(), _fixture.Create(), _fixture.Create() )); - _fixture.Register(() => new WrittenContentMetadataModel( + _fixture.Register(() => new WrittenContentMetadataEntity( _fixture.Create()[255..], LimitStringLength(_fixture.Create(), 255), LimitStringLength(_fixture.Create(), 2000), - _fixture.Create(), - _fixture.Create>(), - _fixture.Create>(), - _fixture.Create(), - _fixture.Create(), + _fixture.Create(), + _fixture.Create>(), + _fixture.Create>(), + _fixture.Create(), + _fixture.Create(), _fixture.Create(), _fixture.Create() )); - _fixture.Register(() => new BookSeriesModel( + _fixture.Register(() => new BookSeriesEntity( _fixture.Create() )); - _fixture.Register(() => new MediaContributorRoleModel( + _fixture.Register(() => new MediaContributorRoleEntity( _fixture.Create(), _fixture.Create() )); - _fixture.Register(() => new MediaContributorNameModel( + _fixture.Register(() => new MediaContributorNameEntity( _fixture.Create(), _fixture.Create() )); - _fixture.Register(() => new MediaContributorModel( - _fixture.Create(), - _fixture.Create() + _fixture.Register(() => new MediaContributorEntity( + _fixture.Create(), + _fixture.Create() )); } diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/WrittenContentLibrary/BooksLibrary/Books/Commands/AddBook/Fixtures/AddBookRequestFixture.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/WrittenContentLibrary/BooksLibrary/Books/Commands/AddBook/Fixtures/AddBookRequestFixture.cs new file mode 100644 index 00000000..9f67c57b --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/WrittenContentLibrary/BooksLibrary/Books/Commands/AddBook/Fixtures/AddBookRequestFixture.cs @@ -0,0 +1,274 @@ +#region ========================================================================= USING ===================================================================================== +using AutoFixture; +using Bogus; +using Lumina.Application.UnitTests.Common.Setup; +using Lumina.Contracts.Entities.Common; +using Lumina.Contracts.Entities.MediaContributors; +using Lumina.Contracts.Entities.WrittenContentLibrary; +using Lumina.Contracts.Entities.WrittenContentLibrary.BookLibrary; +using Lumina.Contracts.Enums.BookLibrary; +using Lumina.Contracts.Requests.WrittenContentLibrary.BookLibrary.Books; +using System; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Application.UnitTests.Core.WrittenContentLibrary.BooksLibrary.Books.Commands.AddBook.Fixtures; + +/// +/// Fixture class for the class. +/// +[ExcludeFromCodeCoverage] +public class AddBookRequestFixture +{ + private readonly Fixture _fixture; + private readonly Random _random = new(); + private readonly Faker _faker; + + /// + /// Initializes a new instance of the class. + /// + public AddBookRequestFixture() + { + _fixture = new Fixture(); + _fixture.Customizations.Add(new DateOnlySpecimenBuilder()); + _fixture.Customizations.Add(new NullableDateOnlySpecimenBuilder()); + _faker = new Faker(); + } + + /// + /// Creates a random valid request to add a book. + /// + /// The created request to add a book. + public AddBookRequest CreateRequestBook() + { + int releaseYear = _random.Next(2000, 2010); + int reReleaseYear = _random.Next(2010, 2020); + + ReleaseInfoEntity releaseInfo = new Faker() + .CustomInstantiator(f => new ReleaseInfoEntity( + default, + default, + default, + default, + default, + default + )) + .RuleFor(x => x.OriginalReleaseDate, _faker.DateOnlyBetween(new DateOnly(releaseYear, 1, 1), new DateOnly(releaseYear, 12, 31))) + .RuleFor(x => x.OriginalReleaseYear, releaseYear) + .RuleFor(x => x.ReReleaseDate, _faker.DateOnlyBetween(new DateOnly(reReleaseYear, 1, 1), new DateOnly(reReleaseYear, 12, 31))) + .RuleFor(x => x.ReReleaseYear, reReleaseYear) + .RuleFor(x => x.ReleaseCountry, f => f.Random.String2(2)) + .RuleFor(x => x.ReleaseVersion, f => f.Random.String2(f.Random.Number(1, 50))) + .Generate(); + + Faker genre = new Faker() + .CustomInstantiator(f => new GenreEntity( + default! + )) + .RuleFor(e => e.Name, f => f.Random.String2(f.Random.Number(1, 50))); + + Faker tag = new Faker() + .CustomInstantiator(f => new TagEntity( + default! + )) + .RuleFor(e => e.Name, f => f.Random.String2(f.Random.Number(1, 50))); + + Faker mediaContributorRole = new Faker() + .CustomInstantiator(f => new MediaContributorRoleEntity( + default!, + default! + )) + .RuleFor(e => e.Name, f => f.Random.String2(f.Random.Number(1, 50))) + .RuleFor(e => e.Category, f => f.Random.String2(f.Random.Number(1, 50))); + + Faker mediaContributorName = new Faker() + .CustomInstantiator(f => new MediaContributorNameEntity( + default!, + default! + )) + .RuleFor(e => e.DisplayName, f => f.Random.String2(f.Random.Number(1, 50))) + .RuleFor(e => e.LegalName, f => f.Random.String2(f.Random.Number(1, 50))); + + Faker mediaContributor = new Faker() + .CustomInstantiator(f => new MediaContributorEntity( + default!, + default! + )) + .RuleFor(e => e.Name, mediaContributorName) + .RuleFor(e => e.Role, mediaContributorRole); + + Faker rating = new Faker() + .CustomInstantiator(f => new BookRatingEntity( + default, + default, + default, + default + )) + .RuleFor(e => e.Value, _random.Next(1, 5)) + .RuleFor(e => e.MaxValue, 5) + .RuleFor(e => e.Source, _fixture.Create()) + .RuleFor(e => e.VoteCount, _random.Next(1, 1000)); + + Faker language = new Faker() + .CustomInstantiator(f => new LanguageInfoEntity( + default!, + default!, + default + )) + .RuleFor(e => e.LanguageName, f => f.Random.String2(f.Random.Number(1, 50))) + .RuleFor(e => e.LanguageCode, f => f.Random.String2(2)) + .RuleFor(e => e.NativeName, f => f.Random.String2(f.Random.Number(1, 50))); + + Faker originalLanguage = new Faker() + .CustomInstantiator(f => new LanguageInfoEntity( + default!, + default!, + default + )) + .RuleFor(e => e.LanguageName, f => f.Random.String2(f.Random.Number(1, 50))) + .RuleFor(e => e.LanguageCode, f => f.Random.String2(2)) + .RuleFor(e => e.NativeName, f => f.Random.String2(f.Random.Number(1, 50))); + + Faker metadata = new Faker() + .CustomInstantiator(f => new WrittenContentMetadataEntity( + default!, + default, + default, + default!, + default!, + default!, + default, + default, + default, + default + )) + .RuleFor(x => x.Title, f => f.Random.String2(f.Random.Number(1, 255))) + .RuleFor(x => x.OriginalTitle, f => f.Random.String2(f.Random.Number(1, 255))) + .RuleFor(x => x.Description, f => f.Random.String2(f.Random.Number(1, 2000))) + .RuleFor(x => x.ReleaseInfo, releaseInfo) + .RuleFor(p => p.Genres, f => genre.Generate(f.Random.Number(1, 5))) + .RuleFor(x => x.Tags, f => tag.Generate(f.Random.Number(1, 5))) + .RuleFor(x => x.Language, language) + .RuleFor(x => x.OriginalLanguage, originalLanguage) + .RuleFor(x => x.Publisher, f => f.Random.String2(f.Random.Number(1, 100))) + .RuleFor(x => x.PageCount, _random.Next(100, 300)); + + Faker isbn = new Faker() + .CustomInstantiator(f => new IsbnEntity( + default!, + default + )) + .RuleFor(i => i.Value, f => + { + bool isIsbn13 = f.Random.Bool(); + if (isIsbn13) + { + string prefix = f.Random.Bool() ? "978" : "979"; + string group = f.Random.Number(0, 99999).ToString().PadLeft(5, '0'); + string publisher = f.Random.Number(0, 999999).ToString().PadLeft(6, '0'); + string title = f.Random.Number(0, 99).ToString().PadLeft(2, '0'); + string isbn = $"{prefix}{group[..1]}{publisher}{title}"; + int sum = 0; + for (int i = 0; i < 12; i++) + sum += (i % 2 == 0 ? 1 : 3) * int.Parse(isbn[i].ToString()); + int checkDigit = (10 - (sum % 10)) % 10; + return $"{prefix}-{group[..1]}-{publisher}-{title}-{checkDigit}"; + } + else + { + int[] digits = new int[9]; + for (int i = 0; i < 9; i++) + digits[i] = f.Random.Number(0, 9); + int sum = 0; + for (int i = 0; i < 9; i++) + sum += (10 - i) * digits[i]; + int checkDigit = (11 - (sum % 11)) % 11; + string checkChar = checkDigit == 10 ? "X" : checkDigit.ToString(); + return $"{digits[0]}-{digits[1]}{digits[2]}-{digits[3]}{digits[4]}{digits[5]}{digits[6]}{digits[7]}{digits[8]}-{checkChar}"; + } + }) + .RuleFor(i => i.Format, (f, i) => i.Value!.Length > 13 ? IsbnFormat.Isbn13 : IsbnFormat.Isbn10); + + return new Faker() + .CustomInstantiator(f => new AddBookRequest( + default!, + default, + default, + default, + default, + default, + default, + default, + default, + default, + default, + default, + default, + default, + default!, + default!, + default! + )) + .RuleFor(x => x.Metadata, metadata) + .RuleFor(x => x.Format, _fixture.Create()) + .RuleFor(x => x.Edition, f => f.Random.String2(f.Random.Number(1, 50))) + .RuleFor(x => x.VolumeNumber, _random.Next(1, 3)) + .RuleFor(x => x.ASIN, f => f.Random.String2(10)) + .RuleFor(x => x.GoodreadsId, _random.Next(100000, 500000).ToString()) + .RuleFor(x => x.LCCN, f => + { + string letters = new(Enumerable.Range(0, f.Random.Number(0, 3)) + .Select(_ => f.Random.Char('a', 'z')) + .ToArray()); + string digits = f.Random.String2(f.Random.Number(8, 10), "0123456789"); + return letters + digits; + }) + .RuleFor(x => x.OCLCNumber, f => + { + string[] prefixes = ["ocm", "ocn", "on", "(OCoLC)"]; + string prefix = f.Random.ArrayElement(prefixes); + string number; + switch (prefix) + { + case "ocm": + number = f.Random.String2(8, "0123456789"); + break; + case "ocn": + number = f.Random.String2(f.Random.Number(9, 11), "0123456789"); + break; + case "on": + number = f.Random.String2(10, "0123456789"); + break; + case "(OCoLC)": + number = f.Random.String2(f.Random.Number(8, 10), "0123456789"); + break; + default: + number = f.Random.String2(f.Random.Number(8, 10), "0123456789"); + return number; + } + return prefix + number; + }) + .RuleFor(x => x.OpenLibraryId, f => + { + int firstDigit = f.Random.Number(1, 9); + string remainingDigits = f.Random.String2(f.Random.Number(0, 6), "0123456789"); + char suffix = f.Random.ArrayElement(new[] { 'A', 'M', 'W' }); + return $"OL{firstDigit}{remainingDigits}{suffix}"; + }) + .RuleFor(x => x.LibraryThingId, f => f.Random.String2(f.Random.Number(1, 50))) + .RuleFor(x => x.GoogleBooksId, f => + { + const string VALID_CHARS = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_"; + return new string(Enumerable.Repeat(VALID_CHARS, 12) + .Select(s => s[f.Random.Number(VALID_CHARS.Length - 1)]) + .ToArray()); + }) + .RuleFor(x => x.BarnesAndNobleId, f => f.Random.String2(10, "0123456789")) + .RuleFor(x => x.AppleBooksId, f => $"id{f.Random.Number(1, 999999)}") + .RuleFor(x => x.AppleBooksId, f => $"id{f.Random.Number(1, 999999)}") + .RuleFor(p => p.ISBNs, f => isbn.Generate(f.Random.Number(1, 5))) + .RuleFor(p => p.Ratings, f => rating.Generate(f.Random.Number(1, 5))) + .RuleFor(x => x.Contributors, f => mediaContributor.Generate(f.Random.Number(1, 5))); + } +} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/WrittenContentLibrary/BooksLibrary/Books/Commands/AddBook/Fixtures/BookEntityFixture.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/WrittenContentLibrary/BooksLibrary/Books/Commands/AddBook/Fixtures/BookEntityFixture.cs new file mode 100644 index 00000000..26d1a4f5 --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/WrittenContentLibrary/BooksLibrary/Books/Commands/AddBook/Fixtures/BookEntityFixture.cs @@ -0,0 +1,145 @@ +#region ========================================================================= USING ===================================================================================== +using AutoFixture; +using Bogus; +using Lumina.Application.UnitTests.Common.Setup; +using Lumina.Contracts.Entities.Common; +using Lumina.Contracts.Entities.WrittenContentLibrary.BookLibrary; +using Lumina.Contracts.Enums.BookLibrary; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Application.UnitTests.Core.WrittenContentLibrary.BooksLibrary.Books.Commands.AddBook.Fixtures; + +/// +/// Fixture class for the class. +/// +[ExcludeFromCodeCoverage] +public class BookEntityFixture +{ + private readonly Fixture _fixture; + private readonly Random _random = new(); + private readonly Faker _faker; + + /// + /// Initializes a new instance of the class. + /// + public BookEntityFixture() + { + _fixture = new Fixture(); + _fixture.Customizations.Add(new DateOnlySpecimenBuilder()); + _fixture.Customizations.Add(new NullableDateOnlySpecimenBuilder()); + _faker = new Faker(); + } + + /// + /// Creates a random valid book entity. + /// + /// The created book entity. + public BookEntity CreateBook() + { + int releaseYear = _random.Next(2000, 2010); + int reReleaseYear = _random.Next(2010, 2020); + + Faker genre = new Faker() + .CustomInstantiator(f => new GenreEntity( + default! + )) + .RuleFor(e => e.Name, f => f.Random.String2(f.Random.Number(1, 50))); + + Faker tag = new Faker() + .CustomInstantiator(f => new TagEntity( + default! + )) + .RuleFor(e => e.Name, f => f.Random.String2(f.Random.Number(1, 50))); + + Faker rating = new Faker() + .CustomInstantiator(f => new BookRatingEntity( + default, + default, + default, + default + )) + .RuleFor(e => e.Value, _random.Next(1, 5)) + .RuleFor(e => e.MaxValue, 5) + .RuleFor(e => e.Source, _fixture.Create()) + .RuleFor(e => e.VoteCount, _random.Next(1, 1000)); + + Faker isbn = new Faker() + .CustomInstantiator(f => new IsbnEntity( + default!, + default + )) + .RuleFor(i => i.Value, f => + { + bool isIsbn13 = f.Random.Bool(); + if (isIsbn13) + { + string prefix = f.Random.Bool() ? "978" : "979"; + string group = f.Random.Number(0, 99999).ToString().PadLeft(5, '0'); + string publisher = f.Random.Number(0, 999999).ToString().PadLeft(6, '0'); + string title = f.Random.Number(0, 99).ToString().PadLeft(2, '0'); + string isbn = $"{prefix}{group[..1]}{publisher}{title}"; + int sum = 0; + for (int i = 0; i < 12; i++) + sum += (i % 2 == 0 ? 1 : 3) * int.Parse(isbn[i].ToString()); + int checkDigit = (10 - (sum % 10)) % 10; + return $"{prefix}-{group[..1]}-{publisher}-{title}-{checkDigit}"; + } + else + { + int[] digits = new int[9]; + for (int i = 0; i < 9; i++) + digits[i] = f.Random.Number(0, 9); + int sum = 0; + for (int i = 0; i < 9; i++) + sum += (10 - i) * digits[i]; + int checkDigit = (11 - (sum % 11)) % 11; + string checkChar = checkDigit == 10 ? "X" : checkDigit.ToString(); + return $"{digits[0]}-{digits[1]}{digits[2]}-{digits[3]}{digits[4]}{digits[5]}{digits[6]}{digits[7]}{digits[8]}-{checkChar}"; + } + }) + .RuleFor(i => i.Format, (f, i) => i.Value!.Length > 13 ? IsbnFormat.Isbn13 : IsbnFormat.Isbn10); + + return new BookEntity + { + Id = Guid.NewGuid(), + Title = _faker.Random.String2(_faker.Random.Number(1, 255)), + OriginalTitle = _faker.Random.Bool() ? _faker.Random.String2(_faker.Random.Number(1, 255)) : null, + Description = _faker.Random.Bool() ? _faker.Random.String2(_faker.Random.Number(1, 2000)) : null, + OriginalReleaseDate = _faker.DateOnlyBetween(new DateOnly(releaseYear, 1, 1), new DateOnly(releaseYear, 12, 31)), + OriginalReleaseYear = releaseYear, + ReReleaseDate = _faker.DateOnlyBetween(new DateOnly(reReleaseYear, 1, 1), new DateOnly(reReleaseYear, 12, 31)), + ReReleaseYear = reReleaseYear, + ReleaseCountry = _faker.Random.String2(2), + ReleaseVersion = _faker.Random.Bool() ? _faker.Random.String2(_faker.Random.Number(1, 50)) : null, + LanguageCode = _faker.Random.String2(2), + LanguageName = _faker.Random.String2(_faker.Random.Number(1, 50)), + LanguageNativeName = _faker.Random.Bool() ? _faker.Random.String2(_faker.Random.Number(1, 50)) : null, + OriginalLanguageCode = _faker.Random.String2(2), + OriginalLanguageName = _faker.Random.String2(_faker.Random.Number(1, 50)), + OriginalLanguageNativeName = _faker.Random.Bool() ? _faker.Random.String2(_faker.Random.Number(1, 50)) : null, + Tags = new HashSet(tag.Generate(_faker.Random.Number(1, 5))), + Genres = new HashSet(genre.Generate(_faker.Random.Number(1, 5))), + Publisher = _faker.Random.Bool() ? _faker.Random.String2(_faker.Random.Number(1, 100)) : null, + PageCount = _random.Next(100, 1000), + Format = _faker.PickRandom(new[] { "Hardcover", "Paperback", "eBook", "Audiobook" }), + Edition = _faker.Random.Bool() ? _faker.Random.String2(_faker.Random.Number(1, 50)) : null, + VolumeNumber = _faker.Random.Bool() ? _random.Next(1, 20) : null, + ASIN = _faker.Random.String2(10), + GoodreadsId = _random.Next(100000, 500000).ToString(), + LCCN = _faker.Random.String2(_faker.Random.Number(8, 12)), + OCLCNumber = _faker.Random.String2(_faker.Random.Number(8, 12)), + OpenLibraryId = $"OL{_random.Next(1000000, 9999999)}M", + LibraryThingId = _faker.Random.String2(_faker.Random.Number(1, 50)), + GoogleBooksId = _faker.Random.String2(12), + BarnesAndNobleId = _faker.Random.String2(10), + AppleBooksId = $"id{_random.Next(1, 999999)}", + ISBNs = isbn.Generate(_faker.Random.Number(1, 5)), + Ratings = rating.Generate(_faker.Random.Number(1, 5)), + Created = DateTime.UtcNow, + Updated = _faker.Random.Bool() ? DateTime.UtcNow.AddDays(-_random.Next(1, 100)) : null + }; + } +} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/WrittenContentLibrary/BooksLibrary/Books/Commands/AddBook/Fixtures/DomainBookFixture.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/WrittenContentLibrary/BooksLibrary/Books/Commands/AddBook/Fixtures/DomainBookFixture.cs new file mode 100644 index 00000000..b1543e1e --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/WrittenContentLibrary/BooksLibrary/Books/Commands/AddBook/Fixtures/DomainBookFixture.cs @@ -0,0 +1,107 @@ +#region ========================================================================= USING ===================================================================================== +using AutoFixture; +using Lumina.Application.UnitTests.Common.Setup; +using Lumina.Contracts.Enums.BookLibrary; +using Lumina.Domain.Common.Primitives; +using Lumina.Domain.Common.ValueObjects.Metadata; +using Lumina.Domain.Core.Aggregates.MediaContributor.MediaContributorAggregate.ValueObjects; +using Lumina.Domain.Core.Aggregates.WrittenContentLibrary.BookLibraryAggregate; +using Lumina.Domain.Core.Aggregates.WrittenContentLibrary.BookLibraryAggregate.Entities; +using Lumina.Domain.Core.Aggregates.WrittenContentLibrary.BookLibraryAggregate.ValueObjects; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Application.UnitTests.Core.WrittenContentLibrary.BooksLibrary.Books.Commands.AddBook.Fixtures; + +/// +/// Fixture class for the domain entity. +/// +[ExcludeFromCodeCoverage] +public class DomainBookFixture +{ + private readonly Fixture _fixture; + + /// + /// Initializes a new instance of the class. + /// + public DomainBookFixture() + { + _fixture = new Fixture(); + _fixture.Customizations.Add(new DateOnlySpecimenBuilder()); + _fixture.Customizations.Add(new NullableDateOnlySpecimenBuilder()); + ConfigureCustomDomainTypes(); + } + + public Book CreateDomainBook() + { + return Book.Create( + _fixture.Create(), + _fixture.Create(), + _fixture.Create>(), + _fixture.Create>(), + _fixture.Create>(), + _fixture.Create>(), + _fixture.Create>(), + _fixture.Create>(), + _fixture.Create>(), + _fixture.Create>(), + _fixture.Create>(), + _fixture.Create>(), + _fixture.Create>(), + _fixture.Create>(), + _fixture.Create>(), + _fixture.Create>(), + _fixture.Create>() + ).Value; + } + + private void ConfigureCustomDomainTypes() + { + _fixture.Register(() => Optional.Some(_fixture.Create())); + _fixture.Register(() => Optional.Some(_fixture.Create())); + + _fixture.Register(() => ReleaseInfo.Create( + _fixture.Create>(), + _fixture.Create>(), + _fixture.Create>(), + _fixture.Create>(), + _fixture.Create>(), + _fixture.Create>() + ).Value); + + _fixture.Register(() => Genre.Create( + _fixture.Create() + ).Value); + + _fixture.Register(() => Tag.Create( + _fixture.Create() + ).Value); + + _fixture.Register(() => WrittenContentMetadata.Create( + _fixture.Create(), + _fixture.Create>(), + _fixture.Create>(), + _fixture.Create(), + _fixture.Create>(), + _fixture.Create>(), + _fixture.Create>(), + _fixture.Create>(), + _fixture.Create>(), + _fixture.Create>() + ).Value); + + _fixture.Register(() => Isbn.Create( + _fixture.Create(), + _fixture.Create() + ).Value); + + _fixture.Register(() => BookRating.Create( + _fixture.Create(), + _fixture.Create(), + _fixture.Create>(), + _fixture.Create>() + ).Value); + } +} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/WrittenContentLibrary/BooksLibrary/Common/Fixtures/BookRatingEntityFixture.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/WrittenContentLibrary/BooksLibrary/Common/Fixtures/BookRatingEntityFixture.cs new file mode 100644 index 00000000..b055f6c1 --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/WrittenContentLibrary/BooksLibrary/Common/Fixtures/BookRatingEntityFixture.cs @@ -0,0 +1,72 @@ +#region ========================================================================= USING ===================================================================================== +using AutoFixture; +using Bogus; +using Lumina.Contracts.Entities.WrittenContentLibrary.BookLibrary; +using Lumina.Contracts.Enums.BookLibrary; +using System; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Application.UnitTests.Core.WrittenContentLibrary.BooksLibrary.Common.Fixtures; + +/// +/// Fixture class for the . +/// +[ExcludeFromCodeCoverage] +public class BookRatingEntityFixture +{ + private readonly Fixture _fixture; + private readonly Random _random = new(); + private readonly Faker _faker; + + /// + /// Initializes a new instance of the class. + /// + public BookRatingEntityFixture() + { + _fixture = new Fixture(); + _faker = new Faker(); + } + + /// + /// Creates a complete book rating entity with all properties. + /// + /// The created book rating entity. + public BookRatingEntity CreateComplete() + { + return new BookRatingEntity( + _random.Next(1, 5), + 5, + _fixture.Create(), + _random.Next(1, 1000) + ); + } + + /// + /// Creates a minimal book rating entity with only required properties. + /// + /// The created book rating entity. + public BookRatingEntity CreateMinimal() + { + return new BookRatingEntity( + _random.Next(1, 5), + 5, + null, + null + ); + } + + /// + /// Creates an invalid book rating entity. + /// + /// The created invalid book rating entity. + public BookRatingEntity CreateInvalid() + { + return new BookRatingEntity( + 10, // invalid: value > maxValue + 5, + _fixture.Create(), + _random.Next(1, 1000) + ); + } +} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/WrittenContentLibrary/BooksLibrary/Common/Fixtures/BookRatingFixture.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/WrittenContentLibrary/BooksLibrary/Common/Fixtures/BookRatingFixture.cs new file mode 100644 index 00000000..6af30743 --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/WrittenContentLibrary/BooksLibrary/Common/Fixtures/BookRatingFixture.cs @@ -0,0 +1,85 @@ +#region ========================================================================= USING ===================================================================================== +using AutoFixture; +using Lumina.Contracts.Enums.BookLibrary; +using Lumina.Domain.Common.Primitives; +using Lumina.Domain.Core.Aggregates.WrittenContentLibrary.BookLibraryAggregate.ValueObjects; +using System; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Application.UnitTests.Core.WrittenContentLibrary.BooksLibrary.Common.Fixtures; + +/// +/// Fixture class for the domain entity. +/// +[ExcludeFromCodeCoverage] +public class BookRatingFixture +{ + private readonly Fixture _fixture; + private readonly Random _random = new(); + + /// + /// Initializes a new instance of the class. + /// + public BookRatingFixture() + { + _fixture = new Fixture(); + } + + /// + /// Creates a random valid book rating. + /// + /// The created book rating. + public BookRating CreateBookRating() + { + decimal maxValue = _random.Next(5, 10); + decimal value = _random.Next(1, (int)maxValue); + Optional source = Optional.Some(_fixture.Create()); + Optional voteCount = Optional.Some(_random.Next(1, 1000)); + + return BookRating.Create(value, maxValue, source, voteCount).Value; + } + + /// + /// Creates a random valid book rating with specific parameters. + /// + /// The rating value. + /// The maximum possible rating value. + /// The rating source. + /// The number of votes. + /// The created book rating. + public BookRating CreateBookRating( + decimal value, + decimal maxValue, + Optional source, + Optional voteCount) + { + return BookRating.Create(value, maxValue, source, voteCount).Value; + } + + /// + /// Creates a random valid book rating without a source. + /// + /// The created book rating. + public BookRating CreateBookRatingWithoutSource() + { + decimal maxValue = _random.Next(5, 10); + decimal value = _random.Next(1, (int)maxValue); + Optional voteCount = Optional.Some(_random.Next(1, 1000)); + + return BookRating.Create(value, maxValue, Optional.None(), voteCount).Value; + } + + /// + /// Creates a random valid book rating without vote count. + /// + /// The created book rating. + public BookRating CreateBookRatingWithoutVoteCount() + { + decimal maxValue = _random.Next(5, 10); + decimal value = _random.Next(1, (int)maxValue); + Optional source = Optional.Some(_fixture.Create()); + + return BookRating.Create(value, maxValue, source, Optional.None()).Value; + } +} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/WrittenContentLibrary/BooksLibrary/Common/Fixtures/IsbnEntityFixture.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/WrittenContentLibrary/BooksLibrary/Common/Fixtures/IsbnEntityFixture.cs new file mode 100644 index 00000000..ce0ca888 --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/WrittenContentLibrary/BooksLibrary/Common/Fixtures/IsbnEntityFixture.cs @@ -0,0 +1,98 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Contracts.Entities.WrittenContentLibrary.BookLibrary; +using Lumina.Contracts.Enums.BookLibrary; +using System; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Application.UnitTests.Core.WrittenContentLibrary.BooksLibrary.Common.Fixtures; + +/// +/// Fixture class for the . +/// +[ExcludeFromCodeCoverage] +public class IsbnEntityFixture +{ + private readonly Random _random = new(); + + /// + /// Creates a valid ISBN-10 entity. + /// + /// The created ISBN entity. + public IsbnEntity CreateIsbn10() + { + return new IsbnEntity( + GenerateValidIsbn10(), + IsbnFormat.Isbn10 + ); + } + + /// + /// Creates a valid ISBN-13 entity. + /// + /// The created ISBN entity. + public IsbnEntity CreateIsbn13() + { + return new IsbnEntity( + GenerateValidIsbn13(), + IsbnFormat.Isbn13 + ); + } + + /// + /// Creates an invalid ISBN entity. + /// + /// The created invalid ISBN entity. + public IsbnEntity CreateInvalid() + { + return new IsbnEntity( + "invalid-isbn", + IsbnFormat.Isbn13 + ); + } + + /// + /// Creates an ISBN entity without format. + /// + /// The created ISBN entity. + public IsbnEntity CreateWithoutFormat() + { + return new IsbnEntity( + GenerateValidIsbn13(), + null + ); + } + + private string GenerateValidIsbn10() + { + int[] digits = new int[9]; + for (int i = 0; i < 9; i++) + digits[i] = _random.Next(0, 10); + + int sum = 0; + for (int i = 0; i < 9; i++) + sum += (10 - i) * digits[i]; + + int checkDigit = (11 - (sum % 11)) % 11; + string checkChar = checkDigit == 10 ? "X" : checkDigit.ToString(); + + return $"{digits[0]}-{digits[1]}{digits[2]}-{digits[3]}{digits[4]}{digits[5]}{digits[6]}{digits[7]}{digits[8]}-{checkChar}"; + } + + private string GenerateValidIsbn13() + { + string prefix = _random.Next(2) == 0 ? "978" : "979"; + string group = _random.Next(0, 99999).ToString().PadLeft(5, '0'); + string publisher = _random.Next(0, 999999).ToString().PadLeft(6, '0'); + string title = _random.Next(0, 99).ToString().PadLeft(2, '0'); + + string isbn = $"{prefix}{group[..1]}{publisher}{title}"; + int sum = 0; + for (int i = 0; i < 12; i++) + sum += (i % 2 == 0 ? 1 : 3) * int.Parse(isbn[i].ToString()); + + int checkDigit = (10 - (sum % 10)) % 10; + + return $"{prefix}-{group[..1]}-{publisher}-{title}-{checkDigit}"; + } +} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/WrittenContentLibrary/BooksLibrary/Common/Fixtures/IsbnFixture.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/WrittenContentLibrary/BooksLibrary/Common/Fixtures/IsbnFixture.cs new file mode 100644 index 00000000..a62c1dde --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/WrittenContentLibrary/BooksLibrary/Common/Fixtures/IsbnFixture.cs @@ -0,0 +1,70 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Contracts.Enums.BookLibrary; +using Lumina.Domain.Core.Aggregates.WrittenContentLibrary.BookLibraryAggregate.ValueObjects; +using System; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Application.UnitTests.Core.WrittenContentLibrary.BooksLibrary.Common.Fixtures; + +/// +/// Fixture class for the domain entity. +/// +[ExcludeFromCodeCoverage] +public class IsbnFixture +{ + private readonly Random _random = new(); + + /// + /// Creates a valid ISBN-10. + /// + /// The created ISBN. + public Isbn CreateIsbn10() + { + string isbn = GenerateValidIsbn10(); + return Isbn.Create(isbn, IsbnFormat.Isbn10).Value; + } + + /// + /// Creates a valid ISBN-13. + /// + /// The created ISBN. + public Isbn CreateIsbn13() + { + string isbn = GenerateValidIsbn13(); + return Isbn.Create(isbn, IsbnFormat.Isbn13).Value; + } + + private string GenerateValidIsbn10() + { + int[] digits = new int[9]; + for (int i = 0; i < 9; i++) + digits[i] = _random.Next(0, 10); + + int sum = 0; + for (int i = 0; i < 9; i++) + sum += (10 - i) * digits[i]; + + int checkDigit = (11 - (sum % 11)) % 11; + string checkChar = checkDigit == 10 ? "X" : checkDigit.ToString(); + + return $"{digits[0]}-{digits[1]}{digits[2]}-{digits[3]}{digits[4]}{digits[5]}{digits[6]}{digits[7]}{digits[8]}-{checkChar}"; + } + + private string GenerateValidIsbn13() + { + string prefix = _random.Next(2) == 0 ? "978" : "979"; + string group = _random.Next(0, 99999).ToString().PadLeft(5, '0'); + string publisher = _random.Next(0, 999999).ToString().PadLeft(6, '0'); + string title = _random.Next(0, 99).ToString().PadLeft(2, '0'); + + string isbn = $"{prefix}{group[..1]}{publisher}{title}"; + int sum = 0; + for (int i = 0; i < 12; i++) + sum += (i % 2 == 0 ? 1 : 3) * int.Parse(isbn[i].ToString()); + + int checkDigit = (10 - (sum % 10)) % 10; + + return $"{prefix}-{group[..1]}-{publisher}-{title}-{checkDigit}"; + } +} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Lumina.Application.UnitTests.csproj b/tests/UnitTests/Lumina.Application.UnitTests/Lumina.Application.UnitTests.csproj index 3fbf85a6..be3baccd 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Lumina.Application.UnitTests.csproj +++ b/tests/UnitTests/Lumina.Application.UnitTests/Lumina.Application.UnitTests.csproj @@ -13,13 +13,19 @@ - - - - + + all + runtime; build; native; contentfiles; analyzers; buildtransitive + + + + - - + + + all + runtime; build; native; contentfiles; analyzers; buildtransitive + diff --git a/tests/UnitTests/Lumina.DataAccess.UnitTests/Common/DependencyInjection/DataAccessLayerServicesTests.cs b/tests/UnitTests/Lumina.DataAccess.UnitTests/Common/DependencyInjection/DataAccessLayerServicesTests.cs index dfd92280..c6f72763 100644 --- a/tests/UnitTests/Lumina.DataAccess.UnitTests/Common/DependencyInjection/DataAccessLayerServicesTests.cs +++ b/tests/UnitTests/Lumina.DataAccess.UnitTests/Common/DependencyInjection/DataAccessLayerServicesTests.cs @@ -1,6 +1,4 @@ -#region ========================================================================= USING ===================================================================================== -using AutoFixture; -using AutoFixture.AutoNSubstitute; +#region ========================================================================= USING ===================================================================================== using FluentAssertions; using Lumina.Application.Common.DataAccess.Repositories.Books; using Lumina.Application.Common.DataAccess.UoW; @@ -23,16 +21,6 @@ namespace Lumina.DataAccess.UnitTests.Common.DependencyInjection; [ExcludeFromCodeCoverage] public class DataAccessLayerServicesTests { - private readonly IFixture _fixture; - - /// - /// Initializes a new instance of the class. - /// - public DataAccessLayerServicesTests() - { - _fixture = new Fixture().Customize(new AutoNSubstituteCustomization()); - } - [Fact] public void AddDataAccessLayerServices_WhenBasePathExists_ShouldAddServices() { @@ -83,4 +71,4 @@ public class DataAccessLayerServicesTests IBookRepository? repository = serviceProvider.GetService(); repository.Should().NotBeNull(); } -} \ No newline at end of file +} diff --git a/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Repositories/Books/BookRepositoryTests.cs b/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Repositories/Books/BookRepositoryTests.cs index a3d1604d..a5c103f5 100644 --- a/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Repositories/Books/BookRepositoryTests.cs +++ b/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Repositories/Books/BookRepositoryTests.cs @@ -2,9 +2,9 @@ using EntityFrameworkCore.Testing.NSubstitute; using ErrorOr; using FluentAssertions; +using Lumina.Contracts.Entities.Common; +using Lumina.Contracts.Entities.WrittenContentLibrary.BookLibrary; using Lumina.Contracts.Enums.BookLibrary; -using Lumina.Contracts.Models.Common; -using Lumina.Contracts.Models.WrittenContentLibrary.BookLibrary; using Lumina.DataAccess.Core.Repositories.Books; using Lumina.DataAccess.Core.UoW; using Lumina.DataAccess.UnitTests.Core.Repositories.Books.Fixtures; @@ -44,7 +44,7 @@ public class BookRepositoryTests public async Task InsertAsync_WhenBookDoesNotExist_ShouldAddBookToContextAndReturnCreated() { // Arrange - BookModel bookModel = _bookModelFixture.CreateBookModel(); + BookEntity bookModel = _bookModelFixture.CreateBookModel(); // Act ErrorOr result = await _sut.InsertAsync(bookModel, CancellationToken.None); @@ -54,7 +54,7 @@ public class BookRepositoryTests result.Value.Should().Be(Result.Created); // Check if the book was added to the context's ChangeTracker - EntityEntry? addedBook = _mockContext.ChangeTracker.Entries() + EntityEntry? addedBook = _mockContext.ChangeTracker.Entries() .FirstOrDefault(e => e.State == EntityState.Added && e.Entity.Id == bookModel.Id); addedBook.Should().NotBeNull(); } @@ -63,7 +63,7 @@ public class BookRepositoryTests public async Task InsertAsync_WhenBookAlreadyExists_ShouldReturnError() { // Arrange - BookModel bookModel = _bookModelFixture.CreateBookModel(); + BookEntity bookModel = _bookModelFixture.CreateBookModel(); _mockContext.Books.Add(bookModel); await _mockContext.SaveChangesAsync(); @@ -74,18 +74,18 @@ public class BookRepositoryTests // Assert result.IsError.Should().BeTrue(); result.FirstError.Should().Be(Errors.WrittenContent.BookAlreadyExists); - _mockContext.ChangeTracker.Entries().Should().HaveCount(1); // Only the existing book should be in the context} + _mockContext.ChangeTracker.Entries().Should().HaveCount(1); // Only the existing book should be in the context} } [Fact] public async Task InsertAsync_WhenExistingTagsFound_ShouldReplaceTagsWithExistingOnes() { // Arrange - TagModel existingTag = new("Existing"); - _mockContext.Set().Add(existingTag); + TagEntity existingTag = new("Existing"); + _mockContext.Set().Add(existingTag); await _mockContext.SaveChangesAsync(); - BookModel bookModel = _bookModelFixture.CreateBookModel(); + BookEntity bookModel = _bookModelFixture.CreateBookModel(); bookModel.Tags = [new("Existing"), new("New")]; // Act @@ -95,10 +95,10 @@ public class BookRepositoryTests result.IsError.Should().BeFalse(); result.Value.Should().Be(Result.Created); - EntityEntry? addedBook = _mockContext.ChangeTracker.Entries() + EntityEntry? addedBook = _mockContext.ChangeTracker.Entries() .FirstOrDefault(e => e.State == EntityState.Added && e.Entity.Id == bookModel.Id); addedBook.Should().NotBeNull(); - BookModel addedBookEntity = addedBook!.Entity; + BookEntity addedBookEntity = addedBook!.Entity; addedBookEntity.Tags.Should().HaveCount(2); addedBookEntity.Tags.Should().Contain(t => t.Name == "Existing" && t == existingTag); addedBookEntity.Tags.Should().Contain(t => t.Name == "New" && t != existingTag); @@ -108,11 +108,11 @@ public class BookRepositoryTests public async Task InsertAsync_WhenExistingGenresFound_ShouldReplaceGenresWithExistingOnes() { // Arrange - GenreModel existingGenre = new("Existing"); - _mockContext.Set().Add(existingGenre); + GenreEntity existingGenre = new("Existing"); + _mockContext.Set().Add(existingGenre); await _mockContext.SaveChangesAsync(); - BookModel bookModel = _bookModelFixture.CreateBookModel(); + BookEntity bookModel = _bookModelFixture.CreateBookModel(); bookModel.Genres = [new("Existing"), new("New")]; // Act @@ -122,10 +122,10 @@ public class BookRepositoryTests result.IsError.Should().BeFalse(); result.Value.Should().Be(Result.Created); - EntityEntry? addedBook = _mockContext.ChangeTracker.Entries() + EntityEntry? addedBook = _mockContext.ChangeTracker.Entries() .FirstOrDefault(e => e.State == EntityState.Added && e.Entity.Id == bookModel.Id); addedBook.Should().NotBeNull(); - BookModel addedBookEntity = addedBook!.Entity; + BookEntity addedBookEntity = addedBook!.Entity; addedBookEntity.Genres.Should().HaveCount(2); addedBookEntity.Genres.Should().Contain(g => g.Name == "Existing" && g == existingGenre); addedBookEntity.Genres.Should().Contain(g => g.Name == "New" && g != existingGenre); @@ -135,7 +135,7 @@ public class BookRepositoryTests public async Task GetAllAsync_WhenCalled_ShouldReturnAllBooks() { // Arrange - List books = + List books = [ _bookModelFixture.CreateBookModel(), _bookModelFixture.CreateBookModel(), @@ -145,7 +145,7 @@ public class BookRepositoryTests await _mockContext.SaveChangesAsync(); // Act - ErrorOr> result = await _sut.GetAllAsync(CancellationToken.None); + ErrorOr> result = await _sut.GetAllAsync(CancellationToken.None); // Assert result.IsError.Should().BeFalse(); @@ -158,7 +158,7 @@ public class BookRepositoryTests public async Task GetAllAsync_WhenNoBooksExist_ShouldReturnEmptyList() { // Act - ErrorOr> result = await _sut.GetAllAsync(CancellationToken.None); + ErrorOr> result = await _sut.GetAllAsync(CancellationToken.None); // Assert result.IsError.Should().BeFalse(); @@ -170,21 +170,21 @@ public class BookRepositoryTests public async Task GetAllAsync_WhenCalled_ShouldIncludeRelatedEntities() { // Arrange - BookModel book = _bookModelFixture.CreateBookModel(); - book.Tags = [new TagModel("Tag1"), new TagModel("Tag2")]; - book.Genres = [new GenreModel("Genre1"), new GenreModel("Genre2")]; - book.ISBNs = [new IsbnModel("1234567890", IsbnFormat.Isbn10), new IsbnModel("1234567890123", IsbnFormat.Isbn13)]; + BookEntity book = _bookModelFixture.CreateBookModel(); + book.Tags = [new TagEntity("Tag1"), new TagEntity("Tag2")]; + book.Genres = [new GenreEntity("Genre1"), new GenreEntity("Genre2")]; + book.ISBNs = [new IsbnEntity("1234567890", IsbnFormat.Isbn10), new IsbnEntity("1234567890123", IsbnFormat.Isbn13)]; _mockContext.Books.Add(book); await _mockContext.SaveChangesAsync(); // Act - ErrorOr> result = await _sut.GetAllAsync(CancellationToken.None); + ErrorOr> result = await _sut.GetAllAsync(CancellationToken.None); // Assert result.IsError.Should().BeFalse(); result.Value.Should().NotBeNull(); result.Value.Should().HaveCount(1); - BookModel retrievedBook = result.Value.First(); + BookEntity retrievedBook = result.Value.First(); retrievedBook.Tags.Should().HaveCount(2); retrievedBook.Genres.Should().HaveCount(2); retrievedBook.ISBNs.Should().HaveCount(2); diff --git a/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Repositories/Books/Fixtures/BookModelFixture.cs b/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Repositories/Books/Fixtures/BookModelFixture.cs index 59d653c6..992d345f 100644 --- a/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Repositories/Books/Fixtures/BookModelFixture.cs +++ b/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Repositories/Books/Fixtures/BookModelFixture.cs @@ -1,9 +1,9 @@ #region ========================================================================= USING ===================================================================================== using AutoFixture; using Bogus; +using Lumina.Contracts.Entities.Common; +using Lumina.Contracts.Entities.WrittenContentLibrary.BookLibrary; using Lumina.Contracts.Enums.BookLibrary; -using Lumina.Contracts.Models.Common; -using Lumina.Contracts.Models.WrittenContentLibrary.BookLibrary; using Lumina.DataAccess.UnitTests.Common.Setup; using System; using System.Collections.Generic; @@ -14,7 +14,7 @@ using System.Linq; namespace Lumina.DataAccess.UnitTests.Core.Repositories.Books.Fixtures; /// -/// Fixture class for the class. +/// Fixture class for the class. /// [ExcludeFromCodeCoverage] public class BookModelFixture @@ -39,12 +39,12 @@ public class BookModelFixture /// Creates a random valid BookModel. /// /// The created BookModel. - public BookModel CreateBookModel() + public BookEntity CreateBookModel() { int releaseYear = _random.Next(2000, 2010); int reReleaseYear = _random.Next(2010, 2020); - return new Faker() + return new Faker() .RuleFor(x => x.Id, f => f.Random.Guid()) .RuleFor(x => x.Title, f => f.Random.String2(f.Random.Number(1, 255))) .RuleFor(x => x.OriginalTitle, f => f.Random.String2(f.Random.Number(1, 255))) @@ -61,8 +61,8 @@ public class BookModelFixture .RuleFor(x => x.OriginalLanguageCode, f => f.Random.String2(2)) .RuleFor(x => x.OriginalLanguageName, f => f.Random.String2(f.Random.Number(1, 50))) .RuleFor(x => x.OriginalLanguageNativeName, f => f.Random.String2(f.Random.Number(1, 50))) - .RuleFor(x => x.Tags, f => new HashSet(CreateTags(f.Random.Number(1, 5)))) - .RuleFor(x => x.Genres, f => new HashSet(CreateGenres(f.Random.Number(1, 5)))) + .RuleFor(x => x.Tags, f => new HashSet(CreateTags(f.Random.Number(1, 5)))) + .RuleFor(x => x.Genres, f => new HashSet(CreateGenres(f.Random.Number(1, 5)))) .RuleFor(x => x.Publisher, f => f.Random.String2(f.Random.Number(1, 100))) .RuleFor(x => x.PageCount, _random.Next(100, 300)) .RuleFor(x => x.Format, f => f.PickRandom().ToString()) @@ -84,17 +84,17 @@ public class BookModelFixture .Generate(); } - private List CreateTags(int count) + private static List CreateTags(int count) { - return new Faker() - .CustomInstantiator(f => new TagModel(f.Random.String2(f.Random.Number(1, 50)))) + return new Faker() + .CustomInstantiator(f => new TagEntity(f.Random.String2(f.Random.Number(1, 50)))) .Generate(count); } - private List CreateGenres(int count) + private static List CreateGenres(int count) { - return new Faker() - .CustomInstantiator(f => new GenreModel(f.Random.String2(f.Random.Number(1, 50)))) + return new Faker() + .CustomInstantiator(f => new GenreEntity(f.Random.String2(f.Random.Number(1, 50)))) .Generate(count); } @@ -138,14 +138,14 @@ public class BookModelFixture .ToArray()); } - private List CreateIsbns(int count) + private static List CreateIsbns(int count) { - return new Faker() - .CustomInstantiator(f => new IsbnModel(CreateIsbn(f), f.PickRandom())) + return new Faker() + .CustomInstantiator(f => new IsbnEntity(CreateIsbn(f), f.PickRandom())) .Generate(count); } - private string CreateIsbn(Faker f) + private static string CreateIsbn(Faker f) { bool isIsbn13 = f.Random.Bool(); if (isIsbn13) @@ -175,10 +175,10 @@ public class BookModelFixture } } - private List CreateBookRatings(int count) + private static List CreateBookRatings(int count) { - return new Faker() - .CustomInstantiator(f => new BookRatingModel( + return new Faker() + .CustomInstantiator(f => new BookRatingEntity( f.Random.Decimal(1, 5), 5, f.PickRandom(), @@ -189,10 +189,10 @@ public class BookModelFixture private void ConfigureCustomTypes() { - _fixture.Register(() => new TagModel(_fixture.Create())); - _fixture.Register(() => new GenreModel(_fixture.Create())); - _fixture.Register(() => new IsbnModel(_fixture.Create(), _fixture.Create())); - _fixture.Register(() => new BookRatingModel( + _fixture.Register(() => new TagEntity(_fixture.Create())); + _fixture.Register(() => new GenreEntity(_fixture.Create())); + _fixture.Register(() => new IsbnEntity(_fixture.Create(), _fixture.Create())); + _fixture.Register(() => new BookRatingEntity( _fixture.Create(), _fixture.Create(), _fixture.Create(), diff --git a/tests/UnitTests/Lumina.DataAccess.UnitTests/Lumina.DataAccess.UnitTests.csproj b/tests/UnitTests/Lumina.DataAccess.UnitTests/Lumina.DataAccess.UnitTests.csproj index 73227087..9df609a8 100644 --- a/tests/UnitTests/Lumina.DataAccess.UnitTests/Lumina.DataAccess.UnitTests.csproj +++ b/tests/UnitTests/Lumina.DataAccess.UnitTests/Lumina.DataAccess.UnitTests.csproj @@ -13,15 +13,21 @@ - - - - + + all + runtime; build; native; contentfiles; analyzers; buildtransitive + + + + - + - - + + + all + runtime; build; native; contentfiles; analyzers; buildtransitive + diff --git a/tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/FileManagementAggregate/Entities/DirectoryTests.cs b/tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/FileSystemManagementAggregate/Entities/DirectoryTests.cs similarity index 89% rename from tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/FileManagementAggregate/Entities/DirectoryTests.cs rename to tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/FileSystemManagementAggregate/Entities/DirectoryTests.cs index 6c4a7959..e1fc5b52 100644 --- a/tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/FileManagementAggregate/Entities/DirectoryTests.cs +++ b/tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/FileSystemManagementAggregate/Entities/DirectoryTests.cs @@ -2,17 +2,17 @@ using ErrorOr; using FluentAssertions; using Lumina.Contracts.Enums.FileSystem; +using Lumina.Domain.Common.Errors; using Lumina.Domain.Common.Primitives; -using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.Entities; +using Lumina.Domain.Core.Aggregates.FileSystemManagement.FileSystemManagementAggregate; +using Lumina.Domain.Core.Aggregates.FileSystemManagement.FileSystemManagementAggregate.Entities; +using Lumina.Domain.Core.Aggregates.FileSystemManagement.FileSystemManagementAggregate.ValueObjects; +using Lumina.Domain.UnitTests.Core.Aggregates.FileSystemManagementAggregate.Fixtures; using System; using System.Diagnostics.CodeAnalysis; -using Lumina.Domain.Common.Errors; -using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.ValueObjects; -using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate; -using Lumina.Domain.UnitTests.Core.Aggregates.FileManagementAggregate.Fixtures; #endregion -namespace Lumina.Domain.UnitTests.Core.Aggregates.FileManagementAggregate.Entities; +namespace Lumina.Domain.UnitTests.Core.Aggregates.FileSystemManagementAggregate.Entities; /// /// Contains unit tests for the class. @@ -55,7 +55,7 @@ public class DirectoryTests // Assert result.IsError.Should().BeTrue(); - result.FirstError.Should().Be(Errors.FileManagement.InvalidPath); + result.FirstError.Should().Be(Errors.FileSystemManagement.InvalidPath); } [Fact] diff --git a/tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/FileManagementAggregate/Entities/FileTests.cs b/tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/FileSystemManagementAggregate/Entities/FileTests.cs similarity index 91% rename from tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/FileManagementAggregate/Entities/FileTests.cs rename to tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/FileSystemManagementAggregate/Entities/FileTests.cs index 7b0a2597..e64d2512 100644 --- a/tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/FileManagementAggregate/Entities/FileTests.cs +++ b/tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/FileSystemManagementAggregate/Entities/FileTests.cs @@ -4,13 +4,13 @@ using FluentAssertions; using Lumina.Contracts.Enums.FileSystem; using Lumina.Domain.Common.Errors; using Lumina.Domain.Common.Primitives; -using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.Entities; -using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.ValueObjects; +using Lumina.Domain.Core.Aggregates.FileSystemManagement.FileSystemManagementAggregate.Entities; +using Lumina.Domain.Core.Aggregates.FileSystemManagement.FileSystemManagementAggregate.ValueObjects; using System; using System.Diagnostics.CodeAnalysis; #endregion -namespace Lumina.Domain.UnitTests.Core.Aggregates.FileManagementAggregate.Entities; +namespace Lumina.Domain.UnitTests.Core.Aggregates.FileSystemManagementAggregate.Entities; /// /// Contains unit tests for the class. @@ -56,7 +56,7 @@ public class FileTests // Assert result.IsError.Should().BeTrue(); - result.FirstError.Should().Be(Errors.FileManagement.InvalidPath); + result.FirstError.Should().Be(Errors.FileSystemManagement.InvalidPath); } [Fact] @@ -150,7 +150,7 @@ public class FileTests // Assert result.IsError.Should().BeTrue(); - result.FirstError.Should().Be(Errors.FileManagement.NameCannotBeEmpty); + result.FirstError.Should().Be(Errors.FileSystemManagement.NameCannotBeEmpty); file.Name.Should().Be("file.txt"); } } diff --git a/tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/FileManagementAggregate/Entities/Fixtures/DirectoryFixture.cs b/tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/FileSystemManagementAggregate/Entities/Fixtures/DirectoryFixture.cs similarity index 94% rename from tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/FileManagementAggregate/Entities/Fixtures/DirectoryFixture.cs rename to tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/FileSystemManagementAggregate/Entities/Fixtures/DirectoryFixture.cs index cb9cf9d5..c575a9b6 100644 --- a/tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/FileManagementAggregate/Entities/Fixtures/DirectoryFixture.cs +++ b/tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/FileSystemManagementAggregate/Entities/Fixtures/DirectoryFixture.cs @@ -3,15 +3,15 @@ using Bogus; using ErrorOr; using Lumina.Contracts.Enums.FileSystem; using Lumina.Domain.Common.Primitives; -using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate; -using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.Entities; +using Lumina.Domain.Core.Aggregates.FileSystemManagement.FileSystemManagementAggregate; +using Lumina.Domain.Core.Aggregates.FileSystemManagement.FileSystemManagementAggregate.Entities; using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Linq; #endregion -namespace Lumina.Domain.UnitTests.Core.Aggregates.FileManagementAggregate.Entities.Fixtures; +namespace Lumina.Domain.UnitTests.Core.Aggregates.FileSystemManagementAggregate.Entities.Fixtures; /// /// Fixture class for the class. diff --git a/tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/FileManagementAggregate/Entities/Fixtures/FileFixture.cs b/tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/FileSystemManagementAggregate/Entities/Fixtures/FileFixture.cs similarity index 93% rename from tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/FileManagementAggregate/Entities/Fixtures/FileFixture.cs rename to tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/FileSystemManagementAggregate/Entities/Fixtures/FileFixture.cs index 361e9fef..33708170 100644 --- a/tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/FileManagementAggregate/Entities/Fixtures/FileFixture.cs +++ b/tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/FileSystemManagementAggregate/Entities/Fixtures/FileFixture.cs @@ -3,14 +3,14 @@ using Bogus; using ErrorOr; using Lumina.Contracts.Enums.FileSystem; using Lumina.Domain.Common.Primitives; -using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.Entities; +using Lumina.Domain.Core.Aggregates.FileSystemManagement.FileSystemManagementAggregate.Entities; using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Linq; #endregion -namespace Lumina.Domain.UnitTests.Core.Aggregates.FileManagementAggregate.Entities.Fixtures; +namespace Lumina.Domain.UnitTests.Core.Aggregates.FileSystemManagementAggregate.Entities.Fixtures; /// /// Fixture class for the class. diff --git a/tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/FileManagementAggregate/Entities/UnixRootItemTests.cs b/tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/FileSystemManagementAggregate/Entities/UnixRootItemTests.cs similarity index 90% rename from tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/FileManagementAggregate/Entities/UnixRootItemTests.cs rename to tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/FileSystemManagementAggregate/Entities/UnixRootItemTests.cs index 6673132d..17656f13 100644 --- a/tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/FileManagementAggregate/Entities/UnixRootItemTests.cs +++ b/tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/FileSystemManagementAggregate/Entities/UnixRootItemTests.cs @@ -3,13 +3,13 @@ using ErrorOr; using FluentAssertions; using Lumina.Contracts.Enums.FileSystem; using Lumina.Domain.Common.Errors; -using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate; -using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.Entities; +using Lumina.Domain.Core.Aggregates.FileSystemManagement.FileSystemManagementAggregate; +using Lumina.Domain.Core.Aggregates.FileSystemManagement.FileSystemManagementAggregate.Entities; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; #endregion -namespace Lumina.Domain.UnitTests.Core.Aggregates.FileManagementAggregate.Entities; +namespace Lumina.Domain.UnitTests.Core.Aggregates.FileSystemManagementAggregate.Entities; /// /// Contains unit tests for the class. @@ -92,13 +92,13 @@ public class UnixRootItemTests ErrorOr createResult = UnixRootItem.Create(); createResult.IsError.Should().BeFalse(); UnixRootItem unixRootItem = createResult.Value; - + // Act ErrorOr result = unixRootItem.SetParent(null!); // Assert result.IsError.Should().BeTrue(); - result.FirstError.Should().Be(Errors.FileManagement.ParentNodeCannotBeNull); + result.FirstError.Should().Be(Errors.FileSystemManagement.ParentNodeCannotBeNull); unixRootItem.Parent.HasValue.Should().BeFalse(); } } diff --git a/tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/FileManagementAggregate/Entities/WindowsRootItemTests.cs b/tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/FileSystemManagementAggregate/Entities/WindowsRootItemTests.cs similarity index 89% rename from tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/FileManagementAggregate/Entities/WindowsRootItemTests.cs rename to tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/FileSystemManagementAggregate/Entities/WindowsRootItemTests.cs index ba5c708e..e5bf5b25 100644 --- a/tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/FileManagementAggregate/Entities/WindowsRootItemTests.cs +++ b/tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/FileSystemManagementAggregate/Entities/WindowsRootItemTests.cs @@ -3,14 +3,14 @@ using ErrorOr; using FluentAssertions; using Lumina.Contracts.Enums.FileSystem; using Lumina.Domain.Common.Errors; -using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate; -using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.Entities; -using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.ValueObjects; +using Lumina.Domain.Core.Aggregates.FileSystemManagement.FileSystemManagementAggregate; +using Lumina.Domain.Core.Aggregates.FileSystemManagement.FileSystemManagementAggregate.Entities; +using Lumina.Domain.Core.Aggregates.FileSystemManagement.FileSystemManagementAggregate.ValueObjects; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; #endregion -namespace Lumina.Domain.UnitTests.Core.Aggregates.FileManagementAggregate.Entities; +namespace Lumina.Domain.UnitTests.Core.Aggregates.FileSystemManagementAggregate.Entities; /// /// Contains unit tests for the class. @@ -50,7 +50,7 @@ public class WindowsRootItemTests // Assert result.IsError.Should().BeTrue(); - result.FirstError.Should().Be(Errors.FileManagement.InvalidPath); + result.FirstError.Should().Be(Errors.FileSystemManagement.InvalidPath); } [Fact] @@ -140,7 +140,7 @@ public class WindowsRootItemTests // Assert result.IsError.Should().BeTrue(); - result.FirstError.Should().Be(Errors.FileManagement.ParentNodeCannotBeNull); + result.FirstError.Should().Be(Errors.FileSystemManagement.ParentNodeCannotBeNull); windowsRootItem.Parent.HasValue.Should().BeFalse(); } } diff --git a/tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/FileManagementAggregate/FileSystemItemTests.cs b/tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/FileSystemManagementAggregate/FileSystemItemTests.cs similarity index 90% rename from tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/FileManagementAggregate/FileSystemItemTests.cs rename to tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/FileSystemManagementAggregate/FileSystemItemTests.cs index d833b891..37b768a1 100644 --- a/tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/FileManagementAggregate/FileSystemItemTests.cs +++ b/tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/FileSystemManagementAggregate/FileSystemItemTests.cs @@ -6,15 +6,14 @@ using FluentAssertions; using Lumina.Contracts.Enums.FileSystem; using Lumina.Domain.Common.Errors; using Lumina.Domain.Common.Primitives; -using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate; -using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.ValueObjects; -using Lumina.Domain.UnitTests.Core.Aggregates.FileManagementAggregate.Fixtures; -using Lumina.Domain.UnitTests.Core.Aggregates.FileManagementAggregate.ValueObjects.Fixtures; +using Lumina.Domain.Core.Aggregates.FileSystemManagement.FileSystemManagementAggregate; +using Lumina.Domain.Core.Aggregates.FileSystemManagement.FileSystemManagementAggregate.ValueObjects; +using Lumina.Domain.UnitTests.Core.Aggregates.FileSystemManagementAggregate.Fixtures; +using Lumina.Domain.UnitTests.Core.Aggregates.FileSystemManagementAggregate.ValueObjects.Fixtures; using System.Diagnostics.CodeAnalysis; #endregion - -namespace Lumina.Domain.UnitTests.Core.Aggregates.FileManagementAggregate; +namespace Lumina.Domain.UnitTests.Core.Aggregates.FileSystemManagementAggregate; /// /// Contains unit tests for the class. @@ -96,7 +95,7 @@ public class FileSystemItemTests // Assert result.IsError.Should().BeTrue(); - result.FirstError.Should().Be(Errors.FileManagement.ParentNodeCannotBeNull); + result.FirstError.Should().Be(Errors.FileSystemManagement.ParentNodeCannotBeNull); item.Parent.Should().Be(Optional.None()); } diff --git a/tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/FileManagementAggregate/Fixtures/FileSystemItemFixture.cs b/tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/FileSystemManagementAggregate/Fixtures/FileSystemItemFixture.cs similarity index 77% rename from tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/FileManagementAggregate/Fixtures/FileSystemItemFixture.cs rename to tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/FileSystemManagementAggregate/Fixtures/FileSystemItemFixture.cs index 7d30ac75..84dc1c62 100644 --- a/tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/FileManagementAggregate/Fixtures/FileSystemItemFixture.cs +++ b/tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/FileSystemManagementAggregate/Fixtures/FileSystemItemFixture.cs @@ -1,11 +1,11 @@ #region ========================================================================= USING ===================================================================================== using Lumina.Contracts.Enums.FileSystem; -using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate; -using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.ValueObjects; +using Lumina.Domain.Core.Aggregates.FileSystemManagement.FileSystemManagementAggregate; +using Lumina.Domain.Core.Aggregates.FileSystemManagement.FileSystemManagementAggregate.ValueObjects; using System.Diagnostics.CodeAnalysis; #endregion -namespace Lumina.Domain.UnitTests.Core.Aggregates.FileManagementAggregate.Fixtures; +namespace Lumina.Domain.UnitTests.Core.Aggregates.FileSystemManagementAggregate.Fixtures; /// /// Fixture class for the class. diff --git a/tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/FileManagementAggregate/Services/DirectoryProviderServiceTests.cs b/tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/FileSystemManagementAggregate/Services/DirectoryProviderServiceTests.cs similarity index 96% rename from tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/FileManagementAggregate/Services/DirectoryProviderServiceTests.cs rename to tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/FileSystemManagementAggregate/Services/DirectoryProviderServiceTests.cs index cdd02283..9216a582 100644 --- a/tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/FileManagementAggregate/Services/DirectoryProviderServiceTests.cs +++ b/tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/FileSystemManagementAggregate/Services/DirectoryProviderServiceTests.cs @@ -6,9 +6,9 @@ using FluentAssertions; using Lumina.Contracts.Enums.FileSystem; using Lumina.Domain.Common.Errors; using Lumina.Domain.Common.Primitives; -using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.Services; -using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.ValueObjects; -using Lumina.Domain.UnitTests.Core.Aggregates.FileManagementAggregate.ValueObjects.Fixtures; +using Lumina.Domain.Core.Aggregates.FileSystemManagement.FileSystemManagementAggregate.Services; +using Lumina.Domain.Core.Aggregates.FileSystemManagement.FileSystemManagementAggregate.ValueObjects; +using Lumina.Domain.UnitTests.Core.Aggregates.FileSystemManagementAggregate.ValueObjects.Fixtures; using NSubstitute; using NSubstitute.ExceptionExtensions; using System; @@ -22,7 +22,7 @@ using System.Text; #endregion -namespace Lumina.Domain.UnitTests.Core.Aggregates.FileManagementAggregate.Services; +namespace Lumina.Domain.UnitTests.Core.Aggregates.FileSystemManagementAggregate.Services; /// /// Contains unit tests for the class. @@ -174,16 +174,16 @@ public class DirectoryProviderServiceTests { // Arrange FileSystemPathId path = _fileSystemPathIdFixture.CreateFileSystemPathId(); - string[] subdirectories = s_isLinux - ? new[] { "/C", "/A", "/B" } - : new[] { @"C:\C", @"C:\A", @"C:\B" }; + string[] subdirectories = s_isLinux + ? ["/C", "/A", "/B"] + : [@"C:\C", @"C:\A", @"C:\B"]; _mockFileSystemPermissionsService.CanAccessPath(path, FileAccessMode.ListDirectory, false).Returns(true); _mockFileSystem.Directory.GetDirectories(path.Path).Returns(subdirectories); _mockFileSystem.Path.DirectorySeparatorChar.Returns(_dirSeparator); _mockFileSystem.File.GetAttributes(Arg.Any()).Returns(FileAttributes.Directory); - string[] expectedPaths = s_isLinux - ? new[] { "/A/", "/B/", "/C/" } - : new[] { @"C:\A\", @"C:\B\", @"C:\C\" }; + string[] expectedPaths = s_isLinux + ? ["/A/", "/B/", "/C/"] + : [@"C:\A\", @"C:\B\", @"C:\C\"]; // Act ErrorOr> result = _sut.GetSubdirectoryPaths(path, false); @@ -243,8 +243,8 @@ public class DirectoryProviderServiceTests public void GetFileName_WhenPathIsValid_ShouldReturnFileName() { // Arrange - string fullPath = s_isLinux - ? "/folder/subfolder/file.txt" + string fullPath = s_isLinux + ? "/folder/subfolder/file.txt" : @"C:\folder\subfolder\file.txt"; FileSystemPathId path = _fileSystemPathIdFixture.CreateFileSystemPathId(fullPath); _mockFileSystem.Path.GetFileName(fullPath).Returns("file.txt"); @@ -261,8 +261,8 @@ public class DirectoryProviderServiceTests public void GetFileName_WhenPathEndsWithDirectorySeparator_ShouldReturnLastSegment() { // Arrange - string fullPath = s_isLinux - ? "/folder/subfolder/" + string fullPath = s_isLinux + ? "/folder/subfolder/" : @"C:\folder\subfolder\"; FileSystemPathId path = _fileSystemPathIdFixture.CreateFileSystemPathId(fullPath); _mockFileSystem.Path.GetFileName(fullPath[..^1]).Returns("subfolder"); @@ -280,8 +280,8 @@ public class DirectoryProviderServiceTests public void GetFileName_WhenPathIsRoot_ShouldReturnEmptyString() { // Arrange - string fullPath = s_isLinux - ? "/C/" + string fullPath = s_isLinux + ? "/C/" : @"/"; FileSystemPathId path = _fileSystemPathIdFixture.CreateFileSystemPathId(fullPath); _mockFileSystem.Path.GetFileName(fullPath[..^1]).Returns(string.Empty); @@ -367,8 +367,8 @@ public class DirectoryProviderServiceTests // Arrange FileSystemPathId parentPath = _fileSystemPathIdFixture.CreateFileSystemPathId(@"C:\Parent"); string directoryName = "NewDirectory"; - string fullPath = s_isLinux - ? "/Parent/NewDirectory" + string fullPath = s_isLinux + ? "/Parent/NewDirectory" : @"C:\Parent\NewDirectory"; _mockFileSystemPermissionsService.CanAccessPath(parentPath, FileAccessMode.Write, false).Returns(true); @@ -484,7 +484,7 @@ public class DirectoryProviderServiceTests // Assert result.IsError.Should().BeTrue(); - result.FirstError.Should().Be(Errors.FileManagement.DirectoryNotFound); + result.FirstError.Should().Be(Errors.FileSystemManagement.DirectoryNotFound); } [Fact] @@ -493,8 +493,8 @@ public class DirectoryProviderServiceTests // Arrange FileSystemPathId sourcePath = _fileSystemPathIdFixture.CreateFileSystemPathId(_pathSource); FileSystemPathId destinationPath = _fileSystemPathIdFixture.CreateFileSystemPathId(_pathDestination); - string expectedNewDirectoryPath = s_isLinux - ? "/Destination - Copy (1)" + string expectedNewDirectoryPath = s_isLinux + ? "/Destination - Copy (1)" : @"C:\Destination - Copy (1)"; bool overrideExisting = false; @@ -528,13 +528,14 @@ public class DirectoryProviderServiceTests FileSystemPathId sourcePath = _fileSystemPathIdFixture.CreateFileSystemPathId(_pathSource); FileSystemPathId destinationPath = _fileSystemPathIdFixture.CreateFileSystemPathId(_pathDestination); bool overrideExisting = true; - - + + // ensure all relevant directories exist _mockFileSystem.Directory.Exists(_pathSource).Returns(true); _mockFileSystem.Directory.Exists(_pathSourceSubDir).Returns(true); _mockFileSystem.Directory.Exists(_pathDestination).Returns(false); - _mockFileSystem.Directory.CreateDirectory(Arg.Any()).Returns(callInfo => { + _mockFileSystem.Directory.CreateDirectory(Arg.Any()).Returns(callInfo => + { IDirectoryInfo mockDirInfo = Substitute.For(); mockDirInfo.FullName.Returns(callInfo.Arg()); return mockDirInfo; @@ -591,7 +592,7 @@ public class DirectoryProviderServiceTests // Assert result.IsError.Should().BeTrue(); - result.FirstError.Should().Be(Errors.FileManagement.DirectoryCopyError); + result.FirstError.Should().Be(Errors.FileSystemManagement.DirectoryCopyError); } [Fact] @@ -611,7 +612,7 @@ public class DirectoryProviderServiceTests // Assert result.IsError.Should().BeTrue(); - result.FirstError.Should().Be(Errors.FileManagement.DirectoryNotFound); + result.FirstError.Should().Be(Errors.FileSystemManagement.DirectoryNotFound); } [Fact] @@ -667,7 +668,7 @@ public class DirectoryProviderServiceTests result.Value.Path.Should().Be(destinationPath.Path); _mockFileSystem.File.Received(1).Move(_pathSourceFile1, _pathDestinationFile1); _mockFileSystem.Directory.Received(1).Move( - _pathSourceSubDir, + _pathSourceSubDir, s_isLinux ? "/Destination/SubDir" : @"C:\Destination\SubDir" ); _mockFileSystem.Directory.Received(1).Delete(sourcePath.Path); @@ -691,7 +692,7 @@ public class DirectoryProviderServiceTests // Assert result.IsError.Should().BeTrue(); - result.FirstError.Should().Be(Errors.FileManagement.DirectoryMoveError); + result.FirstError.Should().Be(Errors.FileSystemManagement.DirectoryMoveError); } [Fact] @@ -835,7 +836,7 @@ public class DirectoryProviderServiceTests result.IsError.Should().BeFalse(); result.Value.Should().Be(destPath); _mockFileSystem.File.Received(1).Move( - s_isLinux ? "/Source/SubDir/file.txt" : @"C:\Source\SubDir\file.txt", + s_isLinux ? "/Source/SubDir/file.txt" : @"C:\Source\SubDir\file.txt", s_isLinux ? "/Destination/SubDir/file.txt" : @"C:\Destination\SubDir\file.txt" ); _mockFileSystem.Directory.Received(1).Delete(_pathSourceSubDir); @@ -938,7 +939,7 @@ public class DirectoryProviderServiceTests // Assert result.IsError.Should().BeTrue(); - result.FirstError.Should().Be(Errors.FileManagement.InvalidPath); + result.FirstError.Should().Be(Errors.FileSystemManagement.InvalidPath); _mockFileSystem.Directory.DidNotReceive().Move(Arg.Any(), Arg.Any()); } @@ -962,7 +963,7 @@ public class DirectoryProviderServiceTests // Assert result.IsError.Should().BeTrue(); - result.FirstError.Should().Be(Errors.FileManagement.InvalidPath); + result.FirstError.Should().Be(Errors.FileSystemManagement.InvalidPath); _mockFileSystem.Directory.DidNotReceive().Move(Arg.Any(), Arg.Any()); } diff --git a/tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/FileManagementAggregate/Services/DirectoryServiceTests.cs b/tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/FileSystemManagementAggregate/Services/DirectoryServiceTests.cs similarity index 94% rename from tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/FileManagementAggregate/Services/DirectoryServiceTests.cs rename to tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/FileSystemManagementAggregate/Services/DirectoryServiceTests.cs index 9236132f..2d46dcbb 100644 --- a/tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/FileManagementAggregate/Services/DirectoryServiceTests.cs +++ b/tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/FileSystemManagementAggregate/Services/DirectoryServiceTests.cs @@ -4,13 +4,13 @@ using FluentAssertions; using Lumina.Contracts.Enums.FileSystem; using Lumina.Domain.Common.Errors; using Lumina.Domain.Common.Primitives; -using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.Entities; -using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.Services; -using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.Strategies.Environment; -using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.Strategies.Platform; -using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.ValueObjects; -using Lumina.Domain.UnitTests.Core.Aggregates.FileManagementAggregate.Entities.Fixtures; -using Lumina.Domain.UnitTests.Core.Aggregates.FileManagementAggregate.ValueObjects.Fixtures; +using Lumina.Domain.Core.Aggregates.FileSystemManagement.FileSystemManagementAggregate.Entities; +using Lumina.Domain.Core.Aggregates.FileSystemManagement.FileSystemManagementAggregate.Services; +using Lumina.Domain.Core.Aggregates.FileSystemManagement.FileSystemManagementAggregate.Strategies.Environment; +using Lumina.Domain.Core.Aggregates.FileSystemManagement.FileSystemManagementAggregate.Strategies.Platform; +using Lumina.Domain.Core.Aggregates.FileSystemManagement.FileSystemManagementAggregate.ValueObjects; +using Lumina.Domain.UnitTests.Core.Aggregates.FileSystemManagementAggregate.Entities.Fixtures; +using Lumina.Domain.UnitTests.Core.Aggregates.FileSystemManagementAggregate.ValueObjects.Fixtures; using NSubstitute; using System; using System.Collections.Generic; @@ -20,7 +20,7 @@ using System.Runtime.InteropServices; #endregion -namespace Lumina.Domain.UnitTests.Core.Aggregates.FileManagementAggregate.Services; +namespace Lumina.Domain.UnitTests.Core.Aggregates.FileSystemManagementAggregate.Services; /// /// Contains unit tests for the class. @@ -38,7 +38,6 @@ public class DirectoryServiceTests private readonly string _pathDirTest = s_isLinux ? "/TestDir" : @"C:\TestDir"; private readonly string _pathDirTestSubDir1 = s_isLinux ? "/TestDir/Sub1" : @"C:\TestDir\Sub1"; private readonly string _pathDirTestSubDir2 = s_isLinux ? "/TestDir/Sub2" : @"C:\TestDir\Sub2"; - private readonly char _dirSeparator = s_isLinux ? '/' : '\\'; /// /// Initializes a new instance of the class. @@ -101,7 +100,7 @@ public class DirectoryServiceTests // Assert result.IsError.Should().BeTrue(); - result.FirstError.Should().Be(Errors.FileManagement.InvalidPath); + result.FirstError.Should().Be(Errors.FileSystemManagement.InvalidPath); } [Fact] @@ -353,7 +352,7 @@ public class DirectoryServiceTests // Assert result.IsError.Should().BeTrue(); - result.FirstError.Should().Be(Errors.FileManagement.InvalidPath); + result.FirstError.Should().Be(Errors.FileSystemManagement.InvalidPath); } [Fact] @@ -464,7 +463,7 @@ public class DirectoryServiceTests // Assert result.IsError.Should().BeTrue(); - result.FirstError.Should().Be(Errors.FileManagement.DirectoryAlreadyExists); + result.FirstError.Should().Be(Errors.FileSystemManagement.DirectoryAlreadyExists); } [Fact] @@ -475,14 +474,14 @@ public class DirectoryServiceTests string newDirName = "NewDirectory"; _mockPlatformContext.PathStrategy.CombinePath(parentPathId, newDirName) - .Returns(Errors.FileManagement.InvalidPath); + .Returns(Errors.FileSystemManagement.InvalidPath); // Act ErrorOr result = _sut.CreateDirectory(parentPathId, newDirName); // Assert result.IsError.Should().BeTrue(); - result.FirstError.Should().Be(Errors.FileManagement.InvalidPath); + result.FirstError.Should().Be(Errors.FileSystemManagement.InvalidPath); // Verify that DirectoryExists was not called _mockEnvironmentContext.DirectoryProviderService.DidNotReceive().DirectoryExists(Arg.Any()); @@ -530,7 +529,7 @@ public class DirectoryServiceTests // Assert result.IsError.Should().BeTrue(); - result.FirstError.Should().Be(Errors.FileManagement.InvalidPath); + result.FirstError.Should().Be(Errors.FileSystemManagement.InvalidPath); } [Fact] @@ -638,7 +637,7 @@ public class DirectoryServiceTests // Assert result.IsError.Should().BeTrue(); - result.FirstError.Should().Be(Errors.FileManagement.DirectoryAlreadyExists); + result.FirstError.Should().Be(Errors.FileSystemManagement.DirectoryAlreadyExists); } [Fact] @@ -651,14 +650,14 @@ public class DirectoryServiceTests string newName = "NewName"; _mockPlatformContext.PathStrategy.CombinePath(Arg.Any(), newName) - .Returns(Errors.FileManagement.InvalidPath); + .Returns(Errors.FileSystemManagement.InvalidPath); // Act ErrorOr result = _sut.RenameDirectory(oldPathId, newName); // Assert result.IsError.Should().BeTrue(); - result.FirstError.Should().Be(Errors.FileManagement.InvalidPath); + result.FirstError.Should().Be(Errors.FileSystemManagement.InvalidPath); // Verify that DirectoryExists and RenameDirectory were not called _mockEnvironmentContext.DirectoryProviderService.DidNotReceive().DirectoryExists(Arg.Any()); @@ -722,7 +721,7 @@ public class DirectoryServiceTests // Assert result.IsError.Should().BeTrue(); - result.FirstError.Should().Be(Errors.FileManagement.InvalidPath); + result.FirstError.Should().Be(Errors.FileSystemManagement.InvalidPath); } [Fact] @@ -772,13 +771,13 @@ public class DirectoryServiceTests ); _mockEnvironmentContext.DirectoryProviderService.DeleteDirectory(pathId) - .Returns(Errors.FileManagement.DirectoryNotFound); + .Returns(Errors.FileSystemManagement.DirectoryNotFound); // Act ErrorOr result = _sut.DeleteDirectory(pathId); // Assert result.IsError.Should().BeTrue(); - result.FirstError.Should().Be(Errors.FileManagement.DirectoryNotFound); + result.FirstError.Should().Be(Errors.FileSystemManagement.DirectoryNotFound); } } diff --git a/tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/FileManagementAggregate/Services/DriveServiceTests.cs b/tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/FileSystemManagementAggregate/Services/DriveServiceTests.cs similarity index 85% rename from tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/FileManagementAggregate/Services/DriveServiceTests.cs rename to tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/FileSystemManagementAggregate/Services/DriveServiceTests.cs index 5615212e..f5d6b0a9 100644 --- a/tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/FileManagementAggregate/Services/DriveServiceTests.cs +++ b/tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/FileSystemManagementAggregate/Services/DriveServiceTests.cs @@ -2,11 +2,10 @@ using ErrorOr; using FluentAssertions; using Lumina.Contracts.Enums.FileSystem; -using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate; -using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.Entities; -using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.Services; -using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.Strategies.Platform; -using Lumina.Domain.UnitTests.Core.Aggregates.FileManagementAggregate.Fixtures; +using Lumina.Domain.Core.Aggregates.FileSystemManagement.FileSystemManagementAggregate; +using Lumina.Domain.Core.Aggregates.FileSystemManagement.FileSystemManagementAggregate.Entities; +using Lumina.Domain.Core.Aggregates.FileSystemManagement.FileSystemManagementAggregate.Services; +using Lumina.Domain.Core.Aggregates.FileSystemManagement.FileSystemManagementAggregate.Strategies.Platform; using NSubstitute; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; @@ -14,7 +13,7 @@ using System.IO.Abstractions; using System.Linq; #endregion -namespace Lumina.Domain.UnitTests.Core.Aggregates.FileManagementAggregate.Services; +namespace Lumina.Domain.UnitTests.Core.Aggregates.FileSystemManagementAggregate.Services; /// /// Contains unit tests for the class. diff --git a/tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/FileManagementAggregate/Services/FileProviderServiceTests.cs b/tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/FileSystemManagementAggregate/Services/FileProviderServiceTests.cs similarity index 96% rename from tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/FileManagementAggregate/Services/FileProviderServiceTests.cs rename to tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/FileSystemManagementAggregate/Services/FileProviderServiceTests.cs index 88623896..a9165ffd 100644 --- a/tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/FileManagementAggregate/Services/FileProviderServiceTests.cs +++ b/tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/FileSystemManagementAggregate/Services/FileProviderServiceTests.cs @@ -6,9 +6,9 @@ using FluentAssertions; using Lumina.Contracts.Enums.FileSystem; using Lumina.Domain.Common.Errors; using Lumina.Domain.Common.Primitives; -using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.Services; -using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.ValueObjects; -using Lumina.Domain.UnitTests.Core.Aggregates.FileManagementAggregate.ValueObjects.Fixtures; +using Lumina.Domain.Core.Aggregates.FileSystemManagement.FileSystemManagementAggregate.Services; +using Lumina.Domain.Core.Aggregates.FileSystemManagement.FileSystemManagementAggregate.ValueObjects; +using Lumina.Domain.UnitTests.Core.Aggregates.FileSystemManagementAggregate.ValueObjects.Fixtures; using NSubstitute; using NSubstitute.ExceptionExtensions; using System; @@ -21,7 +21,7 @@ using System.Runtime.InteropServices; #endregion -namespace Lumina.Domain.UnitTests.Core.Aggregates.FileManagementAggregate.Services; +namespace Lumina.Domain.UnitTests.Core.Aggregates.FileSystemManagementAggregate.Services; /// /// Contains unit tests for the class. @@ -35,7 +35,6 @@ public class FileProviderServiceTests private readonly FileProviderService _sut; private readonly FileSystemPathIdFixture _fileSystemPathIdFixture; private static readonly bool s_isLinux = RuntimeInformation.IsOSPlatform(OSPlatform.Linux); - private readonly string _pathDirTest = s_isLinux ? "/TestDir" : @"C:\TestDir"; private readonly string _pathVisible1 = s_isLinux ? "/Visible.txt" : @"C:\Visible.txt"; private readonly string _pathHidden1 = s_isLinux ? "/Hidden.txt" : @"C:\Hidden.txt"; private readonly string _pathValid1 = s_isLinux ? "/Valid.txt" : @"C:\Valid.txt"; @@ -44,7 +43,6 @@ public class FileProviderServiceTests private readonly string _pathDestinationFile = s_isLinux ? "/Destination/file.txt" : @"C:\Destination\file.txt"; private readonly string _pathSource = s_isLinux ? "/Source" : @"C:\Source"; private readonly string _pathDestination = s_isLinux ? "/Destination" : @"C:\Destination"; - private readonly char _dirSeparator = s_isLinux ? '/' : '\\'; /// /// Initializes a new instance of the class. @@ -156,10 +154,10 @@ public class FileProviderServiceTests { // Arrange FileSystemPathId path = _fileSystemPathIdFixture.CreateFileSystemPathId(); - string[] files = s_isLinux + string[] files = s_isLinux ? ["/C.txt", "/A.txt", "/B.txt"] : [@"C:\C.txt", @"C:\A.txt", @"C:\B.txt"]; - string[] expectedFiles = s_isLinux + string[] expectedFiles = s_isLinux ? ["/A.txt", "/B.txt", "/C.txt"] : [@"C:\A.txt", @"C:\B.txt", @"C:\C.txt"]; _mockFileSystemPermissionsService.CanAccessPath(path, FileAccessMode.ListDirectory).Returns(true); @@ -506,7 +504,7 @@ public class FileProviderServiceTests // Assert result.IsError.Should().BeTrue(); - result.FirstError.Should().Be(Errors.FileManagement.FileNotFound); + result.FirstError.Should().Be(Errors.FileSystemManagement.FileNotFound); } [Fact] @@ -532,7 +530,7 @@ public class FileProviderServiceTests // Assert result.IsError.Should().BeTrue(); - result.FirstError.Should().Be(Errors.FileManagement.FileAlreadyExists); + result.FirstError.Should().Be(Errors.FileSystemManagement.FileAlreadyExists); _mockFileSystem.File.DidNotReceive().Copy(Arg.Any(), Arg.Any(), Arg.Any()); } @@ -576,7 +574,7 @@ public class FileProviderServiceTests // Assert result.IsError.Should().BeTrue(); - result.FirstError.Should().Be(Errors.FileManagement.FileCopyError); + result.FirstError.Should().Be(Errors.FileSystemManagement.FileCopyError); } [Fact] @@ -604,7 +602,8 @@ public class FileProviderServiceTests // Simulate the behavior of CreateUniqueFilePath int copyNumber = 1; _mockFileSystem.File.Exists(Arg.Any()) - .Returns(x => { + .Returns(x => + { string path = x.Arg(); if (path == expectedNewFilePath) return false; @@ -638,7 +637,7 @@ public class FileProviderServiceTests // Assert result.IsError.Should().BeTrue(); - result.FirstError.Should().Be(Errors.FileManagement.FileNotFound); + result.FirstError.Should().Be(Errors.FileSystemManagement.FileNotFound); } [Fact] @@ -706,7 +705,7 @@ public class FileProviderServiceTests // Assert result.IsError.Should().BeTrue(); - result.FirstError.Should().Be(Errors.FileManagement.FileAlreadyExists); + result.FirstError.Should().Be(Errors.FileSystemManagement.FileAlreadyExists); } [Fact] @@ -730,7 +729,7 @@ public class FileProviderServiceTests // Assert result.IsError.Should().BeTrue(); - result.FirstError.Should().Be(Errors.FileManagement.FileMoveError); + result.FirstError.Should().Be(Errors.FileSystemManagement.FileMoveError); } [Fact] @@ -829,7 +828,7 @@ public class FileProviderServiceTests // Assert result.IsError.Should().BeTrue(); - result.FirstError.Should().Be(Errors.FileManagement.CannotNavigateUp); + result.FirstError.Should().Be(Errors.FileSystemManagement.CannotNavigateUp); _mockFileSystem.File.DidNotReceive().Move(Arg.Any(), Arg.Any()); } @@ -853,7 +852,7 @@ public class FileProviderServiceTests // Assert result.IsError.Should().BeTrue(); - result.FirstError.Should().Be(Errors.FileManagement.InvalidPath); + result.FirstError.Should().Be(Errors.FileSystemManagement.InvalidPath); _mockFileSystem.File.DidNotReceive().Move(Arg.Any(), Arg.Any()); } @@ -867,7 +866,7 @@ public class FileProviderServiceTests string newName = "NewName.txt"; string parentPath = s_isLinux ? "/" : @"C:\"; string newPath = s_isLinux ? "/NewName.txt" : @"C:\NewName.txt"; - + IFileInfo fileInfo = Substitute.For(); fileInfo.DirectoryName.Returns(parentPath); _mockFileSystem.FileInfo.New(path.Path).Returns(fileInfo); diff --git a/tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/FileManagementAggregate/Services/FileServiceTests.cs b/tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/FileSystemManagementAggregate/Services/FileServiceTests.cs similarity index 96% rename from tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/FileManagementAggregate/Services/FileServiceTests.cs rename to tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/FileSystemManagementAggregate/Services/FileServiceTests.cs index 62617709..bea2b73f 100644 --- a/tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/FileManagementAggregate/Services/FileServiceTests.cs +++ b/tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/FileSystemManagementAggregate/Services/FileServiceTests.cs @@ -4,13 +4,13 @@ using FluentAssertions; using Lumina.Contracts.Enums.FileSystem; using Lumina.Domain.Common.Errors; using Lumina.Domain.Common.Primitives; -using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.Entities; -using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.Services; -using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.Strategies.Environment; -using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.Strategies.Platform; -using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.ValueObjects; -using Lumina.Domain.UnitTests.Core.Aggregates.FileManagementAggregate.Entities.Fixtures; -using Lumina.Domain.UnitTests.Core.Aggregates.FileManagementAggregate.ValueObjects.Fixtures; +using Lumina.Domain.Core.Aggregates.FileSystemManagement.FileSystemManagementAggregate.Entities; +using Lumina.Domain.Core.Aggregates.FileSystemManagement.FileSystemManagementAggregate.Services; +using Lumina.Domain.Core.Aggregates.FileSystemManagement.FileSystemManagementAggregate.Strategies.Environment; +using Lumina.Domain.Core.Aggregates.FileSystemManagement.FileSystemManagementAggregate.Strategies.Platform; +using Lumina.Domain.Core.Aggregates.FileSystemManagement.FileSystemManagementAggregate.ValueObjects; +using Lumina.Domain.UnitTests.Core.Aggregates.FileSystemManagementAggregate.Entities.Fixtures; +using Lumina.Domain.UnitTests.Core.Aggregates.FileSystemManagementAggregate.ValueObjects.Fixtures; using NSubstitute; using System; using System.Collections.Generic; @@ -20,7 +20,7 @@ using System.Runtime.InteropServices; #endregion -namespace Lumina.Domain.UnitTests.Core.Aggregates.FileManagementAggregate.Services; +namespace Lumina.Domain.UnitTests.Core.Aggregates.FileSystemManagementAggregate.Services; /// /// Contains unit tests for the class. @@ -35,7 +35,7 @@ public class FileServiceTests private readonly FileSystemPathIdFixture _fileSystemPathIdFixture; private readonly FileFixture _fileFixture; private static readonly bool s_isLinux = RuntimeInformation.IsOSPlatform(OSPlatform.Linux); - private readonly string _pathTestDir= s_isLinux ? "/TestDir" : @"C:\TestDir"; + private readonly string _pathTestDir = s_isLinux ? "/TestDir" : @"C:\TestDir"; private readonly string _pathTestDirFile1 = s_isLinux ? "/TestDir/File1.txt" : @"C:\TestDir\File1.txt"; private readonly string _pathTestDirFile2 = s_isLinux ? "/TestDir/File2.txt" : @"C:\TestDir\File2.txt"; private readonly string _pathTestDirInaccessible = s_isLinux ? "/TestDir/InaccessibleFile.txt" : @"C:\TestDir\InaccessibleFile.txt"; @@ -112,7 +112,7 @@ public class FileServiceTests // Assert result.IsError.Should().BeTrue(); - result.FirstError.Should().Be(Errors.FileManagement.InvalidPath); + result.FirstError.Should().Be(Errors.FileSystemManagement.InvalidPath); } [Fact] @@ -380,7 +380,7 @@ public class FileServiceTests // Assert result.IsError.Should().BeTrue(); - result.FirstError.Should().Be(Errors.FileManagement.FileNotFound); + result.FirstError.Should().Be(Errors.FileSystemManagement.FileNotFound); } [Fact] @@ -449,7 +449,7 @@ public class FileServiceTests // Assert result.IsError.Should().BeTrue(); - result.FirstError.Should().Be(Errors.FileManagement.InvalidPath); + result.FirstError.Should().Be(Errors.FileSystemManagement.InvalidPath); } [Fact] @@ -460,13 +460,13 @@ public class FileServiceTests string invalidDestinationPath = string.Empty; bool overrideExisting = true; _mockPlatformContext.PathStrategy.PathSeparator.Returns(_dirSeparator); - + // Act ErrorOr result = _sut.CopyFile(sourcePath, invalidDestinationPath, overrideExisting); // Assert result.IsError.Should().BeTrue(); - result.FirstError.Should().Be(Errors.FileManagement.InvalidPath); + result.FirstError.Should().Be(Errors.FileSystemManagement.InvalidPath); } [Fact] @@ -513,7 +513,7 @@ public class FileServiceTests // Assert result.IsError.Should().BeTrue(); - result.FirstError.Should().Be(Errors.FileManagement.FileNotFound); + result.FirstError.Should().Be(Errors.FileSystemManagement.FileNotFound); } [Fact] @@ -614,7 +614,7 @@ public class FileServiceTests // Assert result.IsError.Should().BeTrue(); - result.FirstError.Should().Be(Errors.FileManagement.FileNotFound); + result.FirstError.Should().Be(Errors.FileSystemManagement.FileNotFound); } [Fact] @@ -687,7 +687,7 @@ public class FileServiceTests // Assert result.IsError.Should().BeTrue(); - result.FirstError.Should().Be(Errors.FileManagement.InvalidPath); + result.FirstError.Should().Be(Errors.FileSystemManagement.InvalidPath); } [Fact] @@ -705,7 +705,7 @@ public class FileServiceTests // Assert result.IsError.Should().BeTrue(); - result.FirstError.Should().Be(Errors.FileManagement.InvalidPath); + result.FirstError.Should().Be(Errors.FileSystemManagement.InvalidPath); } [Fact] @@ -754,7 +754,7 @@ public class FileServiceTests // Assert result.IsError.Should().BeTrue(); - result.FirstError.Should().Be(Errors.FileManagement.FileNotFound); + result.FirstError.Should().Be(Errors.FileSystemManagement.FileNotFound); } [Fact] @@ -875,7 +875,7 @@ public class FileServiceTests // Assert result.IsError.Should().BeTrue(); - result.FirstError.Should().Be(Errors.FileManagement.FileAlreadyExists); + result.FirstError.Should().Be(Errors.FileSystemManagement.FileAlreadyExists); } [Fact] @@ -946,7 +946,7 @@ public class FileServiceTests // Assert result.IsError.Should().BeTrue(); - result.FirstError.Should().Be(Errors.FileManagement.InvalidPath); + result.FirstError.Should().Be(Errors.FileSystemManagement.InvalidPath); } [Fact] @@ -996,7 +996,7 @@ public class FileServiceTests // Assert result.IsError.Should().BeTrue(); - result.FirstError.Should().Be(Errors.FileManagement.FileAlreadyExists); + result.FirstError.Should().Be(Errors.FileSystemManagement.FileAlreadyExists); } [Fact] @@ -1055,17 +1055,17 @@ public class FileServiceTests // Arrange string path = _pathSourceOldFile; string newName = "newfile.txt"; - + _mockPlatformContext.PathStrategy.PathSeparator.Returns(_dirSeparator); _mockPlatformContext.PathStrategy.CombinePath(Arg.Any(), newName) - .Returns(Errors.FileManagement.InvalidPath); + .Returns(Errors.FileSystemManagement.InvalidPath); // Act ErrorOr result = _sut.RenameFile(path, newName); // Assert result.IsError.Should().BeTrue(); - result.FirstError.Should().Be(Errors.FileManagement.InvalidPath); + result.FirstError.Should().Be(Errors.FileSystemManagement.InvalidPath); } [Fact] @@ -1098,14 +1098,14 @@ public class FileServiceTests string newName = "newfile.txt"; _mockPlatformContext.PathStrategy.CombinePath(Arg.Any(), newName) - .Returns(Errors.FileManagement.InvalidPath); + .Returns(Errors.FileSystemManagement.InvalidPath); // Act ErrorOr result = _sut.RenameFile(pathId, newName); // Assert result.IsError.Should().BeTrue(); - result.FirstError.Should().Be(Errors.FileManagement.InvalidPath); + result.FirstError.Should().Be(Errors.FileSystemManagement.InvalidPath); } [Fact] @@ -1158,7 +1158,7 @@ public class FileServiceTests // Assert result.IsError.Should().BeTrue(); - result.FirstError.Should().Be(Errors.FileManagement.InvalidPath); + result.FirstError.Should().Be(Errors.FileSystemManagement.InvalidPath); } [Fact] diff --git a/tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/FileManagementAggregate/Services/FileTypeServiceTests.cs b/tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/FileSystemManagementAggregate/Services/FileTypeServiceTests.cs similarity index 94% rename from tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/FileManagementAggregate/Services/FileTypeServiceTests.cs rename to tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/FileSystemManagementAggregate/Services/FileTypeServiceTests.cs index 694db8c3..04354651 100644 --- a/tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/FileManagementAggregate/Services/FileTypeServiceTests.cs +++ b/tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/FileSystemManagementAggregate/Services/FileTypeServiceTests.cs @@ -4,11 +4,11 @@ using FluentAssertions; using Lumina.Contracts.Enums.FileSystem; using Lumina.Contracts.Enums.PhotoLibrary; using Lumina.Domain.Common.Errors; -using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.Entities; -using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.Services; -using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.ValueObjects; -using Lumina.Domain.UnitTests.Core.Aggregates.FileManagementAggregate.Entities.Fixtures; -using Lumina.Domain.UnitTests.Core.Aggregates.FileManagementAggregate.ValueObjects.Fixtures; +using Lumina.Domain.Core.Aggregates.FileSystemManagement.FileSystemManagementAggregate.Entities; +using Lumina.Domain.Core.Aggregates.FileSystemManagement.FileSystemManagementAggregate.Services; +using Lumina.Domain.Core.Aggregates.FileSystemManagement.FileSystemManagementAggregate.ValueObjects; +using Lumina.Domain.UnitTests.Core.Aggregates.FileSystemManagementAggregate.Entities.Fixtures; +using Lumina.Domain.UnitTests.Core.Aggregates.FileSystemManagementAggregate.ValueObjects.Fixtures; using NSubstitute; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; @@ -19,7 +19,7 @@ using System.Threading; using System.Threading.Tasks; #endregion -namespace Lumina.Domain.UnitTests.Core.Aggregates.FileManagementAggregate.Services; +namespace Lumina.Domain.UnitTests.Core.Aggregates.FileSystemManagementAggregate.Services; /// /// Contains unit tests for the class. diff --git a/tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/FileManagementAggregate/Services/Fixtures/ImageTypeFixture.cs b/tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/FileSystemManagementAggregate/Services/Fixtures/ImageTypeFixture.cs similarity index 94% rename from tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/FileManagementAggregate/Services/Fixtures/ImageTypeFixture.cs rename to tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/FileSystemManagementAggregate/Services/Fixtures/ImageTypeFixture.cs index 41a13121..54dabd4a 100644 --- a/tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/FileManagementAggregate/Services/Fixtures/ImageTypeFixture.cs +++ b/tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/FileSystemManagementAggregate/Services/Fixtures/ImageTypeFixture.cs @@ -11,7 +11,7 @@ using System.Diagnostics.CodeAnalysis; using System.IO; #endregion -namespace Lumina.Domain.UnitTests.Core.Aggregates.FileManagementAggregate.Services.Fixtures; +namespace Lumina.Domain.UnitTests.Core.Aggregates.FileSystemManagementAggregate.Services.Fixtures; /// /// Fixture class for the enum. diff --git a/tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/FileManagementAggregate/Services/PathServiceTests.cs b/tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/FileSystemManagementAggregate/Services/PathServiceTests.cs similarity index 90% rename from tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/FileManagementAggregate/Services/PathServiceTests.cs rename to tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/FileSystemManagementAggregate/Services/PathServiceTests.cs index a5abbb34..003fa963 100644 --- a/tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/FileManagementAggregate/Services/PathServiceTests.cs +++ b/tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/FileSystemManagementAggregate/Services/PathServiceTests.cs @@ -2,18 +2,18 @@ using ErrorOr; using FluentAssertions; using Lumina.Domain.Common.Errors; -using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.Services; -using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.Strategies.Path; -using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.Strategies.Platform; -using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.ValueObjects; -using Lumina.Domain.UnitTests.Core.Aggregates.FileManagementAggregate.ValueObjects.Fixtures; +using Lumina.Domain.Core.Aggregates.FileSystemManagement.FileSystemManagementAggregate.Services; +using Lumina.Domain.Core.Aggregates.FileSystemManagement.FileSystemManagementAggregate.Strategies.Path; +using Lumina.Domain.Core.Aggregates.FileSystemManagement.FileSystemManagementAggregate.Strategies.Platform; +using Lumina.Domain.Core.Aggregates.FileSystemManagement.FileSystemManagementAggregate.ValueObjects; +using Lumina.Domain.UnitTests.Core.Aggregates.FileSystemManagementAggregate.ValueObjects.Fixtures; using NSubstitute; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Linq; #endregion -namespace Lumina.Domain.UnitTests.Core.Aggregates.FileManagementAggregate.Services; +namespace Lumina.Domain.UnitTests.Core.Aggregates.FileSystemManagementAggregate.Services; /// /// Contains unit tests for the class. @@ -226,7 +226,7 @@ public class PathServiceTests // Assert result.IsError.Should().BeTrue(); - result.FirstError.Should().Be(Errors.FileManagement.InvalidPath); + result.FirstError.Should().Be(Errors.FileSystemManagement.InvalidPath); _mockPathStrategy.DidNotReceive().CombinePath(Arg.Any(), Arg.Any()); } @@ -237,14 +237,14 @@ public class PathServiceTests string path = @"C:\BaseDir"; string name = "Invalid*Name"; FileSystemPathId pathId = _fileSystemPathIdFixture.CreateFileSystemPathId(path); - _mockPathStrategy.CombinePath(pathId, name).Returns(Errors.FileManagement.InvalidPath); + _mockPathStrategy.CombinePath(pathId, name).Returns(Errors.FileSystemManagement.InvalidPath); // Act ErrorOr result = _sut.CombinePath(path, name); // Assert result.IsError.Should().BeTrue(); - result.FirstError.Should().Be(Errors.FileManagement.InvalidPath); + result.FirstError.Should().Be(Errors.FileSystemManagement.InvalidPath); _mockPathStrategy.Received(1).CombinePath(Arg.Is(id => id.Path == path), name); } @@ -260,7 +260,7 @@ public class PathServiceTests // Assert result.IsError.Should().BeTrue(); - result.FirstError.Should().Be(Errors.FileManagement.InvalidPath); + result.FirstError.Should().Be(Errors.FileSystemManagement.InvalidPath); _mockPathStrategy.DidNotReceive().CombinePath(Arg.Any(), Arg.Any()); } @@ -293,7 +293,7 @@ public class PathServiceTests // Assert result.IsError.Should().BeTrue(); - result.FirstError.Should().Be(Errors.FileManagement.InvalidPath); + result.FirstError.Should().Be(Errors.FileSystemManagement.InvalidPath); _mockPathStrategy.DidNotReceive().ParsePath(Arg.Any()); } @@ -303,14 +303,14 @@ public class PathServiceTests // Arrange string path = @"C:\InvalidPath\*SubDir"; FileSystemPathId pathId = _fileSystemPathIdFixture.CreateFileSystemPathId(path); - _mockPathStrategy.ParsePath(pathId).Returns(Errors.FileManagement.InvalidPath); + _mockPathStrategy.ParsePath(pathId).Returns(Errors.FileSystemManagement.InvalidPath); // Act ErrorOr> result = _sut.ParsePath(path); // Assert result.IsError.Should().BeTrue(); - result.FirstError.Should().Be(Errors.FileManagement.InvalidPath); + result.FirstError.Should().Be(Errors.FileSystemManagement.InvalidPath); _mockPathStrategy.Received(1).ParsePath(Arg.Is(id => id.Path == path)); } @@ -325,7 +325,7 @@ public class PathServiceTests // Assert result.IsError.Should().BeTrue(); - result.FirstError.Should().Be(Errors.FileManagement.InvalidPath); + result.FirstError.Should().Be(Errors.FileSystemManagement.InvalidPath); _mockPathStrategy.DidNotReceive().ParsePath(Arg.Any()); } @@ -376,7 +376,7 @@ public class PathServiceTests // Assert result.IsError.Should().BeTrue(); - result.FirstError.Should().Be(Errors.FileManagement.InvalidPath); + result.FirstError.Should().Be(Errors.FileSystemManagement.InvalidPath); _mockPathStrategy.DidNotReceive().GoUpOneLevel(Arg.Any()); } @@ -386,14 +386,14 @@ public class PathServiceTests // Arrange string path = @"C:\InvalidPath\*SubDir"; FileSystemPathId pathId = _fileSystemPathIdFixture.CreateFileSystemPathId(path); - _mockPathStrategy.GoUpOneLevel(pathId).Returns(Errors.FileManagement.InvalidPath); + _mockPathStrategy.GoUpOneLevel(pathId).Returns(Errors.FileSystemManagement.InvalidPath); // Act ErrorOr> result = _sut.GoUpOneLevel(path); // Assert result.IsError.Should().BeTrue(); - result.FirstError.Should().Be(Errors.FileManagement.InvalidPath); + result.FirstError.Should().Be(Errors.FileSystemManagement.InvalidPath); _mockPathStrategy.Received(1).GoUpOneLevel(Arg.Is(id => id.Path == path)); } @@ -408,7 +408,7 @@ public class PathServiceTests // Assert result.IsError.Should().BeTrue(); - result.FirstError.Should().Be(Errors.FileManagement.InvalidPath); + result.FirstError.Should().Be(Errors.FileSystemManagement.InvalidPath); _mockPathStrategy.DidNotReceive().GoUpOneLevel(Arg.Any()); } @@ -488,7 +488,7 @@ public class PathServiceTests // Assert result.IsError.Should().BeTrue(); - result.FirstError.Should().Be(Errors.FileManagement.InvalidPath); + result.FirstError.Should().Be(Errors.FileSystemManagement.InvalidPath); _mockPathStrategy.DidNotReceive().GetPathRoot(Arg.Any()); } @@ -498,14 +498,14 @@ public class PathServiceTests // Arrange string path = @"C:\InvalidPath\*SubDir"; FileSystemPathId pathId = _fileSystemPathIdFixture.CreateFileSystemPathId(path); - _mockPathStrategy.GetPathRoot(pathId).Returns(Errors.FileManagement.InvalidPath); + _mockPathStrategy.GetPathRoot(pathId).Returns(Errors.FileSystemManagement.InvalidPath); // Act ErrorOr result = _sut.GetPathRoot(path); // Assert result.IsError.Should().BeTrue(); - result.FirstError.Should().Be(Errors.FileManagement.InvalidPath); + result.FirstError.Should().Be(Errors.FileSystemManagement.InvalidPath); _mockPathStrategy.Received(1).GetPathRoot(Arg.Is(id => id.Path == path)); } @@ -520,7 +520,7 @@ public class PathServiceTests // Assert result.IsError.Should().BeTrue(); - result.FirstError.Should().Be(Errors.FileManagement.InvalidPath); + result.FirstError.Should().Be(Errors.FileSystemManagement.InvalidPath); _mockPathStrategy.DidNotReceive().GetPathRoot(Arg.Any()); } } diff --git a/tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/FileManagementAggregate/Services/ThumbnailServiceTests.cs b/tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/FileSystemManagementAggregate/Services/ThumbnailServiceTests.cs similarity index 90% rename from tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/FileManagementAggregate/Services/ThumbnailServiceTests.cs rename to tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/FileSystemManagementAggregate/Services/ThumbnailServiceTests.cs index 6c66a407..ef428348 100644 --- a/tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/FileManagementAggregate/Services/ThumbnailServiceTests.cs +++ b/tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/FileSystemManagementAggregate/Services/ThumbnailServiceTests.cs @@ -3,11 +3,11 @@ using ErrorOr; using FluentAssertions; using Lumina.Contracts.Enums.PhotoLibrary; using Lumina.Domain.Common.Errors; -using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.Services; -using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.Strategies.Environment; -using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.ValueObjects; -using Lumina.Domain.UnitTests.Core.Aggregates.FileManagementAggregate.Services.Fixtures; -using Lumina.Domain.UnitTests.Core.Aggregates.FileManagementAggregate.ValueObjects.Fixtures; +using Lumina.Domain.Core.Aggregates.FileSystemManagement.FileSystemManagementAggregate.Services; +using Lumina.Domain.Core.Aggregates.FileSystemManagement.FileSystemManagementAggregate.Strategies.Environment; +using Lumina.Domain.Core.Aggregates.FileSystemManagement.FileSystemManagementAggregate.ValueObjects; +using Lumina.Domain.UnitTests.Core.Aggregates.FileSystemManagementAggregate.Services.Fixtures; +using Lumina.Domain.UnitTests.Core.Aggregates.FileSystemManagementAggregate.ValueObjects.Fixtures; using NSubstitute; using SixLabors.ImageSharp; using SixLabors.ImageSharp.Formats.Jpeg; @@ -18,7 +18,7 @@ using System.Threading; using System.Threading.Tasks; #endregion -namespace Lumina.Domain.UnitTests.Core.Aggregates.FileManagementAggregate.Services; +namespace Lumina.Domain.UnitTests.Core.Aggregates.FileSystemManagementAggregate.Services; /// /// Contains unit tests for the class. @@ -83,7 +83,7 @@ public class ThumbnailServiceTests // Assert result.IsError.Should().BeTrue(); - result.FirstError.Should().Be(Errors.FileManagement.InvalidPath); + result.FirstError.Should().Be(Errors.FileSystemManagement.InvalidPath); } [Fact] diff --git a/tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/FileManagementAggregate/Strategies/Environment/EnvironmentContextTests.cs b/tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/FileSystemManagementAggregate/Strategies/Environment/EnvironmentContextTests.cs similarity index 90% rename from tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/FileManagementAggregate/Strategies/Environment/EnvironmentContextTests.cs rename to tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/FileSystemManagementAggregate/Strategies/Environment/EnvironmentContextTests.cs index 22002449..893ca812 100644 --- a/tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/FileManagementAggregate/Strategies/Environment/EnvironmentContextTests.cs +++ b/tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/FileSystemManagementAggregate/Strategies/Environment/EnvironmentContextTests.cs @@ -1,12 +1,12 @@ #region ========================================================================= USING ===================================================================================== using FluentAssertions; -using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.Services; -using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.Strategies.Environment; +using Lumina.Domain.Core.Aggregates.FileSystemManagement.FileSystemManagementAggregate.Services; +using Lumina.Domain.Core.Aggregates.FileSystemManagement.FileSystemManagementAggregate.Strategies.Environment; using NSubstitute; using System.Diagnostics.CodeAnalysis; #endregion -namespace Lumina.Domain.UnitTests.Core.Aggregates.FileManagementAggregate.Strategies.Environment; +namespace Lumina.Domain.UnitTests.Core.Aggregates.FileSystemManagementAggregate.Strategies.Environment; /// /// Contains unit tests for the class. diff --git a/tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/FileManagementAggregate/Strategies/Path/UnixPathStrategyTests.cs b/tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/FileSystemManagementAggregate/Strategies/Path/UnixPathStrategyTests.cs similarity index 95% rename from tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/FileManagementAggregate/Strategies/Path/UnixPathStrategyTests.cs rename to tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/FileSystemManagementAggregate/Strategies/Path/UnixPathStrategyTests.cs index 2e11147e..769904fa 100644 --- a/tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/FileManagementAggregate/Strategies/Path/UnixPathStrategyTests.cs +++ b/tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/FileSystemManagementAggregate/Strategies/Path/UnixPathStrategyTests.cs @@ -2,9 +2,9 @@ using ErrorOr; using FluentAssertions; using Lumina.Domain.Common.Errors; -using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.Strategies.Path; -using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.ValueObjects; -using Lumina.Domain.UnitTests.Core.Aggregates.FileManagementAggregate.ValueObjects.Fixtures; +using Lumina.Domain.Core.Aggregates.FileSystemManagement.FileSystemManagementAggregate.Strategies.Path; +using Lumina.Domain.Core.Aggregates.FileSystemManagement.FileSystemManagementAggregate.ValueObjects; +using Lumina.Domain.UnitTests.Core.Aggregates.FileSystemManagementAggregate.ValueObjects.Fixtures; using NSubstitute; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; @@ -12,7 +12,7 @@ using System.IO.Abstractions; using System.Linq; #endregion -namespace Lumina.Domain.UnitTests.Core.Aggregates.FileManagementAggregate.Strategies.Path; +namespace Lumina.Domain.UnitTests.Core.Aggregates.FileSystemManagementAggregate.Strategies.Path; /// /// Contains unit tests for the class. @@ -128,7 +128,7 @@ public class UnixPathStrategyTests // Arrange string existingPath = "/home/user/existing_file.txt"; FileSystemPathId pathId = _fileSystemPathIdFixture.CreateFileSystemPathId(existingPath); - + _mockFileSystem.Path.Exists(existingPath).Returns(true); _mockFileSystem.File.Exists(existingPath).Returns(true); @@ -283,7 +283,7 @@ public class UnixPathStrategyTests // Assert result.IsError.Should().BeTrue(); - result.FirstError.Should().Be(Errors.FileManagement.NameCannotBeEmpty); + result.FirstError.Should().Be(Errors.FileSystemManagement.NameCannotBeEmpty); } [Fact] @@ -298,7 +298,7 @@ public class UnixPathStrategyTests // Assert result.IsError.Should().BeTrue(); - result.FirstError.Should().Be(Errors.FileManagement.NameCannotBeEmpty); + result.FirstError.Should().Be(Errors.FileSystemManagement.NameCannotBeEmpty); } [Fact] @@ -376,7 +376,7 @@ public class UnixPathStrategyTests // Assert result.IsError.Should().BeTrue(); - result.FirstError.Should().Be(Errors.FileManagement.InvalidPath); + result.FirstError.Should().Be(Errors.FileSystemManagement.InvalidPath); } [Fact] @@ -422,7 +422,7 @@ public class UnixPathStrategyTests // Assert result.IsError.Should().BeTrue(); - result.FirstError.Should().Be(Errors.FileManagement.CannotNavigateUp); + result.FirstError.Should().Be(Errors.FileSystemManagement.CannotNavigateUp); } [Fact] @@ -452,7 +452,7 @@ public class UnixPathStrategyTests // Assert result.IsError.Should().BeTrue(); - result.FirstError.Should().Be(Errors.FileManagement.InvalidPath); + result.FirstError.Should().Be(Errors.FileSystemManagement.InvalidPath); } [Fact] @@ -549,6 +549,6 @@ public class UnixPathStrategyTests // Assert result.IsError.Should().BeTrue(); - result.FirstError.Should().Be(Errors.FileManagement.InvalidPath); + result.FirstError.Should().Be(Errors.FileSystemManagement.InvalidPath); } } diff --git a/tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/FileManagementAggregate/Strategies/Path/WindowsPathStrategyTests.cs b/tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/FileSystemManagementAggregate/Strategies/Path/WindowsPathStrategyTests.cs similarity index 94% rename from tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/FileManagementAggregate/Strategies/Path/WindowsPathStrategyTests.cs rename to tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/FileSystemManagementAggregate/Strategies/Path/WindowsPathStrategyTests.cs index 15fb9ee4..fe11b50f 100644 --- a/tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/FileManagementAggregate/Strategies/Path/WindowsPathStrategyTests.cs +++ b/tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/FileSystemManagementAggregate/Strategies/Path/WindowsPathStrategyTests.cs @@ -2,9 +2,9 @@ using ErrorOr; using FluentAssertions; using Lumina.Domain.Common.Errors; -using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.Strategies.Path; -using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.ValueObjects; -using Lumina.Domain.UnitTests.Core.Aggregates.FileManagementAggregate.ValueObjects.Fixtures; +using Lumina.Domain.Core.Aggregates.FileSystemManagement.FileSystemManagementAggregate.Strategies.Path; +using Lumina.Domain.Core.Aggregates.FileSystemManagement.FileSystemManagementAggregate.ValueObjects; +using Lumina.Domain.UnitTests.Core.Aggregates.FileSystemManagementAggregate.ValueObjects.Fixtures; using NSubstitute; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; @@ -12,7 +12,7 @@ using System.IO.Abstractions; using System.Linq; #endregion -namespace Lumina.Domain.UnitTests.Core.Aggregates.FileManagementAggregate.Strategies.Path; +namespace Lumina.Domain.UnitTests.Core.Aggregates.FileSystemManagementAggregate.Strategies.Path; /// /// Contains unit tests for the class. @@ -326,7 +326,7 @@ public class WindowsPathStrategyTests // Assert result.IsError.Should().BeTrue(); - result.FirstError.Should().Be(Errors.FileManagement.NameCannotBeEmpty); + result.FirstError.Should().Be(Errors.FileSystemManagement.NameCannotBeEmpty); } [Fact] @@ -419,7 +419,7 @@ public class WindowsPathStrategyTests // Assert result.IsError.Should().BeTrue(); - result.FirstError.Should().Be(Errors.FileManagement.InvalidPath); + result.FirstError.Should().Be(Errors.FileSystemManagement.InvalidPath); } [Fact] @@ -484,7 +484,7 @@ public class WindowsPathStrategyTests // Assert result.IsError.Should().BeTrue(); - result.FirstError.Should().Be(Errors.FileManagement.CannotNavigateUp); + result.FirstError.Should().Be(Errors.FileSystemManagement.CannotNavigateUp); } [Fact] @@ -514,7 +514,7 @@ public class WindowsPathStrategyTests // Assert result.IsError.Should().BeTrue(); - result.FirstError.Should().Be(Errors.FileManagement.InvalidPath); + result.FirstError.Should().Be(Errors.FileSystemManagement.InvalidPath); } [Fact] @@ -561,7 +561,7 @@ public class WindowsPathStrategyTests // Assert result.IsError.Should().BeTrue(); - result.FirstError.Should().Be(Errors.FileManagement.CannotNavigateUp); + result.FirstError.Should().Be(Errors.FileSystemManagement.CannotNavigateUp); } [Fact] @@ -592,7 +592,7 @@ public class WindowsPathStrategyTests // Assert result.IsError.Should().BeTrue(); - result.FirstError.Should().Be(Errors.FileManagement.CannotNavigateUp); + result.FirstError.Should().Be(Errors.FileSystemManagement.CannotNavigateUp); } [Fact] @@ -602,7 +602,7 @@ public class WindowsPathStrategyTests char[] result = _sut.GetInvalidPathCharsForPlatform(); // Assert - result.Should().BeEquivalentTo(['<', '>', '"', '/', '|', '?', '*' ]); + result.Should().BeEquivalentTo(['<', '>', '"', '/', '|', '?', '*']); } [Fact] @@ -667,7 +667,7 @@ public class WindowsPathStrategyTests // Assert result.IsError.Should().BeTrue(); - result.FirstError.Should().Be(Errors.FileManagement.InvalidPath); + result.FirstError.Should().Be(Errors.FileSystemManagement.InvalidPath); } [Fact] @@ -695,7 +695,7 @@ public class WindowsPathStrategyTests // Assert result.IsError.Should().BeTrue(); - result.FirstError.Should().Be(Errors.FileManagement.InvalidPath); + result.FirstError.Should().Be(Errors.FileSystemManagement.InvalidPath); } [Fact] @@ -709,7 +709,7 @@ public class WindowsPathStrategyTests // Assert result.IsError.Should().BeTrue(); - result.FirstError.Should().Be(Errors.FileManagement.InvalidPath); + result.FirstError.Should().Be(Errors.FileSystemManagement.InvalidPath); } [Fact] @@ -723,7 +723,7 @@ public class WindowsPathStrategyTests // Assert result.IsError.Should().BeTrue(); - result.FirstError.Should().Be(Errors.FileManagement.InvalidPath); + result.FirstError.Should().Be(Errors.FileSystemManagement.InvalidPath); } [Fact] @@ -737,7 +737,7 @@ public class WindowsPathStrategyTests // Assert result.IsError.Should().BeTrue(); - result.FirstError.Should().Be(Errors.FileManagement.InvalidPath); + result.FirstError.Should().Be(Errors.FileSystemManagement.InvalidPath); } [Fact] @@ -765,6 +765,6 @@ public class WindowsPathStrategyTests // Assert result.IsError.Should().BeTrue(); - result.FirstError.Should().Be(Errors.FileManagement.InvalidPath); + result.FirstError.Should().Be(Errors.FileSystemManagement.InvalidPath); } } diff --git a/tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/FileManagementAggregate/Strategies/Platform/Fixtures/INonExistentPlatformContextFixture.cs b/tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/FileSystemManagementAggregate/Strategies/Platform/Fixtures/INonExistentPlatformContextFixture.cs similarity index 61% rename from tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/FileManagementAggregate/Strategies/Platform/Fixtures/INonExistentPlatformContextFixture.cs rename to tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/FileSystemManagementAggregate/Strategies/Platform/Fixtures/INonExistentPlatformContextFixture.cs index 33106e51..f0597d1f 100644 --- a/tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/FileManagementAggregate/Strategies/Platform/Fixtures/INonExistentPlatformContextFixture.cs +++ b/tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/FileSystemManagementAggregate/Strategies/Platform/Fixtures/INonExistentPlatformContextFixture.cs @@ -1,8 +1,8 @@ #region ========================================================================= USING ===================================================================================== -using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.Strategies.Platform; +using Lumina.Domain.Core.Aggregates.FileSystemManagement.FileSystemManagementAggregate.Strategies.Platform; #endregion -namespace Lumina.Domain.UnitTests.Core.Aggregates.FileManagementAggregate.Strategies.Platform.Fixtures; +namespace Lumina.Domain.UnitTests.Core.Aggregates.FileSystemManagementAggregate.Strategies.Platform.Fixtures; /// /// Fixture interface for non existing platform context. diff --git a/tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/FileManagementAggregate/Strategies/Platform/PlatformContextFactoryTests.cs b/tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/FileSystemManagementAggregate/Strategies/Platform/PlatformContextFactoryTests.cs similarity index 84% rename from tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/FileManagementAggregate/Strategies/Platform/PlatformContextFactoryTests.cs rename to tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/FileSystemManagementAggregate/Strategies/Platform/PlatformContextFactoryTests.cs index bb6ad999..1e77260d 100644 --- a/tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/FileManagementAggregate/Strategies/Platform/PlatformContextFactoryTests.cs +++ b/tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/FileSystemManagementAggregate/Strategies/Platform/PlatformContextFactoryTests.cs @@ -1,15 +1,15 @@ #region ========================================================================= USING ===================================================================================== using FluentAssertions; -using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.Strategies.Path; -using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.Strategies.Platform; -using Lumina.Domain.UnitTests.Core.Aggregates.FileManagementAggregate.Strategies.Platform.Fixtures; +using Lumina.Domain.Core.Aggregates.FileSystemManagement.FileSystemManagementAggregate.Strategies.Path; +using Lumina.Domain.Core.Aggregates.FileSystemManagement.FileSystemManagementAggregate.Strategies.Platform; +using Lumina.Domain.UnitTests.Core.Aggregates.FileSystemManagementAggregate.Strategies.Platform.Fixtures; using Microsoft.Extensions.DependencyInjection; using System; using System.Diagnostics.CodeAnalysis; using System.IO.Abstractions; #endregion -namespace Lumina.Domain.UnitTests.Core.Aggregates.FileManagementAggregate.Strategies.Platform; +namespace Lumina.Domain.UnitTests.Core.Aggregates.FileSystemManagementAggregate.Strategies.Platform; /// /// Contains unit tests for the class. diff --git a/tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/FileManagementAggregate/Strategies/Platform/PlatformContextManagerTests.cs b/tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/FileSystemManagementAggregate/Strategies/Platform/PlatformContextManagerTests.cs similarity index 96% rename from tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/FileManagementAggregate/Strategies/Platform/PlatformContextManagerTests.cs rename to tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/FileSystemManagementAggregate/Strategies/Platform/PlatformContextManagerTests.cs index 80a69f65..a6518136 100644 --- a/tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/FileManagementAggregate/Strategies/Platform/PlatformContextManagerTests.cs +++ b/tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/FileSystemManagementAggregate/Strategies/Platform/PlatformContextManagerTests.cs @@ -1,14 +1,14 @@ #region ========================================================================= USING ===================================================================================== using FluentAssertions; using Lumina.Contracts.Enums.FileSystem; -using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.Strategies.Platform; +using Lumina.Domain.Core.Aggregates.FileSystemManagement.FileSystemManagementAggregate.Strategies.Platform; using NSubstitute; using System; using System.Diagnostics.CodeAnalysis; using System.Runtime.InteropServices; #endregion -namespace Lumina.Domain.UnitTests.Core.Aggregates.FileManagementAggregate.Strategies.Platform; +namespace Lumina.Domain.UnitTests.Core.Aggregates.FileSystemManagementAggregate.Strategies.Platform; /// /// Contains unit tests for the class. diff --git a/tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/FileManagementAggregate/Strategies/Platform/PlatformContextTests.cs b/tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/FileSystemManagementAggregate/Strategies/Platform/PlatformContextTests.cs similarity index 92% rename from tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/FileManagementAggregate/Strategies/Platform/PlatformContextTests.cs rename to tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/FileSystemManagementAggregate/Strategies/Platform/PlatformContextTests.cs index ac2720c7..c0c95882 100644 --- a/tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/FileManagementAggregate/Strategies/Platform/PlatformContextTests.cs +++ b/tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/FileSystemManagementAggregate/Strategies/Platform/PlatformContextTests.cs @@ -1,13 +1,13 @@ #region ========================================================================= USING ===================================================================================== using FluentAssertions; using Lumina.Contracts.Enums.FileSystem; -using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.Strategies.Path; -using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.Strategies.Platform; +using Lumina.Domain.Core.Aggregates.FileSystemManagement.FileSystemManagementAggregate.Strategies.Path; +using Lumina.Domain.Core.Aggregates.FileSystemManagement.FileSystemManagementAggregate.Strategies.Platform; using NSubstitute; using System.Diagnostics.CodeAnalysis; #endregion -namespace Lumina.Domain.UnitTests.Core.Aggregates.FileManagementAggregate.Strategies.Platform; +namespace Lumina.Domain.UnitTests.Core.Aggregates.FileSystemManagementAggregate.Strategies.Platform; /// /// Contains unit tests for the and classes. diff --git a/tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/FileManagementAggregate/ValueObjects/FileSystemPathIdTests.cs b/tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/FileSystemManagementAggregate/ValueObjects/FileSystemPathIdTests.cs similarity index 89% rename from tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/FileManagementAggregate/ValueObjects/FileSystemPathIdTests.cs rename to tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/FileSystemManagementAggregate/ValueObjects/FileSystemPathIdTests.cs index 40460aee..417f60bd 100644 --- a/tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/FileManagementAggregate/ValueObjects/FileSystemPathIdTests.cs +++ b/tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/FileSystemManagementAggregate/ValueObjects/FileSystemPathIdTests.cs @@ -2,12 +2,12 @@ using ErrorOr; using FluentAssertions; using Lumina.Domain.Common.Errors; -using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.ValueObjects; -using Lumina.Domain.UnitTests.Core.Aggregates.FileManagementAggregate.ValueObjects.Fixtures; +using Lumina.Domain.Core.Aggregates.FileSystemManagement.FileSystemManagementAggregate.ValueObjects; +using Lumina.Domain.UnitTests.Core.Aggregates.FileSystemManagementAggregate.ValueObjects.Fixtures; using System.Diagnostics.CodeAnalysis; #endregion -namespace Lumina.Domain.UnitTests.Core.Aggregates.FileManagementAggregate.ValueObjects; +namespace Lumina.Domain.UnitTests.Core.Aggregates.FileSystemManagementAggregate.ValueObjects; /// /// Contains unit tests for the class. @@ -43,14 +43,14 @@ public class FileSystemPathIdTests [InlineData(null)] [InlineData("")] [InlineData(" ")] - public void Create_WithInvalidPath_ShouldReturnError(string invalidPath) + public void Create_WithInvalidPath_ShouldReturnError(string? invalidPath) { // Act - ErrorOr result = FileSystemPathId.Create(invalidPath); + ErrorOr result = FileSystemPathId.Create(invalidPath!); // Assert result.IsError.Should().BeTrue(); - result.FirstError.Should().Be(Errors.FileManagement.InvalidPath); + result.FirstError.Should().Be(Errors.FileSystemManagement.InvalidPath); } [Fact] diff --git a/tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/FileSystemManagementAggregate/ValueObjects/Fixtures/FileSystemPathIdFixture.cs b/tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/FileSystemManagementAggregate/ValueObjects/Fixtures/FileSystemPathIdFixture.cs new file mode 100644 index 00000000..22a96da2 --- /dev/null +++ b/tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/FileSystemManagementAggregate/ValueObjects/Fixtures/FileSystemPathIdFixture.cs @@ -0,0 +1,42 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using ErrorOr; +using Lumina.Domain.Core.Aggregates.FileSystemManagement.FileSystemManagementAggregate.ValueObjects; +using System; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Domain.UnitTests.Core.Aggregates.FileSystemManagementAggregate.ValueObjects.Fixtures; + +/// +/// Fixture class for the class. +/// +[ExcludeFromCodeCoverage] +public class FileSystemPathIdFixture +{ + private readonly Faker _faker; + + /// + /// Initializes a new instance of the class. + /// + public FileSystemPathIdFixture() + { + _faker = new Faker(); + } + + /// + /// Creates a random valid . + /// + /// The path of the file system path element. + /// The created . + public FileSystemPathId CreateFileSystemPathId(string? path = null) + { + path ??= _faker.System.FilePath(); + + ErrorOr fileSystemPathIdResult = FileSystemPathId.Create(path); + + if (fileSystemPathIdResult.IsError) + throw new InvalidOperationException("Failed to create FileSystemPathId: " + string.Join(", ", fileSystemPathIdResult.Errors)); + return fileSystemPathIdResult.Value; + } +} diff --git a/tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/FileManagementAggregate/ValueObjects/Fixtures/PathSegmentFixture.cs b/tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/FileSystemManagementAggregate/ValueObjects/Fixtures/PathSegmentFixture.cs similarity index 89% rename from tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/FileManagementAggregate/ValueObjects/Fixtures/PathSegmentFixture.cs rename to tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/FileSystemManagementAggregate/ValueObjects/Fixtures/PathSegmentFixture.cs index 06c2aed4..158ba047 100644 --- a/tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/FileManagementAggregate/ValueObjects/Fixtures/PathSegmentFixture.cs +++ b/tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/FileSystemManagementAggregate/ValueObjects/Fixtures/PathSegmentFixture.cs @@ -1,14 +1,14 @@ #region ========================================================================= USING ===================================================================================== using Bogus; using ErrorOr; -using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.ValueObjects; +using Lumina.Domain.Core.Aggregates.FileSystemManagement.FileSystemManagementAggregate.ValueObjects; using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Linq; #endregion -namespace Lumina.Domain.UnitTests.Core.Aggregates.FileManagementAggregate.ValueObjects.Fixtures; +namespace Lumina.Domain.UnitTests.Core.Aggregates.FileSystemManagementAggregate.ValueObjects.Fixtures; /// /// Fixture class for the class. diff --git a/tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/FileManagementAggregate/ValueObjects/Fixtures/StreamInfoFixture.cs b/tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/FileSystemManagementAggregate/ValueObjects/Fixtures/StreamInfoFixture.cs similarity index 95% rename from tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/FileManagementAggregate/ValueObjects/Fixtures/StreamInfoFixture.cs rename to tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/FileSystemManagementAggregate/ValueObjects/Fixtures/StreamInfoFixture.cs index 0bc3fb71..27a5d0c9 100644 --- a/tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/FileManagementAggregate/ValueObjects/Fixtures/StreamInfoFixture.cs +++ b/tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/FileSystemManagementAggregate/ValueObjects/Fixtures/StreamInfoFixture.cs @@ -2,14 +2,14 @@ using Bogus; using ErrorOr; using Lumina.Domain.Common.Primitives; -using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.ValueObjects; +using Lumina.Domain.Core.Aggregates.FileSystemManagement.FileSystemManagementAggregate.ValueObjects; using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Linq; #endregion -namespace Lumina.Domain.UnitTests.Core.Aggregates.FileManagementAggregate.ValueObjects.Fixtures; +namespace Lumina.Domain.UnitTests.Core.Aggregates.FileSystemManagementAggregate.ValueObjects.Fixtures; /// /// Fixture class for the class. diff --git a/tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/FileManagementAggregate/ValueObjects/Fixtures/ThumbnailFixture.cs b/tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/FileSystemManagementAggregate/ValueObjects/Fixtures/ThumbnailFixture.cs similarity index 89% rename from tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/FileManagementAggregate/ValueObjects/Fixtures/ThumbnailFixture.cs rename to tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/FileSystemManagementAggregate/ValueObjects/Fixtures/ThumbnailFixture.cs index b38dbb87..b9aa8a21 100644 --- a/tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/FileManagementAggregate/ValueObjects/Fixtures/ThumbnailFixture.cs +++ b/tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/FileSystemManagementAggregate/ValueObjects/Fixtures/ThumbnailFixture.cs @@ -1,13 +1,13 @@ #region ========================================================================= USING ===================================================================================== using Bogus; using Lumina.Contracts.Enums.PhotoLibrary; -using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.ValueObjects; +using Lumina.Domain.Core.Aggregates.FileSystemManagement.FileSystemManagementAggregate.ValueObjects; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Linq; #endregion -namespace Lumina.Domain.UnitTests.Core.Aggregates.FileManagementAggregate.ValueObjects.Fixtures; +namespace Lumina.Domain.UnitTests.Core.Aggregates.FileSystemManagementAggregate.ValueObjects.Fixtures; /// /// Fixture class for the class. diff --git a/tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/FileManagementAggregate/ValueObjects/PathSegmentTests.cs b/tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/FileSystemManagementAggregate/ValueObjects/PathSegmentTests.cs similarity index 89% rename from tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/FileManagementAggregate/ValueObjects/PathSegmentTests.cs rename to tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/FileSystemManagementAggregate/ValueObjects/PathSegmentTests.cs index e4548c2e..f6fbe4bc 100644 --- a/tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/FileManagementAggregate/ValueObjects/PathSegmentTests.cs +++ b/tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/FileSystemManagementAggregate/ValueObjects/PathSegmentTests.cs @@ -2,12 +2,12 @@ using ErrorOr; using FluentAssertions; using Lumina.Domain.Common.Errors; -using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.ValueObjects; -using Lumina.Domain.UnitTests.Core.Aggregates.FileManagementAggregate.ValueObjects.Fixtures; +using Lumina.Domain.Core.Aggregates.FileSystemManagement.FileSystemManagementAggregate.ValueObjects; +using Lumina.Domain.UnitTests.Core.Aggregates.FileSystemManagementAggregate.ValueObjects.Fixtures; using System.Diagnostics.CodeAnalysis; #endregion -namespace Lumina.Domain.UnitTests.Core.Aggregates.FileManagementAggregate.ValueObjects; +namespace Lumina.Domain.UnitTests.Core.Aggregates.FileSystemManagementAggregate.ValueObjects; /// /// Contains unit tests for the class. @@ -47,14 +47,14 @@ public class PathSegmentTests [InlineData(null)] [InlineData("")] [InlineData(" ")] - public void Create_WithInvalidName_ShouldReturnError(string invalidName) + public void Create_WithInvalidName_ShouldReturnError(string? invalidName) { // Act - ErrorOr result = PathSegment.Create(invalidName, true, false); + ErrorOr result = PathSegment.Create(invalidName!, true, false); // Assert result.IsError.Should().BeTrue(); - result.FirstError.Should().Be(Errors.FileManagement.NameCannotBeEmpty); + result.FirstError.Should().Be(Errors.FileSystemManagement.NameCannotBeEmpty); } [Fact] diff --git a/tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/FileManagementAggregate/ValueObjects/StreamInfoTests.cs b/tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/FileSystemManagementAggregate/ValueObjects/StreamInfoTests.cs similarity index 82% rename from tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/FileManagementAggregate/ValueObjects/StreamInfoTests.cs rename to tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/FileSystemManagementAggregate/ValueObjects/StreamInfoTests.cs index 78b8ebe0..5c58d76d 100644 --- a/tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/FileManagementAggregate/ValueObjects/StreamInfoTests.cs +++ b/tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/FileSystemManagementAggregate/ValueObjects/StreamInfoTests.cs @@ -1,25 +1,15 @@ #region ========================================================================= USING ===================================================================================== using ErrorOr; using FluentAssertions; -using Lumina.Contracts.Enums.FileSystem; using Lumina.Domain.Common.Errors; using Lumina.Domain.Common.Primitives; -using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.Entities; -using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.Services; -using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.Strategies.Environment; -using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.Strategies.Platform; -using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.ValueObjects; -using Lumina.Domain.UnitTests.Core.Aggregates.FileManagementAggregate.Entities.Fixtures; -using Lumina.Domain.UnitTests.Core.Aggregates.FileManagementAggregate.ValueObjects.Fixtures; -using NSubstitute; -using System; -using System.Collections.Generic; +using Lumina.Domain.Core.Aggregates.FileSystemManagement.FileSystemManagementAggregate.ValueObjects; +using Lumina.Domain.UnitTests.Core.Aggregates.FileSystemManagementAggregate.ValueObjects.Fixtures; using System.Diagnostics.CodeAnalysis; -using System.Linq; #endregion -namespace Lumina.Domain.UnitTests.Core.Aggregates.FileManagementAggregate.ValueObjects; +namespace Lumina.Domain.UnitTests.Core.Aggregates.FileSystemManagementAggregate.ValueObjects; /// /// Contains unit tests for the class. @@ -79,7 +69,7 @@ public class StreamInfoTests // Assert result.IsError.Should().BeTrue(); - result.FirstError.Should().Be(Errors.FileManagement.StreamIdCannotBeEmpty); + result.FirstError.Should().Be(Errors.FileSystemManagement.StreamIdCannotBeEmpty); } [Fact] @@ -96,7 +86,7 @@ public class StreamInfoTests // Assert result.IsError.Should().BeTrue(); - result.FirstError.Should().Be(Errors.FileManagement.CodecCannotBeEmpty); + result.FirstError.Should().Be(Errors.FileSystemManagement.CodecCannotBeEmpty); } [Fact] @@ -113,7 +103,7 @@ public class StreamInfoTests // Assert result.IsError.Should().BeTrue(); - result.FirstError.Should().Be(Errors.FileManagement.BitrateMustBeAPositiveNumber); + result.FirstError.Should().Be(Errors.FileSystemManagement.BitrateMustBeAPositiveNumber); } [Fact] diff --git a/tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/FileManagementAggregate/ValueObjects/ThumbnailTests.cs b/tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/FileSystemManagementAggregate/ValueObjects/ThumbnailTests.cs similarity index 92% rename from tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/FileManagementAggregate/ValueObjects/ThumbnailTests.cs rename to tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/FileSystemManagementAggregate/ValueObjects/ThumbnailTests.cs index 0b085c48..57298a16 100644 --- a/tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/FileManagementAggregate/ValueObjects/ThumbnailTests.cs +++ b/tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/FileSystemManagementAggregate/ValueObjects/ThumbnailTests.cs @@ -1,15 +1,15 @@ #region ========================================================================= USING ===================================================================================== using FluentAssertions; using Lumina.Contracts.Enums.PhotoLibrary; -using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.ValueObjects; -using Lumina.Domain.UnitTests.Core.Aggregates.FileManagementAggregate.ValueObjects.Fixtures; +using Lumina.Domain.Core.Aggregates.FileSystemManagement.FileSystemManagementAggregate.ValueObjects; +using Lumina.Domain.UnitTests.Core.Aggregates.FileSystemManagementAggregate.ValueObjects.Fixtures; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Linq; #endregion -namespace Lumina.Domain.UnitTests.Core.Aggregates.FileManagementAggregate.ValueObjects; +namespace Lumina.Domain.UnitTests.Core.Aggregates.FileSystemManagementAggregate.ValueObjects; /// /// Contains unit tests for the class. diff --git a/tests/UnitTests/Lumina.Domain.UnitTests/Lumina.Domain.UnitTests.csproj b/tests/UnitTests/Lumina.Domain.UnitTests/Lumina.Domain.UnitTests.csproj index ed1f2d9f..5d139de7 100644 --- a/tests/UnitTests/Lumina.Domain.UnitTests/Lumina.Domain.UnitTests.csproj +++ b/tests/UnitTests/Lumina.Domain.UnitTests/Lumina.Domain.UnitTests.csproj @@ -14,13 +14,19 @@ - - - - + + all + runtime; build; native; contentfiles; analyzers; buildtransitive + + + + - - + + + all + runtime; build; native; contentfiles; analyzers; buildtransitive + diff --git a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Common/Validators/CommonSettingsModelValidatorTests.cs b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Common/Validators/CommonSettingsModelValidatorTests.cs index c046626e..142993de 100644 --- a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Common/Validators/CommonSettingsModelValidatorTests.cs +++ b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Common/Validators/CommonSettingsModelValidatorTests.cs @@ -10,7 +10,6 @@ using System.Diagnostics.CodeAnalysis; namespace Lumina.Infrastructure.UnitTests.Common.Validators; - /// /// Contains unit tests for the class. /// @@ -59,6 +58,6 @@ public class CommonSettingsModelValidatorTests // Assert result.IsValid.Should().BeFalse(); result.Errors.Should().ContainSingle() - .Which.ErrorMessage.Should().Be(Errors.Configuration.ApplicationThemeCannotBeEmpty.Code); + .Which.ErrorMessage.Should().Be(Errors.Configuration.ApplicationThemeCannotBeEmpty.Description); } -} \ No newline at end of file +} diff --git a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Common/Validators/DatabaseSettingsModelValidatorTests.cs b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Common/Validators/DatabaseSettingsModelValidatorTests.cs index afe33f36..9ac065ef 100644 --- a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Common/Validators/DatabaseSettingsModelValidatorTests.cs +++ b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Common/Validators/DatabaseSettingsModelValidatorTests.cs @@ -58,6 +58,6 @@ public class DatabaseSettingsModelValidatorTests // Assert result.IsValid.Should().BeFalse(); result.Errors.Should().ContainSingle() - .Which.ErrorMessage.Should().Be(Errors.Configuration.DatabaseConnectionStringCannotBeEmpty.Code); + .Which.ErrorMessage.Should().Be(Errors.Configuration.DatabaseConnectionStringCannotBeEmpty.Description); } } \ No newline at end of file diff --git a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Lumina.Infrastructure.UnitTests.csproj b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Lumina.Infrastructure.UnitTests.csproj index 2ab8a24c..a7903a6d 100644 --- a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Lumina.Infrastructure.UnitTests.csproj +++ b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Lumina.Infrastructure.UnitTests.csproj @@ -12,13 +12,19 @@ - - - - + + all + runtime; build; native; contentfiles; analyzers; buildtransitive + + + + - - + + + all + runtime; build; native; contentfiles; analyzers; buildtransitive + diff --git a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Controllers/Common/ApiControllerTests.cs b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Controllers/Common/ApiControllerTests.cs deleted file mode 100644 index 3c606339..00000000 --- a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Controllers/Common/ApiControllerTests.cs +++ /dev/null @@ -1,278 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using ErrorOr; -using FluentAssertions; -using Lumina.Presentation.Api.Common.Http; -using Lumina.Presentation.Api.Core.Controllers.Common; -using Lumina.Presentation.Api.UnitTests.Core.Controllers.Common.Fixtures; -using Microsoft.AspNetCore.Http; -using Microsoft.AspNetCore.Mvc; -using Microsoft.AspNetCore.Mvc.Infrastructure; -using Microsoft.AspNetCore.Mvc.ModelBinding; -using NSubstitute; -using System.Collections.Generic; -using System.Diagnostics.CodeAnalysis; -#endregion - -namespace Lumina.Presentation.Api.UnitTests.Core.Controllers.Common; - -/// -/// Contains unit tests for the class. -/// -[ExcludeFromCodeCoverage] -public class ApiControllerTests -{ - private readonly ApiControllerFixture _sut; - private readonly HttpContext _mockHttpContext; - private readonly ProblemDetailsFactory _mockProblemDetailsFactory; - - /// - /// Initializes a new instance of the class. - /// - public ApiControllerTests() - { - _sut = new ApiControllerFixture(); - _mockHttpContext = Substitute.For(); - _mockProblemDetailsFactory = Substitute.For(); - _sut.ControllerContext = new ControllerContext - { - HttpContext = _mockHttpContext - }; - _sut.ProblemDetailsFactory = _mockProblemDetailsFactory; - } - - [Fact] - public void Problem_WhenCalledWithNoErrors_ShouldReturnGenericProblem() - { - // Arrange - ProblemDetailsFactory mockProblemDetailsFactory = Substitute.For(); - mockProblemDetailsFactory.CreateProblemDetails( - Arg.Any(), - Arg.Any(), - Arg.Any(), - Arg.Any(), - Arg.Any(), - Arg.Any()) - .Returns(new ProblemDetails()); - - _sut.ProblemDetailsFactory = mockProblemDetailsFactory; - - // Act - IActionResult result = _sut.TestProblem([]); - - // Assert - result.Should().BeOfType(); - ObjectResult objectResult = (ObjectResult)result; - objectResult.Value.Should().BeOfType(); - } - - [Fact] - public void Problem_WhenCalledWithValidationErrors_ShouldReturnValidationProblem() - { - // Arrange - List errors = [ - Error.Validation("Code1", "Description1"), - Error.Validation("Code2", "Description2") - ]; - - _mockProblemDetailsFactory.CreateValidationProblemDetails( - Arg.Any(), - Arg.Any(), - Arg.Any(), - Arg.Any(), - Arg.Any(), - Arg.Any(), - Arg.Any()) - .Returns(new ValidationProblemDetails()); - - // Act - IActionResult result = _sut.TestProblem(errors); - - // Assert - result.Should().BeOfType(); - ObjectResult objectResult = (ObjectResult)result; - objectResult.Value.Should().BeOfType(); - } - - [Theory] - [InlineData(ErrorType.Conflict, StatusCodes.Status409Conflict)] - [InlineData(ErrorType.NotFound, StatusCodes.Status404NotFound)] - [InlineData(ErrorType.Validation, StatusCodes.Status400BadRequest)] - [InlineData(ErrorType.Failure, StatusCodes.Status403Forbidden)] - [InlineData(ErrorType.Unexpected, StatusCodes.Status500InternalServerError)] - public void Problem_WhenCalledWithSingleError_ShouldReturnCorrectStatusCode(ErrorType errorType, int expectedStatusCode) - { - // Arrange - Error error = errorType switch - { - ErrorType.Conflict => Error.Conflict("ErrorCode", "ErrorDescription"), - ErrorType.NotFound => Error.NotFound("ErrorCode", "ErrorDescription"), - ErrorType.Validation => Error.Validation("ErrorCode", "ErrorDescription"), - ErrorType.Failure => Error.Failure("ErrorCode", "ErrorDescription"), - _ => Error.Unexpected("ErrorCode", "ErrorDescription"), - }; - List errors = [error]; - - ProblemDetailsFactory mockProblemDetailsFactory = Substitute.For(); - mockProblemDetailsFactory.CreateProblemDetails( - Arg.Any(), - Arg.Any(), - Arg.Any(), - Arg.Any(), - Arg.Any(), - Arg.Any()) - .Returns(new ProblemDetails { Status = expectedStatusCode }); - - mockProblemDetailsFactory.CreateValidationProblemDetails( - Arg.Any(), - Arg.Any(), - Arg.Any(), - Arg.Any(), - Arg.Any(), - Arg.Any(), - Arg.Any()) - .Returns(new ValidationProblemDetails { Status = expectedStatusCode }); - - _sut.ProblemDetailsFactory = mockProblemDetailsFactory; - - // Act - IActionResult result = _sut.TestProblem(errors); - - // Assert - if (errorType == ErrorType.Validation) - { - result.Should().BeOfType(); - BadRequestObjectResult badRequestResult = (BadRequestObjectResult)result; - badRequestResult.StatusCode.Should().Be(expectedStatusCode); - badRequestResult.Value.Should().BeOfType(); - ((ValidationProblemDetails)badRequestResult.Value!).Status.Should().Be(expectedStatusCode); - - mockProblemDetailsFactory.Received(1).CreateValidationProblemDetails( - Arg.Any(), - Arg.Any(), - Arg.Is(status => status == null), - Arg.Is(title => title == "One or more validation errors occurred."), - Arg.Any(), - Arg.Any(), - Arg.Any()); - } - else - { - result.Should().BeOfType(); - ObjectResult objectResult = (ObjectResult)result; - objectResult.StatusCode.Should().Be(expectedStatusCode); - objectResult.Value.Should().BeOfType(); - ((ProblemDetails)objectResult.Value!).Status.Should().Be(expectedStatusCode); - - mockProblemDetailsFactory.Received(1).CreateProblemDetails( - Arg.Any(), - Arg.Is(status => status == expectedStatusCode), - Arg.Any(), - Arg.Any(), - Arg.Any(), - Arg.Any()); - } - } - - [Fact] - public void Problem_WhenCalledWithMixedErrors_ShouldReturnBadRequestObjectResult() - { - // Arrange - List errors = [ - Error.Validation("ValidationCode", "Validation Error"), - Error.Failure("FailureCode", "Failure Error") - ]; - - ProblemDetailsFactory mockProblemDetailsFactory = Substitute.For(); - mockProblemDetailsFactory.CreateProblemDetails( - Arg.Any(), - Arg.Any(), - Arg.Any(), - Arg.Any(), - Arg.Any(), - Arg.Any()) - .Returns(new ProblemDetails { Status = StatusCodes.Status400BadRequest }); - - _sut.ProblemDetailsFactory = mockProblemDetailsFactory; - - // Act - IActionResult result = _sut.TestProblem(errors); - - // Assert - result.Should().BeOfType(); - ObjectResult objectResult = (ObjectResult)result; - objectResult.StatusCode.Should().Be(StatusCodes.Status400BadRequest); - objectResult.Value.Should().BeOfType(); - ((ProblemDetails)objectResult.Value!).Status.Should().Be(StatusCodes.Status400BadRequest); - - mockProblemDetailsFactory.Received(1).CreateProblemDetails( - Arg.Any(), - Arg.Is(status => status == StatusCodes.Status400BadRequest), - Arg.Is(title => title == "Validation"), - Arg.Any(), - Arg.Is(detail => detail == "Validation Error"), - Arg.Any()); - } - - [Fact] - public void Problem_WhenCalled_ShouldAddErrorsToHttpContext() - { - // Arrange - List errors = [Error.Failure("ErrorCode", "ErrorDescription")]; - Dictionary mockItems = []; - _mockHttpContext.Items.Returns(mockItems!); - - ProblemDetailsFactory mockProblemDetailsFactory = Substitute.For(); - mockProblemDetailsFactory.CreateProblemDetails( - Arg.Any(), - Arg.Any(), - Arg.Any(), - Arg.Any(), - Arg.Any(), - Arg.Any()) - .Returns(new ProblemDetails()); - - _sut.ProblemDetailsFactory = mockProblemDetailsFactory; - - // Act - _sut.TestProblem(errors); - - // Assert - mockItems.Should().ContainKey(HttpContextItemKeys.ERRORS); - mockItems[HttpContextItemKeys.ERRORS].Should().BeEquivalentTo(errors); - } - - [Fact] - public void ValidationProblem_WhenCalled_ShouldAddErrorsToModelState() - { - // Arrange - List errors = [ - Error.Validation("Code1", "Description1"), - Error.Validation("Code2", "Description2") - ]; - - _mockProblemDetailsFactory.CreateValidationProblemDetails( - Arg.Any(), - Arg.Any(), - Arg.Any(), - Arg.Any(), - Arg.Any(), - Arg.Any(), - Arg.Any()) - .Returns(callInfo => - { - ModelStateDictionary modelState = callInfo.ArgAt(1); - return new ValidationProblemDetails(modelState); - }); - - // Act - IActionResult result = _sut.TestValidationProblem(errors); - - // Assert - result.Should().BeOfType(); - ObjectResult objectResult = (ObjectResult)result; - ValidationProblemDetails validationProblem = objectResult.Value.Should().BeOfType().Subject; - validationProblem.Errors.Should().ContainKeys("Code1", "Code2"); - validationProblem.Errors["Code1"].Should().Contain("Description1"); - validationProblem.Errors["Code2"].Should().Contain("Description2"); - } -} diff --git a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Controllers/Common/Fixtures/ApiControllerFixture.cs b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Controllers/Common/Fixtures/ApiControllerFixture.cs deleted file mode 100644 index 7a51238e..00000000 --- a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Controllers/Common/Fixtures/ApiControllerFixture.cs +++ /dev/null @@ -1,36 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using ErrorOr; -using Lumina.Presentation.Api.Core.Controllers.Common; -using Microsoft.AspNetCore.Mvc; -using System.Collections.Generic; -using System.Diagnostics.CodeAnalysis; -#endregion - -namespace Lumina.Presentation.Api.UnitTests.Core.Controllers.Common.Fixtures; - -/// -/// Fixture class for the class. -/// -[ExcludeFromCodeCoverage] -public class ApiControllerFixture : ApiController -{ - /// - /// Returns a standardized error response using the format. - /// - /// A list of errors to include in the response. - /// An with the problem details containing the specified errors. - public IActionResult TestProblem(List errors) - { - return Problem(errors); - } - - /// - /// Returns a standardized validation error response using the format. - /// - /// A list of validation errors to include in the response. - /// An with the validation problem details containing the specified errors. - public IActionResult TestValidationProblem(List errors) - { - return ValidationProblem(errors); - } -} diff --git a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Controllers/FileManagement/DirectoriesControllerTests.cs b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Controllers/FileManagement/DirectoriesControllerTests.cs deleted file mode 100644 index 956307b5..00000000 --- a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Controllers/FileManagement/DirectoriesControllerTests.cs +++ /dev/null @@ -1,228 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using AutoFixture; -using AutoFixture.AutoNSubstitute; -using ErrorOr; -using FluentAssertions; -using Lumina.Application.Core.FileManagement.Directories.Queries.GetDirectories; -using Lumina.Application.Core.FileManagement.Directories.Queries.GetDirectoryTree; -using Lumina.Application.Core.FileManagement.Directories.Queries.GetTreeDirectories; -using Lumina.Contracts.Responses.FileManagement; -using Lumina.Domain.Common.Errors; -using Lumina.Presentation.Api.Core.Controllers.FileManagement; -using Lumina.Presentation.Api.UnitTests.Core.Controllers.FileManagement.Fixtures; -using Mediator; -using NSubstitute; -using System.Collections.Generic; -using System.Diagnostics.CodeAnalysis; -using System.Linq; -using System.Threading; -using System.Threading.Tasks; -#endregion - -namespace Lumina.Presentation.Api.UnitTests.Core.Controllers.FileManagement; - -/// -/// Contains unit tests for the class. -/// -[ExcludeFromCodeCoverage] -public class DirectoriesControllerTests -{ - private readonly IFixture _fixture; - private readonly ISender _mockMediator; - private readonly DirectoriesController _sut; - private readonly FileSystemTreeNodeResponseFixture _fileSystemTreeNodeResponseFixture; - - /// - /// Initializes a new instance of the class. - /// - public DirectoriesControllerTests() - { - _fixture = new Fixture().Customize(new AutoNSubstituteCustomization()); - _mockMediator = Substitute.For(); - _sut = new DirectoriesController(_mockMediator); - _fileSystemTreeNodeResponseFixture = new FileSystemTreeNodeResponseFixture(); - } - - [Fact] - public async Task GetDirectoryTree_WhenCalled_ShouldReturnFileSystemTreeNodeResponses() - { - // Arrange - string path = @"C:\TestDir"; - bool includeFiles = true; - bool includeHiddenElements = false; - CancellationToken cancellationToken = CancellationToken.None; - - List expectedResponses = _fileSystemTreeNodeResponseFixture.CreateMany(3, 3, 5); - _mockMediator.Send(Arg.Any(), Arg.Any()) - .Returns(ErrorOrFactory.From(expectedResponses.AsEnumerable())); - - // Act - IAsyncEnumerable result = _sut.GetDirectoryTree(path, includeFiles, includeHiddenElements, cancellationToken); - - // Assert - List actualResponses = await result.ToListAsync(cancellationToken); - actualResponses.Should().BeEquivalentTo(expectedResponses); - } - - [Fact] - public async Task GetDirectoryTree_WhenMediatorReturnsError_ShouldReturnEmptyEnumerable() - { - // Arrange - string path = @"C:\TestDir"; - bool includeFiles = true; - bool includeHiddenElements = false; - CancellationToken cancellationToken = CancellationToken.None; - - _mockMediator.Send(Arg.Any(), Arg.Any()) - .Returns(Errors.FileManagement.DirectoryNotFound); - - // Act - IAsyncEnumerable result = _sut.GetDirectoryTree(path, includeFiles, includeHiddenElements, cancellationToken); - - // Assert - List actualResponses = await result.ToListAsync(cancellationToken); - actualResponses.Should().BeEmpty(); - } - - [Fact] - public async Task GetTreeDirectories_WhenCalled_ShouldReturnFileSystemTreeNodeResponses() - { - // Arrange - string path = @"C:\TestDir"; - bool includeHiddenElements = false; - CancellationToken cancellationToken = CancellationToken.None; - - List expectedResponses = _fileSystemTreeNodeResponseFixture.CreateMany(3, 3, 5); - _mockMediator.Send(Arg.Any(), Arg.Any()) - .Returns(ErrorOrFactory.From(expectedResponses.AsEnumerable())); - - // Act - IAsyncEnumerable result = _sut.GetTreeDirectories(path, includeHiddenElements, cancellationToken); - - // Assert - List actualResponses = await result.ToListAsync(cancellationToken); - actualResponses.Should().BeEquivalentTo(expectedResponses); - } - - [Fact] - public async Task GetTreeDirectories_WhenMediatorReturnsError_ShouldReturnEmptyEnumerable() - { - // Arrange - string path = @"C:\TestDir"; - bool includeHiddenElements = false; - CancellationToken cancellationToken = CancellationToken.None; - - _mockMediator.Send(Arg.Any(), Arg.Any()) - .Returns(Errors.FileManagement.DirectoryNotFound); - - // Act - IAsyncEnumerable result = _sut.GetTreeDirectories(path, includeHiddenElements, cancellationToken); - - // Assert - List actualResponses = await result.ToListAsync(cancellationToken); - actualResponses.Should().BeEmpty(); - } - - [Fact] - public async Task GetDirectories_WhenCalled_ShouldReturnDirectoryResponses() - { - // Arrange - string path = @"C:\TestDir"; - bool includeHiddenElements = false; - CancellationToken cancellationToken = CancellationToken.None; - - List expectedResponses = _fixture.CreateMany(3).ToList(); - _mockMediator.Send(Arg.Any(), Arg.Any()) - .Returns(ErrorOrFactory.From(expectedResponses.AsEnumerable())); - - // Act - IAsyncEnumerable result = _sut.GetDirectories(path, includeHiddenElements, cancellationToken); - - // Assert - List actualResponses = await result.ToListAsync(cancellationToken); - actualResponses.Should().BeEquivalentTo(expectedResponses); - } - - [Fact] - public async Task GetDirectories_WhenMediatorReturnsError_ShouldReturnEmptyEnumerable() - { - // Arrange - string path = @"C:\TestDir"; - bool includeHiddenElements = false; - CancellationToken cancellationToken = CancellationToken.None; - - _mockMediator.Send(Arg.Any(), Arg.Any()) - .Returns(Errors.FileManagement.DirectoryNotFound); - - // Act - IAsyncEnumerable result = _sut.GetDirectories(path, includeHiddenElements, cancellationToken); - - // Assert - List actualResponses = await result.ToListAsync(cancellationToken); - actualResponses.Should().BeEmpty(); - } - - [Fact] - public async Task GetDirectoryTree_WhenCancellationRequested_ShouldCancelEnumeration() - { - // Arrange - string path = @"C:\TestDir"; - bool includeFiles = true; - bool includeHiddenElements = false; - CancellationTokenSource cts = new(); - - List expectedResponses = _fileSystemTreeNodeResponseFixture.CreateMany(100, 3, 5); - _mockMediator.Send(Arg.Any(), Arg.Any()) - .Returns(ErrorOrFactory.From(expectedResponses.AsEnumerable())); - - // Act - IAsyncEnumerable result = _sut.GetDirectoryTree(path, includeFiles, includeHiddenElements, cts.Token); - cts.Cancel(); - - // Assert - List actualResponses = await result.ToListAsync(); - actualResponses.Should().BeEmpty(); - } - - [Fact] - public async Task GetTreeDirectories_WhenCalled_ShouldCancelEnumerationWhenCancellationRequested() - { - // Arrange - string path = @"C:\TestDir"; - bool includeHiddenElements = false; - CancellationTokenSource cts = new(); - - List expectedResponses = _fileSystemTreeNodeResponseFixture.CreateMany(100, 3, 5); - _mockMediator.Send(Arg.Any(), Arg.Any()) - .Returns(ErrorOrFactory.From(expectedResponses.AsEnumerable())); - - // Act - IAsyncEnumerable result = _sut.GetTreeDirectories(path, includeHiddenElements, cts.Token); - cts.Cancel(); - - // Assert - List actualResponses = await result.ToListAsync(); - actualResponses.Should().BeEmpty(); - } - - [Fact] - public async Task GetDirectories_WhenCancellationRequested_ShouldCancelEnumeration() - { - // Arrange - string path = @"C:\TestDir"; - bool includeHiddenElements = false; - CancellationTokenSource cts = new(); - - List expectedResponses = _fixture.CreateMany(100).ToList(); - _mockMediator.Send(Arg.Any(), Arg.Any()) - .Returns(ErrorOrFactory.From(expectedResponses.AsEnumerable())); - - // Act - IAsyncEnumerable result = _sut.GetDirectories(path, includeHiddenElements, cts.Token); - cts.Cancel(); - - // Assert - List actualResponses = await result.ToListAsync(); - actualResponses.Should().BeEmpty(); - } -} diff --git a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Controllers/FileManagement/DrivesControllerTests.cs b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Controllers/FileManagement/DrivesControllerTests.cs deleted file mode 100644 index d7dc628a..00000000 --- a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Controllers/FileManagement/DrivesControllerTests.cs +++ /dev/null @@ -1,149 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using ErrorOr; -using FluentAssertions; -using Lumina.Application.Core.FileManagement.Drives.Queries.GetDrives; -using Lumina.Contracts.Responses.FileManagement; -using Lumina.Presentation.Api.Common.Http; -using Lumina.Presentation.Api.Core.Controllers.FileManagement; -using Lumina.Presentation.Api.UnitTests.Core.Controllers.FileManagement.Fixtures; -using Mediator; -using Microsoft.AspNetCore.Http; -using Microsoft.AspNetCore.Mvc; -using Microsoft.AspNetCore.Mvc.Infrastructure; -using NSubstitute; -using System; -using System.Collections.Generic; -using System.Diagnostics.CodeAnalysis; -using System.Linq; -using System.Threading; -using System.Threading.Tasks; -#endregion - -namespace Lumina.Presentation.Api.UnitTests.Core.Controllers.FileManagement; - -/// -/// Contains unit tests for the class. -/// -[ExcludeFromCodeCoverage] -public class DrivesControllerTests -{ - private readonly ISender _mockMediator; - private readonly DrivesController _sut; - private readonly FileSystemTreeNodeResponseFixture _fileSystemTreeNodeResponseFixture; - - /// - /// Initializes a new instance of the class. - /// - public DrivesControllerTests() - { - _mockMediator = Substitute.For(); - _sut = new DrivesController(_mockMediator); - _fileSystemTreeNodeResponseFixture = new FileSystemTreeNodeResponseFixture(); - } - - [Fact] - public async Task GetDrives_WhenCalled_ShouldReturnOkResultWithFileSystemTreeNodeResponses() - { - // Arrange - CancellationToken cancellationToken = CancellationToken.None; - List expectedResponses = _fileSystemTreeNodeResponseFixture.CreateMany(3, 1, 1); - _mockMediator.Send(Arg.Any(), Arg.Any()) - .Returns(ErrorOrFactory.From(expectedResponses.AsEnumerable())); - - // Act - IActionResult result = await _sut.GetDrives(cancellationToken); - - // Assert - OkObjectResult okResult = result.Should().BeOfType().Subject; - IEnumerable actualResponses = okResult.Value.Should().BeAssignableTo>().Subject; - actualResponses.Should().BeEquivalentTo(expectedResponses); - } - - [Fact] - public async Task GetDrives_WhenMediatorReturnsError_ShouldReturnProblemResult() - { - // Arrange - CancellationToken cancellationToken = CancellationToken.None; - Error expectedError = Error.NotFound("Drive.NotFound", "The requested drive was not found."); - _mockMediator.Send(Arg.Any(), Arg.Any()) - .Returns(expectedError); - HttpContext mockHttpContext = Substitute.For(); - Dictionary mockItems = []; - mockHttpContext.Items.Returns(mockItems!); - _sut.ControllerContext = new ControllerContext - { - HttpContext = mockHttpContext - }; - ProblemDetailsFactory mockProblemDetailsFactory = Substitute.For(); - mockProblemDetailsFactory.CreateProblemDetails( - Arg.Any(), - Arg.Any(), - Arg.Any(), - Arg.Any(), - Arg.Any(), - Arg.Any()) - .Returns(new ProblemDetails - { - Status = StatusCodes.Status404NotFound, - Title = ErrorType.NotFound.ToString(), - Detail = "The requested drive was not found." - }); - _sut.ProblemDetailsFactory = mockProblemDetailsFactory; - - // Act - IActionResult result = await _sut.GetDrives(cancellationToken); - - // Assert - ObjectResult objectResult = result.Should().BeOfType().Subject; - objectResult.StatusCode.Should().Be(StatusCodes.Status404NotFound); - - ProblemDetails problemDetails = objectResult.Value.Should().BeOfType().Subject; - problemDetails.Title.Should().Be(ErrorType.NotFound.ToString()); - problemDetails.Detail.Should().Be("The requested drive was not found."); - problemDetails.Status.Should().Be(StatusCodes.Status404NotFound); - mockItems.Should().ContainKey(HttpContextItemKeys.ERRORS); - mockItems[HttpContextItemKeys.ERRORS].Should().BeEquivalentTo(new List { expectedError }); - } - - [Fact] - public async Task GetDrives_WhenCalled_ShouldSendGetDrivesQueryToMediator() - { - // Arrange - CancellationToken cancellationToken = CancellationToken.None; - _mockMediator.Send(Arg.Any(), Arg.Any()) - .Returns(ErrorOrFactory.From(Enumerable.Empty())); - - // Act - await _sut.GetDrives(cancellationToken); - - // Assert - await _mockMediator.Received(1).Send(Arg.Any(), Arg.Is(cancellationToken)); - } - - [Fact] - public async Task GetDrives_WhenCancellationRequested_ShouldCancelOperation() - { - // Arrange - CancellationTokenSource cts = new(); - TaskCompletionSource operationStarted = new(); - TaskCompletionSource cancellationRequested = new(); - - _mockMediator.Send(Arg.Any(), Arg.Any()) - .Returns(callInfo => new ValueTask>>(Task.Run(async () => - { - operationStarted.SetResult(true); - await cancellationRequested.Task; - callInfo.Arg().ThrowIfCancellationRequested(); - return ErrorOrFactory.From(_fileSystemTreeNodeResponseFixture.CreateMany(3, 1, 1).AsEnumerable()); - }, callInfo.Arg()))); - - // Act - Task operationTask = _sut.GetDrives(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/Controllers/FileManagement/FileSystemControllerTests.cs b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Controllers/FileManagement/FileSystemControllerTests.cs deleted file mode 100644 index ddbef04a..00000000 --- a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Controllers/FileManagement/FileSystemControllerTests.cs +++ /dev/null @@ -1,115 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using FluentAssertions; -using Lumina.Application.Core.FileManagement.FileSystem.Queries.GetFileSystem; -using Lumina.Contracts.Enums.FileSystem; -using Lumina.Contracts.Responses.FileManagement; -using Lumina.Presentation.Api.Core.Controllers.FileManagement; -using Mediator; -using Microsoft.AspNetCore.Mvc; -using NSubstitute; -using System; -using System.Diagnostics.CodeAnalysis; -using System.Threading; -using System.Threading.Tasks; -#endregion - -namespace Lumina.Presentation.Api.UnitTests.Core.Controllers.FileManagement; - -/// -/// Contains unit tests for the class. -/// -[ExcludeFromCodeCoverage] -public class FileSystemControllerTests -{ - private readonly ISender _mockMediator; - private readonly FileSystemController _sut; - - /// - /// Initializes a new instance of the class. - /// - public FileSystemControllerTests() - { - _mockMediator = Substitute.For(); - _sut = new FileSystemController(_mockMediator); - } - - [Fact] - public async Task GetType_WhenCalled_ShouldReturnOkResultWithFileSystemTypeResponse() - { - // Arrange - CancellationToken cancellationToken = CancellationToken.None; - FileSystemTypeResponse expectedResponse = new(PlatformType.Windows); - _mockMediator.Send(Arg.Any(), Arg.Any()) - .Returns(expectedResponse); - - // Act - IActionResult result = await _sut.GetType(cancellationToken); - - // Assert - OkObjectResult okResult = result.Should().BeOfType().Subject; - FileSystemTypeResponse actualResponse = okResult.Value.Should().BeAssignableTo().Subject; - actualResponse.Should().BeEquivalentTo(expectedResponse); - } - - [Theory] - [InlineData(PlatformType.Windows)] - [InlineData(PlatformType.Unix)] - public async Task GetType_WithDifferentPlatformTypes_ShouldReturnCorrectResponse(PlatformType platformType) - { - // Arrange - CancellationToken cancellationToken = CancellationToken.None; - FileSystemTypeResponse expectedResponse = new(platformType); - _mockMediator.Send(Arg.Any(), Arg.Any()) - .Returns(expectedResponse); - - // Act - IActionResult result = await _sut.GetType(cancellationToken); - - // Assert - OkObjectResult okResult = result.Should().BeOfType().Subject; - FileSystemTypeResponse actualResponse = okResult.Value.Should().BeAssignableTo().Subject; - actualResponse.PlatformType.Should().Be(platformType); - } - - [Fact] - public async Task GetType_WhenCalled_ShouldSendGetFileSystemQueryToMediator() - { - // Arrange - CancellationToken cancellationToken = CancellationToken.None; - _mockMediator.Send(Arg.Any(), Arg.Any()) - .Returns(new FileSystemTypeResponse(PlatformType.Windows)); - - // Act - await _sut.GetType(cancellationToken); - - // Assert - await _mockMediator.Received(1).Send(Arg.Any(), Arg.Is(cancellationToken)); - } - - [Fact] - public async Task GetType_WhenCancellationRequested_ShouldCancelOperation() - { - // Arrange - CancellationTokenSource cts = new(); - TaskCompletionSource operationStarted = new(); - TaskCompletionSource cancellationRequested = new(); - - _mockMediator.Send(Arg.Any(), Arg.Any()) - .Returns(callInfo => new ValueTask(Task.Run(async () => - { - operationStarted.SetResult(true); - await cancellationRequested.Task; - callInfo.Arg().ThrowIfCancellationRequested(); - return new FileSystemTypeResponse(PlatformType.Windows); - }, callInfo.Arg()))); - - // Act - Task operationTask = _sut.GetType(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/Controllers/FileManagement/FilesControllerTests.cs b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Controllers/FileManagement/FilesControllerTests.cs deleted file mode 100644 index 46516636..00000000 --- a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Controllers/FileManagement/FilesControllerTests.cs +++ /dev/null @@ -1,165 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using AutoFixture; -using AutoFixture.AutoNSubstitute; -using ErrorOr; -using FluentAssertions; -using Lumina.Application.Core.FileManagement.Files.Queries.GetFiles; -using Lumina.Application.Core.FileManagement.Files.Queries.GetTreeFiles; -using Lumina.Contracts.Responses.FileManagement; -using Lumina.Domain.Common.Errors; -using Lumina.Presentation.Api.Core.Controllers.FileManagement; -using Lumina.Presentation.Api.UnitTests.Core.Controllers.FileManagement.Fixtures; -using Mediator; -using NSubstitute; -using System.Collections.Generic; -using System.Diagnostics.CodeAnalysis; -using System.Linq; -using System.Threading; -using System.Threading.Tasks; -#endregion - - -namespace Lumina.Presentation.Api.UnitTests.Core.Controllers.FileManagement; - -/// -/// Contains unit tests for the class. -/// -[ExcludeFromCodeCoverage] -public class FilesControllerTests -{ - private readonly IFixture _fixture; - private readonly ISender _mockMediator; - private readonly FilesController _sut; - private readonly FileSystemTreeNodeResponseFixture _fileSystemTreeNodeResponseFixture; - - /// - /// Initializes a new instance of the class. - /// - public FilesControllerTests() - { - _fixture = new Fixture().Customize(new AutoNSubstituteCustomization()); - _mockMediator = Substitute.For(); - _sut = new FilesController(_mockMediator); - _fileSystemTreeNodeResponseFixture = new FileSystemTreeNodeResponseFixture(); - } - - [Fact] - public async Task GetTreeFiles_WhenCalled_ShouldReturnFileSystemTreeNodeResponses() - { - // Arrange - string path = @"C:\TestDir"; - bool includeHiddenElements = false; - CancellationToken cancellationToken = CancellationToken.None; - - List expectedResponses = _fileSystemTreeNodeResponseFixture.CreateMany(3, 3, 5); - _mockMediator.Send(Arg.Any(), Arg.Any()) - .Returns(ErrorOrFactory.From(expectedResponses.AsEnumerable())); - - // Act - IAsyncEnumerable result = _sut.GetTreeFiles(path, includeHiddenElements, cancellationToken); - - // Assert - List actualResponses = await result.ToListAsync(cancellationToken); - actualResponses.Should().BeEquivalentTo(expectedResponses); - } - - [Fact] - public async Task GetTreeFiles_WhenMediatorReturnsError_ShouldReturnEmptyEnumerable() - { - // Arrange - string path = @"C:\TestDir"; - bool includeHiddenElements = false; - CancellationToken cancellationToken = CancellationToken.None; - - _mockMediator.Send(Arg.Any(), Arg.Any()) - .Returns(Errors.FileManagement.DirectoryNotFound); - - // Act - IAsyncEnumerable result = _sut.GetTreeFiles(path, includeHiddenElements, cancellationToken); - - // Assert - List actualResponses = await result.ToListAsync(cancellationToken); - actualResponses.Should().BeEmpty(); - } - - [Fact] - public async Task GetFiles_WhenCalled_ShouldReturnFileResponses() - { - // Arrange - string path = @"C:\TestDir"; - bool includeHiddenElements = false; - CancellationToken cancellationToken = CancellationToken.None; - - List expectedResponses = _fixture.CreateMany(3).ToList(); - _mockMediator.Send(Arg.Any(), Arg.Any()) - .Returns(ErrorOrFactory.From(expectedResponses.AsEnumerable())); - - // Act - IAsyncEnumerable result = _sut.GetFiles(path, includeHiddenElements, cancellationToken); - - // Assert - List actualResponses = await result.ToListAsync(cancellationToken); - actualResponses.Should().BeEquivalentTo(expectedResponses); - } - - [Fact] - public async Task GetFiles_WhenMediatorReturnsError_ShouldReturnEmptyEnumerable() - { - // Arrange - string path = @"C:\TestDir"; - bool includeHiddenElements = false; - CancellationToken cancellationToken = CancellationToken.None; - - _mockMediator.Send(Arg.Any(), Arg.Any()) - .Returns(Errors.FileManagement.DirectoryNotFound); - - // Act - IAsyncEnumerable result = _sut.GetFiles(path, includeHiddenElements, cancellationToken); - - // Assert - List actualResponses = await result.ToListAsync(cancellationToken); - actualResponses.Should().BeEmpty(); - } - - [Fact] - public async Task GetTreeFiles_WhenCancellationRequested_ShouldCancelEnumeration() - { - // Arrange - string path = @"C:\TestDir"; - bool includeHiddenElements = false; - CancellationTokenSource cts = new(); - - List expectedResponses = _fileSystemTreeNodeResponseFixture.CreateMany(100, 3, 5); - _mockMediator.Send(Arg.Any(), Arg.Any()) - .Returns(ErrorOrFactory.From(expectedResponses.AsEnumerable())); - - // Act - IAsyncEnumerable result = _sut.GetTreeFiles(path, includeHiddenElements, cts.Token); - cts.Cancel(); - - // Assert - List actualResponses = await result.ToListAsync(); - actualResponses.Should().BeEmpty(); - } - - [Fact] - public async Task GetFiles_WhenCancellationRequested_ShouldCancelEnumeration() - { - // Arrange - string path = @"C:\TestDir"; - bool includeHiddenElements = false; - CancellationTokenSource cts = new(); - - List expectedResponses = _fixture.CreateMany(100).ToList(); - _mockMediator.Send(Arg.Any(), Arg.Any()) - .Returns(ErrorOrFactory.From(expectedResponses.AsEnumerable())); - - // Act - IAsyncEnumerable result = _sut.GetFiles(path, includeHiddenElements, cts.Token); - cts.Cancel(); - - // Assert - List actualResponses = await result.ToListAsync(); - actualResponses.Should().BeEmpty(); - } -} diff --git a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Controllers/FileManagement/PathControllerTests.cs b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Controllers/FileManagement/PathControllerTests.cs deleted file mode 100644 index a751ce21..00000000 --- a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Controllers/FileManagement/PathControllerTests.cs +++ /dev/null @@ -1,737 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using ErrorOr; -using FluentAssertions; -using Lumina.Application.Core.FileManagement.Paths.Commands.CombinePath; -using Lumina.Application.Core.FileManagement.Paths.Commands.SplitPath; -using Lumina.Application.Core.FileManagement.Paths.Queries.CheckPathExists; -using Lumina.Application.Core.FileManagement.Paths.Queries.GetPathParent; -using Lumina.Application.Core.FileManagement.Paths.Queries.GetPathRoot; -using Lumina.Application.Core.FileManagement.Paths.Queries.GetPathSeparator; -using Lumina.Application.Core.FileManagement.Paths.Queries.ValidatePath; -using Lumina.Contracts.Responses.FileManagement; -using Lumina.Presentation.Api.Core.Controllers.FileManagement; -using Lumina.Presentation.Api.UnitTests.Core.Controllers.FileManagement.Fixtures; -using Mediator; -using Microsoft.AspNetCore.Http; -using Microsoft.AspNetCore.Mvc; -using Microsoft.AspNetCore.Mvc.Infrastructure; -using Microsoft.AspNetCore.Mvc.ModelBinding; -using NSubstitute; -using System; -using System.Collections.Generic; -using System.Diagnostics.CodeAnalysis; -using System.Linq; -using System.Threading; -using System.Threading.Tasks; -#endregion - -namespace Lumina.Presentation.Api.UnitTests.Core.Controllers.FileManagement; - -/// -/// Contains unit tests for the class. -/// -[ExcludeFromCodeCoverage] -public class PathControllerTests -{ - private readonly ISender _mockMediator; - private readonly PathController _sut; - private readonly PathSegmentResponseFixture _pathSegmentResponseFixture; - private readonly PathSeparatorResponseFixture _pathSeparatorResponseFixture; - - /// - /// Initializes a new instance of the class. - /// - public PathControllerTests() - { - _mockMediator = Substitute.For(); - _sut = new PathController(_mockMediator); - _pathSegmentResponseFixture = new PathSegmentResponseFixture(); - _pathSeparatorResponseFixture = new PathSeparatorResponseFixture(); - } - - [Fact] - public async Task GetPathRoot_WhenCalled_ShouldReturnOkResultWithPathSegmentResponse() - { - // Arrange - string path = @"C:\Users\TestUser"; - CancellationToken cancellationToken = CancellationToken.None; - PathSegmentResponse expectedResponse = _pathSegmentResponseFixture.Create(); - _mockMediator.Send(Arg.Any(), Arg.Any()) - .Returns(ErrorOrFactory.From(expectedResponse)); - - // Act - IActionResult result = await _sut.GetPathRoot(path, cancellationToken); - - // Assert - OkObjectResult okResult = result.Should().BeOfType().Subject; - PathSegmentResponse actualResponse = okResult.Value.Should().BeAssignableTo().Subject; - actualResponse.Should().BeEquivalentTo(expectedResponse); - } - - [Fact] - public async Task GetPathRoot_WhenMediatorReturnsError_ShouldReturnProblemResult() - { - // Arrange - string path = @"InvalidPath"; - CancellationToken cancellationToken = CancellationToken.None; - Error expectedError = Error.Validation("Path.Invalid", "The provided path is invalid."); - _mockMediator.Send(Arg.Any(), Arg.Any()) - .Returns(expectedError); - - _sut.ControllerContext = new ControllerContext(); - - ProblemDetailsFactory mockProblemDetailsFactory = Substitute.For(); - mockProblemDetailsFactory.CreateProblemDetails( - Arg.Any(), - Arg.Any(), - Arg.Is(ErrorType.Validation.ToString()), - Arg.Any(), - Arg.Any(), - Arg.Any()) - .Returns(new ProblemDetails - { - Status = StatusCodes.Status400BadRequest, - Title = ErrorType.Validation.ToString(), - Detail = "The provided path is invalid." - }); - _sut.ProblemDetailsFactory = mockProblemDetailsFactory; - ValidationProblemDetails expectedValidationProblemDetails = new() - { - Status = StatusCodes.Status400BadRequest, - Title = "One or more validation errors occurred.", - Errors = - { - { "Path.Invalid", new[] { "The provided path is invalid." } } - } - }; - - mockProblemDetailsFactory.CreateValidationProblemDetails( - Arg.Any(), - Arg.Any(), - Arg.Any(), - Arg.Any(), - Arg.Any(), - Arg.Any(), - Arg.Any()) - .Returns(expectedValidationProblemDetails); - - // Act - IActionResult result = await _sut.GetPathRoot(path, cancellationToken); - - // Assert - BadRequestObjectResult badRequestResult = result.Should().BeOfType().Subject; - badRequestResult.StatusCode.Should().Be(StatusCodes.Status400BadRequest); - - ValidationProblemDetails actualValidationProblemDetails = badRequestResult.Value.Should().BeOfType().Subject; - actualValidationProblemDetails.Should().BeEquivalentTo(expectedValidationProblemDetails); - } - - [Fact] - public async Task GetPathRoot_WhenCalled_ShouldSendGetPathRootQueryToMediator() - { - // Arrange - string path = @"C:\Users\TestUser"; - CancellationToken cancellationToken = CancellationToken.None; - _mockMediator.Send(Arg.Any(), Arg.Any()) - .Returns(ErrorOrFactory.From(_pathSegmentResponseFixture.Create())); - - // Act - await _sut.GetPathRoot(path, cancellationToken); - - // Assert - await _mockMediator.Received(1).Send(Arg.Is(q => q.Path == path), Arg.Is(cancellationToken)); - } - - [Fact] - public async Task GetPathRoot_WhenCancellationRequested_ShouldCancelOperation() - { - // Arrange - string path = @"C:\Users\TestUser"; - CancellationTokenSource cts = new(); - TaskCompletionSource operationStarted = new(); - TaskCompletionSource cancellationRequested = new(); - - _mockMediator.Send(Arg.Any(), Arg.Any()) - .Returns(callInfo => new ValueTask>(Task.Run(async () => - { - operationStarted.SetResult(true); - await cancellationRequested.Task; - callInfo.Arg().ThrowIfCancellationRequested(); - return ErrorOrFactory.From(_pathSegmentResponseFixture.Create()); - }, callInfo.Arg()))); - - // Act - Task operationTask = _sut.GetPathRoot(path, cts.Token); - await operationStarted.Task; - cts.Cancel(); - cancellationRequested.SetResult(true); - - // Assert - await Assert.ThrowsAnyAsync(() => operationTask); - } - - [Fact] - public async Task GetPathSeparator_WhenCalled_ShouldReturnOkResultWithPathSeparatorResponse() - { - // Arrange - CancellationToken cancellationToken = CancellationToken.None; - PathSeparatorResponse expectedResponse = _pathSeparatorResponseFixture.Create(); - _mockMediator.Send(Arg.Any(), Arg.Any()) - .Returns(expectedResponse); - - // Act - IActionResult result = await _sut.GetPathSeparator(cancellationToken); - - // Assert - OkObjectResult okResult = result.Should().BeOfType().Subject; - PathSeparatorResponse actualResponse = okResult.Value.Should().BeAssignableTo().Subject; - actualResponse.Should().BeEquivalentTo(expectedResponse); - } - - [Fact] - public async Task GetPathSeparator_WhenCalled_ShouldSendGetPathSeparatorQueryToMediator() - { - // Arrange - CancellationToken cancellationToken = CancellationToken.None; - _mockMediator.Send(Arg.Any(), Arg.Any()) - .Returns(_pathSeparatorResponseFixture.Create()); - - // Act - await _sut.GetPathSeparator(cancellationToken); - - // Assert - await _mockMediator.Received(1).Send(Arg.Any(), Arg.Is(cancellationToken)); - } - - [Fact] - public async Task GetPathSeparator_WhenCancellationRequested_ShouldCancelOperation() - { - // Arrange - CancellationTokenSource cts = new(); - TaskCompletionSource operationStarted = new(); - TaskCompletionSource cancellationRequested = new(); - - _mockMediator.Send(Arg.Any(), Arg.Any()) - .Returns(callInfo => new ValueTask(Task.Run(async () => - { - operationStarted.SetResult(true); - await cancellationRequested.Task; - callInfo.Arg().ThrowIfCancellationRequested(); - return _pathSeparatorResponseFixture.Create(); - }, callInfo.Arg()))); - - // Act - Task operationTask = _sut.GetPathSeparator(cts.Token); - await operationStarted.Task; - cts.Cancel(); - cancellationRequested.SetResult(true); - - // Assert - await Assert.ThrowsAnyAsync(() => operationTask); - } - - [Fact] - public async Task GetPathParent_WhenCalled_ShouldReturnOkResultWithPathSegmentResponses() - { - // Arrange - string path = @"C:\Users\TestUser\Documents"; - CancellationToken cancellationToken = CancellationToken.None; - IEnumerable expectedResponse = - [ - _pathSegmentResponseFixture.Create(), - _pathSegmentResponseFixture.Create() - ]; - _mockMediator.Send(Arg.Any(), Arg.Any()) - .Returns(ErrorOrFactory.From(expectedResponse)); - - // Act - IActionResult result = await _sut.GetPathParent(path, cancellationToken); - - // Assert - OkObjectResult okResult = result.Should().BeOfType().Subject; - IEnumerable actualResponse = okResult.Value.Should().BeAssignableTo>().Subject; - actualResponse.Should().BeEquivalentTo(expectedResponse); - } - - [Fact] - public async Task GetPathParent_WhenMediatorReturnsError_ShouldReturnProblemResult() - { - // Arrange - string path = @"InvalidPath"; - CancellationToken cancellationToken = CancellationToken.None; - Error expectedError = Error.Validation("Path.Invalid", "The provided path is invalid."); - _mockMediator.Send(Arg.Any(), Arg.Any()) - .Returns(expectedError); - - _sut.ControllerContext = new ControllerContext(); - - ProblemDetailsFactory mockProblemDetailsFactory = Substitute.For(); - mockProblemDetailsFactory.CreateProblemDetails( - Arg.Any(), - Arg.Any(), - Arg.Is(ErrorType.Validation.ToString()), - Arg.Any(), - Arg.Any(), - Arg.Any()) - .Returns(new ProblemDetails - { - Status = StatusCodes.Status400BadRequest, - Title = ErrorType.Validation.ToString(), - Detail = "The provided path is invalid." - }); - _sut.ProblemDetailsFactory = mockProblemDetailsFactory; - ValidationProblemDetails expectedValidationProblemDetails = new() - { - Status = StatusCodes.Status400BadRequest, - Title = "One or more validation errors occurred.", - Errors = - { - { "Path.Invalid", new[] { "The provided path is invalid." } } - } - }; - mockProblemDetailsFactory.CreateValidationProblemDetails( - Arg.Any(), - Arg.Any(), - Arg.Any(), - Arg.Any(), - Arg.Any(), - Arg.Any(), - Arg.Any()) - .Returns(expectedValidationProblemDetails); - - // Act - IActionResult result = await _sut.GetPathParent(path, cancellationToken); - - // Assert - BadRequestObjectResult badRequestResult = result.Should().BeOfType().Subject; - badRequestResult.StatusCode.Should().Be(StatusCodes.Status400BadRequest); - - ValidationProblemDetails actualValidationProblemDetails = badRequestResult.Value.Should().BeOfType().Subject; - actualValidationProblemDetails.Should().BeEquivalentTo(expectedValidationProblemDetails); - } - - [Fact] - public async Task GetPathParent_WhenCalled_ShouldSendGetPathParentQueryToMediator() - { - // Arrange - string path = @"C:\Users\TestUser\Documents"; - CancellationToken cancellationToken = CancellationToken.None; - _mockMediator.Send(Arg.Any(), Arg.Any()) - .Returns(new List { _pathSegmentResponseFixture.Create() }); - - // Act - await _sut.GetPathParent(path, cancellationToken); - - // Assert - await _mockMediator.Received(1).Send(Arg.Is(q => q.Path == path), Arg.Is(cancellationToken)); - } - - [Fact] - public async Task GetPathParent_WhenCancellationRequested_ShouldCancelOperation() - { - // Arrange - string path = @"C:\Users\TestUser\Documents"; - CancellationTokenSource cts = new(); - TaskCompletionSource operationStarted = new(); - TaskCompletionSource cancellationRequested = new(); - - _mockMediator.Send(Arg.Any(), Arg.Any()) - .Returns(callInfo => new ValueTask>>(Task.Run(async () => - { - operationStarted.SetResult(true); - await cancellationRequested.Task; - callInfo.Arg().ThrowIfCancellationRequested(); - return ErrorOrFactory.From(new List - { - _pathSegmentResponseFixture.Create() - }.AsEnumerable()); - }, callInfo.Arg()))); - - // Act - Task operationTask = _sut.GetPathParent(path, cts.Token); - await operationStarted.Task; - cts.Cancel(); - cancellationRequested.SetResult(true); - - // Assert - await Assert.ThrowsAnyAsync(() => operationTask); - } - - [Fact] - public async Task CombinePath_WhenCalled_ShouldReturnOkResultWithPathSegmentResponse() - { - // Arrange - string originalPath = @"C:\Users"; - string newPath = "TestUser"; - CancellationToken cancellationToken = CancellationToken.None; - PathSegmentResponse expectedResponse = _pathSegmentResponseFixture.Create(); - _mockMediator.Send(Arg.Any(), Arg.Any()) - .Returns(ErrorOrFactory.From(expectedResponse)); - - // Act - IActionResult result = await _sut.CombinePath(originalPath, newPath, cancellationToken); - - // Assert - OkObjectResult okResult = result.Should().BeOfType().Subject; - PathSegmentResponse actualResponse = okResult.Value.Should().BeAssignableTo().Subject; - actualResponse.Should().BeEquivalentTo(expectedResponse); - } - - [Fact] - public async Task CombinePath_WhenMediatorReturnsError_ShouldReturnProblemResult() - { - // Arrange - string originalPath = @"InvalidPath"; - string newPath = "TestUser"; - CancellationToken cancellationToken = CancellationToken.None; - Error expectedError = Error.Validation("Path.Invalid", "The provided path is invalid."); - _mockMediator.Send(Arg.Any(), Arg.Any()) - .Returns(expectedError); - - _sut.ControllerContext = new ControllerContext(); - - ProblemDetailsFactory mockProblemDetailsFactory = Substitute.For(); - mockProblemDetailsFactory.CreateProblemDetails( - Arg.Any(), - Arg.Any(), - Arg.Is(ErrorType.Validation.ToString()), - Arg.Any(), - Arg.Any(), - Arg.Any()) - .Returns(new ProblemDetails - { - Status = StatusCodes.Status400BadRequest, - Title = ErrorType.Validation.ToString(), - Detail = "The provided path is invalid." - }); - _sut.ProblemDetailsFactory = mockProblemDetailsFactory; - ValidationProblemDetails expectedValidationProblemDetails = new() - { - Status = StatusCodes.Status400BadRequest, - Title = "One or more validation errors occurred.", - Errors = - { - { "Path.Invalid", new[] { "The provided path is invalid." } } - } - }; - mockProblemDetailsFactory.CreateValidationProblemDetails( - Arg.Any(), - Arg.Any(), - Arg.Any(), - Arg.Any(), - Arg.Any(), - Arg.Any(), - Arg.Any()) - .Returns(expectedValidationProblemDetails); - - // Act - IActionResult result = await _sut.CombinePath(originalPath, newPath, cancellationToken); - - // Assert - BadRequestObjectResult badRequestResult = result.Should().BeOfType().Subject; - badRequestResult.StatusCode.Should().Be(StatusCodes.Status400BadRequest); - - ValidationProblemDetails actualValidationProblemDetails = badRequestResult.Value.Should().BeOfType().Subject; - actualValidationProblemDetails.Should().BeEquivalentTo(expectedValidationProblemDetails); - } - - [Fact] - public async Task CombinePath_WhenCalled_ShouldSendCombinePathCommandToMediator() - { - // Arrange - string originalPath = @"C:\Users"; - string newPath = "TestUser"; - CancellationToken cancellationToken = CancellationToken.None; - _mockMediator.Send(Arg.Any(), Arg.Any()) - .Returns(ErrorOrFactory.From(_pathSegmentResponseFixture.Create())); - - // Act - await _sut.CombinePath(originalPath, newPath, cancellationToken); - - // Assert - await _mockMediator.Received(1).Send(Arg.Is(c => c.OriginalPath == originalPath && c.NewPath == newPath), Arg.Is(cancellationToken)); - } - - [Fact] - public async Task CombinePath_WhenCancellationRequested_ShouldCancelOperation() - { - // Arrange - string originalPath = @"C:\Users"; - string newPath = "TestUser"; - CancellationTokenSource cts = new(); - TaskCompletionSource operationStarted = new(); - TaskCompletionSource cancellationRequested = new(); - - _mockMediator.Send(Arg.Any(), Arg.Any()) - .Returns(callInfo => new ValueTask>(Task.Run(async () => - { - operationStarted.SetResult(true); - await cancellationRequested.Task; - callInfo.Arg().ThrowIfCancellationRequested(); - return ErrorOrFactory.From(_pathSegmentResponseFixture.Create()); - }, callInfo.Arg()))); - - // Act - Task operationTask = _sut.CombinePath(originalPath, newPath, cts.Token); - await operationStarted.Task; - cts.Cancel(); - cancellationRequested.SetResult(true); - - // Assert - await Assert.ThrowsAnyAsync(() => operationTask); - } - - [Fact] - public async Task SplitPath_WhenCalled_ShouldReturnOkResultWithPathSegmentResponses() - { - // Arrange - string path = @"C:\Users\TestUser\Documents"; - CancellationToken cancellationToken = CancellationToken.None; - IEnumerable expectedResponse = - [ - _pathSegmentResponseFixture.Create(), - _pathSegmentResponseFixture.Create(), - _pathSegmentResponseFixture.Create() - ]; - _mockMediator.Send(Arg.Any(), Arg.Any()) - .Returns(ErrorOrFactory.From(expectedResponse)); - - // Act - IActionResult result = await _sut.SplitPath(path, cancellationToken); - - // Assert - OkObjectResult okResult = result.Should().BeOfType().Subject; - IEnumerable actualResponse = okResult.Value.Should().BeAssignableTo>().Subject; - actualResponse.Should().BeEquivalentTo(expectedResponse); - } - - [Fact] - public async Task SplitPath_WhenMediatorReturnsError_ShouldReturnProblemResult() - { - // Arrange - string path = @"InvalidPath"; - CancellationToken cancellationToken = CancellationToken.None; - Error expectedError = Error.Validation("Path.Invalid", "The provided path is invalid."); - _mockMediator.Send(Arg.Any(), Arg.Any()) - .Returns(expectedError); - - _sut.ControllerContext = new ControllerContext(); - - ProblemDetailsFactory mockProblemDetailsFactory = Substitute.For(); - mockProblemDetailsFactory.CreateProblemDetails( - Arg.Any(), - Arg.Any(), - Arg.Is(ErrorType.Validation.ToString()), - Arg.Any(), - Arg.Any(), - Arg.Any()) - .Returns(new ProblemDetails - { - Status = StatusCodes.Status400BadRequest, - Title = ErrorType.Validation.ToString(), - Detail = "The provided path is invalid." - }); - _sut.ProblemDetailsFactory = mockProblemDetailsFactory; - ValidationProblemDetails expectedValidationProblemDetails = new() - { - Status = StatusCodes.Status400BadRequest, - Title = "One or more validation errors occurred.", - Errors = - { - { "Path.Invalid", new[] { "The provided path is invalid." } } - } - }; - mockProblemDetailsFactory.CreateValidationProblemDetails( - Arg.Any(), - Arg.Any(), - Arg.Any(), - Arg.Any(), - Arg.Any(), - Arg.Any(), - Arg.Any()) - .Returns(expectedValidationProblemDetails); - - // Act - IActionResult result = await _sut.SplitPath(path, cancellationToken); - - // Assert - BadRequestObjectResult badRequestResult = result.Should().BeOfType().Subject; - badRequestResult.StatusCode.Should().Be(StatusCodes.Status400BadRequest); - - ValidationProblemDetails actualValidationProblemDetails = badRequestResult.Value.Should().BeOfType().Subject; - actualValidationProblemDetails.Should().BeEquivalentTo(expectedValidationProblemDetails); - } - - [Fact] - public async Task SplitPath_WhenCalled_ShouldSendSplitPathCommandToMediator() - { - // Arrange - string path = @"C:\Users\TestUser\Documents"; - CancellationToken cancellationToken = CancellationToken.None; - _mockMediator.Send(Arg.Any(), Arg.Any()) - .Returns(new List { _pathSegmentResponseFixture.Create() }); - - // Act - await _sut.SplitPath(path, cancellationToken); - - // Assert - await _mockMediator.Received(1).Send(Arg.Is(c => c.Path == path), Arg.Is(cancellationToken)); - } - - [Fact] - public async Task SplitPath_WhenCancellationRequested_ShouldCancelOperation() - { - // Arrange - string path = @"C:\Users\TestUser\Documents"; - CancellationTokenSource cts = new(); - TaskCompletionSource operationStarted = new(); - TaskCompletionSource cancellationRequested = new(); - - _mockMediator.Send(Arg.Any(), Arg.Any()) - .Returns(callInfo => new ValueTask>>(Task.Run(async () => - { - operationStarted.SetResult(true); - await cancellationRequested.Task; - callInfo.Arg().ThrowIfCancellationRequested(); - return ErrorOrFactory.From(new List - { - _pathSegmentResponseFixture.Create() - }.AsEnumerable()); - }, callInfo.Arg()))); - - // Act - Task operationTask = _sut.SplitPath(path, cts.Token); - await operationStarted.Task; - cts.Cancel(); - cancellationRequested.SetResult(true); - - // Assert - await Assert.ThrowsAnyAsync(() => operationTask); - } - - [Fact] - public async Task ValidatePath_WhenCalled_ShouldReturnOkResultWithPathValidResponse() - { - // Arrange - string path = @"C:\Users\TestUser\Documents"; - CancellationToken cancellationToken = CancellationToken.None; - PathValidResponse expectedResponse = new(true); - _mockMediator.Send(Arg.Any(), Arg.Any()) - .Returns(expectedResponse); - - // Act - IActionResult result = await _sut.ValidatePath(path, cancellationToken); - - // Assert - OkObjectResult okResult = result.Should().BeOfType().Subject; - PathValidResponse actualResponse = okResult.Value.Should().BeAssignableTo().Subject; - actualResponse.Should().BeEquivalentTo(expectedResponse); - } - - [Fact] - public async Task ValidatePath_WhenCalled_ShouldSendValidatePathQueryToMediator() - { - // Arrange - string path = @"C:\Users\TestUser\Documents"; - CancellationToken cancellationToken = CancellationToken.None; - _mockMediator.Send(Arg.Any(), Arg.Any()) - .Returns(new PathValidResponse(true)); - - // Act - await _sut.ValidatePath(path, cancellationToken); - - // Assert - await _mockMediator.Received(1).Send(Arg.Is(q => q.Path == path), Arg.Is(cancellationToken)); - } - - [Fact] - public async Task ValidatePath_WhenCancellationRequested_ShouldCancelOperation() - { - // Arrange - string path = @"C:\Users\TestUser\Documents"; - CancellationTokenSource cts = new(); - TaskCompletionSource operationStarted = new(); - TaskCompletionSource cancellationRequested = new(); - - _mockMediator.Send(Arg.Any(), Arg.Any()) - .Returns(callInfo => new ValueTask(Task.Run(async () => - { - operationStarted.SetResult(true); - await cancellationRequested.Task; - callInfo.Arg().ThrowIfCancellationRequested(); - return new PathValidResponse(true); - }, callInfo.Arg()))); - - // Act - Task operationTask = _sut.ValidatePath(path, cts.Token); - await operationStarted.Task; - cts.Cancel(); - cancellationRequested.SetResult(true); - - // Assert - await Assert.ThrowsAnyAsync(() => operationTask); - } - - [Fact] - public async Task CheckPathExists_WhenCalled_ShouldReturnOkResultWithPathExistsResponse() - { - // Arrange - string path = @"C:\Users\TestUser\Documents"; - CancellationToken cancellationToken = CancellationToken.None; - PathExistsResponse expectedResponse = new(true); - _mockMediator.Send(Arg.Any(), Arg.Any()) - .Returns(expectedResponse); - - // Act - IActionResult result = await _sut.CheckPathExists(path, true, cancellationToken); - - // Assert - OkObjectResult okResult = result.Should().BeOfType().Subject; - PathExistsResponse actualResponse = okResult.Value.Should().BeAssignableTo().Subject; - actualResponse.Should().BeEquivalentTo(expectedResponse); - } - - [Fact] - public async Task CheckPathExists_WhenCalled_ShouldSendCheckPathExistsQueryToMediator() - { - // Arrange - string path = @"C:\Users\TestUser\Documents"; - CancellationToken cancellationToken = CancellationToken.None; - _mockMediator.Send(Arg.Any(), Arg.Any()) - .Returns(new PathExistsResponse(true)); - - // Act - await _sut.CheckPathExists(path, true, cancellationToken); - - // Assert - await _mockMediator.Received(1).Send(Arg.Is(q => q.Path == path), Arg.Is(cancellationToken)); - } - - [Fact] - public async Task CheckPathExists_WhenCancellationRequested_ShouldCancelOperation() - { - // Arrange - string path = @"C:\Users\TestUser\Documents"; - CancellationTokenSource cts = new(); - TaskCompletionSource operationStarted = new(); - TaskCompletionSource cancellationRequested = new(); - - _mockMediator.Send(Arg.Any(), Arg.Any()) - .Returns(callInfo => new ValueTask(Task.Run(async () => - { - operationStarted.SetResult(true); - await cancellationRequested.Task; - callInfo.Arg().ThrowIfCancellationRequested(); - return new PathExistsResponse(true); - }, callInfo.Arg()))); - - // Act - Task operationTask = _sut.CheckPathExists(path, true, 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/Controllers/FileManagement/ThumbnailsControllerTests.cs b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Controllers/FileManagement/ThumbnailsControllerTests.cs deleted file mode 100644 index 07e9e129..00000000 --- a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Controllers/FileManagement/ThumbnailsControllerTests.cs +++ /dev/null @@ -1,157 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using ErrorOr; -using FluentAssertions; -using Lumina.Application.Core.FileManagement.Drives.Queries.GetDrives; -using Lumina.Application.Core.FileManagement.Thumbnails.Queries.GetThumbnail; -using Lumina.Contracts.Responses.FileManagement; -using Lumina.Presentation.Api.Common.Http; -using Lumina.Presentation.Api.Common.Utilities; -using Lumina.Presentation.Api.Core.Controllers.FileManagement; -using Lumina.Presentation.Api.UnitTests.Core.Controllers.FileManagement.Fixtures; -using Mediator; -using Microsoft.AspNetCore.Http; -using Microsoft.AspNetCore.Mvc; -using Microsoft.AspNetCore.Mvc.Infrastructure; -using NSubstitute; -using System; -using System.Collections.Generic; -using System.Diagnostics.CodeAnalysis; -using System.Linq; -using System.Threading; -using System.Threading.Tasks; -#endregion - -namespace Lumina.Presentation.Api.UnitTests.Core.Controllers.FileManagement; - -/// -/// Contains unit tests for the class. -/// -[ExcludeFromCodeCoverage] -public class ThumbnailsControllerTests -{ - private readonly ISender _mockMediator; - private readonly ThumbnailsController _sut; - - /// - /// Initializes a new instance of the class. - /// - public ThumbnailsControllerTests() - { - _mockMediator = Substitute.For(); - _sut = new ThumbnailsController(_mockMediator); - } - - [Fact] - public async Task GetThumbnail_WhenCalled_ShouldReturnFileResultWithThumbnailResponse() - { - // Arrange - string path = "/path/to/file.jpg"; - int quality = 80; - CancellationToken cancellationToken = CancellationToken.None; - ThumbnailResponse expectedResponse = ThumbnailResponseFixture.CreateThumbnailResponse(); - _mockMediator.Send(Arg.Any(), Arg.Any()) - .Returns(ErrorOrFactory.From(expectedResponse)); - - // Act - IActionResult result = await _sut.GetThumbnail(path, quality, cancellationToken); - - // Assert - FileContentResult fileResult = result.Should().BeOfType().Subject; - fileResult.FileContents.Should().BeEquivalentTo(expectedResponse.Bytes); - fileResult.ContentType.Should().Be(MimeTypes.GetMimeType(expectedResponse.Type)); - } - - [Fact] - public async Task GetThumbnail_WhenMediatorReturnsError_ShouldReturnProblemResult() - { - // Arrange - string path = "/path/to/nonexistent/file.jpg"; - int quality = 80; - CancellationToken cancellationToken = CancellationToken.None; - Error expectedError = Error.NotFound("Thumbnail.NotFound", "The requested thumbnail was not found."); - _mockMediator.Send(Arg.Any(), Arg.Any()) - .Returns(expectedError); - HttpContext mockHttpContext = Substitute.For(); - Dictionary mockItems = []; - mockHttpContext.Items.Returns(mockItems!); - _sut.ControllerContext = new ControllerContext - { - HttpContext = mockHttpContext - }; - ProblemDetailsFactory mockProblemDetailsFactory = Substitute.For(); - mockProblemDetailsFactory.CreateProblemDetails( - Arg.Any(), - Arg.Any(), - Arg.Any(), - Arg.Any(), - Arg.Any(), - Arg.Any()) - .Returns(new ProblemDetails - { - Status = StatusCodes.Status404NotFound, - Title = ErrorType.NotFound.ToString(), - Detail = "The requested thumbnail was not found." - }); - _sut.ProblemDetailsFactory = mockProblemDetailsFactory; - - // Act - IActionResult result = await _sut.GetThumbnail(path, quality, cancellationToken); - - // Assert - ObjectResult objectResult = result.Should().BeOfType().Subject; - objectResult.StatusCode.Should().Be(StatusCodes.Status404NotFound); - - ProblemDetails problemDetails = objectResult.Value.Should().BeOfType().Subject; - problemDetails.Title.Should().Be(ErrorType.NotFound.ToString()); - problemDetails.Detail.Should().Be("The requested thumbnail was not found."); - problemDetails.Status.Should().Be(StatusCodes.Status404NotFound); - mockItems.Should().ContainKey(HttpContextItemKeys.ERRORS); - mockItems[HttpContextItemKeys.ERRORS].Should().BeEquivalentTo(new List { expectedError }); - } - - [Fact] - public async Task GetThumbnail_WhenCalled_ShouldSendGetThumbnailQueryToMediator() - { - // Arrange - string path = "/path/to/file.jpg"; - int quality = 80; - CancellationToken cancellationToken = CancellationToken.None; - _mockMediator.Send(Arg.Any(), Arg.Any()) - .Returns(ErrorOrFactory.From(ThumbnailResponseFixture.CreateThumbnailResponse())); - - // Act - await _sut.GetThumbnail(path, quality, cancellationToken); - - // Assert - await _mockMediator.Received(1).Send(Arg.Is(q => q.Path == path && q.Quality == quality), Arg.Is(cancellationToken)); - } - - [Fact] - public async Task GetThumbnail_WhenCancellationRequested_ShouldCancelOperation() - { - // Arrange - string path = "/path/to/file.jpg"; - int quality = 80; - CancellationTokenSource cts = new(); - TaskCompletionSource operationStarted = new(); - TaskCompletionSource cancellationRequested = new(); - - _mockMediator.Send(Arg.Any(), Arg.Any()) - .Returns(callInfo => new ValueTask>(Task.Run(async () => - { - operationStarted.SetResult(true); - await cancellationRequested.Task; - callInfo.Arg().ThrowIfCancellationRequested(); - return ErrorOrFactory.From(ThumbnailResponseFixture.CreateThumbnailResponse()); - }, callInfo.Arg()))); - - // Act - Task operationTask = _sut.GetThumbnail(path, quality, 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/Common/BaseEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Common/BaseEndpointTests.cs new file mode 100644 index 00000000..77a60786 --- /dev/null +++ b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Common/BaseEndpointTests.cs @@ -0,0 +1,191 @@ +#region ========================================================================= USING ===================================================================================== +using ErrorOr; +using FastEndpoints; +using FluentAssertions; +using Lumina.Presentation.Api.UnitTests.Core.Endpoints.Common.Fixtures; +using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Http.HttpResults; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Presentation.Api.UnitTests.Core.Endpoints.Common; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class BaseEndpointTests +{ + private readonly BaseEndpointFixture _sut; + + /// + /// Initializes a new instance of the class. + /// + public BaseEndpointTests() + { + _sut = Factory.Create(); + } + + [Fact] + public void Problem_WhenCalledWithNoErrors_ShouldReturnGenericProblem() + { + // Act + IResult result = _sut.TestProblem([]); + + // Assert + result.Should().BeOfType(); + } + + [Fact] + public void Problem_WhenCalledWithValidationErrors_ShouldReturnValidationProblem() + { + // Arrange + List errors = [ + Error.Validation("Code1", "Description1"), + Error.Validation("Code2", "Description2") + ]; + + // Act + IResult result = _sut.TestProblem(errors); + + // Assert + result.Should().BeOfType(); + ProblemHttpResult problemDetails = (ProblemHttpResult)result; + problemDetails.StatusCode.Should().Be(StatusCodes.Status422UnprocessableEntity); + problemDetails.ContentType.Should().Be("application/problem+json"); + problemDetails.ProblemDetails.Should().BeOfType(); + HttpValidationProblemDetails validationProblemDetails = (HttpValidationProblemDetails)problemDetails.ProblemDetails; + validationProblemDetails.Status.Should().Be(StatusCodes.Status422UnprocessableEntity); + validationProblemDetails.Title.Should().Be("Validation Error"); + validationProblemDetails.Detail.Should().Be("One or more validation errors occurred."); + validationProblemDetails.Type.Should().Be("https://tools.ietf.org/html/rfc4918#section-11.2"); + validationProblemDetails.Errors.Should().HaveCount(2); + validationProblemDetails.Errors["Code1"].Should().BeEquivalentTo(["Description1"]); + validationProblemDetails.Errors["Code2"].Should().BeEquivalentTo(["Description2"]); + } + + [Theory] + [InlineData(ErrorType.Conflict, StatusCodes.Status409Conflict)] + [InlineData(ErrorType.NotFound, StatusCodes.Status404NotFound)] + [InlineData(ErrorType.Failure, StatusCodes.Status403Forbidden)] + [InlineData(ErrorType.Unexpected, StatusCodes.Status500InternalServerError)] + public void Problem_WhenCalledWithSingleError_ShouldReturnCorrectStatusCode(ErrorType errorType, int expectedStatusCode) + { + // Arrange + Error error = errorType switch + { + ErrorType.Conflict => Error.Conflict("ErrorCode", "ErrorDescription"), + ErrorType.NotFound => Error.NotFound("ErrorCode", "ErrorDescription"), + ErrorType.Validation => Error.Validation("ErrorCode", "ErrorDescription"), + ErrorType.Failure => Error.Failure("ErrorCode", "ErrorDescription"), + _ => Error.Unexpected("ErrorCode", "ErrorDescription"), + }; + List errors = [error]; + + // Act + IResult result = _sut.TestProblem(errors); + + // Assert + result.Should().BeOfType(); + ProblemHttpResult problemResult = (ProblemHttpResult)result; + problemResult.StatusCode.Should().Be(expectedStatusCode); + problemResult.ProblemDetails.Status.Should().Be(expectedStatusCode); + problemResult.ProblemDetails.Title.Should().Be("ErrorCode"); + problemResult.ProblemDetails.Detail.Should().Be("ErrorDescription"); + problemResult.ProblemDetails.Instance.Should().NotBeNull(); + problemResult.ProblemDetails.Extensions.Should().ContainKey("traceId"); + } + + [Fact] + public void Problem_WhenCalledWithSingleValidationError_ShouldReturnCorrectStatusCode() + { + // Arrange + Error error = Error.Validation(); + List errors = [error]; + + // Act + IResult result = _sut.TestProblem(errors); + + // Assert + result.Should().BeOfType(); + ProblemHttpResult problemResult = (ProblemHttpResult)result; + problemResult.StatusCode.Should().Be(422); + problemResult.ProblemDetails.Status.Should().Be(StatusCodes.Status422UnprocessableEntity); + problemResult.ProblemDetails.Title.Should().Be("Validation Error"); + problemResult.ProblemDetails.Detail.Should().Be("One or more validation errors occurred."); + problemResult.ProblemDetails.Instance.Should().NotBeNull(); + problemResult.ProblemDetails.Extensions.Should().ContainKey("traceId"); + } + + [Fact] + public void Problem_WhenCalledWithMixedErrors_ShouldReturnProblemResult() + { + // Arrange + List errors = [ + Error.NotFound("FailureCode", "Failure Error"), + Error.Failure("FailureCode", "Failure Error") + ]; + + // Act + IResult result = _sut.TestProblem(errors); + + // Assert + result.Should().BeOfType(); + ProblemHttpResult problemResult = (ProblemHttpResult)result; + problemResult.StatusCode.Should().BeOneOf(StatusCodes.Status404NotFound, StatusCodes.Status400BadRequest); + problemResult.ProblemDetails.Status.Should().BeOneOf(StatusCodes.Status404NotFound, StatusCodes.Status400BadRequest); + problemResult.ProblemDetails.Title.Should().Be("FailureCode"); + problemResult.ProblemDetails.Detail.Should().Be("Failure Error"); + } + + [Fact] + public void ValidationProblem_WhenCalled_ShouldReturnValidationProblemResult() + { + // Arrange + List errors = [ + Error.Validation("Code1", "Description1"), + Error.Validation("Code2", "Description2") + ]; + + // Act + IResult result = _sut.TestValidationProblem(errors); + + // Assert + result.Should().BeOfType(); + ProblemHttpResult problemDetails = (ProblemHttpResult)result; + problemDetails.StatusCode.Should().Be(StatusCodes.Status422UnprocessableEntity); + problemDetails.ContentType.Should().Be("application/problem+json"); + problemDetails.ProblemDetails.Should().BeOfType(); + HttpValidationProblemDetails validationProblemDetails = (HttpValidationProblemDetails)problemDetails.ProblemDetails; + validationProblemDetails.Status.Should().Be(StatusCodes.Status422UnprocessableEntity); + validationProblemDetails.Title.Should().Be("Validation Error"); + validationProblemDetails.Detail.Should().Be("One or more validation errors occurred."); + validationProblemDetails.Type.Should().Be("https://tools.ietf.org/html/rfc4918#section-11.2"); + validationProblemDetails.Errors.Should().HaveCount(2); + validationProblemDetails.Errors["Code1"].Should().BeEquivalentTo(["Description1"]); + validationProblemDetails.Errors["Code2"].Should().BeEquivalentTo(["Description2"]); + } + + [Fact] + public void ValidationProblem_WhenCalledWithDuplicateErrorCodes_ShouldMergeDescriptions() + { + // Arrange + List errors = [ + Error.Validation("Code1", "Description1"), + Error.Validation("Code1", "Description2"), + Error.Validation("Code2", "Description3") + ]; + + // Act + IResult result = _sut.TestValidationProblem(errors); + + // Assert + result.Should().BeOfType(); + ProblemHttpResult problemDetails = (ProblemHttpResult)result; + HttpValidationProblemDetails validationProblemDetails = (HttpValidationProblemDetails)problemDetails.ProblemDetails; + validationProblemDetails.Errors.Should().ContainKeys("Code1", "Code2"); + validationProblemDetails.Errors["Code1"].Should().BeEquivalentTo(["Description1", "Description2"]); + validationProblemDetails.Errors["Code2"].Should().BeEquivalentTo(["Description3"]); + } +} diff --git a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Common/Fixtures/BaseEndpointFixture.cs b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Common/Fixtures/BaseEndpointFixture.cs new file mode 100644 index 00000000..a3081e5f --- /dev/null +++ b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Common/Fixtures/BaseEndpointFixture.cs @@ -0,0 +1,57 @@ +#region ========================================================================= USING ===================================================================================== +using ErrorOr; +using Lumina.Presentation.Api.Core.Endpoints.Common; +using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Mvc; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Api.UnitTests.Core.Endpoints.Common.Fixtures; + +/// +/// Fixture class for the class. +/// +[ExcludeFromCodeCoverage] +public class BaseEndpointFixture : BaseEndpoint +{ + /// + /// Returns a standardized error response using the format. + /// + /// A list of errors to include in the response. + /// An with the problem details containing the specified errors. + public IResult TestProblem(List errors) + { + return Problem(errors); + } + + /// + /// Returns a standardized validation error response using the format. + /// + /// A list of validation errors to include in the response. + /// An with the validation problem details containing the specified errors. + public IResult TestValidationProblem(List errors) + { + return ValidationProblem(errors); + } + + /// + /// Configures the API endpoint. + /// + public override void Configure() + { + + } + + /// + /// Handles the API request. + /// + /// The request containing the file system path for which to get the root. + /// Cancellation token that can be used to stop the execution. + public override Task ExecuteAsync(object request, CancellationToken cancellationToken) + { + return Task.FromResult(new object()); + } +} diff --git a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/FileSystemManagement/Directories/GetDirectoriesEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/FileSystemManagement/Directories/GetDirectoriesEndpointTests.cs new file mode 100644 index 00000000..4039a33a --- /dev/null +++ b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/FileSystemManagement/Directories/GetDirectoriesEndpointTests.cs @@ -0,0 +1,167 @@ +#region ========================================================================= USING ===================================================================================== +using AutoFixture; +using AutoFixture.AutoNSubstitute; +using ErrorOr; +using FastEndpoints; +using FluentAssertions; +using Lumina.Application.Core.FileSystemManagement.Directories.Queries.GetDirectories; +using Lumina.Contracts.Requests.FileSystemManagement.Directories; +using Lumina.Contracts.Responses.FileSystemManagement.Directories; +using Lumina.Presentation.Api.Core.Endpoints.FileSystemManagement.Directories.GetDirectories; +using Mediator; +using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Http.HttpResults; +using NSubstitute; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Api.UnitTests.Core.Endpoints.FileSystemManagement.Directories; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class GetDirectoriesEndpointTests +{ + private readonly IFixture _fixture; + private readonly ISender _mockSender; + private readonly GetDirectoriesEndpoint _sut; + + /// + /// Initializes a new instance of the class. + /// + public GetDirectoriesEndpointTests() + { + _fixture = new Fixture().Customize(new AutoNSubstituteCustomization()); + _mockSender = Substitute.For(); + _sut = Factory.Create(_mockSender); + } + + [Fact] + public async Task ExecuteAsync_WhenCalled_ShouldReturnOkResultWithDirectoryResponses() + { + // Arrange + GetDirectoriesRequest request = _fixture.Create(); + CancellationToken cancellationToken = CancellationToken.None; + List expectedResponses = _fixture.CreateMany(3).ToList(); + _mockSender.Send(Arg.Any(), Arg.Any()) + .Returns(ErrorOrFactory.From(expectedResponses.AsEnumerable())); + + // Act + IResult result = await _sut.ExecuteAsync(request, cancellationToken); + + // Assert + IEnumerable actualResponses = result.Should().BeOfType>>().Subject.Value!; + actualResponses.Should().BeEquivalentTo(expectedResponses); + } + + [Fact] + public async Task ExecuteAsync_WhenMediatorReturnsError_ShouldReturnProblemResult() + { + // Arrange + GetDirectoriesRequest request = _fixture.Create(); + CancellationToken cancellationToken = CancellationToken.None; + Error expectedError = Error.NotFound("Directory.NotFound", "The requested directory was not found."); + _mockSender.Send(Arg.Any(), Arg.Any()) + .Returns(expectedError); + + // Act + IResult result = await _sut.ExecuteAsync(request, cancellationToken); + + // Assert + result.Should().BeOfType(); + ProblemHttpResult problemDetails = (ProblemHttpResult)result; + problemDetails.StatusCode.Should().Be(StatusCodes.Status404NotFound); + problemDetails.ContentType.Should().Be("application/problem+json"); + problemDetails.ProblemDetails.Should().BeOfType(); + + problemDetails.ProblemDetails.Title.Should().Be("Directory.NotFound"); + problemDetails.ProblemDetails.Detail.Should().Be("The requested directory was not found."); + problemDetails.ProblemDetails.Status.Should().Be(StatusCodes.Status404NotFound); + problemDetails.ProblemDetails.Type.Should().Be("https://tools.ietf.org/html/rfc9110#section-15.5.5"); + problemDetails.ProblemDetails.Extensions["traceId"].Should().NotBeNull(); + } + + [Fact] + public async Task ExecuteAsync_WhenMediatorReturnsValidationError_ShouldReturnValidationProblemResult() + { + // Arrange + GetDirectoriesRequest request = _fixture.Create(); + CancellationToken cancellationToken = CancellationToken.None; + Error expectedError = Error.Validation("Path.Invalid", "The provided path is invalid."); + _mockSender.Send(Arg.Any(), Arg.Any()) + .Returns(expectedError); + + // Act + IResult result = await _sut.ExecuteAsync(request, cancellationToken); + + // Assert + result.Should().BeOfType(); + ProblemHttpResult problemDetails = (ProblemHttpResult)result; + problemDetails.StatusCode.Should().Be(StatusCodes.Status422UnprocessableEntity); + problemDetails.ContentType.Should().Be("application/problem+json"); + problemDetails.ProblemDetails.Should().BeOfType(); + HttpValidationProblemDetails validationProblemDetails = (HttpValidationProblemDetails)problemDetails.ProblemDetails; + validationProblemDetails.Status.Should().Be(StatusCodes.Status422UnprocessableEntity); + validationProblemDetails.Title.Should().Be("Validation Error"); + validationProblemDetails.Detail.Should().Be("One or more validation errors occurred."); + validationProblemDetails.Type.Should().Be("https://tools.ietf.org/html/rfc4918#section-11.2"); + validationProblemDetails.Errors.Should().ContainSingle() + .Which.Should().BeEquivalentTo(new + { + Key = "Path.Invalid", + Value = new[] { "The provided path is invalid." } + }); + } + + [Fact] + public async Task ExecuteAsync_WhenCalled_ShouldSendGetDirectoriesQueryToMediator() + { + // Arrange + GetDirectoriesRequest request = _fixture.Create(); + CancellationToken cancellationToken = CancellationToken.None; + _mockSender.Send(Arg.Any(), Arg.Any()) + .Returns(ErrorOrFactory.From(Enumerable.Empty())); + + // Act + await _sut.ExecuteAsync(request, cancellationToken); + + // Assert + await _mockSender.Received(1).Send( + Arg.Is(q => q.Path == request.Path && q.IncludeHiddenElements == request.IncludeHiddenElements), + Arg.Is(cancellationToken)); + } + + [Fact] + public async Task ExecuteAsync_WhenCancellationRequested_ShouldCancelOperation() + { + // Arrange + GetDirectoriesRequest request = _fixture.Create(); + CancellationTokenSource cts = new(); + TaskCompletionSource operationStarted = new(); + TaskCompletionSource cancellationRequested = new(); + + _mockSender.Send(Arg.Any(), Arg.Any()) + .Returns(callInfo => new ValueTask>>(Task.Run(async () => + { + operationStarted.SetResult(true); + await cancellationRequested.Task; + callInfo.Arg().ThrowIfCancellationRequested(); + return ErrorOrFactory.From(_fixture.CreateMany(3).AsEnumerable()); + }, 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/FileSystemManagement/Directories/GetDirectoryTreeEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/FileSystemManagement/Directories/GetDirectoryTreeEndpointTests.cs new file mode 100644 index 00000000..50de4ade --- /dev/null +++ b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/FileSystemManagement/Directories/GetDirectoryTreeEndpointTests.cs @@ -0,0 +1,170 @@ +#region ========================================================================= USING ===================================================================================== +using AutoFixture; +using AutoFixture.AutoNSubstitute; +using ErrorOr; +using FastEndpoints; +using FluentAssertions; +using Lumina.Application.Core.FileSystemManagement.Directories.Queries.GetDirectoryTree; +using Lumina.Contracts.Requests.FileSystemManagement.Directories; +using Lumina.Contracts.Responses.FileSystemManagement.Common; +using Lumina.Presentation.Api.Core.Endpoints.FileSystemManagement.Directories.GetDirectoryTree; +using Lumina.Presentation.Api.UnitTests.Core.Endpoints.FileSystemManagement.Fixtures; +using Mediator; +using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Http.HttpResults; +using NSubstitute; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Api.UnitTests.Core.Endpoints.FileSystemManagement.Directories; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class GetDirectoryTreeEndpointTests +{ + private readonly IFixture _fixture; + private readonly ISender _mockSender; + private readonly GetDirectoryTreeEndpoint _sut; + private readonly FileSystemTreeNodeResponseFixture _fileSystemTreeNodeResponseFixture; + + /// + /// Initializes a new instance of the class. + /// + public GetDirectoryTreeEndpointTests() + { + _fixture = new Fixture().Customize(new AutoNSubstituteCustomization()); + _mockSender = Substitute.For(); + _sut = Factory.Create(_mockSender); + _fileSystemTreeNodeResponseFixture = new FileSystemTreeNodeResponseFixture(); + } + + [Fact] + public async Task ExecuteAsync_WhenCalled_ShouldReturnOkResultWithFileSystemTreeNodeResponses() + { + // Arrange + GetDirectoryTreeRequest request = _fixture.Create(); + CancellationToken cancellationToken = CancellationToken.None; + List expectedResponses = _fileSystemTreeNodeResponseFixture.CreateMany(3, 3, 5); + _mockSender.Send(Arg.Any(), Arg.Any()) + .Returns(ErrorOrFactory.From(expectedResponses.AsEnumerable())); + + // Act + IResult result = await _sut.ExecuteAsync(request, cancellationToken); + + // Assert + IEnumerable actualResponses = result.Should().BeOfType>>().Subject.Value!; + actualResponses.Should().BeEquivalentTo(expectedResponses); + } + + [Fact] + public async Task ExecuteAsync_WhenMediatorReturnsError_ShouldReturnProblemResult() + { + // Arrange + GetDirectoryTreeRequest request = _fixture.Create(); + CancellationToken cancellationToken = CancellationToken.None; + Error expectedError = Error.NotFound("Directory.NotFound", "The requested directory was not found."); + _mockSender.Send(Arg.Any(), Arg.Any()) + .Returns(expectedError); + + // Act + IResult result = await _sut.ExecuteAsync(request, cancellationToken); + + // Assert + result.Should().BeOfType(); + ProblemHttpResult problemDetails = (ProblemHttpResult)result; + problemDetails.StatusCode.Should().Be(StatusCodes.Status404NotFound); + problemDetails.ContentType.Should().Be("application/problem+json"); + problemDetails.ProblemDetails.Should().BeOfType(); + + problemDetails.ProblemDetails.Title.Should().Be("Directory.NotFound"); + problemDetails.ProblemDetails.Detail.Should().Be("The requested directory was not found."); + problemDetails.ProblemDetails.Status.Should().Be(StatusCodes.Status404NotFound); + problemDetails.ProblemDetails.Type.Should().Be("https://tools.ietf.org/html/rfc9110#section-15.5.5"); + problemDetails.ProblemDetails.Extensions["traceId"].Should().NotBeNull(); + } + + [Fact] + public async Task ExecuteAsync_WhenMediatorReturnsValidationError_ShouldReturnValidationProblemResult() + { + // Arrange + GetDirectoryTreeRequest request = _fixture.Create(); + CancellationToken cancellationToken = CancellationToken.None; + Error expectedError = Error.Validation("Path.Invalid", "The provided path is invalid."); + _mockSender.Send(Arg.Any(), Arg.Any()) + .Returns(expectedError); + + // Act + IResult result = await _sut.ExecuteAsync(request, cancellationToken); + + // Assert + result.Should().BeOfType(); + ProblemHttpResult problemDetails = (ProblemHttpResult)result; + problemDetails.StatusCode.Should().Be(StatusCodes.Status422UnprocessableEntity); + problemDetails.ContentType.Should().Be("application/problem+json"); + problemDetails.ProblemDetails.Should().BeOfType(); + HttpValidationProblemDetails validationProblemDetails = (HttpValidationProblemDetails)problemDetails.ProblemDetails; + validationProblemDetails.Status.Should().Be(StatusCodes.Status422UnprocessableEntity); + validationProblemDetails.Title.Should().Be("Validation Error"); + validationProblemDetails.Detail.Should().Be("One or more validation errors occurred."); + validationProblemDetails.Type.Should().Be("https://tools.ietf.org/html/rfc4918#section-11.2"); + validationProblemDetails.Errors.Should().ContainSingle() + .Which.Should().BeEquivalentTo(new + { + Key = "Path.Invalid", + Value = new[] { "The provided path is invalid." } + }); + } + + [Fact] + public async Task ExecuteAsync_WhenCalled_ShouldSendGetDirectoryTreeQueryToMediator() + { + // Arrange + GetDirectoryTreeRequest request = _fixture.Create(); + CancellationToken cancellationToken = CancellationToken.None; + _mockSender.Send(Arg.Any(), Arg.Any()) + .Returns(ErrorOrFactory.From(Enumerable.Empty())); + + // Act + await _sut.ExecuteAsync(request, cancellationToken); + + // Assert + await _mockSender.Received(1).Send( + Arg.Is(q => q.Path == request.Path && q.IncludeFiles == request.IncludeFiles && q.IncludeHiddenElements == request.IncludeHiddenElements), + Arg.Is(cancellationToken)); + } + + [Fact] + public async Task ExecuteAsync_WhenCancellationRequested_ShouldCancelOperation() + { + // Arrange + GetDirectoryTreeRequest request = _fixture.Create(); + CancellationTokenSource cts = new(); + TaskCompletionSource operationStarted = new(); + TaskCompletionSource cancellationRequested = new(); + + _mockSender.Send(Arg.Any(), Arg.Any()) + .Returns(callInfo => new ValueTask>>(Task.Run(async () => + { + operationStarted.SetResult(true); + await cancellationRequested.Task; + callInfo.Arg().ThrowIfCancellationRequested(); + return ErrorOrFactory.From(_fileSystemTreeNodeResponseFixture.CreateMany(3, 3, 5).AsEnumerable()); + }, 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/FileSystemManagement/Directories/GetTreeDirectoriesEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/FileSystemManagement/Directories/GetTreeDirectoriesEndpointTests.cs new file mode 100644 index 00000000..edde8820 --- /dev/null +++ b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/FileSystemManagement/Directories/GetTreeDirectoriesEndpointTests.cs @@ -0,0 +1,170 @@ +#region ========================================================================= USING ===================================================================================== +using AutoFixture; +using AutoFixture.AutoNSubstitute; +using ErrorOr; +using FastEndpoints; +using FluentAssertions; +using Lumina.Application.Core.FileSystemManagement.Directories.Queries.GetTreeDirectories; +using Lumina.Contracts.Requests.FileSystemManagement.Directories; +using Lumina.Contracts.Responses.FileSystemManagement.Common; +using Lumina.Presentation.Api.Core.Endpoints.FileSystemManagement.Directories.GetTreeDirectories; +using Lumina.Presentation.Api.UnitTests.Core.Endpoints.FileSystemManagement.Fixtures; +using Mediator; +using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Http.HttpResults; +using NSubstitute; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Api.UnitTests.Core.Endpoints.FileSystemManagement.Directories; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class GetTreeDirectoriesEndpointTests +{ + private readonly IFixture _fixture; + private readonly ISender _mockSender; + private readonly GetTreeDirectoriesEndpoint _sut; + private readonly FileSystemTreeNodeResponseFixture _fileSystemTreeNodeResponseFixture; + + /// + /// Initializes a new instance of the class. + /// + public GetTreeDirectoriesEndpointTests() + { + _fixture = new Fixture().Customize(new AutoNSubstituteCustomization()); + _mockSender = Substitute.For(); + _sut = Factory.Create(_mockSender); + _fileSystemTreeNodeResponseFixture = new FileSystemTreeNodeResponseFixture(); + } + + [Fact] + public async Task ExecuteAsync_WhenCalled_ShouldReturnOkResultWithFileSystemTreeNodeResponses() + { + // Arrange + GetTreeDirectoriesRequest request = _fixture.Create(); + CancellationToken cancellationToken = CancellationToken.None; + List expectedResponses = _fileSystemTreeNodeResponseFixture.CreateMany(3, 3, 5); + _mockSender.Send(Arg.Any(), Arg.Any()) + .Returns(ErrorOrFactory.From(expectedResponses.AsEnumerable())); + + // Act + IResult result = await _sut.ExecuteAsync(request, cancellationToken); + + // Assert + IEnumerable actualResponses = result.Should().BeOfType>>().Subject.Value!; + actualResponses.Should().BeEquivalentTo(expectedResponses); + } + + [Fact] + public async Task ExecuteAsync_WhenMediatorReturnsError_ShouldReturnProblemResult() + { + // Arrange + GetTreeDirectoriesRequest request = _fixture.Create(); + CancellationToken cancellationToken = CancellationToken.None; + Error expectedError = Error.NotFound("Directory.NotFound", "The requested directory was not found."); + _mockSender.Send(Arg.Any(), Arg.Any()) + .Returns(expectedError); + + // Act + IResult result = await _sut.ExecuteAsync(request, cancellationToken); + + // Assert + result.Should().BeOfType(); + ProblemHttpResult problemDetails = (ProblemHttpResult)result; + problemDetails.StatusCode.Should().Be(StatusCodes.Status404NotFound); + problemDetails.ContentType.Should().Be("application/problem+json"); + problemDetails.ProblemDetails.Should().BeOfType(); + + problemDetails.ProblemDetails.Title.Should().Be("Directory.NotFound"); + problemDetails.ProblemDetails.Detail.Should().Be("The requested directory was not found."); + problemDetails.ProblemDetails.Status.Should().Be(StatusCodes.Status404NotFound); + problemDetails.ProblemDetails.Type.Should().Be("https://tools.ietf.org/html/rfc9110#section-15.5.5"); + problemDetails.ProblemDetails.Extensions["traceId"].Should().NotBeNull(); + } + + [Fact] + public async Task ExecuteAsync_WhenMediatorReturnsValidationError_ShouldReturnValidationProblemResult() + { + // Arrange + GetTreeDirectoriesRequest request = _fixture.Create(); + CancellationToken cancellationToken = CancellationToken.None; + Error expectedError = Error.Validation("Path.Invalid", "The provided path is invalid."); + _mockSender.Send(Arg.Any(), Arg.Any()) + .Returns(expectedError); + + // Act + IResult result = await _sut.ExecuteAsync(request, cancellationToken); + + // Assert + result.Should().BeOfType(); + ProblemHttpResult problemDetails = (ProblemHttpResult)result; + problemDetails.StatusCode.Should().Be(StatusCodes.Status422UnprocessableEntity); + problemDetails.ContentType.Should().Be("application/problem+json"); + problemDetails.ProblemDetails.Should().BeOfType(); + HttpValidationProblemDetails validationProblemDetails = (HttpValidationProblemDetails)problemDetails.ProblemDetails; + validationProblemDetails.Status.Should().Be(StatusCodes.Status422UnprocessableEntity); + validationProblemDetails.Title.Should().Be("Validation Error"); + validationProblemDetails.Detail.Should().Be("One or more validation errors occurred."); + validationProblemDetails.Type.Should().Be("https://tools.ietf.org/html/rfc4918#section-11.2"); + validationProblemDetails.Errors.Should().ContainSingle() + .Which.Should().BeEquivalentTo(new + { + Key = "Path.Invalid", + Value = new[] { "The provided path is invalid." } + }); + } + + [Fact] + public async Task ExecuteAsync_WhenCalled_ShouldSendGetTreeDirectoriesQueryToMediator() + { + // Arrange + GetTreeDirectoriesRequest request = _fixture.Create(); + CancellationToken cancellationToken = CancellationToken.None; + _mockSender.Send(Arg.Any(), Arg.Any()) + .Returns(ErrorOrFactory.From(Enumerable.Empty())); + + // Act + await _sut.ExecuteAsync(request, cancellationToken); + + // Assert + await _mockSender.Received(1).Send( + Arg.Is(q => q.Path == request.Path && q.IncludeHiddenElements == request.IncludeHiddenElements), + Arg.Is(cancellationToken)); + } + + [Fact] + public async Task ExecuteAsync_WhenCancellationRequested_ShouldCancelOperation() + { + // Arrange + GetTreeDirectoriesRequest request = _fixture.Create(); + CancellationTokenSource cts = new(); + TaskCompletionSource operationStarted = new(); + TaskCompletionSource cancellationRequested = new(); + + _mockSender.Send(Arg.Any(), Arg.Any()) + .Returns(callInfo => new ValueTask>>(Task.Run(async () => + { + operationStarted.SetResult(true); + await cancellationRequested.Task; + callInfo.Arg().ThrowIfCancellationRequested(); + return ErrorOrFactory.From(_fileSystemTreeNodeResponseFixture.CreateMany(3, 3, 5).AsEnumerable()); + }, 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/FileSystemManagement/Drives/GetDrivesEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/FileSystemManagement/Drives/GetDrivesEndpointTests.cs new file mode 100644 index 00000000..dee60129 --- /dev/null +++ b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/FileSystemManagement/Drives/GetDrivesEndpointTests.cs @@ -0,0 +1,127 @@ +#region ========================================================================= USING ===================================================================================== +using ErrorOr; +using FastEndpoints; +using FluentAssertions; +using Lumina.Application.Core.FileSystemManagement.Drives.Queries.GetDrives; +using Lumina.Contracts.Responses.FileSystemManagement.Common; +using Lumina.Presentation.Api.Core.Endpoints.FileSystemManagement.Drives.GetDrives; +using Lumina.Presentation.Api.UnitTests.Core.Endpoints.FileSystemManagement.Fixtures; +using Mediator; +using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Http.HttpResults; +using NSubstitute; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Api.UnitTests.Core.Endpoints.FileSystemManagement.Drives; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class GetDrivesEndpointTests +{ + private readonly ISender _mockSender; + private readonly GetDrivesEndpoint _sut; + private readonly FileSystemTreeNodeResponseFixture _fileSystemTreeNodeResponseFixture; + + /// + /// Initializes a new instance of the class. + /// + public GetDrivesEndpointTests() + { + _mockSender = Substitute.For(); + _fileSystemTreeNodeResponseFixture = new FileSystemTreeNodeResponseFixture(); + _sut = Factory.Create(_mockSender); + } + + [Fact] + public async Task ExecuteAsync_WhenCalled_ShouldReturnOkResultWithFileSystemTreeNodeResponses() + { + // Arrange + CancellationToken cancellationToken = CancellationToken.None; + List expectedResponses = _fileSystemTreeNodeResponseFixture.CreateMany(3, 1, 1); + _mockSender.Send(Arg.Any(), Arg.Any()) + .Returns(ErrorOrFactory.From(expectedResponses.AsEnumerable())); + + // Act + IResult result = await _sut.ExecuteAsync(new EmptyRequest(), cancellationToken); + + // Assert + IEnumerable actualResponses = result.Should().BeOfType>>().Subject.Value!; + actualResponses.Should().BeEquivalentTo(expectedResponses); + } + + [Fact] + public async Task ExecuteAsync_WhenMediatorReturnsError_ShouldReturnProblemResult() + { + // Arrange + CancellationToken cancellationToken = CancellationToken.None; + Error expectedError = Error.NotFound("Drive.NotFound", "The requested drive was not found."); + _mockSender.Send(Arg.Any(), Arg.Any()) + .Returns(expectedError); + + // Act + IResult result = await _sut.ExecuteAsync(new EmptyRequest(), cancellationToken); + + // Assert + result.Should().BeOfType(); + ProblemHttpResult problemDetails = (ProblemHttpResult)result; + problemDetails.StatusCode.Should().Be(StatusCodes.Status404NotFound); + problemDetails.ContentType.Should().Be("application/problem+json"); + problemDetails.ProblemDetails.Should().BeOfType(); + + problemDetails.ProblemDetails.Title.Should().Be("Drive.NotFound"); + problemDetails.ProblemDetails.Detail.Should().Be("The requested drive was not found."); + problemDetails.ProblemDetails.Status.Should().Be(StatusCodes.Status404NotFound); + problemDetails.ProblemDetails.Type.Should().Be("https://tools.ietf.org/html/rfc9110#section-15.5.5"); + problemDetails.ProblemDetails.Extensions["traceId"].Should().NotBeNull(); + } + + [Fact] + public async Task ExecuteAsync_WhenCalled_ShouldSendGetDrivesQueryToMediator() + { + // Arrange + CancellationToken cancellationToken = CancellationToken.None; + _mockSender.Send(Arg.Any(), Arg.Any()) + .Returns(ErrorOrFactory.From(Enumerable.Empty())); + + // Act + await _sut.ExecuteAsync(new EmptyRequest(), cancellationToken); + + // Assert + await _mockSender.Received(1).Send(Arg.Any(), Arg.Is(cancellationToken)); + } + + [Fact] + public async Task ExecuteAsync_WhenCancellationRequested_ShouldCancelOperation() + { + // Arrange + CancellationTokenSource cts = new(); + TaskCompletionSource operationStarted = new(); + TaskCompletionSource cancellationRequested = new(); + + _mockSender.Send(Arg.Any(), Arg.Any()) + .Returns(callInfo => new ValueTask>>(Task.Run(async () => + { + operationStarted.SetResult(true); + await cancellationRequested.Task; + callInfo.Arg().ThrowIfCancellationRequested(); + return ErrorOrFactory.From(_fileSystemTreeNodeResponseFixture.CreateMany(3, 1, 1).AsEnumerable()); + }, callInfo.Arg()))); + + // Act + Task operationTask = _sut.ExecuteAsync(new EmptyRequest(), 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/FileSystemManagement/FileSystem/GetTypeEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/FileSystemManagement/FileSystem/GetTypeEndpointTests.cs new file mode 100644 index 00000000..b173bcba --- /dev/null +++ b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/FileSystemManagement/FileSystem/GetTypeEndpointTests.cs @@ -0,0 +1,115 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using FluentAssertions; +using Lumina.Application.Core.FileSystemManagement.FileSystem.Queries.GetFileSystem; +using Lumina.Contracts.Enums.FileSystem; +using Lumina.Contracts.Responses.FileSystemManagement.FileSystem; +using Lumina.Presentation.Api.Core.Endpoints.FileSystemManagement.FileSystem.GetType; +using Mediator; +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.FileSystemManagement.FileSystem; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class GetFileSystemTypeEndpointTests +{ + private readonly ISender _mockSender; + private readonly GetTypeEndpoint _sut; + + /// + /// Initializes a new instance of the class. + /// + public GetFileSystemTypeEndpointTests() + { + _mockSender = Substitute.For(); + _sut = Factory.Create(_mockSender); + } + + [Fact] + public async Task ExecuteAsync_WhenCalled_ShouldReturnOkResultWithFileSystemTypeResponse() + { + // Arrange + CancellationToken cancellationToken = CancellationToken.None; + FileSystemTypeResponse expectedResponse = new(PlatformType.Windows); + _mockSender.Send(Arg.Any(), Arg.Any()) + .Returns(expectedResponse); + + // Act + IResult result = await _sut.ExecuteAsync(new EmptyRequest(), cancellationToken); + + // Assert + Ok okResult = result.Should().BeOfType>().Subject; + okResult.Value.Should().BeEquivalentTo(expectedResponse); + } + + [Theory] + [InlineData(PlatformType.Windows)] + [InlineData(PlatformType.Unix)] + public async Task ExecuteAsync_WithDifferentPlatformTypes_ShouldReturnCorrectResponse(PlatformType platformType) + { + // Arrange + CancellationToken cancellationToken = CancellationToken.None; + FileSystemTypeResponse expectedResponse = new(platformType); + _mockSender.Send(Arg.Any(), Arg.Any()) + .Returns(expectedResponse); + + // Act + IResult result = await _sut.ExecuteAsync(new EmptyRequest(), cancellationToken); + + // Assert + Ok okResult = result.Should().BeOfType>().Subject; + okResult.Value!.PlatformType.Should().Be(platformType); + } + + [Fact] + public async Task ExecuteAsync_WhenCalled_ShouldSendGetFileSystemQueryToMediator() + { + // Arrange + CancellationToken cancellationToken = CancellationToken.None; + _mockSender.Send(Arg.Any(), Arg.Any()) + .Returns(new FileSystemTypeResponse(PlatformType.Windows)); + + // Act + await _sut.ExecuteAsync(new EmptyRequest(), cancellationToken); + + // Assert + await _mockSender.Received(1).Send(Arg.Any(), Arg.Is(cancellationToken)); + } + + [Fact] + public async Task ExecuteAsync_WhenCancellationRequested_ShouldCancelOperation() + { + // Arrange + CancellationTokenSource cts = new(); + TaskCompletionSource operationStarted = new(); + TaskCompletionSource cancellationRequested = new(); + + _mockSender.Send(Arg.Any(), Arg.Any()) + .Returns(callInfo => new ValueTask(Task.Run(async () => + { + operationStarted.SetResult(true); + await cancellationRequested.Task; + callInfo.Arg().ThrowIfCancellationRequested(); + return new FileSystemTypeResponse(PlatformType.Windows); + }, callInfo.Arg()))); + + // Act + Task operationTask = _sut.ExecuteAsync(new EmptyRequest(), 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/FileSystemManagement/Files/GetFilesEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/FileSystemManagement/Files/GetFilesEndpointTests.cs new file mode 100644 index 00000000..5e819ebd --- /dev/null +++ b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/FileSystemManagement/Files/GetFilesEndpointTests.cs @@ -0,0 +1,170 @@ +#region ========================================================================= USING ===================================================================================== +using AutoFixture; +using AutoFixture.AutoNSubstitute; +using ErrorOr; +using FastEndpoints; +using FluentAssertions; +using Lumina.Application.Core.FileSystemManagement.Files.Queries.GetFiles; +using Lumina.Contracts.Requests.FileSystemManagement.Files; +using Lumina.Contracts.Responses.FileSystemManagement.Files; +using Lumina.Presentation.Api.Common.Http; +using Lumina.Presentation.Api.Core.Endpoints.FileSystemManagement.Files.GetFiles; +using Mediator; +using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Http.HttpResults; +using NSubstitute; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +using System.Reflection; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Api.UnitTests.Core.Endpoints.FileSystemManagement.Files; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class GetFilesEndpointTests +{ + private readonly IFixture _fixture; + private readonly ISender _mockSender; + private readonly GetFilesEndpoint _sut; + + /// + /// Initializes a new instance of the class. + /// + public GetFilesEndpointTests() + { + _fixture = new Fixture().Customize(new AutoNSubstituteCustomization()); + _mockSender = Substitute.For(); + _sut = Factory.Create(_mockSender); + } + + [Fact] + public async Task ExecuteAsync_WhenCalled_ShouldReturnOkResultWithFileResponses() + { + // Arrange + GetFilesRequest request = _fixture.Create(); + CancellationToken cancellationToken = CancellationToken.None; + List expectedResponses = _fixture.CreateMany(3).ToList(); + _mockSender.Send(Arg.Any(), Arg.Any()) + .Returns(ErrorOrFactory.From(expectedResponses.AsEnumerable())); + + // Act + IResult result = await _sut.ExecuteAsync(request, cancellationToken); + + // Assert + IEnumerable actualResponses = result.Should().BeOfType>>().Subject.Value!; + actualResponses.Should().BeEquivalentTo(expectedResponses); + } + + [Fact] + public async Task ExecuteAsync_WhenMediatorReturnsError_ShouldReturnProblemResult() + { + // Arrange + GetFilesRequest request = _fixture.Create(); + CancellationToken cancellationToken = CancellationToken.None; + Error expectedError = Error.NotFound("File.NotFound", "The requested file was not found."); + _mockSender.Send(Arg.Any(), Arg.Any()) + .Returns(expectedError); + + // Act + IResult result = await _sut.ExecuteAsync(request, cancellationToken); + + // Assert + result.Should().BeOfType(); + ProblemHttpResult problemDetails = (ProblemHttpResult)result; + problemDetails.StatusCode.Should().Be(StatusCodes.Status404NotFound); + problemDetails.ContentType.Should().Be("application/problem+json"); + problemDetails.ProblemDetails.Should().BeOfType(); + + problemDetails.ProblemDetails.Title.Should().Be("File.NotFound"); + problemDetails.ProblemDetails.Detail.Should().Be("The requested file was not found."); + problemDetails.ProblemDetails.Status.Should().Be(StatusCodes.Status404NotFound); + problemDetails.ProblemDetails.Type.Should().Be("https://tools.ietf.org/html/rfc9110#section-15.5.5"); + problemDetails.ProblemDetails.Extensions["traceId"].Should().NotBeNull(); + } + + [Fact] + public async Task ExecuteAsync_WhenMediatorReturnsValidationError_ShouldReturnValidationProblemResult() + { + // Arrange + GetFilesRequest request = _fixture.Create(); + CancellationToken cancellationToken = CancellationToken.None; + Error expectedError = Error.Validation("Path.Invalid", "The provided path is invalid."); + _mockSender.Send(Arg.Any(), Arg.Any()) + .Returns(expectedError); + + // Act + IResult result = await _sut.ExecuteAsync(request, cancellationToken); + + // Assert + result.Should().BeOfType(); + ProblemHttpResult problemDetails = (ProblemHttpResult)result; + problemDetails.StatusCode.Should().Be(StatusCodes.Status422UnprocessableEntity); + problemDetails.ContentType.Should().Be("application/problem+json"); + problemDetails.ProblemDetails.Should().BeOfType(); + HttpValidationProblemDetails validationProblemDetails = (HttpValidationProblemDetails)problemDetails.ProblemDetails; + validationProblemDetails.Status.Should().Be(StatusCodes.Status422UnprocessableEntity); + validationProblemDetails.Title.Should().Be("Validation Error"); + validationProblemDetails.Detail.Should().Be("One or more validation errors occurred."); + validationProblemDetails.Type.Should().Be("https://tools.ietf.org/html/rfc4918#section-11.2"); + validationProblemDetails.Errors.Should().ContainSingle() + .Which.Should().BeEquivalentTo(new + { + Key = "Path.Invalid", + Value = new[] { "The provided path is invalid." } + }); + } + + [Fact] + public async Task ExecuteAsync_WhenCalled_ShouldSendGetFilesQueryToSender() + { + // Arrange + GetFilesRequest request = _fixture.Create(); + CancellationToken cancellationToken = CancellationToken.None; + _mockSender.Send(Arg.Any(), Arg.Any()) + .Returns(ErrorOrFactory.From(Enumerable.Empty())); + + // Act + await _sut.ExecuteAsync(request, cancellationToken); + + // Assert + await _mockSender.Received(1).Send(Arg.Is(q => + q.Path == request.Path && + q.IncludeHiddenElements == request.IncludeHiddenElements), + Arg.Is(cancellationToken)); + } + + [Fact] + public async Task ExecuteAsync_WhenCancellationRequested_ShouldCancelOperation() + { + // Arrange + GetFilesRequest request = _fixture.Create(); + CancellationTokenSource cts = new(); + TaskCompletionSource operationStarted = new(); + TaskCompletionSource cancellationRequested = new(); + + _mockSender.Send(Arg.Any(), Arg.Any()) + .Returns(callInfo => new ValueTask>>(Task.Run(async () => + { + operationStarted.SetResult(true); + await cancellationRequested.Task; + callInfo.Arg().ThrowIfCancellationRequested(); + return ErrorOrFactory.From(_fixture.CreateMany(3).AsEnumerable()); + }, 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/FileSystemManagement/Files/GetTreeFilesEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/FileSystemManagement/Files/GetTreeFilesEndpointTests.cs new file mode 100644 index 00000000..b247bd38 --- /dev/null +++ b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/FileSystemManagement/Files/GetTreeFilesEndpointTests.cs @@ -0,0 +1,171 @@ +#region ========================================================================= USING ===================================================================================== +using AutoFixture; +using AutoFixture.AutoNSubstitute; +using ErrorOr; +using FastEndpoints; +using FluentAssertions; +using Lumina.Application.Core.FileSystemManagement.Files.Queries.GetTreeFiles; +using Lumina.Contracts.Requests.FileSystemManagement.Files; +using Lumina.Contracts.Responses.FileSystemManagement.Common; +using Lumina.Presentation.Api.Core.Endpoints.FileSystemManagement.Files.GetTreeFiles; +using Lumina.Presentation.Api.UnitTests.Core.Endpoints.FileSystemManagement.Fixtures; +using Mediator; +using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Http.HttpResults; +using NSubstitute; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Api.UnitTests.Core.Endpoints.FileSystemManagement.Files; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class GetTreeFilesEndpointTests +{ + private readonly IFixture _fixture; + private readonly ISender _mockSender; + private readonly GetTreeFilesEndpoint _sut; + private readonly FileSystemTreeNodeResponseFixture _fileSystemTreeNodeResponseFixture; + + /// + /// Initializes a new instance of the class. + /// + public GetTreeFilesEndpointTests() + { + _fixture = new Fixture().Customize(new AutoNSubstituteCustomization()); + _mockSender = Substitute.For(); + _fileSystemTreeNodeResponseFixture = new FileSystemTreeNodeResponseFixture(); + _sut = Factory.Create(_mockSender); + } + + [Fact] + public async Task ExecuteAsync_WhenCalled_ShouldReturnOkResultWithFileSystemTreeNodeResponses() + { + // Arrange + GetTreeFilesRequest request = _fixture.Create(); + CancellationToken cancellationToken = CancellationToken.None; + List expectedResponses = _fileSystemTreeNodeResponseFixture.CreateMany(3, 3, 5); + _mockSender.Send(Arg.Any(), Arg.Any()) + .Returns(ErrorOrFactory.From(expectedResponses.AsEnumerable())); + + // Act + IResult result = await _sut.ExecuteAsync(request, cancellationToken); + + // Assert + IEnumerable actualResponses = result.Should().BeOfType>>().Subject.Value!; + actualResponses.Should().BeEquivalentTo(expectedResponses); + } + + [Fact] + public async Task ExecuteAsync_WhenMediatorReturnsError_ShouldReturnProblemResult() + { + // Arrange + GetTreeFilesRequest request = _fixture.Create(); + CancellationToken cancellationToken = CancellationToken.None; + Error expectedError = Error.NotFound("File.NotFound", "The requested file was not found."); + _mockSender.Send(Arg.Any(), Arg.Any()) + .Returns(expectedError); + + // Act + IResult result = await _sut.ExecuteAsync(request, cancellationToken); + + // Assert + result.Should().BeOfType(); + ProblemHttpResult problemDetails = (ProblemHttpResult)result; + problemDetails.StatusCode.Should().Be(StatusCodes.Status404NotFound); + problemDetails.ContentType.Should().Be("application/problem+json"); + problemDetails.ProblemDetails.Should().BeOfType(); + + problemDetails.ProblemDetails.Title.Should().Be("File.NotFound"); + problemDetails.ProblemDetails.Detail.Should().Be("The requested file was not found."); + problemDetails.ProblemDetails.Status.Should().Be(StatusCodes.Status404NotFound); + problemDetails.ProblemDetails.Type.Should().Be("https://tools.ietf.org/html/rfc9110#section-15.5.5"); + problemDetails.ProblemDetails.Extensions["traceId"].Should().NotBeNull(); + } + + [Fact] + public async Task ExecuteAsync_WhenMediatorReturnsValidationError_ShouldReturnValidationProblemResult() + { + // Arrange + GetTreeFilesRequest request = _fixture.Create(); + CancellationToken cancellationToken = CancellationToken.None; + Error expectedError = Error.Validation("Path.Invalid", "The provided path is invalid."); + _mockSender.Send(Arg.Any(), Arg.Any()) + .Returns(expectedError); + + // Act + IResult result = await _sut.ExecuteAsync(request, cancellationToken); + + // Assert + result.Should().BeOfType(); + ProblemHttpResult problemDetails = (ProblemHttpResult)result; + problemDetails.StatusCode.Should().Be(StatusCodes.Status422UnprocessableEntity); + problemDetails.ContentType.Should().Be("application/problem+json"); + problemDetails.ProblemDetails.Should().BeOfType(); + HttpValidationProblemDetails validationProblemDetails = (HttpValidationProblemDetails)problemDetails.ProblemDetails; + validationProblemDetails.Status.Should().Be(StatusCodes.Status422UnprocessableEntity); + validationProblemDetails.Title.Should().Be("Validation Error"); + validationProblemDetails.Detail.Should().Be("One or more validation errors occurred."); + validationProblemDetails.Type.Should().Be("https://tools.ietf.org/html/rfc4918#section-11.2"); + validationProblemDetails.Errors.Should().ContainSingle() + .Which.Should().BeEquivalentTo(new + { + Key = "Path.Invalid", + Value = new[] { "The provided path is invalid." } + }); + } + + [Fact] + public async Task ExecuteAsync_WhenCalled_ShouldSendGetTreeFilesQueryToSender() + { + // Arrange + GetTreeFilesRequest request = _fixture.Create(); + CancellationToken cancellationToken = CancellationToken.None; + _mockSender.Send(Arg.Any(), Arg.Any()) + .Returns(ErrorOrFactory.From(Enumerable.Empty())); + + // Act + await _sut.ExecuteAsync(request, cancellationToken); + + // Assert + await _mockSender.Received(1).Send(Arg.Is(q => + q.Path == request.Path && + q.IncludeHiddenElements == request.IncludeHiddenElements), + Arg.Is(cancellationToken)); + } + + [Fact] + public async Task ExecuteAsync_WhenCancellationRequested_ShouldCancelOperation() + { + // Arrange + GetTreeFilesRequest request = _fixture.Create(); + CancellationTokenSource cts = new(); + TaskCompletionSource operationStarted = new(); + TaskCompletionSource cancellationRequested = new(); + + _mockSender.Send(Arg.Any(), Arg.Any()) + .Returns(callInfo => new ValueTask>>(Task.Run(async () => + { + operationStarted.SetResult(true); + await cancellationRequested.Task; + callInfo.Arg().ThrowIfCancellationRequested(); + return ErrorOrFactory.From(_fileSystemTreeNodeResponseFixture.CreateMany(3, 3, 5).AsEnumerable()); + }, 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/FileSystemManagement/Fixtures/CheckPathExistsRequestFixture.cs b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/FileSystemManagement/Fixtures/CheckPathExistsRequestFixture.cs new file mode 100644 index 00000000..69448b86 --- /dev/null +++ b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/FileSystemManagement/Fixtures/CheckPathExistsRequestFixture.cs @@ -0,0 +1,30 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Contracts.Requests.FileSystemManagement.Path; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Presentation.Api.UnitTests.Core.Endpoints.FileSystemManagement.Fixtures; + +/// +/// Fixture class for the record. +/// +[ExcludeFromCodeCoverage] +public class CheckPathExistsRequestFixture +{ + private readonly Faker _faker = new(); + + /// + /// Creates a with default or random values. + /// + /// The path to check. + /// Whether to include hidden elements. + /// The created . + public CheckPathExistsRequest Create(string? path = null, bool? includeHiddenElements = null) + { + return new CheckPathExistsRequest( + Path: path ?? _faker.System.FilePath(), + IncludeHiddenElements: includeHiddenElements ?? _faker.Random.Bool() + ); + } +} diff --git a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/FileSystemManagement/Fixtures/CombinePathRequestFixture.cs b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/FileSystemManagement/Fixtures/CombinePathRequestFixture.cs new file mode 100644 index 00000000..a6c65b43 --- /dev/null +++ b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/FileSystemManagement/Fixtures/CombinePathRequestFixture.cs @@ -0,0 +1,30 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Contracts.Requests.FileSystemManagement.Path; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Presentation.Api.UnitTests.Core.Endpoints.FileSystemManagement.Fixtures; + +/// +/// Fixture class for the record. +/// +[ExcludeFromCodeCoverage] +public class CombinePathRequestFixture +{ + private readonly Faker _faker = new(); + + /// + /// Creates a with default or random values. + /// + /// The original path. + /// The new path to combine. + /// The created . + public CombinePathRequest Create(string? originalPath = null, string? newPath = null) + { + return new CombinePathRequest( + OriginalPath: originalPath ?? _faker.System.DirectoryPath(), + NewPath: newPath ?? _faker.System.FileName() + ); + } +} diff --git a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Controllers/FileManagement/Fixtures/FileSystemTreeNodeResponseFixture.cs b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/FileSystemManagement/Fixtures/FileSystemTreeNodeResponseFixture.cs similarity index 94% rename from tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Controllers/FileManagement/Fixtures/FileSystemTreeNodeResponseFixture.cs rename to tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/FileSystemManagement/Fixtures/FileSystemTreeNodeResponseFixture.cs index 06c116b1..983dd4c1 100644 --- a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Controllers/FileManagement/Fixtures/FileSystemTreeNodeResponseFixture.cs +++ b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/FileSystemManagement/Fixtures/FileSystemTreeNodeResponseFixture.cs @@ -1,13 +1,13 @@ #region ========================================================================= USING ===================================================================================== using Bogus; using Lumina.Contracts.Enums.FileSystem; -using Lumina.Contracts.Responses.FileManagement; +using Lumina.Contracts.Responses.FileSystemManagement.Common; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Linq; #endregion -namespace Lumina.Presentation.Api.UnitTests.Core.Controllers.FileManagement.Fixtures; +namespace Lumina.Presentation.Api.UnitTests.Core.Endpoints.FileSystemManagement.Fixtures; /// /// Fixture class for the class. diff --git a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/FileSystemManagement/Fixtures/GetPathParentRequestFixture.cs b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/FileSystemManagement/Fixtures/GetPathParentRequestFixture.cs new file mode 100644 index 00000000..df3f0c82 --- /dev/null +++ b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/FileSystemManagement/Fixtures/GetPathParentRequestFixture.cs @@ -0,0 +1,28 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Contracts.Requests.FileSystemManagement.Path; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Presentation.Api.UnitTests.Core.Endpoints.FileSystemManagement.Fixtures; + +/// +/// Fixture class for the record. +/// +[ExcludeFromCodeCoverage] +public class GetPathParentRequestFixture +{ + private readonly Faker _faker = new(); + + /// + /// Creates a with a default or random value. + /// + /// The path to get the parent of. + /// The created . + public GetPathParentRequest Create(string? path = null) + { + return new GetPathParentRequest( + Path: path ?? _faker.System.FilePath() + ); + } +} diff --git a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/FileSystemManagement/Fixtures/GetPathRootRequestFixture.cs b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/FileSystemManagement/Fixtures/GetPathRootRequestFixture.cs new file mode 100644 index 00000000..e7bf83a6 --- /dev/null +++ b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/FileSystemManagement/Fixtures/GetPathRootRequestFixture.cs @@ -0,0 +1,28 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Contracts.Requests.FileSystemManagement.Path; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Presentation.Api.UnitTests.Core.Endpoints.FileSystemManagement.Fixtures; + +/// +/// Fixture class for the record. +/// +[ExcludeFromCodeCoverage] +public class GetPathRootRequestFixture +{ + private readonly Faker _faker = new(); + + /// + /// Creates a with a default or random value. + /// + /// The path to get the root of. + /// The created . + public GetPathRootRequest Create(string? path = null) + { + return new GetPathRootRequest( + Path: path ?? _faker.System.FilePath() + ); + } +} diff --git a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/FileSystemManagement/Fixtures/GetThumbnailRequestFixture.cs b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/FileSystemManagement/Fixtures/GetThumbnailRequestFixture.cs new file mode 100644 index 00000000..b27cd17f --- /dev/null +++ b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/FileSystemManagement/Fixtures/GetThumbnailRequestFixture.cs @@ -0,0 +1,30 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Contracts.Requests.FileSystemManagement.Thumbnails; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Presentation.Api.UnitTests.Core.Endpoints.FileSystemManagement.Fixtures; + +/// +/// Fixture class for the record. +/// +[ExcludeFromCodeCoverage] +public class GetThumbnailRequestFixture +{ + private readonly Faker _faker = new(); + + /// + /// Creates a with default or random values. + /// + /// The path of the file to get the thumbnail for. + /// The quality of the thumbnail. + /// The created . + public GetThumbnailRequest Create(string? path = null, int? quality = null) + { + return new GetThumbnailRequest( + Path: path ?? _faker.System.FilePath(), + Quality: quality ?? _faker.Random.Int(1, 100) + ); + } +} diff --git a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Controllers/FileManagement/Fixtures/PathSegmentResponseFixture.cs b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/FileSystemManagement/Fixtures/PathSegmentResponseFixture.cs similarity index 88% rename from tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Controllers/FileManagement/Fixtures/PathSegmentResponseFixture.cs rename to tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/FileSystemManagement/Fixtures/PathSegmentResponseFixture.cs index eedceead..e38fb301 100644 --- a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Controllers/FileManagement/Fixtures/PathSegmentResponseFixture.cs +++ b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/FileSystemManagement/Fixtures/PathSegmentResponseFixture.cs @@ -1,12 +1,12 @@ #region ========================================================================= USING ===================================================================================== using Bogus; -using Lumina.Contracts.Responses.FileManagement; +using Lumina.Contracts.Responses.FileSystemManagement.Path; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Linq; #endregion -namespace Lumina.Presentation.Api.UnitTests.Core.Controllers.FileManagement.Fixtures; +namespace Lumina.Presentation.Api.UnitTests.Core.Endpoints.FileSystemManagement.Fixtures; /// /// Fixture class for the class. diff --git a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Controllers/FileManagement/Fixtures/PathSeparatorResponseFixture.cs b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/FileSystemManagement/Fixtures/PathSeparatorResponseFixture.cs similarity index 88% rename from tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Controllers/FileManagement/Fixtures/PathSeparatorResponseFixture.cs rename to tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/FileSystemManagement/Fixtures/PathSeparatorResponseFixture.cs index 56b2745f..79a80e14 100644 --- a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Controllers/FileManagement/Fixtures/PathSeparatorResponseFixture.cs +++ b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/FileSystemManagement/Fixtures/PathSeparatorResponseFixture.cs @@ -1,12 +1,12 @@ #region ========================================================================= USING ===================================================================================== using Bogus; -using Lumina.Contracts.Responses.FileManagement; +using Lumina.Contracts.Responses.FileSystemManagement.Path; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Linq; #endregion -namespace Lumina.Presentation.Api.UnitTests.Core.Controllers.FileManagement.Fixtures; +namespace Lumina.Presentation.Api.UnitTests.Core.Endpoints.FileSystemManagement.Fixtures; /// /// Fixture class for the class. diff --git a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/FileSystemManagement/Fixtures/SplitPathRequestFixture.cs b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/FileSystemManagement/Fixtures/SplitPathRequestFixture.cs new file mode 100644 index 00000000..59b1d008 --- /dev/null +++ b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/FileSystemManagement/Fixtures/SplitPathRequestFixture.cs @@ -0,0 +1,28 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Contracts.Requests.FileSystemManagement.Path; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Presentation.Api.UnitTests.Core.Endpoints.FileSystemManagement.Fixtures; + +/// +/// Fixture class for the record. +/// +[ExcludeFromCodeCoverage] +public class SplitPathRequestFixture +{ + private readonly Faker _faker = new(); + + /// + /// Creates a with a default or random value. + /// + /// The path to split. + /// The created . + public SplitPathRequest Create(string? path = null) + { + return new SplitPathRequest( + Path: path ?? _faker.System.FilePath() + ); + } +} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/FileManagement/Thumbnails/Fixtures/ThumbnailResponseFixture.cs b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/FileSystemManagement/Fixtures/ThumbnailResponseFixture.cs similarity index 85% rename from tests/UnitTests/Lumina.Application.UnitTests/Core/FileManagement/Thumbnails/Fixtures/ThumbnailResponseFixture.cs rename to tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/FileSystemManagement/Fixtures/ThumbnailResponseFixture.cs index f82b0d76..3b03733e 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/FileManagement/Thumbnails/Fixtures/ThumbnailResponseFixture.cs +++ b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/FileSystemManagement/Fixtures/ThumbnailResponseFixture.cs @@ -1,11 +1,11 @@ #region ========================================================================= USING ===================================================================================== using Bogus; using Lumina.Contracts.Enums.PhotoLibrary; -using Lumina.Contracts.Responses.FileManagement; +using Lumina.Contracts.Responses.FileSystemManagement.Thumbnails; using System.Diagnostics.CodeAnalysis; #endregion -namespace Lumina.Application.UnitTests.Core.FileManagement.Thumbnails.Fixtures; +namespace Lumina.Presentation.Api.UnitTests.Core.Endpoints.FileSystemManagement.Fixtures; /// /// Fixture class for the class. diff --git a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/FileSystemManagement/Fixtures/ValidatePathRequestFixture.cs b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/FileSystemManagement/Fixtures/ValidatePathRequestFixture.cs new file mode 100644 index 00000000..3645ddfe --- /dev/null +++ b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/FileSystemManagement/Fixtures/ValidatePathRequestFixture.cs @@ -0,0 +1,28 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Contracts.Requests.FileSystemManagement.Path; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Presentation.Api.UnitTests.Core.Endpoints.FileSystemManagement.Fixtures; + +/// +/// Fixture class for the record. +/// +[ExcludeFromCodeCoverage] +public class ValidatePathRequestFixture +{ + private readonly Faker _faker = new(); + + /// + /// Creates a with a default or random value. + /// + /// The path to validate. + /// The created . + public ValidatePathRequest Create(string? path = null) + { + return new ValidatePathRequest( + Path: path ?? _faker.System.FilePath() + ); + } +} diff --git a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/FileSystemManagement/Path/CheckPathExistsEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/FileSystemManagement/Path/CheckPathExistsEndpointTests.cs new file mode 100644 index 00000000..fcca5a67 --- /dev/null +++ b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/FileSystemManagement/Path/CheckPathExistsEndpointTests.cs @@ -0,0 +1,104 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using FluentAssertions; +using Lumina.Application.Core.FileSystemManagement.Paths.Queries.CheckPathExists; +using Lumina.Contracts.Requests.FileSystemManagement.Path; +using Lumina.Contracts.Responses.FileSystemManagement.Path; +using Lumina.Presentation.Api.Core.Endpoints.FileSystemManagement.Path.CheckPathExists; +using Lumina.Presentation.Api.UnitTests.Core.Endpoints.FileSystemManagement.Fixtures; +using Mediator; +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.FileSystemManagement.Path; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class CheckPathExistsEndpointTests +{ + private readonly ISender _mockSender; + private readonly CheckPathExistsEndpoint _sut; + private readonly CheckPathExistsRequestFixture _checkPathExistsRequestFixture; + + /// + /// Initializes a new instance of the class. + /// + public CheckPathExistsEndpointTests() + { + _mockSender = Substitute.For(); + _sut = Factory.Create(_mockSender); + _checkPathExistsRequestFixture = new CheckPathExistsRequestFixture(); + } + + [Fact] + public async Task ExecuteAsync_WhenCalled_ShouldReturnOkResultWithPathExistsResponse() + { + // Arrange + CheckPathExistsRequest request = _checkPathExistsRequestFixture.Create(path: @"C:\Users\TestUser\Documents", includeHiddenElements: true); + CancellationToken cancellationToken = CancellationToken.None; + PathExistsResponse expectedResponse = new(true); + _mockSender.Send(Arg.Any(), Arg.Any()) + .Returns(expectedResponse); + + // Act + IResult result = await _sut.ExecuteAsync(request, cancellationToken); + + // Assert + PathExistsResponse actualResponse = result.Should().BeOfType>().Subject.Value!; + actualResponse.Should().BeEquivalentTo(expectedResponse); + } + + [Fact] + public async Task ExecuteAsync_WhenCalled_ShouldSendCheckPathExistsQueryToMediator() + { + // Arrange + CheckPathExistsRequest request = _checkPathExistsRequestFixture.Create(path: @"C:\Users\TestUser\Documents", includeHiddenElements: true); + CancellationToken cancellationToken = CancellationToken.None; + _mockSender.Send(Arg.Any(), Arg.Any()) + .Returns(new PathExistsResponse(true)); + + // Act + await _sut.ExecuteAsync(request, cancellationToken); + + // Assert + await _mockSender.Received(1).Send( + Arg.Is(q => q.Path == request.Path && q.IncludeHiddenElements == request.IncludeHiddenElements), + Arg.Is(cancellationToken)); + } + + [Fact] + public async Task ExecuteAsync_WhenCancellationRequested_ShouldCancelOperation() + { + // Arrange + CheckPathExistsRequest request = _checkPathExistsRequestFixture.Create(path: @"C:\Users\TestUser\Documents", includeHiddenElements: true); + CancellationTokenSource cts = new(); + TaskCompletionSource operationStarted = new(); + TaskCompletionSource cancellationRequested = new(); + + _mockSender.Send(Arg.Any(), Arg.Any()) + .Returns(callInfo => new ValueTask(Task.Run(async () => + { + operationStarted.SetResult(true); + await cancellationRequested.Task; + callInfo.Arg().ThrowIfCancellationRequested(); + return new PathExistsResponse(true); + }, 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/FileSystemManagement/Path/CombinePathEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/FileSystemManagement/Path/CombinePathEndpointTests.cs new file mode 100644 index 00000000..85533cec --- /dev/null +++ b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/FileSystemManagement/Path/CombinePathEndpointTests.cs @@ -0,0 +1,166 @@ +#region ========================================================================= USING ===================================================================================== +using ErrorOr; +using FastEndpoints; +using FluentAssertions; +using Lumina.Application.Core.FileSystemManagement.Paths.Commands.CombinePath; +using Lumina.Contracts.Requests.FileSystemManagement.Path; +using Lumina.Contracts.Responses.FileSystemManagement.Path; +using Lumina.Presentation.Api.Core.Endpoints.FileSystemManagement.Path.CombinePath; +using Lumina.Presentation.Api.UnitTests.Core.Endpoints.FileSystemManagement.Fixtures; +using Mediator; +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.FileSystemManagement.Path; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class CombinePathEndpointTests +{ + private readonly ISender _mockSender; + private readonly CombinePathEndpoint _sut; + private readonly PathSegmentResponseFixture _pathSegmentResponseFixture; + private readonly CombinePathRequestFixture _combinePathRequestFixture; + + /// + /// Initializes a new instance of the class. + /// + public CombinePathEndpointTests() + { + _mockSender = Substitute.For(); + _sut = Factory.Create(_mockSender); + _pathSegmentResponseFixture = new PathSegmentResponseFixture(); + _combinePathRequestFixture = new CombinePathRequestFixture(); + } + + [Fact] + public async Task ExecuteAsync_WhenCalled_ShouldReturnOkResultWithPathSegmentResponse() + { + // Arrange + CombinePathRequest request = _combinePathRequestFixture.Create("C:\\Users", "TestUser"); + CancellationToken cancellationToken = CancellationToken.None; + PathSegmentResponse expectedResponse = _pathSegmentResponseFixture.Create(); + _mockSender.Send(Arg.Any(), Arg.Any()) + .Returns(ErrorOrFactory.From(expectedResponse)); + + // Act + IResult result = await _sut.ExecuteAsync(request, cancellationToken); + + // Assert + PathSegmentResponse actualResponse = result.Should().BeOfType>().Subject.Value!; + actualResponse.Should().BeEquivalentTo(expectedResponse); + } + + [Fact] + public async Task ExecuteAsync_WhenMediatorReturnsError_ShouldReturnProblemResult() + { + // Arrange + CombinePathRequest request = _combinePathRequestFixture.Create("InvalidPath", "TestUser"); + CancellationToken cancellationToken = CancellationToken.None; + Error expectedError = Error.NotFound("Path.NotFound", "The requested path was not found."); + _mockSender.Send(Arg.Any(), Arg.Any()) + .Returns(expectedError); + + // Act + IResult result = await _sut.ExecuteAsync(request, cancellationToken); + + // Assert + result.Should().BeOfType(); + ProblemHttpResult problemDetails = (ProblemHttpResult)result; + problemDetails.StatusCode.Should().Be(StatusCodes.Status404NotFound); + problemDetails.ContentType.Should().Be("application/problem+json"); + problemDetails.ProblemDetails.Should().BeOfType(); + + problemDetails.ProblemDetails.Title.Should().Be("Path.NotFound"); + problemDetails.ProblemDetails.Detail.Should().Be("The requested path was not found."); + problemDetails.ProblemDetails.Status.Should().Be(StatusCodes.Status404NotFound); + problemDetails.ProblemDetails.Type.Should().Be("https://tools.ietf.org/html/rfc9110#section-15.5.5"); + problemDetails.ProblemDetails.Extensions["traceId"].Should().NotBeNull(); + } + + [Fact] + public async Task ExecuteAsync_WhenMediatorReturnsValidationError_ShouldReturnValidationProblemResult() + { + // Arrange + CombinePathRequest request = _combinePathRequestFixture.Create("InvalidPath", "TestUser"); + CancellationToken cancellationToken = CancellationToken.None; + Error expectedError = Error.Validation("Path.Invalid", "The provided path is invalid."); + _mockSender.Send(Arg.Any(), Arg.Any()) + .Returns(expectedError); + + // Act + IResult result = await _sut.ExecuteAsync(request, cancellationToken); + + // Assert + result.Should().BeOfType(); + ProblemHttpResult problemDetails = (ProblemHttpResult)result; + problemDetails.StatusCode.Should().Be(StatusCodes.Status422UnprocessableEntity); + problemDetails.ContentType.Should().Be("application/problem+json"); + problemDetails.ProblemDetails.Should().BeOfType(); + HttpValidationProblemDetails validationProblemDetails = (HttpValidationProblemDetails)problemDetails.ProblemDetails; + validationProblemDetails.Status.Should().Be(StatusCodes.Status422UnprocessableEntity); + validationProblemDetails.Title.Should().Be("Validation Error"); + validationProblemDetails.Detail.Should().Be("One or more validation errors occurred."); + validationProblemDetails.Type.Should().Be("https://tools.ietf.org/html/rfc4918#section-11.2"); + validationProblemDetails.Errors.Should().ContainSingle() + .Which.Should().BeEquivalentTo(new + { + Key = "Path.Invalid", + Value = new[] { "The provided path is invalid." } + }); + } + + [Fact] + public async Task ExecuteAsync_WhenCalled_ShouldSendCombinePathCommandToMediator() + { + // Arrange + CombinePathRequest request = _combinePathRequestFixture.Create("C:\\Users", "TestUser"); + CancellationToken cancellationToken = CancellationToken.None; + _mockSender.Send(Arg.Any(), Arg.Any()) + .Returns(ErrorOrFactory.From(_pathSegmentResponseFixture.Create())); + + // Act + await _sut.ExecuteAsync(request, cancellationToken); + + // Assert + await _mockSender.Received(1).Send( + Arg.Is(c => c.OriginalPath == request.OriginalPath && c.NewPath == request.NewPath), + Arg.Is(cancellationToken)); + } + + [Fact] + public async Task ExecuteAsync_WhenCancellationRequested_ShouldCancelOperation() + { + // Arrange + CombinePathRequest request = _combinePathRequestFixture.Create("C:\\Users", "TestUser"); + CancellationTokenSource cts = new(); + TaskCompletionSource operationStarted = new(); + TaskCompletionSource cancellationRequested = new(); + + _mockSender.Send(Arg.Any(), Arg.Any()) + .Returns(callInfo => new ValueTask>(Task.Run(async () => + { + operationStarted.SetResult(true); + await cancellationRequested.Task; + callInfo.Arg().ThrowIfCancellationRequested(); + return ErrorOrFactory.From(_pathSegmentResponseFixture.Create()); + }, callInfo.Arg()))); + + // Act + Task operationTask = _sut.ExecuteAsync(request, cts.Token); + await operationStarted.Task; + cts.Cancel(); + cancellationRequested.SetResult(true); + + // Assert + await Assert.ThrowsAnyAsync(() => operationTask); + } +} diff --git a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/FileSystemManagement/Path/GetPathParentEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/FileSystemManagement/Path/GetPathParentEndpointTests.cs new file mode 100644 index 00000000..8acd397d --- /dev/null +++ b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/FileSystemManagement/Path/GetPathParentEndpointTests.cs @@ -0,0 +1,166 @@ +#region ========================================================================= USING ===================================================================================== +using ErrorOr; +using FastEndpoints; +using FluentAssertions; +using Lumina.Application.Core.FileSystemManagement.Paths.Queries.GetPathParent; +using Lumina.Contracts.Requests.FileSystemManagement.Path; +using Lumina.Contracts.Responses.FileSystemManagement.Path; +using Lumina.Presentation.Api.Core.Endpoints.FileSystemManagement.Path.GetPathParent; +using Lumina.Presentation.Api.UnitTests.Core.Endpoints.FileSystemManagement.Fixtures; +using Mediator; +using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Http.HttpResults; +using NSubstitute; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Api.UnitTests.Core.Endpoints.FileSystemManagement.Path; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class GetPathParentEndpointTests +{ + private readonly ISender _mockSender; + private readonly GetPathParentEndpoint _sut; + private readonly PathSegmentResponseFixture _pathSegmentResponseFixture; + private readonly GetPathParentRequestFixture _getPathParentRequestFixture; + + /// + /// Initializes a new instance of the class. + /// + public GetPathParentEndpointTests() + { + _mockSender = Substitute.For(); + _sut = Factory.Create(_mockSender); + _pathSegmentResponseFixture = new PathSegmentResponseFixture(); + _getPathParentRequestFixture = new GetPathParentRequestFixture(); + } + + [Fact] + public async Task ExecuteAsync_WhenCalled_ShouldReturnOkResultWithPathSegmentResponse() + { + // Arrange + GetPathParentRequest request = _getPathParentRequestFixture.Create(@"C:\Users\TestUser"); + CancellationToken cancellationToken = CancellationToken.None; + IEnumerable expectedResponse = _pathSegmentResponseFixture.CreateMany(); + _mockSender.Send(Arg.Any(), Arg.Any()) + .Returns(ErrorOrFactory.From(expectedResponse)); + + // Act + IResult result = await _sut.ExecuteAsync(request, cancellationToken); + + // Assert + IEnumerable actualResponse = result.Should().BeOfType>>().Subject.Value!; + actualResponse.Should().BeEquivalentTo(expectedResponse); + } + + [Fact] + public async Task ExecuteAsync_WhenMediatorReturnsError_ShouldReturnProblemResult() + { + // Arrange + GetPathParentRequest request = _getPathParentRequestFixture.Create(@"C:\Users\TestUser"); + CancellationToken cancellationToken = CancellationToken.None; + Error expectedError = Error.NotFound("Path.NotFound", "The requested path was not found."); + _mockSender.Send(Arg.Any(), Arg.Any()) + .Returns(expectedError); + + // Act + IResult result = await _sut.ExecuteAsync(request, cancellationToken); + + // Assert + result.Should().BeOfType(); + ProblemHttpResult problemDetails = (ProblemHttpResult)result; + problemDetails.StatusCode.Should().Be(StatusCodes.Status404NotFound); + problemDetails.ContentType.Should().Be("application/problem+json"); + problemDetails.ProblemDetails.Should().BeOfType(); + + problemDetails.ProblemDetails.Title.Should().Be("Path.NotFound"); + problemDetails.ProblemDetails.Detail.Should().Be("The requested path was not found."); + problemDetails.ProblemDetails.Status.Should().Be(StatusCodes.Status404NotFound); + problemDetails.ProblemDetails.Type.Should().Be("https://tools.ietf.org/html/rfc9110#section-15.5.5"); + problemDetails.ProblemDetails.Extensions["traceId"].Should().NotBeNull(); + } + + [Fact] + public async Task ExecuteAsync_WhenMediatorReturnsValidationError_ShouldReturnValidationProblemResult() + { + // Arrange + GetPathParentRequest request = _getPathParentRequestFixture.Create(@"InvalidPath"); + CancellationToken cancellationToken = CancellationToken.None; + Error expectedError = Error.Validation("Path.Invalid", "The provided path is invalid."); + _mockSender.Send(Arg.Any(), Arg.Any()) + .Returns(expectedError); + + // Act + IResult result = await _sut.ExecuteAsync(request, cancellationToken); + + // Assert + result.Should().BeOfType(); + ProblemHttpResult problemDetails = (ProblemHttpResult)result; + problemDetails.StatusCode.Should().Be(StatusCodes.Status422UnprocessableEntity); + problemDetails.ContentType.Should().Be("application/problem+json"); + problemDetails.ProblemDetails.Should().BeOfType(); + HttpValidationProblemDetails validationProblemDetails = (HttpValidationProblemDetails)problemDetails.ProblemDetails; + validationProblemDetails.Status.Should().Be(StatusCodes.Status422UnprocessableEntity); + validationProblemDetails.Title.Should().Be("Validation Error"); + validationProblemDetails.Detail.Should().Be("One or more validation errors occurred."); + validationProblemDetails.Type.Should().Be("https://tools.ietf.org/html/rfc4918#section-11.2"); + validationProblemDetails.Errors.Should().ContainSingle() + .Which.Should().BeEquivalentTo(new + { + Key = "Path.Invalid", + Value = new[] { "The provided path is invalid." } + }); + } + + [Fact] + public async Task ExecuteAsync_WhenCalled_ShouldSendGetPathParentQueryToMediator() + { + // Arrange + GetPathParentRequest request = _getPathParentRequestFixture.Create(@"C:\Users\TestUser"); + CancellationToken cancellationToken = CancellationToken.None; + _mockSender.Send(Arg.Any(), Arg.Any()) + .Returns(ErrorOrFactory.From(_pathSegmentResponseFixture.CreateMany().AsEnumerable())); + + // Act + await _sut.ExecuteAsync(request, cancellationToken); + + // Assert + await _mockSender.Received(1).Send(Arg.Is(q => q.Path == request.Path), Arg.Is(cancellationToken)); + } + + [Fact] + public async Task ExecuteAsync_WhenCancellationRequested_ShouldCancelOperation() + { + // Arrange + GetPathParentRequest request = _getPathParentRequestFixture.Create(@"C:\Users\TestUser"); + CancellationTokenSource cts = new(); + TaskCompletionSource operationStarted = new(); + TaskCompletionSource cancellationRequested = new(); + + _mockSender.Send(Arg.Any(), Arg.Any()) + .Returns(callInfo => new ValueTask>>(Task.Run(async () => + { + operationStarted.SetResult(true); + await cancellationRequested.Task; + callInfo.Arg().ThrowIfCancellationRequested(); + return ErrorOrFactory.From(_pathSegmentResponseFixture.CreateMany().AsEnumerable()); + }, 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/FileSystemManagement/Path/GetPathRootEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/FileSystemManagement/Path/GetPathRootEndpointTests.cs new file mode 100644 index 00000000..d43874a1 --- /dev/null +++ b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/FileSystemManagement/Path/GetPathRootEndpointTests.cs @@ -0,0 +1,164 @@ +#region ========================================================================= USING ===================================================================================== +using ErrorOr; +using FastEndpoints; +using FluentAssertions; +using Lumina.Application.Core.FileSystemManagement.Paths.Queries.GetPathRoot; +using Lumina.Contracts.Requests.FileSystemManagement.Path; +using Lumina.Contracts.Responses.FileSystemManagement.Path; +using Lumina.Presentation.Api.Core.Endpoints.FileSystemManagement.Path.GetPathRoot; +using Lumina.Presentation.Api.UnitTests.Core.Endpoints.FileSystemManagement.Fixtures; +using Mediator; +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.FileSystemManagement.Path; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class GetPathRootEndpointTests +{ + private readonly ISender _mockSender; + private readonly GetPathRootEndpoint _sut; + private readonly PathSegmentResponseFixture _pathSegmentResponseFixture; + private readonly GetPathRootRequestFixture _getPathRootRequestFixture; + + /// + /// Initializes a new instance of the class. + /// + public GetPathRootEndpointTests() + { + _mockSender = Substitute.For(); + _sut = Factory.Create(_mockSender); + _pathSegmentResponseFixture = new PathSegmentResponseFixture(); + _getPathRootRequestFixture = new GetPathRootRequestFixture(); + } + + [Fact] + public async Task ExecuteAsync_WhenCalled_ShouldReturnOkResultWithPathSegmentResponse() + { + // Arrange + GetPathRootRequest request = _getPathRootRequestFixture.Create(@"C:\Users\TestUser"); + CancellationToken cancellationToken = CancellationToken.None; + PathSegmentResponse expectedResponse = _pathSegmentResponseFixture.Create(); + _mockSender.Send(Arg.Any(), Arg.Any()) + .Returns(ErrorOrFactory.From(expectedResponse)); + + // Act + IResult result = await _sut.ExecuteAsync(request, cancellationToken); + + // Assert + PathSegmentResponse actualResponse = result.Should().BeOfType>().Subject.Value!; + actualResponse.Should().BeEquivalentTo(expectedResponse); + } + + [Fact] + public async Task ExecuteAsync_WhenMediatorReturnsError_ShouldReturnProblemResult() + { + // Arrange + GetPathRootRequest request = _getPathRootRequestFixture.Create(@"C:\Users\TestUser"); + CancellationToken cancellationToken = CancellationToken.None; + Error expectedError = Error.NotFound("Path.NotFound", "The requested path was not found."); + _mockSender.Send(Arg.Any(), Arg.Any()) + .Returns(expectedError); + + // Act + IResult result = await _sut.ExecuteAsync(request, cancellationToken); + + // Assert + result.Should().BeOfType(); + ProblemHttpResult problemDetails = (ProblemHttpResult)result; + problemDetails.StatusCode.Should().Be(StatusCodes.Status404NotFound); + problemDetails.ContentType.Should().Be("application/problem+json"); + problemDetails.ProblemDetails.Should().BeOfType(); + + problemDetails.ProblemDetails.Title.Should().Be("Path.NotFound"); + problemDetails.ProblemDetails.Detail.Should().Be("The requested path was not found."); + problemDetails.ProblemDetails.Status.Should().Be(StatusCodes.Status404NotFound); + problemDetails.ProblemDetails.Type.Should().Be("https://tools.ietf.org/html/rfc9110#section-15.5.5"); + problemDetails.ProblemDetails.Extensions["traceId"].Should().NotBeNull(); + } + + [Fact] + public async Task ExecuteAsync_WhenMediatorReturnsValidationError_ShouldReturnValidationProblemResult() + { + // Arrange + GetPathRootRequest request = _getPathRootRequestFixture.Create(@"InvalidPath"); + CancellationToken cancellationToken = CancellationToken.None; + Error expectedError = Error.Validation("Path.Invalid", "The provided path is invalid."); + _mockSender.Send(Arg.Any(), Arg.Any()) + .Returns(expectedError); + + // Act + IResult result = await _sut.ExecuteAsync(request, cancellationToken); + + // Assert + result.Should().BeOfType(); + ProblemHttpResult problemDetails = (ProblemHttpResult)result; + problemDetails.StatusCode.Should().Be(StatusCodes.Status422UnprocessableEntity); + problemDetails.ContentType.Should().Be("application/problem+json"); + problemDetails.ProblemDetails.Should().BeOfType(); + HttpValidationProblemDetails validationProblemDetails = (HttpValidationProblemDetails)problemDetails.ProblemDetails; + validationProblemDetails.Status.Should().Be(StatusCodes.Status422UnprocessableEntity); + validationProblemDetails.Title.Should().Be("Validation Error"); + validationProblemDetails.Detail.Should().Be("One or more validation errors occurred."); + validationProblemDetails.Type.Should().Be("https://tools.ietf.org/html/rfc4918#section-11.2"); + validationProblemDetails.Errors.Should().ContainSingle() + .Which.Should().BeEquivalentTo(new + { + Key = "Path.Invalid", + Value = new[] { "The provided path is invalid." } + }); + } + + [Fact] + public async Task ExecuteAsync_WhenCalled_ShouldSendGetPathRootQueryToMediator() + { + // Arrange + GetPathRootRequest request = _getPathRootRequestFixture.Create(@"C:\Users\TestUser"); + CancellationToken cancellationToken = CancellationToken.None; + _mockSender.Send(Arg.Any(), Arg.Any()) + .Returns(ErrorOrFactory.From(_pathSegmentResponseFixture.Create())); + + // Act + await _sut.ExecuteAsync(request, cancellationToken); + + // Assert + await _mockSender.Received(1).Send(Arg.Is(q => q.Path == request.Path), Arg.Is(cancellationToken)); + } + + [Fact] + public async Task ExecuteAsync_WhenCancellationRequested_ShouldCancelOperation() + { + // Arrange + GetPathRootRequest request = _getPathRootRequestFixture.Create(@"C:\Users\TestUser"); + CancellationTokenSource cts = new(); + TaskCompletionSource operationStarted = new(); + TaskCompletionSource cancellationRequested = new(); + + _mockSender.Send(Arg.Any(), Arg.Any()) + .Returns(callInfo => new ValueTask>(Task.Run(async () => + { + operationStarted.SetResult(true); + await cancellationRequested.Task; + callInfo.Arg().ThrowIfCancellationRequested(); + return ErrorOrFactory.From(_pathSegmentResponseFixture.Create()); + }, callInfo.Arg()))); + + // Act + Task operationTask = _sut.ExecuteAsync(request, cts.Token); + await operationStarted.Task; + cts.Cancel(); + cancellationRequested.SetResult(true); + + // Assert + await Assert.ThrowsAnyAsync(() => operationTask); + } +} diff --git a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/FileSystemManagement/Path/GetPathSeparatorEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/FileSystemManagement/Path/GetPathSeparatorEndpointTests.cs new file mode 100644 index 00000000..ea675e47 --- /dev/null +++ b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/FileSystemManagement/Path/GetPathSeparatorEndpointTests.cs @@ -0,0 +1,98 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using FluentAssertions; +using Lumina.Application.Core.FileSystemManagement.Paths.Queries.GetPathSeparator; +using Lumina.Contracts.Responses.FileSystemManagement.Path; +using Lumina.Presentation.Api.Core.Endpoints.FileSystemManagement.Path.GetPathSeparator; +using Lumina.Presentation.Api.UnitTests.Core.Endpoints.FileSystemManagement.Fixtures; +using Mediator; +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.FileSystemManagement.Path; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class GetPathSeparatorEndpointTests +{ + private readonly ISender _mockSender; + private readonly GetPathSeparatorEndpoint _sut; + private readonly PathSeparatorResponseFixture _pathSeparatorResponseFixture; + + /// + /// Initializes a new instance of the class. + /// + public GetPathSeparatorEndpointTests() + { + _mockSender = Substitute.For(); + _sut = Factory.Create(_mockSender); + _pathSeparatorResponseFixture = new PathSeparatorResponseFixture(); + } + + [Fact] + public async Task ExecuteAsync_WhenCalled_ShouldReturnOkResultWithPathSeparatorResponse() + { + // Arrange + CancellationToken cancellationToken = CancellationToken.None; + PathSeparatorResponse expectedResponse = _pathSeparatorResponseFixture.Create(); + _mockSender.Send(Arg.Any(), Arg.Any()) + .Returns(expectedResponse); + + // Act + IResult result = await _sut.ExecuteAsync(cancellationToken); + + // Assert + PathSeparatorResponse actualResponse = result.Should().BeOfType>().Subject.Value!; + actualResponse.Should().BeEquivalentTo(expectedResponse); + } + + [Fact] + public async Task ExecuteAsync_WhenCalled_ShouldSendGetPathSeparatorQueryToMediator() + { + // Arrange + CancellationToken cancellationToken = CancellationToken.None; + _mockSender.Send(Arg.Any(), Arg.Any()) + .Returns(_pathSeparatorResponseFixture.Create()); + + // Act + await _sut.ExecuteAsync(cancellationToken); + + // Assert + await _mockSender.Received(1).Send(Arg.Any(), Arg.Is(cancellationToken)); + } + + [Fact] + public async Task ExecuteAsync_WhenCancellationRequested_ShouldCancelOperation() + { + // Arrange + CancellationTokenSource cts = new(); + TaskCompletionSource operationStarted = new(); + TaskCompletionSource cancellationRequested = new(); + + _mockSender.Send(Arg.Any(), Arg.Any()) + .Returns(callInfo => new ValueTask(Task.Run(async () => + { + operationStarted.SetResult(true); + await cancellationRequested.Task; + callInfo.Arg().ThrowIfCancellationRequested(); + return _pathSeparatorResponseFixture.Create(); + }, callInfo.Arg()))); + + // Act + Task operationTask = _sut.ExecuteAsync(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/FileSystemManagement/Path/SplitPathEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/FileSystemManagement/Path/SplitPathEndpointTests.cs new file mode 100644 index 00000000..f15823f4 --- /dev/null +++ b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/FileSystemManagement/Path/SplitPathEndpointTests.cs @@ -0,0 +1,144 @@ +#region ========================================================================= USING ===================================================================================== +using ErrorOr; +using FastEndpoints; +using FluentAssertions; +using Lumina.Application.Core.FileSystemManagement.Paths.Commands.SplitPath; +using Lumina.Contracts.Requests.FileSystemManagement.Path; +using Lumina.Contracts.Responses.FileSystemManagement.Path; +using Lumina.Presentation.Api.Core.Endpoints.FileSystemManagement.Path.SplitPath; +using Lumina.Presentation.Api.UnitTests.Core.Endpoints.FileSystemManagement.Fixtures; +using Mediator; +using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Http.HttpResults; +using NSubstitute; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Api.UnitTests.Core.Endpoints.FileSystemManagement.Path; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class SplitPathEndpointTests +{ + private readonly ISender _mockSender; + private readonly SplitPathEndpoint _sut; + private readonly PathSegmentResponseFixture _pathSegmentResponseFixture; + private readonly SplitPathRequestFixture _splitPathRequestFixture; + + /// + /// Initializes a new instance of the class. + /// + public SplitPathEndpointTests() + { + _mockSender = Substitute.For(); + _sut = Factory.Create(_mockSender); + _pathSegmentResponseFixture = new PathSegmentResponseFixture(); + _splitPathRequestFixture = new SplitPathRequestFixture(); + } + + [Fact] + public async Task ExecuteAsync_WhenCalled_ShouldReturnOkResultWithPathSegmentResponses() + { + // Arrange + SplitPathRequest request = _splitPathRequestFixture.Create(@"C:\Users\TestUser\Documents"); + CancellationToken cancellationToken = CancellationToken.None; + IEnumerable expectedResponse = _pathSegmentResponseFixture.CreateMany(); + _mockSender.Send(Arg.Any(), Arg.Any()) + .Returns(ErrorOrFactory.From(expectedResponse)); + + // Act + IResult result = await _sut.ExecuteAsync(request, cancellationToken); + + // Assert + IEnumerable actualResponse = result.Should().BeOfType>>().Subject.Value!; + actualResponse.Should().BeEquivalentTo(expectedResponse); + } + + [Fact] + public async Task ExecuteAsync_WhenMediatorReturnsError_ShouldReturnProblemResult() + { + // Arrange + SplitPathRequest request = _splitPathRequestFixture.Create(@"InvalidPath"); + CancellationToken cancellationToken = CancellationToken.None; + Error expectedError = Error.Validation("Path.Invalid", "The provided path is invalid."); + _mockSender.Send(Arg.Any(), Arg.Any()) + .Returns(expectedError); + + // Act + IResult result = await _sut.ExecuteAsync(request, cancellationToken); + + // Assert + result.Should().BeOfType(); + ProblemHttpResult problemDetails = (ProblemHttpResult)result; + problemDetails.StatusCode.Should().Be(StatusCodes.Status422UnprocessableEntity); + problemDetails.ContentType.Should().Be("application/problem+json"); + problemDetails.ProblemDetails.Should().BeOfType(); + HttpValidationProblemDetails validationProblemDetails = (HttpValidationProblemDetails)problemDetails.ProblemDetails; + validationProblemDetails.Status.Should().Be(StatusCodes.Status422UnprocessableEntity); + validationProblemDetails.Title.Should().Be("Validation Error"); + validationProblemDetails.Detail.Should().Be("One or more validation errors occurred."); + validationProblemDetails.Type.Should().Be("https://tools.ietf.org/html/rfc4918#section-11.2"); + validationProblemDetails.Errors.Should().ContainSingle() + .Which.Should().BeEquivalentTo(new + { + Key = "Path.Invalid", + Value = new[] { "The provided path is invalid." } + }); + } + + [Fact] + public async Task ExecuteAsync_WhenCalled_ShouldSendSplitPathCommandToMediator() + { + // Arrange + SplitPathRequest request = _splitPathRequestFixture.Create(@"C:\Users\TestUser\Documents"); + CancellationToken cancellationToken = CancellationToken.None; + _mockSender.Send(Arg.Any(), Arg.Any()) + .Returns(ErrorOrFactory.From(_pathSegmentResponseFixture.CreateMany().AsEnumerable())); + + // Act + await _sut.ExecuteAsync(request, cancellationToken); + + // Assert + await _mockSender.Received(1).Send( + Arg.Is(c => c.Path == request.Path), + Arg.Is(cancellationToken)); + } + + [Fact] + public async Task ExecuteAsync_WhenCancellationRequested_ShouldCancelOperation() + { + // Arrange + SplitPathRequest request = _splitPathRequestFixture.Create(@"C:\Users\TestUser\Documents"); + CancellationTokenSource cts = new(); + TaskCompletionSource operationStarted = new(); + TaskCompletionSource cancellationRequested = new(); + + _mockSender.Send(Arg.Any(), Arg.Any()) + .Returns(callInfo => new ValueTask>>(Task.Run(async () => + { + operationStarted.SetResult(true); + await cancellationRequested.Task; + callInfo.Arg().ThrowIfCancellationRequested(); + return ErrorOrFactory.From(new List + { + _pathSegmentResponseFixture.Create() + }.AsEnumerable()); + }, 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/FileSystemManagement/Path/ValidatePathEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/FileSystemManagement/Path/ValidatePathEndpointTests.cs new file mode 100644 index 00000000..6ea1ff35 --- /dev/null +++ b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/FileSystemManagement/Path/ValidatePathEndpointTests.cs @@ -0,0 +1,104 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using FluentAssertions; +using Lumina.Application.Core.FileSystemManagement.Paths.Queries.ValidatePath; +using Lumina.Contracts.Requests.FileSystemManagement.Path; +using Lumina.Contracts.Responses.FileSystemManagement.Path; +using Lumina.Presentation.Api.Core.Endpoints.FileSystemManagement.Path.ValidatePath; +using Lumina.Presentation.Api.UnitTests.Core.Endpoints.FileSystemManagement.Fixtures; +using Mediator; +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.FileSystemManagement.Path; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class ValidatePathEndpointTests +{ + private readonly ISender _mockSender; + private readonly ValidatePathEndpoint _sut; + private readonly ValidatePathRequestFixture _validatePathRequestFixture; + + /// + /// Initializes a new instance of the class. + /// + public ValidatePathEndpointTests() + { + _mockSender = Substitute.For(); + _sut = Factory.Create(_mockSender); + _validatePathRequestFixture = new ValidatePathRequestFixture(); + } + + [Fact] + public async Task ExecuteAsync_WhenCalled_ShouldReturnOkResultWithPathValidResponse() + { + // Arrange + ValidatePathRequest request = _validatePathRequestFixture.Create(@"C:\Users\TestUser\Documents"); + CancellationToken cancellationToken = CancellationToken.None; + PathValidResponse expectedResponse = new(true); + _mockSender.Send(Arg.Any(), Arg.Any()) + .Returns(expectedResponse); + + // Act + IResult result = await _sut.ExecuteAsync(request, cancellationToken); + + // Assert + PathValidResponse actualResponse = result.Should().BeOfType>().Subject.Value!; + actualResponse.Should().BeEquivalentTo(expectedResponse); + } + + [Fact] + public async Task ExecuteAsync_WhenCalled_ShouldSendValidatePathQueryToMediator() + { + // Arrange + ValidatePathRequest request = _validatePathRequestFixture.Create(@"C:\Users\TestUser\Documents"); + CancellationToken cancellationToken = CancellationToken.None; + _mockSender.Send(Arg.Any(), Arg.Any()) + .Returns(new PathValidResponse(true)); + + // Act + await _sut.ExecuteAsync(request, cancellationToken); + + // Assert + await _mockSender.Received(1).Send( + Arg.Is(q => q.Path == request.Path), + Arg.Is(cancellationToken)); + } + + [Fact] + public async Task ExecuteAsync_WhenCancellationRequested_ShouldCancelOperation() + { + // Arrange + ValidatePathRequest request = _validatePathRequestFixture.Create(@"C:\Users\TestUser\Documents"); + CancellationTokenSource cts = new(); + TaskCompletionSource operationStarted = new(); + TaskCompletionSource cancellationRequested = new(); + + _mockSender.Send(Arg.Any(), Arg.Any()) + .Returns(callInfo => new ValueTask(Task.Run(async () => + { + operationStarted.SetResult(true); + await cancellationRequested.Task; + callInfo.Arg().ThrowIfCancellationRequested(); + return new PathValidResponse(true); + }, 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/FileSystemManagement/Thumbnails/GetThumbnailEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/FileSystemManagement/Thumbnails/GetThumbnailEndpointTests.cs new file mode 100644 index 00000000..147c5c82 --- /dev/null +++ b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/FileSystemManagement/Thumbnails/GetThumbnailEndpointTests.cs @@ -0,0 +1,164 @@ +#region ========================================================================= USING ===================================================================================== +using ErrorOr; +using FastEndpoints; +using FluentAssertions; +using Lumina.Application.Core.FileSystemManagement.Thumbnails.Queries.GetThumbnail; +using Lumina.Contracts.Requests.FileSystemManagement.Thumbnails; +using Lumina.Contracts.Responses.FileSystemManagement.Thumbnails; +using Lumina.Presentation.Api.Common.Utilities; +using Lumina.Presentation.Api.Core.Endpoints.FileSystemManagement.Thumbnails.GetThumbnail; +using Lumina.Presentation.Api.UnitTests.Core.Endpoints.FileSystemManagement.Fixtures; +using Mediator; +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.FileSystemManagement.Thumbnails; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class GetThumbnailEndpointTests +{ + private readonly ISender _mockSender; + private readonly GetThumbnailEndpoint _sut; + private readonly GetThumbnailRequestFixture _getThumbnailRequestFixture; + + /// + /// Initializes a new instance of the class. + /// + public GetThumbnailEndpointTests() + { + _mockSender = Substitute.For(); + _sut = Factory.Create(_mockSender); + _getThumbnailRequestFixture = new GetThumbnailRequestFixture(); + } + + [Fact] + public async Task ExecuteAsync_WhenCalled_ShouldReturnFileResultWithThumbnailResponse() + { + // Arrange + GetThumbnailRequest request = _getThumbnailRequestFixture.Create("/path/to/file.jpg", 80); + CancellationToken cancellationToken = CancellationToken.None; + ThumbnailResponse expectedResponse = ThumbnailResponseFixture.CreateThumbnailResponse(); + _mockSender.Send(Arg.Any(), Arg.Any()) + .Returns(ErrorOrFactory.From(expectedResponse)); + + // Act + IResult result = await _sut.ExecuteAsync(request, cancellationToken); + + // Assert + FileContentHttpResult fileResult = result.Should().BeOfType().Subject; + fileResult.FileContents.ToArray().Should().BeEquivalentTo(expectedResponse.Bytes); + fileResult.ContentType.Should().Be(MimeTypes.GetMimeType(expectedResponse.Type)); + } + + [Fact] + public async Task ExecuteAsync_WhenMediatorReturnsError_ShouldReturnProblemResult() + { + // Arrange + GetThumbnailRequest request = _getThumbnailRequestFixture.Create("/path/to/nonexistent/file.jpg", 80); + CancellationToken cancellationToken = CancellationToken.None; + Error expectedError = Error.NotFound("Thumbnail.NotFound", "The requested thumbnail was not found."); + _mockSender.Send(Arg.Any(), Arg.Any()) + .Returns(expectedError); + + // Act + IResult result = await _sut.ExecuteAsync(request, cancellationToken); + + // Assert + result.Should().BeOfType(); + ProblemHttpResult problemDetails = (ProblemHttpResult)result; + problemDetails.StatusCode.Should().Be(StatusCodes.Status404NotFound); + problemDetails.ContentType.Should().Be("application/problem+json"); + problemDetails.ProblemDetails.Should().BeOfType(); + + problemDetails.ProblemDetails.Title.Should().Be("Thumbnail.NotFound"); + problemDetails.ProblemDetails.Detail.Should().Be("The requested thumbnail was not found."); + problemDetails.ProblemDetails.Status.Should().Be(StatusCodes.Status404NotFound); + problemDetails.ProblemDetails.Type.Should().Be("https://tools.ietf.org/html/rfc9110#section-15.5.5"); + problemDetails.ProblemDetails.Extensions["traceId"].Should().NotBeNull(); + } + + [Fact] + public async Task ExecuteAsync_WhenMediatorReturnsValidationError_ShouldReturnValidationProblemResult() + { + // Arrange + GetThumbnailRequest request = _getThumbnailRequestFixture.Create("/path/to/nonexistent/file.jpg", 80); + CancellationToken cancellationToken = CancellationToken.None; + Error expectedError = Error.Validation("Path.Invalid", "The provided path is invalid."); + _mockSender.Send(Arg.Any(), Arg.Any()) + .Returns(expectedError); + + // Act + IResult result = await _sut.ExecuteAsync(request, cancellationToken); + + // Assert + result.Should().BeOfType(); + ProblemHttpResult problemDetails = (ProblemHttpResult)result; + problemDetails.StatusCode.Should().Be(StatusCodes.Status422UnprocessableEntity); + problemDetails.ContentType.Should().Be("application/problem+json"); + problemDetails.ProblemDetails.Should().BeOfType(); + HttpValidationProblemDetails validationProblemDetails = (HttpValidationProblemDetails)problemDetails.ProblemDetails; + validationProblemDetails.Status.Should().Be(StatusCodes.Status422UnprocessableEntity); + validationProblemDetails.Title.Should().Be("Validation Error"); + validationProblemDetails.Detail.Should().Be("One or more validation errors occurred."); + validationProblemDetails.Type.Should().Be("https://tools.ietf.org/html/rfc4918#section-11.2"); + validationProblemDetails.Errors.Should().ContainSingle() + .Which.Should().BeEquivalentTo(new + { + Key = "Path.Invalid", + Value = new[] { "The provided path is invalid." } + }); + } + + [Fact] + public async Task ExecuteAsync_WhenCalled_ShouldSendGetThumbnailQueryToSender() + { + // Arrange + GetThumbnailRequest request = _getThumbnailRequestFixture.Create("/path/to/file.jpg", 80); + CancellationToken cancellationToken = CancellationToken.None; + _mockSender.Send(Arg.Any(), Arg.Any()) + .Returns(ErrorOrFactory.From(ThumbnailResponseFixture.CreateThumbnailResponse())); + + // Act + await _sut.ExecuteAsync(request, cancellationToken); + + // Assert + await _mockSender.Received(1).Send(Arg.Is(q => q.Path == request.Path && q.Quality == request.Quality), Arg.Is(cancellationToken)); + } + + [Fact] + public async Task ExecuteAsync_WhenCancellationRequested_ShouldCancelOperation() + { + // Arrange + GetThumbnailRequest request = _getThumbnailRequestFixture.Create("/path/to/file.jpg", 80); + CancellationTokenSource cts = new(); + TaskCompletionSource operationStarted = new(); + TaskCompletionSource cancellationRequested = new(); + + _mockSender.Send(Arg.Any(), Arg.Any()) + .Returns(callInfo => new ValueTask>(Task.Run(async () => + { + operationStarted.SetResult(true); + await cancellationRequested.Task; + callInfo.Arg().ThrowIfCancellationRequested(); + return ErrorOrFactory.From(ThumbnailResponseFixture.CreateThumbnailResponse()); + }, 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/WrittenContentLibrary/BookLibrary/Books/AddBookEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/WrittenContentLibrary/BookLibrary/Books/AddBookEndpointTests.cs new file mode 100644 index 00000000..0791190b --- /dev/null +++ b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/WrittenContentLibrary/BookLibrary/Books/AddBookEndpointTests.cs @@ -0,0 +1,10 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace Lumina.Presentation.Api.UnitTests.Core.Endpoints.WrittenContentLibrary.BookLibrary.Books; +internal class AddBookEndpointTests +{ +} diff --git a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/ModelBinders/UrlStringBinderTests.cs b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/ModelBinders/UrlStringBinderTests.cs deleted file mode 100644 index 3394c360..00000000 --- a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/ModelBinders/UrlStringBinderTests.cs +++ /dev/null @@ -1,114 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using FluentAssertions; -using Lumina.Presentation.Api.Common.ModelBinders; -using Microsoft.AspNetCore.Mvc.ModelBinding; -using Microsoft.Extensions.Primitives; -using NSubstitute; -using System; -using System.Diagnostics.CodeAnalysis; -using System.Threading.Tasks; -#endregion - -namespace Lumina.Presentation.Api.UnitTests.Core.ModelBinders; - -/// -/// Contains unit tests for the class. -/// -[ExcludeFromCodeCoverage] -public class UrlStringBinderTests -{ - private readonly UrlStringBinder _sut; - - /// - /// Initializes a new instance of the class. - /// - public UrlStringBinderTests() - { - _sut = new UrlStringBinder(); - } - - [Fact] - public async Task BindModelAsync_WhenBindingContextIsNull_ShouldThrowArgumentNullException() - { - // Arrange - ModelBindingContext? bindingContext = null; - - // Act & Assert - await Assert.ThrowsAsync(() => _sut.BindModelAsync(bindingContext!)); - } - - [Fact] - public async Task BindModelAsync_WhenValueProviderResultIsNone_ShouldReturnCompletedTask() - { - // Arrange - ModelBindingContext mockBindingContext = Substitute.For(); - mockBindingContext.ValueProvider.GetValue(Arg.Any()).Returns(ValueProviderResult.None); - - // Act - await _sut.BindModelAsync(mockBindingContext); - - // Assert - mockBindingContext.Result.Should().Be(ModelBindingResult.Failed()); - } - - [Fact] - public async Task BindModelAsync_WhenFirstValueIsNull_ShouldSetFailedResult() - { - // Arrange - ModelBindingContext mockBindingContext = Substitute.For(); - ValueProviderResult valueProviderResult = new(new StringValues((string?)null)); - mockBindingContext.ValueProvider.GetValue(Arg.Any()).Returns(valueProviderResult); - - // Act - await _sut.BindModelAsync(mockBindingContext); - - // Assert - mockBindingContext.Result.Should().Be(ModelBindingResult.Failed()); - } - - [Fact] - public async Task BindModelAsync_WhenFirstValueIsNullButValueProviderResultIsNotNone_ShouldSetFailedResult() - { - // Arrange - ModelBindingContext mockBindingContext = Substitute.For(); - ValueProviderResult valueProviderResult = new(new StringValues([null])); - mockBindingContext.ValueProvider.GetValue(Arg.Any()).Returns(valueProviderResult); - - // Act - await _sut.BindModelAsync(mockBindingContext); - - // Assert - mockBindingContext.Result.Should().Be(ModelBindingResult.Failed()); - } - - [Fact] - public async Task BindModelAsync_WhenValueIsProvided_ShouldDecodeAndSetSuccessResult() - { - // Arrange - const string ENCODED_VALUE = "Hello%20World%21"; - const string DECODED_VALUE = "Hello World!"; - ModelBindingContext mockBindingContext = Substitute.For(); - mockBindingContext.ValueProvider.GetValue(Arg.Any()).Returns(new ValueProviderResult(ENCODED_VALUE)); - - // Act - await _sut.BindModelAsync(mockBindingContext); - - // Assert - mockBindingContext.Result.Should().Be(ModelBindingResult.Success(DECODED_VALUE)); - } - - [Fact] - public async Task BindModelAsync_ShouldUseProvidedModelName() - { - // Arrange - const string MODEL_NAME = "testModel"; - ModelBindingContext mockBindingContext = Substitute.For(); - mockBindingContext.ModelName.Returns(MODEL_NAME); - - // Act - await _sut.BindModelAsync(mockBindingContext); - - // Assert - mockBindingContext.ValueProvider.Received(1).GetValue(MODEL_NAME); - } -} diff --git a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Lumina.Presentation.Api.UnitTests.csproj b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Lumina.Presentation.Api.UnitTests.csproj index d4d449bf..00f5fcd4 100644 --- a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Lumina.Presentation.Api.UnitTests.csproj +++ b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Lumina.Presentation.Api.UnitTests.csproj @@ -13,14 +13,20 @@ - - - - + + all + runtime; build; native; contentfiles; analyzers; buildtransitive + + + + - - + + + all + runtime; build; native; contentfiles; analyzers; buildtransitive + From 5ea02a319236aa10102e29e2fbc978b4359b1951 Mon Sep 17 00:00:00 2001 From: Binary Alley Date: Thu, 24 Oct 2024 12:45:41 +0300 Subject: [PATCH 2/2] Fixes inccorrect fixture class --- .../AddBook/Fixtures/DomainBookFixture.cs | 19 +++++++++++++------ 1 file changed, 13 insertions(+), 6 deletions(-) diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/WrittenContentLibrary/BooksLibrary/Books/Commands/AddBook/Fixtures/DomainBookFixture.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/WrittenContentLibrary/BooksLibrary/Books/Commands/AddBook/Fixtures/DomainBookFixture.cs index b1543e1e..b7366540 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/WrittenContentLibrary/BooksLibrary/Books/Commands/AddBook/Fixtures/DomainBookFixture.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/WrittenContentLibrary/BooksLibrary/Books/Commands/AddBook/Fixtures/DomainBookFixture.cs @@ -11,6 +11,7 @@ using Lumina.Domain.Core.Aggregates.WrittenContentLibrary.BookLibraryAggregate.V using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; +using System.Linq; #endregion namespace Lumina.Application.UnitTests.Core.WrittenContentLibrary.BooksLibrary.Books.Commands.AddBook.Fixtures; @@ -62,14 +63,20 @@ public class DomainBookFixture _fixture.Register(() => Optional.Some(_fixture.Create())); _fixture.Register(() => Optional.Some(_fixture.Create())); - _fixture.Register(() => ReleaseInfo.Create( - _fixture.Create>(), - _fixture.Create>(), - _fixture.Create>(), - _fixture.Create>(), + _fixture.Register(() => + { + int originalYear = _fixture.Create>().First(y => y >= 1900 && y <= 2025); + int reReleaseYear = _fixture.Create>().First(y => y >= originalYear && y <= 2025); + + return ReleaseInfo.Create( + Optional.Some(DateOnly.FromDateTime(new DateTime(originalYear, 1, 1))), + Optional.Some(originalYear), + Optional.Some(DateOnly.FromDateTime(new DateTime(reReleaseYear, 1, 1))), + Optional.Some(reReleaseYear), _fixture.Create>(), _fixture.Create>() - ).Value); + ).Value; + }); _fixture.Register(() => Genre.Create( _fixture.Create()