diff --git a/.github/workflows/run-tests.yml b/.github/workflows/run-tests.yml index 5ae23348..975227db 100644 --- a/.github/workflows/run-tests.yml +++ b/.github/workflows/run-tests.yml @@ -4,10 +4,14 @@ on: pull_request: branches: - master + workflow_dispatch: # enable manual triggers jobs: - test: - runs-on: ubuntu-latest + run-platform-tests: + runs-on: ${{ matrix.os }} + strategy: + matrix: + os: [ubuntu-latest, windows-latest, macOS-latest] steps: - uses: actions/checkout@v2 - name: Set up .NET diff --git a/.github/workflows/validate-branch-name.yml b/.github/workflows/validate-branch-name.yml index ff40b40d..ed7c8625 100644 --- a/.github/workflows/validate-branch-name.yml +++ b/.github/workflows/validate-branch-name.yml @@ -1,4 +1,4 @@ -name: Branch Naming Convention Check +name: Branch Push Naming Convention Check on: push: @@ -6,7 +6,7 @@ on: - master jobs: - check-branch-name: + validate-branch-push: runs-on: ubuntu-latest steps: - name: Check branch name diff --git a/.github/workflows/validate-pull-request-source-branch.yml b/.github/workflows/validate-pull-request-source-branch.yml index bd378bd6..3c28e6bc 100644 --- a/.github/workflows/validate-pull-request-source-branch.yml +++ b/.github/workflows/validate-pull-request-source-branch.yml @@ -1,4 +1,4 @@ -name: PR Source Branch Check +name: Pull Request Source Branch Validation Check on: pull_request: @@ -6,7 +6,7 @@ on: - master jobs: - check-branch-name: + validate-pr-source: runs-on: ubuntu-latest steps: - name: Check source branch name diff --git a/.gitignore b/.gitignore index d507c4d1..925941ae 100644 --- a/.gitignore +++ b/.gitignore @@ -31,7 +31,8 @@ bld/ *.sln.iml # Common -*.Development.json +*.[Dd]evelopment.json +*.[Tt]est.json # Windows image file caches Thumbs.db diff --git a/README.md b/README.md index c3758e48..f45fd375 100644 --- a/README.md +++ b/README.md @@ -38,6 +38,8 @@ Several icons used in this project were adapted from icons sourced from [svgrepo - [`toggle-thumbnails.svg`](https://www.svgrepo.com/svg/370469/page-image) (Public Domain license) - [`toggle-hidden.svg`](https://www.svgrepo.com/svg/470389/hidden) (MIT License) +- [`delete.svg`](https://www.svgrepo.com/svg/488148/delete) (MIT License) +- [`add-directory.svg`](https://www.svgrepo.com/svg/488040/add-folder) (MIT License) ## License diff --git a/docs/CONTRIBUTING.md b/docs/CONTRIBUTING.md index ea1fb5f2..0c02b96a 100644 --- a/docs/CONTRIBUTING.md +++ b/docs/CONTRIBUTING.md @@ -99,39 +99,11 @@ public interface IUserService ### C# Specific #### Code Conventions: -- Each class, interface and struct should use the following `#region`s to group code sections: +- Group `using`s with the following `#region`: ```csharp #region ========================================================================= USING ===================================================================================== using System; #endregion - -namespace Current.Namespace; - -public class DhlDeliveryServiceProvider : IDeliveryServiceProvider -{ - #region ================================================================== FIELD MEMBERS ================================================================================ - private readonly ITaxCalculator _taxCalculator; - #endregion - - #region ====================================================================== CTOR ===================================================================================== - public GetDirectoryTreeQueryHandler(ITaxCalculator taxCalculator) - { - _taxCalculator = taxCalculator; - } - #endregion - - #region ===================================================================== METHODS =================================================================================== - public void Deliver() - { - // code - } - - public decimal CalculateCost() - { - // code - } - #endregion -} ``` - Enforce one type per file. For example: ```csharp diff --git a/docs/INSTALL.md b/docs/INSTALL.md new file mode 100644 index 00000000..48d64613 --- /dev/null +++ b/docs/INSTALL.md @@ -0,0 +1,17 @@ +## Reverse Proxy Setup +### Rate Limiting Headers +The application uses IP-based rate limiting on some endpoints. When deploying behind a reverse proxy, you must forward the +original client IP, otherwise the "per IP" rate limiting will become global, per any request aimed at those endpoints, regardless of origin: + +```text +# Nginx +proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; + +# Apache +RemoteIPHeader X-Forwarded-For + +# Caddy +reverse_proxy { + header_up X-Forwarded-For {remote_host} +} +``` 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/Domain.md b/docs/technical/domain/Domain.md new file mode 100644 index 00000000..1a7f872d --- /dev/null +++ b/docs/technical/domain/Domain.md @@ -0,0 +1,76 @@ +Domain +├── Audio Library Bounded Context +│      └── Audio Library Aggregate +│              └── Audio Metadata +├── Video Library Bounded Context +│      ├── Movie Library Aggregate +│      │        ├── Movie Id +│      │        ├── Video Metadata +│      │        ├── Movie Library Service +│      │        └── Movie +│      ├── Tv Show Library Aggregate +│      │        ├── Episode Id +│      │        ├── Season Id +│      │        ├── Tv Show Id +│      │        ├── Episode +│      │        ├── Season +│      │        ├── Tv Show Library Service +│      │        └── Tv Show +│      └── Video Library Service +├── Photo Library Bounded Context +│      └── Photo Library Aggregate +├── Written Content Library Bounded Context +│      ├── Book Library Aggregate +│      │        ├── Book Id +│      │        ├── Book Rating +│      │        ├── Book Series Id +│      │        ├── ISBN +│      │        ├── Written Content Metadata +│      │        ├── Book Series +│      │        ├── Book Library Service +│      │        └── Book +│      ├── Magazine Library Aggregate +│      │        └── Magazine +│      └── Written Content Library Service +├── Media Contributor Bounded Context +│      └── Media Contributor Aggregate +│              ├── Contributor Name +│              ├── Media Contributor Id +│              ├── Media Contributor Role +│              └── Media Contributor +├── Library Management Bounded Context +│      └── Library Aggregate +│              ├── Library Id +│              └── Library +├── User Management Bounded Context +│      └── User Aggregate +│              ├── User Id +│              └── User +├── File System Management Bounded Context +│      └── File System Management Aggregate +│              ├── File System Path Id +│              ├── Path Segment +│              ├── Stream Info +│              ├── Thumbnail +│              ├── Directory +│              ├── File +│              ├── UNIX Root Item +│              ├── Windows Root Item +│              ├── Directory Provider Service +│              ├── File Provider Service +│              ├── Directory Service +│              ├── File Service +│              ├── Drive Service +│              ├── Path Service +│              ├── Thumbnail Service +│              ├── File System Permissions Service +│              ├── File Type Service +│              └── File System Item + +• Bounded Context +• Aggregate +• Aggregate Root +• Entity +• Value Object +• Event +• Service diff --git a/docs/technical/domain/UbiquitousLanguage.md b/docs/technical/domain/UbiquitousLanguage.md index 6d935dc8..cf31fb0a 100644 --- a/docs/technical/domain/UbiquitousLanguage.md +++ b/docs/technical/domain/UbiquitousLanguage.md @@ -95,6 +95,7 @@ - ComicSeries - Magazine - MagazineIssue +- Newspaper - Manga - GraphicNovel - AcademicPaper @@ -117,11 +118,11 @@ - VideoLibrary (root: VideoLibrary, entities: TVShow, Season, Episode, Movie, FilmSeries, ConcertVideo, Documentary, TutorialVideo, HomeVideo, Anime, YouTubeVideo, MusicVideo) - AudioLibrary (root: AudioLibrary, entities: Song, Album, Artist, Audiobook, LiveRecording, Interview, CoverSong, Remix, SoundEffect) - PodcastLibrary (root: PodcastLibrary, entities: Podcast, PodcastEpisode) -- WrittenContentLibrary (root: WrittenContentLibrary, entities: Book, EBook, BookSeries, ComicBook, ComicSeries, Magazine, MagazineIssue, Manga, GraphicNovel, AcademicPaper, SheetMusic, Screenplay) +- WrittenContentLibrary (root: WrittenContentLibrary, entities: Book, EBook, BookSeries, ComicBook, ComicSeries, Magazine, MagazineIssue, Newspaper, Manga, GraphicNovel, AcademicPaper, SheetMusic, Screenplay) - 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) @@ -133,7 +134,7 @@ - Value Objects: ComicMetadata, SeriesInfo - PeriodicalLibrary (root: PeriodicalLibrary) - - Entities: Magazine, MagazineIssue + - Entities: Magazine, MagazineIssue, Newspaper - Value Objects: PeriodicalMetadata, IssueInfo - AcademicLibrary (root: AcademicLibrary) @@ -219,7 +220,7 @@ - Aggregates: UserProfile - Services: RecommendationEngine, ContentCurationService, UserActivityTrackingService - ContentDelivery - - Aggregates: FileManagement + - Aggregates: FileSystemManagement - Services: StreamingService, ContentSynchronizationService - MetadataManagement - Aggregates: SupplementaryContentLibrary @@ -235,4 +236,4 @@ - PlaylistRepository - CollectionRepository - FileRepository -- StreamRepository \ No newline at end of file +- StreamRepository diff --git a/src/Lumina.Application/Common/Converters/OptionalJsonConverter.cs b/src/Lumina.Application/Common/Converters/OptionalJsonConverter.cs deleted file mode 100644 index 82585b97..00000000 --- a/src/Lumina.Application/Common/Converters/OptionalJsonConverter.cs +++ /dev/null @@ -1,44 +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; - -/// -/// 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/Entities/Common/GenreEntity.cs b/src/Lumina.Application/Common/DataAccess/Entities/Common/GenreEntity.cs new file mode 100644 index 00000000..019ecd4a --- /dev/null +++ b/src/Lumina.Application/Common/DataAccess/Entities/Common/GenreEntity.cs @@ -0,0 +1,14 @@ +#region ========================================================================= USING ===================================================================================== +using System.Diagnostics; +#endregion + +namespace Lumina.Application.Common.DataAccess.Entities.Common; + +/// +/// Represents a genre. +/// +/// Gets the name of the genre. +[DebuggerDisplay("Name: {Name}")] +public record GenreEntity( + string? Name +); diff --git a/src/Lumina.Contracts/Models/Common/IStorageEntity.cs b/src/Lumina.Application/Common/DataAccess/Entities/Common/IStorageEntity.cs similarity index 51% rename from src/Lumina.Contracts/Models/Common/IStorageEntity.cs rename to src/Lumina.Application/Common/DataAccess/Entities/Common/IStorageEntity.cs index a35d558f..f3bb814e 100644 --- a/src/Lumina.Contracts/Models/Common/IStorageEntity.cs +++ b/src/Lumina.Application/Common/DataAccess/Entities/Common/IStorageEntity.cs @@ -1,8 +1,8 @@ -#region ========================================================================= USING ===================================================================================== +#region ========================================================================= USING ===================================================================================== using System; #endregion -namespace Lumina.Contracts.Models.Common; +namespace Lumina.Application.Common.DataAccess.Entities.Common; /// /// Interface for storage models, enforces Id. @@ -15,12 +15,12 @@ public interface IStorageEntity Guid Id { get; init; } /// - /// The time and date when the entity was added. + /// Gets or sets the time and date when the entity was added. /// DateTime Created { get; set; } /// - /// The time and date when the entity was updated. + /// Gets or sets the optional time and date when the entity was updated. /// DateTime? Updated { get; set; } -} \ No newline at end of file +} diff --git a/src/Lumina.Contracts/Models/Common/RatingModel.cs b/src/Lumina.Application/Common/DataAccess/Entities/Common/RatingEntity.cs similarity index 85% rename from src/Lumina.Contracts/Models/Common/RatingModel.cs rename to src/Lumina.Application/Common/DataAccess/Entities/Common/RatingEntity.cs index 86398053..5caef350 100644 --- a/src/Lumina.Contracts/Models/Common/RatingModel.cs +++ b/src/Lumina.Application/Common/DataAccess/Entities/Common/RatingEntity.cs @@ -2,7 +2,7 @@ using System.Diagnostics; #endregion -namespace Lumina.Contracts.Models.Common; +namespace Lumina.Application.Common.DataAccess.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.Application/Common/DataAccess/Entities/Common/TagEntity.cs b/src/Lumina.Application/Common/DataAccess/Entities/Common/TagEntity.cs new file mode 100644 index 00000000..f020608f --- /dev/null +++ b/src/Lumina.Application/Common/DataAccess/Entities/Common/TagEntity.cs @@ -0,0 +1,14 @@ +#region ========================================================================= USING ===================================================================================== +using System.Diagnostics; +#endregion + +namespace Lumina.Application.Common.DataAccess.Entities.Common; + +/// +/// Represents a tag. +/// +/// Gets the name of the tag. +[DebuggerDisplay("Name: {Name}")] +public record TagEntity( + string? Name +); diff --git a/src/Lumina.Application/Common/DataAccess/Entities/FileSystemManagement/FileSystemItemEntity.cs b/src/Lumina.Application/Common/DataAccess/Entities/FileSystemManagement/FileSystemItemEntity.cs new file mode 100644 index 00000000..ec23d0f4 --- /dev/null +++ b/src/Lumina.Application/Common/DataAccess/Entities/FileSystemManagement/FileSystemItemEntity.cs @@ -0,0 +1,21 @@ +#region ========================================================================= USING ===================================================================================== +using System; +using System.Diagnostics; +#endregion + +namespace Lumina.Application.Common.DataAccess.Entities.FileSystemManagement; + +/// +/// Generic filesystem data transfer object. +/// +/// The path of the file system item. +/// 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: {Name}")] +public record FileSystemItemEntity( + string Path, + string Name, + DateTime DateCreated, + DateTime DateModified +); diff --git a/src/Lumina.Application/Common/DataAccess/Entities/MediaContributors/MediaContributorEntity.cs b/src/Lumina.Application/Common/DataAccess/Entities/MediaContributors/MediaContributorEntity.cs new file mode 100644 index 00000000..19929100 --- /dev/null +++ b/src/Lumina.Application/Common/DataAccess/Entities/MediaContributors/MediaContributorEntity.cs @@ -0,0 +1,16 @@ +#region ========================================================================= USING ===================================================================================== +using System.Diagnostics; +#endregion + +namespace Lumina.Application.Common.DataAccess.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.Application/Common/DataAccess/Entities/MediaContributors/MediaContributorNameEntity.cs b/src/Lumina.Application/Common/DataAccess/Entities/MediaContributors/MediaContributorNameEntity.cs new file mode 100644 index 00000000..b454b894 --- /dev/null +++ b/src/Lumina.Application/Common/DataAccess/Entities/MediaContributors/MediaContributorNameEntity.cs @@ -0,0 +1,16 @@ +#region ========================================================================= USING ===================================================================================== +using System.Diagnostics; +#endregion + +namespace Lumina.Application.Common.DataAccess.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.Application/Common/DataAccess/Entities/MediaContributors/MediaContributorRoleEntity.cs b/src/Lumina.Application/Common/DataAccess/Entities/MediaContributors/MediaContributorRoleEntity.cs new file mode 100644 index 00000000..f718f6cd --- /dev/null +++ b/src/Lumina.Application/Common/DataAccess/Entities/MediaContributors/MediaContributorRoleEntity.cs @@ -0,0 +1,16 @@ +#region ========================================================================= USING ===================================================================================== +using System.Diagnostics; +#endregion + +namespace Lumina.Application.Common.DataAccess.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.Application/Common/DataAccess/Entities/MediaLibrary/Management/LibraryContentLocationEntity.cs b/src/Lumina.Application/Common/DataAccess/Entities/MediaLibrary/Management/LibraryContentLocationEntity.cs new file mode 100644 index 00000000..c4c6a8d3 --- /dev/null +++ b/src/Lumina.Application/Common/DataAccess/Entities/MediaLibrary/Management/LibraryContentLocationEntity.cs @@ -0,0 +1,17 @@ +#region ========================================================================= USING ===================================================================================== +using System.Diagnostics; +#endregion + +namespace Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management; + +/// +/// Repository entity for a media library content location. +/// +[DebuggerDisplay("Path: {Path}")] +public class LibraryContentLocationEntity +{ + /// + /// Gets or sets the path of the media library content location. + /// + public required string Path { get; set; } +} diff --git a/src/Lumina.Application/Common/DataAccess/Entities/MediaLibrary/Management/LibraryEntity.cs b/src/Lumina.Application/Common/DataAccess/Entities/MediaLibrary/Management/LibraryEntity.cs new file mode 100644 index 00000000..e498b836 --- /dev/null +++ b/src/Lumina.Application/Common/DataAccess/Entities/MediaLibrary/Management/LibraryEntity.cs @@ -0,0 +1,57 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Entities.Common; +using Lumina.Application.Common.DataAccess.Entities.UsersManagement; +using Lumina.Domain.Common.Enums.MediaLibrary; +using System; +using System.Collections.Generic; +using System.Diagnostics; +#endregion + +namespace Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management; + +/// +/// Repository entity for a media library. +/// +[DebuggerDisplay("Title: {Title}")] +public class LibraryEntity : IStorageEntity +{ + /// + /// Gets the Id of the media library. + /// + public required Guid Id { get; init; } + + /// + /// Gets the Id of the user that owns the media library. + /// + public required Guid UserId { get; init; } + + /// + /// Gets or sets the title of the media library. + /// + public required string Title { get; set; } + + /// + /// Gets or sets the type of the media library. + /// + public required LibraryType LibraryType { get; set; } + + /// + /// Gets or sets the list of file system paths that make up the media library. + /// + public required ICollection ContentLocations { get; init; } = []; + + /// + /// Gets the user that owns the media library. + /// + public UserEntity User { get; init; } = null!; + + /// + /// Gets or sets the time and date when the entity was added. + /// + public required DateTime Created { get; set; } + + /// + /// Gets or sets the optional time and date when the entity was updated. + /// + public DateTime? Updated { get; set; } +} diff --git a/src/Lumina.Application/Common/DataAccess/Entities/MediaLibrary/WrittenContentLibrary/BookLibrary/BookEntity.cs b/src/Lumina.Application/Common/DataAccess/Entities/MediaLibrary/WrittenContentLibrary/BookLibrary/BookEntity.cs new file mode 100644 index 00000000..8073dd34 --- /dev/null +++ b/src/Lumina.Application/Common/DataAccess/Entities/MediaLibrary/WrittenContentLibrary/BookLibrary/BookEntity.cs @@ -0,0 +1,207 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Entities.Common; +using Lumina.Domain.Common.Enums.BookLibrary; +using System; +using System.Collections.Generic; +using System.Diagnostics; +#endregion + +namespace Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary; + +/// +/// Repository entity for a book. +/// +[DebuggerDisplay("Title: {Title}")] +public class BookEntity : IStorageEntity +{ + /// + /// Gets the Id of the media item. + /// + public required Guid Id { get; init; } + + /// + /// Gets or sets the title of the media item. + /// + public required string Title { get; set; } + + /// + /// Gets or sets the original title of the media item. + /// + public string? OriginalTitle { get; set; } + + /// + /// Gets or sets the optional description of the media item. + /// + public string? Description { get; set; } + + /// + /// Gets or sets the optional original release date of the media item. + /// + public DateOnly? OriginalReleaseDate { get; set; } + + /// + /// Gets or sets the optional original release year of the media item. + /// This is useful when only the year of original release is known. + /// + public int? OriginalReleaseYear { get; set; } + + /// + /// Gets or sets the optional re-release or reissue date of the media item. + /// + public DateOnly? ReReleaseDate { get; set; } + + /// + /// Gets or sets the optional re-release or reissue year of the media item. + /// + public int? ReReleaseYear { get; set; } + + /// + /// Gets or sets the optional country or region of release. + /// + public string? ReleaseCountry { get; set; } + + /// + /// Gets or sets the optional release version or edition. (e.g. "Original", "Director's Cut", "2.0") + /// + public string? ReleaseVersion { get; set; } + + /// + /// Gets or sets the ISO 639-1 two-letter language code. + /// + public string? LanguageCode { get; set; } + + /// + /// Gets or sets the full name of the language in English. + /// + public string? LanguageName { get; set; } + + /// + /// Gets or sets an optional native name of the language. + /// + public string? LanguageNativeName { get; set; } + + /// + /// Gets or sets the optional ISO 639-1 two-letter original language code. + /// + public string? OriginalLanguageCode { get; set; } + + /// + /// Gets or sets the optional full name of the original language in English. + /// + public string? OriginalLanguageName { get; set; } + + /// + /// Gets or sets an optional native name of the original language. + /// + public string? OriginalLanguageNativeName { get; set; } + + /// + /// Gets or sets the list of tags associated with the media item. + /// + public HashSet Tags { get; set; } = []; + + /// + /// Gets or sets the list of genres associated with the media item. + /// + public HashSet Genres { get; set; } = []; + + /// + /// Gets or sets the publisher of the written content. + /// + public string? Publisher { get; set; } + + /// + /// Gets or sets the number of pages in the written content. + /// + public int? PageCount { get; set; } + + /// + /// Gets or sets the format of the book (e.g., Hardcover, Paperback), if applicable. + /// + public BookFormat? Format { get; set; } + + /// + /// Gets or sets the edition of the book, if applicable. + /// + public string? Edition { get; set; } + + /// + /// Gets or sets the volume or book number in the series, if applicable. + /// + public int? VolumeNumber { get; set; } + // TODO: uncomment when series is implemented + /// + /// Gets or sets the series id, if the book is part of a series. + /// + //public Guid? BookSeriesId { get; set; } + + /// + /// Gets or sets the ASIN (Amazon Standard Identification Number) of the book. + /// + public string? ASIN { get; set; } + + /// + /// Gets or sets the Goodreads ID of the book. + /// + public string? GoodreadsId { get; set; } + + /// + /// Gets or sets the Library of Congress Control Number (LCCN) of the book. + /// + public string? LCCN { get; set; } + + /// + /// Gets or sets the OCLC Number (WorldCat identifier) of the book. + /// + public string? OCLCNumber { get; set; } + + /// + /// Gets or sets the Open Library ID of the book. + /// + public string? OpenLibraryId { get; set; } + + /// + /// Gets or sets the LibraryThing ID of the book. + /// + public string? LibraryThingId { get; set; } + + /// + /// Gets or sets the Google Books ID of the book. + /// + public string? GoogleBooksId { get; set; } + + /// + /// Gets or sets the Barnes & Noble ID of the book. + /// + public string? BarnesAndNobleId { get; set; } = null!; + + /// + /// Gets or sets the Apple Books ID of the book. + /// + public string? AppleBooksId { get; set; } + + /// + /// Gets or sets the list of ISBN (International Standard Book Number) of the book. + /// + public List ISBNs { get; set; } = []; + + /// + /// Gets or sets the list of media contributors (actors, directors, etc) starring in this book. + /// + //public List ContributorIds { get; set; } = []; + + /// + /// Gets or sets the list of ratings for this book. + /// + public List Ratings { get; set; } = []; + + /// + /// Gets or sets the time and date when the entity was added. + /// + public required DateTime Created { get; set; } + + /// + /// Gets or sets the optional time and date when the entity was updated. + /// + public DateTime? Updated { get; set; } +} diff --git a/src/Lumina.Application/Common/DataAccess/Entities/MediaLibrary/WrittenContentLibrary/BookLibrary/BookRatingEntity.cs b/src/Lumina.Application/Common/DataAccess/Entities/MediaLibrary/WrittenContentLibrary/BookLibrary/BookRatingEntity.cs new file mode 100644 index 00000000..f272b2cb --- /dev/null +++ b/src/Lumina.Application/Common/DataAccess/Entities/MediaLibrary/WrittenContentLibrary/BookLibrary/BookRatingEntity.cs @@ -0,0 +1,22 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Entities.Common; +using Lumina.Domain.Common.Enums.BookLibrary; +using System.Diagnostics; +#endregion + +namespace Lumina.Application.Common.DataAccess.Entities.MediaLibrary.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.Application/Common/DataAccess/Entities/MediaLibrary/WrittenContentLibrary/BookLibrary/BookSeriesEntity.cs b/src/Lumina.Application/Common/DataAccess/Entities/MediaLibrary/WrittenContentLibrary/BookLibrary/BookSeriesEntity.cs new file mode 100644 index 00000000..3fbebff4 --- /dev/null +++ b/src/Lumina.Application/Common/DataAccess/Entities/MediaLibrary/WrittenContentLibrary/BookLibrary/BookSeriesEntity.cs @@ -0,0 +1,14 @@ +#region ========================================================================= USING ===================================================================================== +using System.Diagnostics; +#endregion + +namespace Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary; + +/// +/// Repository entity for book series. +/// +/// The title of the book series. +[DebuggerDisplay("Title: {Title}")] +public record BookSeriesEntity( + string? Title +); diff --git a/src/Lumina.Application/Common/DataAccess/Entities/MediaLibrary/WrittenContentLibrary/BookLibrary/IsbnEntity.cs b/src/Lumina.Application/Common/DataAccess/Entities/MediaLibrary/WrittenContentLibrary/BookLibrary/IsbnEntity.cs new file mode 100644 index 00000000..6a235202 --- /dev/null +++ b/src/Lumina.Application/Common/DataAccess/Entities/MediaLibrary/WrittenContentLibrary/BookLibrary/IsbnEntity.cs @@ -0,0 +1,17 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Domain.Common.Enums.BookLibrary; +using System.Diagnostics; +#endregion + +namespace Lumina.Application.Common.DataAccess.Entities.MediaLibrary.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.Application/Common/DataAccess/Entities/UsersManagement/UserEntity.cs b/src/Lumina.Application/Common/DataAccess/Entities/UsersManagement/UserEntity.cs new file mode 100644 index 00000000..fba2d476 --- /dev/null +++ b/src/Lumina.Application/Common/DataAccess/Entities/UsersManagement/UserEntity.cs @@ -0,0 +1,71 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Entities.Common; +using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management; +using System; +using System.Collections.Generic; +using System.Diagnostics; +#endregion + +namespace Lumina.Application.Common.DataAccess.Entities.UsersManagement; + +/// +/// Repository entity for a user. +/// +[DebuggerDisplay("Username: {Username}")] +public class UserEntity : IStorageEntity +{ + /// + /// Gets the Id of the user. + /// + public Guid Id { get; init; } + + /// + /// Gets or sets the username of the user. + /// + public required string Username { get; set; } + + /// + /// Gets or sets the hashed password of the user. + /// + public required string Password { get; set; } + + /// + /// Gets or sets the temporary hashed password used in password recovery. + /// + public string? TempPassword { get; set; } + + /// + /// Gets or sets the optional Time-based One-Time Password (TOTP) secret for two-factor authentication. + /// + public string? TotpSecret { get; set; } + + /// + /// Gets or sets the optional token used for account verification or password reset. + /// + public string? VerificationToken { get; set; } // TODO: to be deleted, not used + + /// + /// Gets or sets the optional date and time when the verification token was created. + /// + public DateTime? VerificationTokenCreated { get; set; } // TODO: to be deleted, not used + + /// + /// Gets or sets the date and time when the temporary password used in password recovery was created. + /// + public DateTime? TempPasswordCreated { get; set; } + + /// + /// Gets the collection of libraries owned by this user. + /// + public required ICollection Libraries { get; init; } = []; + + /// + /// Gets the time and date when the entity was added. + /// + public required DateTime Created { get; set; } + + /// + /// Gets the optional time and date when the entity was updated. + /// + public DateTime? Updated { get; set; } +} diff --git a/src/Lumina.Application/Common/DataAccess/Repositories/Books/IBookRepository.cs b/src/Lumina.Application/Common/DataAccess/Repositories/Books/IBookRepository.cs index b925c108..6dbabc93 100644 --- a/src/Lumina.Application/Common/DataAccess/Repositories/Books/IBookRepository.cs +++ b/src/Lumina.Application/Common/DataAccess/Repositories/Books/IBookRepository.cs @@ -1,7 +1,7 @@ -#region ========================================================================= USING ===================================================================================== +#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.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary; #endregion namespace Lumina.Application.Common.DataAccess.Repositories.Books; @@ -9,8 +9,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..20bdc021 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.Application.Common.DataAccess.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..244dc604 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.Application.Common.DataAccess.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..dfe43dbd 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.Application.Common.DataAccess.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..06d860c1 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.Application.Common.DataAccess.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..7a32a9e1 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,7 @@ #region ========================================================================= USING ===================================================================================== -using Lumina.Contracts.Models.Common; +using Lumina.Application.Common.DataAccess.Entities.Common; + + #endregion diff --git a/src/Lumina.Application/Common/DataAccess/Repositories/MediaLibrary/ILibraryRepository.cs b/src/Lumina.Application/Common/DataAccess/Repositories/MediaLibrary/ILibraryRepository.cs new file mode 100644 index 00000000..d1e39a1b --- /dev/null +++ b/src/Lumina.Application/Common/DataAccess/Repositories/MediaLibrary/ILibraryRepository.cs @@ -0,0 +1,15 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Repositories.Common.Actions; +using Lumina.Application.Common.DataAccess.Repositories.Common.Base; +using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management; +#endregion + +namespace Lumina.Application.Common.DataAccess.Repositories.MediaLibrary; + +/// +/// Interface for the repository for media libraries. +/// +public interface ILibraryRepository : IRepository, + IInsertRepositoryAction +{ +} diff --git a/src/Lumina.Application/Common/DataAccess/Repositories/Users/IUserRepository.cs b/src/Lumina.Application/Common/DataAccess/Repositories/Users/IUserRepository.cs new file mode 100644 index 00000000..f45bf2fd --- /dev/null +++ b/src/Lumina.Application/Common/DataAccess/Repositories/Users/IUserRepository.cs @@ -0,0 +1,27 @@ +#region ========================================================================= USING ===================================================================================== +using ErrorOr; +using Lumina.Application.Common.DataAccess.Entities.UsersManagement; +using Lumina.Application.Common.DataAccess.Repositories.Common.Actions; +using Lumina.Application.Common.DataAccess.Repositories.Common.Base; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Application.Common.DataAccess.Repositories.Users; + +/// +/// Interface for the repository for users. +/// +public interface IUserRepository : IRepository, + IGetAllRepositoryAction, + IInsertRepositoryAction, + IUpdateRepositoryAction +{ + /// + /// Gets a username identified by from the repository, if it exists. + /// + /// The username of the user to get. + /// Cancellation token that can be used to stop the execution. + /// An containing either a if found, or an error. + Task> GetByUsernameAsync(string username, CancellationToken cancellationToken); +} diff --git a/src/Lumina.Application/Common/DependencyInjection/ApplicationLayerServices.cs b/src/Lumina.Application/Common/DependencyInjection/ApplicationLayerServices.cs index 2c2ae7c9..905573aa 100644 --- a/src/Lumina.Application/Common/DependencyInjection/ApplicationLayerServices.cs +++ b/src/Lumina.Application/Common/DependencyInjection/ApplicationLayerServices.cs @@ -1,10 +1,9 @@ #region ========================================================================= USING ===================================================================================== using FluentValidation; using Lumina.Application.Common.Behaviors; -using Mapster; -using MapsterMapper; using Mediator; using Microsoft.Extensions.DependencyInjection; +using System.Diagnostics.CodeAnalysis; #endregion namespace Lumina.Application.Common.DependencyInjection; @@ -12,6 +11,7 @@ namespace Lumina.Application.Common.DependencyInjection; /// /// Contains all services of the Application layer. /// +[ExcludeFromCodeCoverage] public static class ApplicationLayerServices { /// @@ -33,12 +33,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/Errors/Errors.Authentication.cs b/src/Lumina.Application/Common/Errors/Errors.Authentication.cs new file mode 100644 index 00000000..a6bec2b7 --- /dev/null +++ b/src/Lumina.Application/Common/Errors/Errors.Authentication.cs @@ -0,0 +1,33 @@ +#region ========================================================================= USING ===================================================================================== +using ErrorOr; +#endregion + +namespace Lumina.Application.Common.Errors; + +/// +/// Application authentication related error types. +/// +public static partial class Errors +{ + public static class Authentication + { + public static Error UsernameAlreadyExists => Error.Conflict(description: nameof(UsernameAlreadyExists)); + public static Error UsernameDoesNotExist => Error.NotFound(description: nameof(UsernameDoesNotExist)); + public static Error UsernameCannotBeEmpty => Error.Validation(description: nameof(UsernameCannotBeEmpty)); + public static Error TotpCannotBeEmpty => Error.Validation(description: nameof(TotpCannotBeEmpty)); + public static Error PasswordCannotBeEmpty => Error.Validation(description: nameof(PasswordCannotBeEmpty)); + public static Error NewPasswordCannotBeEmpty => Error.Validation(description: nameof(NewPasswordCannotBeEmpty)); + public static Error CurrentPasswordCannotBeEmpty => Error.Validation(description: nameof(CurrentPasswordCannotBeEmpty)); + public static Error PasswordConfirmCannotBeEmpty => Error.Validation(description: nameof(PasswordConfirmCannotBeEmpty)); + public static Error NewPasswordConfirmCannotBeEmpty => Error.Validation(description: nameof(NewPasswordConfirmCannotBeEmpty)); + public static Error InvalidPassword => Error.Validation(description: nameof(InvalidPassword)); + public static Error UsernameMustBeBetween3And255CharactersLong => Error.Validation(description: nameof(UsernameMustBeBetween3And255CharactersLong)); + public static Error InvalidUsername => Error.Validation(description: nameof(InvalidUsername)); + public static Error PasswordsNotMatch => Error.Validation(description: nameof(PasswordsNotMatch)); + public static Error InvalidTotpCode => Error.Validation(description: nameof(InvalidTotpCode)); + public static Error InvalidUsernameOrPassword => Error.Failure(description: nameof(InvalidUsernameOrPassword)); + public static Error InvalidCurrentPassword => Error.Failure(description: nameof(InvalidCurrentPassword)); + public static Error TempPasswordExpired => Error.Failure(description: nameof(TempPasswordExpired)); + public static Error PasswordResetAlreadyRequested => Error.Failure(description: nameof(PasswordResetAlreadyRequested)); + } +} diff --git a/src/Lumina.Application/Common/Errors/Errors.Authorization.cs b/src/Lumina.Application/Common/Errors/Errors.Authorization.cs new file mode 100644 index 00000000..842f394f --- /dev/null +++ b/src/Lumina.Application/Common/Errors/Errors.Authorization.cs @@ -0,0 +1,16 @@ +#region ========================================================================= USING ===================================================================================== +using ErrorOr; +#endregion + +namespace Lumina.Application.Common.Errors; + +/// +/// Application authorization related error types. +/// +public static partial class Errors +{ + public static class Authorization + { + public static Error AdminAccountAlreadyCreated => Error.Unauthorized(description: nameof(AdminAccountAlreadyCreated)); + } +} diff --git a/src/Lumina.Application/Common/Infrastructure/Authentication/IJwtTokenGenerator.cs b/src/Lumina.Application/Common/Infrastructure/Authentication/IJwtTokenGenerator.cs new file mode 100644 index 00000000..92bad1d3 --- /dev/null +++ b/src/Lumina.Application/Common/Infrastructure/Authentication/IJwtTokenGenerator.cs @@ -0,0 +1,15 @@ +namespace Lumina.Application.Common.Infrastructure.Authentication; + +/// +/// Interface for generating JWT tokens. +/// +public interface IJwtTokenGenerator +{ + /// + /// Generates a new JWT token. + /// + /// The id of the user for which to generate the token. + /// The username for which to generate the token. + /// The generated JWT token. + string GenerateToken(string id, string username); +} diff --git a/src/Lumina.Application/Common/Infrastructure/Authentication/IQRCodeGenerator.cs b/src/Lumina.Application/Common/Infrastructure/Authentication/IQRCodeGenerator.cs new file mode 100644 index 00000000..43b3f53c --- /dev/null +++ b/src/Lumina.Application/Common/Infrastructure/Authentication/IQRCodeGenerator.cs @@ -0,0 +1,15 @@ +namespace Lumina.Application.Common.Infrastructure.Authentication; + +/// +/// Interface for the service for generating QR codes for TOTP. +/// +public interface IQRCodeGenerator +{ + /// + /// Generates a QR code Data URI for the specified TOTP secret. + /// + /// User's username or unique identifier. + /// The TOTP secret for which the QR code should be generated. + /// Data URI for the QR code. + string GenerateQrCodeDataUri(string username, byte[] secret); +} diff --git a/src/Lumina.Application/Common/Infrastructure/Authentication/ITokenGenerator.cs b/src/Lumina.Application/Common/Infrastructure/Authentication/ITokenGenerator.cs new file mode 100644 index 00000000..2ba0f687 --- /dev/null +++ b/src/Lumina.Application/Common/Infrastructure/Authentication/ITokenGenerator.cs @@ -0,0 +1,13 @@ +namespace Lumina.Application.Common.Infrastructure.Authentication; + +/// +/// Interface for the service for generating secure tokens for accounts confirmation or recovery. +/// +public interface ITokenGenerator +{ + /// + /// Generates a secure token. + /// + /// A secure token. + string GenerateToken(); +} diff --git a/src/Lumina.Application/Common/Infrastructure/Authentication/ITotpTokenGenerator.cs b/src/Lumina.Application/Common/Infrastructure/Authentication/ITotpTokenGenerator.cs new file mode 100644 index 00000000..7f369c12 --- /dev/null +++ b/src/Lumina.Application/Common/Infrastructure/Authentication/ITotpTokenGenerator.cs @@ -0,0 +1,21 @@ +namespace Lumina.Application.Common.Infrastructure.Authentication; + +/// +/// Interface for the service for generating and validating TOTP tokens. +/// +public interface ITotpTokenGenerator +{ + /// + /// Generates a new TOTP secret for a user. + /// + /// The generated TOTP secret. + byte[] GenerateSecret(); + + /// + /// Validates a TOTP token against the stored secret. + /// + /// The user's TOTP secret. + /// The token to validate. + /// if valid, otherwise. + bool ValidateToken(byte[] secret, string token); +} diff --git a/src/Lumina.Application/Common/Infrastructure/Security/ICryptographyService.cs b/src/Lumina.Application/Common/Infrastructure/Security/ICryptographyService.cs new file mode 100644 index 00000000..af3a41c8 --- /dev/null +++ b/src/Lumina.Application/Common/Infrastructure/Security/ICryptographyService.cs @@ -0,0 +1,27 @@ +#region ========================================================================= USING ===================================================================================== +using System; +#endregion + +namespace Lumina.Application.Common.Infrastructure.Security; + +/// +/// Interface for the service for cryptographic concerns. +/// +public interface ICryptographyService +{ + /// + /// Encrypts a plaintext string using AES encryption with a randomly generated initialization vector (IV). + /// + /// The plaintext string to encrypt. + /// A Base64-encoded string of the combined IV and encrypted ciphertext. + /// Thrown when is or empty. + string Encrypt(string plaintext); + + /// + /// Decrypts a Base64-encoded string that contains both the IV and ciphertext. + /// + /// The Base64-encoded string containing both IV and ciphertext. + /// The decrypted plaintext string. + /// Thrown when is , empty, or invalid. + string Decrypt(string ciphertext); +} diff --git a/src/Lumina.Application/Common/Infrastructure/Security/IHashService.cs b/src/Lumina.Application/Common/Infrastructure/Security/IHashService.cs new file mode 100644 index 00000000..77395c85 --- /dev/null +++ b/src/Lumina.Application/Common/Infrastructure/Security/IHashService.cs @@ -0,0 +1,22 @@ +namespace Lumina.Application.Common.Infrastructure.Security; + +/// +/// Interface for the service for hashing passwords. +/// +public interface IHashService +{ + /// + /// Creates a hash from a string. + /// + /// The string to be hashed. + /// The hashed string. + string HashString(string password); + + /// + /// Verifies a password against a hash. + /// + /// The string to be checked. + /// The hashed representation of the string to be checked. + /// if and the de-hashed versions of are equal, otherwise. + bool CheckStringAgainstHash(string password, string hashedPassword); +} diff --git a/src/Lumina.Application/Common/Infrastructure/Time/IDateTimeProvider.cs b/src/Lumina.Application/Common/Infrastructure/Time/IDateTimeProvider.cs new file mode 100644 index 00000000..407b41d8 --- /dev/null +++ b/src/Lumina.Application/Common/Infrastructure/Time/IDateTimeProvider.cs @@ -0,0 +1,16 @@ +#region ========================================================================= USING ===================================================================================== +using System; +#endregion + +namespace Lumina.Application.Common.Infrastructure.Time; + +/// +/// Interface for time related concerns. +/// +public interface IDateTimeProvider +{ + /// + /// The current UTC time. + /// + DateTime UtcNow { get; } +} diff --git a/src/Lumina.Application/Common/Mapping/Authentication/ChangePasswordRequestMapping.cs b/src/Lumina.Application/Common/Mapping/Authentication/ChangePasswordRequestMapping.cs new file mode 100644 index 00000000..382a96a7 --- /dev/null +++ b/src/Lumina.Application/Common/Mapping/Authentication/ChangePasswordRequestMapping.cs @@ -0,0 +1,27 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Core.UsersManagement.Authentication.Commands.ChangePassword; +using Lumina.Contracts.Requests.Authentication; +#endregion + +namespace Lumina.Application.Common.Mapping.Authentication; + +/// +/// Extension methods for converting . +/// +public static class ChangePasswordRequestMapping +{ + /// + /// Converts to . + /// + /// The request to be converted. + /// The converted command. + public static ChangePasswordCommand ToCommand(this ChangePasswordRequest request) + { + return new ChangePasswordCommand( + request.Username, + request.CurrentPassword, + request.NewPassword, + request.NewPasswordConfirm + ); + } +} diff --git a/src/Lumina.Application/Common/Mapping/Authentication/LoginRequestMapping.cs b/src/Lumina.Application/Common/Mapping/Authentication/LoginRequestMapping.cs new file mode 100644 index 00000000..018488d0 --- /dev/null +++ b/src/Lumina.Application/Common/Mapping/Authentication/LoginRequestMapping.cs @@ -0,0 +1,26 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Core.UsersManagement.Authentication.Queries.LoginUser; +using Lumina.Contracts.Requests.Authentication; +#endregion + +namespace Lumina.Application.Common.Mapping.Authentication; + +/// +/// Extension methods for converting . +/// +public static class LoginRequestMapping +{ + /// + /// Converts to . + /// + /// The request to be converted. + /// The converted query. + public static LoginUserQuery ToQuery(this LoginRequest request) + { + return new LoginUserQuery( + request.Username, + request.Password, + request.TotpCode + ); + } +} diff --git a/src/Lumina.Application/Common/Mapping/Authentication/RecoverPasswordRequestMapping.cs b/src/Lumina.Application/Common/Mapping/Authentication/RecoverPasswordRequestMapping.cs new file mode 100644 index 00000000..24d58a75 --- /dev/null +++ b/src/Lumina.Application/Common/Mapping/Authentication/RecoverPasswordRequestMapping.cs @@ -0,0 +1,25 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Core.UsersManagement.Authentication.Commands.RecoverPassword; +using Lumina.Contracts.Requests.Authentication; +#endregion + +namespace Lumina.Application.Common.Mapping.Authentication; + +/// +/// Extension methods for converting . +/// +public static class RecoverPasswordRequestMapping +{ + /// + /// Converts to . + /// + /// The request to be converted. + /// The converted command. + public static RecoverPasswordCommand ToCommand(this RecoverPasswordRequest request) + { + return new RecoverPasswordCommand( + request.Username, + request.TotpCode + ); + } +} diff --git a/src/Lumina.Application/Common/Mapping/Authentication/RegistrationRequestMapping.cs b/src/Lumina.Application/Common/Mapping/Authentication/RegistrationRequestMapping.cs new file mode 100644 index 00000000..49cdc0c9 --- /dev/null +++ b/src/Lumina.Application/Common/Mapping/Authentication/RegistrationRequestMapping.cs @@ -0,0 +1,43 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Core.Maintenance.ApplicationSetup.Commands.SetupApplication; +using Lumina.Application.Core.UsersManagement.Authentication.Commands.RegisterUser; +using Lumina.Contracts.Requests.Authentication; +#endregion + +namespace Lumina.Application.Common.Mapping.Authentication; + +/// +/// Extension methods for converting . +/// +public static class RegistrationRequestMapping +{ + /// + /// Converts to . + /// + /// The request to be converted. + /// The converted command. + public static SetupApplicationCommand ToSetupCommand(this RegistrationRequest request) + { + return new SetupApplicationCommand( + request.Username, + request.Password, + request.PasswordConfirm, + request.Use2fa + ); + } + + /// + /// Converts to . + /// + /// The request to be converted. + /// The converted command. + public static RegisterUserCommand ToCommand(this RegistrationRequest request) + { + return new RegisterUserCommand( + request.Username, + request.Password, + request.PasswordConfirm, + request.Use2fa + ); + } +} diff --git a/src/Lumina.Application/Common/Mapping/Common/Metadata/GenreDtoMapping.cs b/src/Lumina.Application/Common/Mapping/Common/Metadata/GenreDtoMapping.cs new file mode 100644 index 00000000..7406368b --- /dev/null +++ b/src/Lumina.Application/Common/Mapping/Common/Metadata/GenreDtoMapping.cs @@ -0,0 +1,37 @@ +#region ========================================================================= USING ===================================================================================== +using ErrorOr; +using Lumina.Contracts.DTO.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 GenreDtoMapping +{ + /// + /// Converts to . + /// + /// The DTO to be converted. + /// The converted domain entity. + public static ErrorOr ToDomainEntity(this GenreDto dto) + { + return Genre.Create( + dto.Name + ); + } + + /// + /// Converts to a collection of . + /// + /// The DTOs to be converted. + /// The converted domain entities. + public static IEnumerable> ToDomainEntities(this IEnumerable dtos) + { + return dtos.Select(repositoryEntity => repositoryEntity.ToDomainEntity()); + } +} diff --git a/src/Lumina.Application/Common/Mapping/Common/Metadata/GenreEntityMapping.cs b/src/Lumina.Application/Common/Mapping/Common/Metadata/GenreEntityMapping.cs new file mode 100644 index 00000000..b2aa43fc --- /dev/null +++ b/src/Lumina.Application/Common/Mapping/Common/Metadata/GenreEntityMapping.cs @@ -0,0 +1,60 @@ +#region ========================================================================= USING ===================================================================================== +using ErrorOr; +using Lumina.Application.Common.DataAccess.Entities.Common; +using Lumina.Contracts.DTO.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 GenreEntityMapping +{ + /// + /// Converts to . + /// + /// The repository entity to be converted. + /// The converted DTO. + public static GenreDto ToResponse(this GenreEntity repositoryEntity) + { + return new GenreDto( + repositoryEntity.Name ?? default + ); + } + + /// + /// Converts to a collection of . + /// + /// The repository entities to be converted. + /// The converted DTOs. + public static IEnumerable ToResponses(this IEnumerable repositoryEntities) + { + return repositoryEntities.Select(responseEntity => responseEntity.ToResponse()); + } + + /// + /// Converts to . + /// + /// The repository entity to be converted. + /// The converted domain entity. + public static ErrorOr ToDomainEntity(this GenreEntity repositoryEntity) + { + return Genre.Create( + repositoryEntity.Name ?? default + ); + } + + /// + /// Converts to a collection of . + /// + /// The repository entities to be converted. + /// The converted domain entities. + public static IEnumerable> ToDomainEntities(this IEnumerable repositoryEntities) + { + return repositoryEntities.Select(domainEntity => domainEntity.ToDomainEntity()); + } +} 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..be53f39d --- /dev/null +++ b/src/Lumina.Application/Common/Mapping/Common/Metadata/GenreMapping.cs @@ -0,0 +1,36 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.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 entity to be converted. + /// The converted repository entity. + public static GenreEntity ToRepositoryEntity(this Genre domainEntity) + { + return new GenreEntity( + domainEntity.Name + ); + } + + /// + /// Converts to a collection of . + /// + /// The domain entities to be converted. + /// The converted repository entities. + public static IEnumerable ToRepositoryEntities(this IEnumerable domainEntities) + { + return domainEntities.Select(domainEntity => domainEntity.ToRepositoryEntity()); + } +} diff --git a/src/Lumina.Application/Common/Mapping/Common/Metadata/TagDtoMapping.cs b/src/Lumina.Application/Common/Mapping/Common/Metadata/TagDtoMapping.cs new file mode 100644 index 00000000..d16b750f --- /dev/null +++ b/src/Lumina.Application/Common/Mapping/Common/Metadata/TagDtoMapping.cs @@ -0,0 +1,37 @@ +#region ========================================================================= USING ===================================================================================== +using ErrorOr; +using Lumina.Contracts.DTO.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 TagDtoMapping +{ + /// + /// Converts to . + /// + /// The DTO to be converted. + /// The converted domain entity. + public static ErrorOr ToDomainEntity(this TagDto dto) + { + return Tag.Create( + dto.Name + ); + } + + /// + /// Converts to a collection of . + /// + /// The DTOs to be converted. + /// The converted domain entities. + public static IEnumerable> ToDomainEntities(this IEnumerable dtos) + { + return dtos.Select(domainEntity => domainEntity.ToDomainEntity()); + } +} diff --git a/src/Lumina.Application/Common/Mapping/Common/Metadata/TagEntityMapping.cs b/src/Lumina.Application/Common/Mapping/Common/Metadata/TagEntityMapping.cs new file mode 100644 index 00000000..802ef48d --- /dev/null +++ b/src/Lumina.Application/Common/Mapping/Common/Metadata/TagEntityMapping.cs @@ -0,0 +1,60 @@ +#region ========================================================================= USING ===================================================================================== +using ErrorOr; +using Lumina.Application.Common.DataAccess.Entities.Common; +using Lumina.Contracts.DTO.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 TagEntityMapping +{ + /// + /// Converts to . + /// + /// The repository entity to be converted. + /// The converted DTO. + public static TagDto ToResponse(this TagEntity repositoryEntity) + { + return new TagDto( + repositoryEntity.Name ?? default + ); + } + + /// + /// Converts to a collection of . + /// + /// The repository entities to be converted. + /// The converted DTOs. + public static IEnumerable ToResponses(this IEnumerable repositoryEntities) + { + return repositoryEntities.Select(responseEntity => responseEntity.ToResponse()); + } + + /// + /// Converts to . + /// + /// The repository entity to be converted. + /// The converted domain entity. + public static ErrorOr ToDomainEntity(this TagEntity repositoryEntity) + { + return Tag.Create( + repositoryEntity.Name ?? default + ); + } + + /// + /// Converts to a collection of . + /// + /// The repository entities to be converted. + /// The converted domain entities. + public static IEnumerable> ToDomainEntities(this IEnumerable repositoryEntities) + { + return repositoryEntities.Select(domainEntity => domainEntity.ToDomainEntity()); + } +} 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..de4d79f7 --- /dev/null +++ b/src/Lumina.Application/Common/Mapping/Common/Metadata/TagMapping.cs @@ -0,0 +1,36 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.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 entity to be converted. + /// The converted repository entity. + public static TagEntity ToRepositoryEntity(this Tag domainEntity) + { + return new TagEntity( + domainEntity.Name + ); + } + + /// + /// Converts to a collection of . + /// + /// The domain entity to be converted. + /// The converted repository entities. + public static IEnumerable ToRepositoryEntities(this IEnumerable domainEntities) + { + return domainEntities.Select(domainEntity => domainEntity.ToRepositoryEntity()); + } +} 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..ce65db5c --- /dev/null +++ b/src/Lumina.Application/Common/Mapping/FileSystemManagement/Common/FileSystemTreeNodeResponseMapping.cs @@ -0,0 +1,40 @@ +#region ========================================================================= USING ===================================================================================== +using ErrorOr; +using Lumina.Domain.Common.Enums.FileSystem; +using Lumina.Contracts.Responses.FileSystemManagement.Common; +using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.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 entity. + 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 entity. + 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..35f4b8d4 --- /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.BoundedContexts.FileSystemManagementBoundedContext.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 entity to be converted. + /// The converted response. + public static FileSystemTreeNodeResponse ToFileSystemTreeNodeResponse(this Directory domainEntity) + { + return new FileSystemTreeNodeResponse() + { + Name = domainEntity.Name, + Path = domainEntity.Id.Path, + ItemType = domainEntity.Type, + IsExpanded = false, + ChildrenLoaded = false, + Children = domainEntity.Items.Select(item => item.ToTreeNodeResponse()) + .ToList() + }; + } + + /// + /// Converts to a collection of . + /// + /// The domain entities to be converted. + /// The converted responses. + public static IEnumerable ToFileSystemTreeNodeResponses(this IEnumerable domainEntities) + { + return domainEntities.Select(domainEntity => domainEntity.ToTreeNodeResponse()); + } + + /// + /// Converts to . + /// + /// The domain entity to be converted. + /// The converted response. + public static DirectoryResponse ToResponse(this Directory domainEntity) + { + return new DirectoryResponse( + domainEntity.Id.Path, + domainEntity.Name, + domainEntity.DateCreated.Value, + domainEntity.DateModified.Value, + domainEntity.Items.Select(fileSystemItem => fileSystemItem.ToFileSystemItemDto()) + .ToList() + ); + } + + /// + /// Converts to a collection of . + /// + /// The domain entities to be converted. + /// The converted responses. + public static IEnumerable ToResponses(this IEnumerable domainEntities) + { + return domainEntities.Select(domainEntity => domainEntity.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..7149ecc5 --- /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.Responses.FileSystemManagement.Common; +using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate; +using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Entities; +using System; +using System.Collections.Generic; +using System.Linq; +using Lumina.Contracts.DTO.FileSystemManagement; +#endregion + +namespace Lumina.Application.Common.Mapping.FileSystemManagement.FileSystem; + +/// +/// Extension methods for converting . +/// +public static class FileSystemItemMapping +{ + /// + /// Converts to . + /// + /// The domain entity to be converted. + /// The converted Dto. + public static FileSystemItemDto ToFileSystemItemDto(this FileSystemItem domainEntity) + { + return new FileSystemItemDto( + domainEntity.Id.Path, + domainEntity.Name, + DateTime.Now, + DateTime.Now + ); + } + + /// + /// Converts to . + /// + /// The domain entity to be converted. + /// The converted entity. + /// Thrown when the provided parameter is not an expected descendant of . + public static FileSystemTreeNodeResponse ToTreeNodeResponse(this FileSystemItem domainEntity) + { + if (domainEntity is Directory directory) + return directory.ToFileSystemTreeNodeResponse(); + else if (domainEntity is File file) + return file.ToFileSystemTreeNodeResponse(); + else if (domainEntity is WindowsRootItem windowsRootItem) + return windowsRootItem.ToTreeNodeResponse(); + else if (domainEntity is UnixRootItem unixRootItem) + return unixRootItem.ToTreeNodeResponse(); + else + throw new ArgumentException("Invalid FileSystemItem"); + } + + /// + /// Converts to . + /// + /// The domain entities to be converted. + /// The converted entities. + public static IEnumerable ToTreeNodeResponses(this IEnumerable domainEntities) + { + return domainEntities.Select(domainEntity => domainEntity.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..ade9cffa --- /dev/null +++ b/src/Lumina.Application/Common/Mapping/FileSystemManagement/FileSystem/UnixRootItemMapping.cs @@ -0,0 +1,33 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Domain.Common.Enums.FileSystem; +using Lumina.Contracts.Responses.FileSystemManagement.Common; +using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.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 entity to be converted. + /// The converted response. + public static FileSystemTreeNodeResponse ToTreeNodeResponse(this UnixRootItem domainEntity) + { + return new FileSystemTreeNodeResponse() + { + Path = domainEntity.Id.Path, + Name = domainEntity.Name, + ItemType = FileSystemItemType.Root, + IsExpanded = false, + ChildrenLoaded = false, + Children = domainEntity.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..68666b1d --- /dev/null +++ b/src/Lumina.Application/Common/Mapping/FileSystemManagement/FileSystem/WindowsRootItemMapping.cs @@ -0,0 +1,29 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Domain.Common.Enums.FileSystem; +using Lumina.Contracts.Responses.FileSystemManagement.Common; +using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Entities; +#endregion + +namespace Lumina.Application.Common.Mapping.FileSystemManagement.FileSystem; + +/// +/// Extension methods for converting . +/// +public static class WindowsRootItemMapping +{ + /// + /// Converts to . + /// + /// The domain entity to be converted. + /// The converted response. + public static FileSystemTreeNodeResponse ToTreeNodeResponse(this WindowsRootItem domainEntity) + { + return new FileSystemTreeNodeResponse() + { + Path = domainEntity.Id.Path, + Name = domainEntity.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..a128da91 --- /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.BoundedContexts.FileSystemManagementBoundedContext.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 entity to be converted. + /// The converted response. + public static FileSystemTreeNodeResponse ToFileSystemTreeNodeResponse(this File domainEntity) + { + return new FileSystemTreeNodeResponse() + { + Name = domainEntity.Name, + Path = domainEntity.Id.Path, + ItemType = domainEntity.Type, + IsExpanded = false, + ChildrenLoaded = false + }; + } + + /// + /// Converts to a collection of . + /// + /// The domain entities to be converted. + /// The converted responses. + public static IEnumerable ToFileSystemTreeNodeResponses(this IEnumerable domainEntities) + { + return domainEntities.Select(domainEntity => domainEntity.ToFileSystemTreeNodeResponse()); + } + + /// + /// Converts to . + /// + /// The domain entity to be converted. + /// The converted response. + public static FileResponse ToResponse(this File domainEntity) + { + return new FileResponse( + domainEntity.Id.Path, + domainEntity.Name, + domainEntity.DateCreated.HasValue ? domainEntity.DateCreated.Value : default, + domainEntity.DateModified.HasValue ? domainEntity.DateModified.Value : default, + domainEntity.Size + ); + } + + /// + /// Converts to a collection of . + /// + /// The domain entities to be converted. + /// The converted responses. + public static IEnumerable ToResponses(this IEnumerable domainEntities) + { + return domainEntities.Select(domainEntity => domainEntity.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/CheckPathExistsRequestMapping.cs b/src/Lumina.Application/Common/Mapping/FileSystemManagement/Paths/CheckPathExistsRequestMapping.cs new file mode 100644 index 00000000..d34f0eb2 --- /dev/null +++ b/src/Lumina.Application/Common/Mapping/FileSystemManagement/Paths/CheckPathExistsRequestMapping.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 CheckPathExistsRequestMapping +{ + /// + /// 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..02a24842 --- /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.BoundedContexts.FileSystemManagementBoundedContext.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 entity to be converted. + /// The converted response. + public static PathSegmentResponse ToResponse(this PathSegment domainEntity) + { + return new PathSegmentResponse( + domainEntity.Name + ); + } + + /// + /// Converts to a collection of . + /// + /// The domain entities to be converted. + /// The converted responses. + public static IEnumerable ToResponses(this IEnumerable domainEntities) + { + return domainEntities.Select(domainEntity => domainEntity.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..bd010de0 --- /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.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.ValueObjects; +#endregion + +namespace Lumina.Application.Common.Mapping.FileSystemManagement.Thumbnails; + +/// +/// Extension methods for converting . +/// +public static class ThumbnailMapping +{ + /// + /// Converts to . + /// + /// The domain entity to be converted. + /// The converted response. + public static ThumbnailResponse ToResponse(this Thumbnail domainEntity) + { + return new ThumbnailResponse( + domainEntity.Type, + domainEntity.Bytes + ); + } +} diff --git a/src/Lumina.Application/Common/Mapping/MediaLibrary/Management/AddMediaLibraryRequestMapping.cs b/src/Lumina.Application/Common/Mapping/MediaLibrary/Management/AddMediaLibraryRequestMapping.cs new file mode 100644 index 00000000..f5c971b3 --- /dev/null +++ b/src/Lumina.Application/Common/Mapping/MediaLibrary/Management/AddMediaLibraryRequestMapping.cs @@ -0,0 +1,28 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Core.MediaLibrary.Management.Commands.AddLibrary; +using Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BooksLibrary.Books.Commands.AddBook; +using Lumina.Contracts.Requests.MediaLibrary.Management; +#endregion + +namespace Lumina.Application.Common.Mapping.MediaLibrary.Management; + +/// +/// Extension methods for converting . +/// +public static class AddMediaLibraryRequestMapping +{ + /// + /// Converts to . + /// + /// The request to be converted. + /// The converted command. + public static AddLibraryCommand ToCommand(this AddLibraryRequest request) + { + return new AddLibraryCommand( + request.UserId, + request.Title, + request.LibraryType, + request.ContentLocations + ); + } +} diff --git a/src/Lumina.Application/Common/Mapping/MediaLibrary/Management/LibraryEntityMapping.cs b/src/Lumina.Application/Common/Mapping/MediaLibrary/Management/LibraryEntityMapping.cs new file mode 100644 index 00000000..36e0d70d --- /dev/null +++ b/src/Lumina.Application/Common/Mapping/MediaLibrary/Management/LibraryEntityMapping.cs @@ -0,0 +1,31 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management; +using Lumina.Contracts.Responses.MediaLibrary.Management; +using System.Linq; +#endregion + +namespace Lumina.Application.Common.Mapping.MediaLibrary.Management; + +/// +/// Extension methods for converting . +/// +public static class LibraryEntityMapping +{ + /// + /// Converts to . + /// + /// The repository entity to be converted. + /// The converted response entity. + public static LibraryResponse ToResponse(this LibraryEntity repositoryEntity) + { + return new LibraryResponse( + repositoryEntity.Id, + repositoryEntity.UserId, + repositoryEntity.Title, + repositoryEntity.LibraryType, + repositoryEntity.ContentLocations.Select(location => location.Path).ToList(), + repositoryEntity.Created, + repositoryEntity.Updated + ); + } +} diff --git a/src/Lumina.Application/Common/Mapping/MediaLibrary/Management/LibraryMapping.cs b/src/Lumina.Application/Common/Mapping/MediaLibrary/Management/LibraryMapping.cs new file mode 100644 index 00000000..4cd847a7 --- /dev/null +++ b/src/Lumina.Application/Common/Mapping/MediaLibrary/Management/LibraryMapping.cs @@ -0,0 +1,32 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management; +using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate; +using System.Linq; +#endregion + +namespace Lumina.Application.Common.Mapping.MediaLibrary.Management; + +/// +/// Extension methods for converting . +/// +public static class LibraryMapping +{ + /// + /// Converts to . + /// + /// The domain entity to be converted. + /// The converted repository entity. + public static LibraryEntity ToRepositoryEntity(this Library domainEntity) + { + return new LibraryEntity + { + Id = domainEntity.Id.Value, + Title = domainEntity.Title, + LibraryType = domainEntity.LibraryType, + UserId = domainEntity.UserId.Value, + ContentLocations = domainEntity.ContentLocations.Select(path => new LibraryContentLocationEntity() { Path = path.Path }).ToList(), + Created = domainEntity.Created, + Updated = domainEntity.Updated.HasValue ? domainEntity.Updated : null + }; + } +} diff --git a/src/Lumina.Application/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/AddBookRequestMapping.cs b/src/Lumina.Application/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/AddBookRequestMapping.cs new file mode 100644 index 00000000..f0f436d8 --- /dev/null +++ b/src/Lumina.Application/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/AddBookRequestMapping.cs @@ -0,0 +1,41 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BooksLibrary.Books.Commands.AddBook; +using Lumina.Contracts.Requests.MediaLibrary.WrittenContentLibrary.BookLibrary.Books; + +#endregion + +namespace Lumina.Application.Common.Mapping.MediaLibrary.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/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/BookEntityMapping.cs b/src/Lumina.Application/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/BookEntityMapping.cs new file mode 100644 index 00000000..5d543790 --- /dev/null +++ b/src/Lumina.Application/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/BookEntityMapping.cs @@ -0,0 +1,224 @@ +#region ========================================================================= USING ===================================================================================== +using ErrorOr; +using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary; +using Lumina.Application.Common.Mapping.Common.Metadata; +using Lumina.Application.Common.Mapping.MediaLibrary.WrittenContentLibrary.BookLibrary.Books; +using Lumina.Application.Common.Mapping.MediaLibrary.WrittenContentLibrary.BookLibrary.Common; +using Lumina.Contracts.DTO.Common; +using Lumina.Contracts.DTO.MediaLibrary.WrittenContentLibrary; +using Lumina.Contracts.Responses.MediaLibrary.WrittenContentLibrary.BookLibrary.Books; +using Lumina.Domain.Common.Enums.BookLibrary; +using Lumina.Domain.Common.Primitives; +using Lumina.Domain.Common.ValueObjects.Metadata; +using Lumina.Domain.Core.BoundedContexts.WrittenContentLibraryBoundedContext.BookLibraryAggregate; +using Lumina.Domain.Core.BoundedContexts.WrittenContentLibraryBoundedContext.BookLibraryAggregate.Entities; +using Lumina.Domain.Core.BoundedContexts.WrittenContentLibraryBoundedContext.BookLibraryAggregate.ValueObjects; +using System; +using System.Collections.Generic; +using System.Linq; +#endregion + +namespace Lumina.Application.Common.Mapping.MediaLibrary.WrittenContentLibrary.BookLibrary.Books; + +/// +/// Extension methods for converting . +/// +public static class BookEntityMapping +{ + /// + /// Converts to . + /// + /// The repository entity to be converted. + /// + /// An containing either a successfully converted , or an error message. + /// + public static ErrorOr ToDomainEntity(this BookEntity repositoryEntity) + { + IEnumerable> tagsResult = repositoryEntity.Tags.ToDomainEntities(); + foreach (ErrorOr tagResult in tagsResult) + if (tagResult.IsError) + return tagResult.Errors; + + IEnumerable> genresResult = repositoryEntity.Genres.ToDomainEntities(); + foreach (ErrorOr genreResult in genresResult) + if (genreResult.IsError) + return genreResult.Errors; + + IEnumerable> isbnsResult = repositoryEntity.ISBNs.ToDomainEntities(); + foreach (ErrorOr isbnResult in isbnsResult) + if (isbnResult.IsError) + return isbnResult.Errors; + + IEnumerable> bookRatingsResult = repositoryEntity.Ratings.ToDomainEntities(); + 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(repositoryEntity.Format); + + 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 entities to be converted. + /// The converted domain entities. + /// + /// An colection of containing either successfully converted , or error messages. + /// + public static IEnumerable> ToDomainEntities(this IEnumerable repositoryEntities) + { + return repositoryEntities.Select(repositoryEntity => repositoryEntity.ToDomainEntity()); + } + + /// + /// Converts to . + /// + /// The repository entity to be converted. + /// The converted response entity. + public static BookResponse ToResponse(this BookEntity repositoryEntity) + { + ReleaseInfoDto releaseInfoEntity = 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 + LanguageInfoDto? languageInfoEntity = !string.IsNullOrWhiteSpace(repositoryEntity.LanguageCode) || + !string.IsNullOrWhiteSpace(repositoryEntity.LanguageName) || + !string.IsNullOrWhiteSpace(repositoryEntity.LanguageNativeName) + ? new LanguageInfoDto( + repositoryEntity.LanguageCode, + repositoryEntity.LanguageName, + repositoryEntity.LanguageNativeName + ) : null; + LanguageInfoDto? originalLanguageInfoEntity = !string.IsNullOrWhiteSpace(repositoryEntity.OriginalLanguageCode) || + !string.IsNullOrWhiteSpace(repositoryEntity.OriginalLanguageName) || + !string.IsNullOrWhiteSpace(repositoryEntity.OriginalLanguageNativeName) + ? new LanguageInfoDto( + repositoryEntity.OriginalLanguageCode, + repositoryEntity.OriginalLanguageName, + repositoryEntity.OriginalLanguageNativeName + ) : null; + WrittenContentMetadataDto metadata = new( + repositoryEntity.Title, + repositoryEntity.OriginalTitle, + repositoryEntity.Description, + releaseInfoEntity, + [.. repositoryEntity.Genres.ToResponses()], + [.. repositoryEntity.Tags.ToResponses()], + languageInfoEntity, + originalLanguageInfoEntity, + repositoryEntity.Publisher, + repositoryEntity.PageCount + ); + return new BookResponse( + repositoryEntity.Id, + metadata, + repositoryEntity.Format, + 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.ToResponses()], + null, + [.. repositoryEntity.Ratings.ToResponses()], + repositoryEntity.Created, + repositoryEntity.Updated + ); + } + + /// + /// Converts to a collection of . + /// + /// The repository entities 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/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/BookMapping.cs b/src/Lumina.Application/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/BookMapping.cs new file mode 100644 index 00000000..52f4e4a5 --- /dev/null +++ b/src/Lumina.Application/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/BookMapping.cs @@ -0,0 +1,63 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary; +using Lumina.Application.Common.Mapping.Common.Metadata; +using Lumina.Application.Common.Mapping.MediaLibrary.WrittenContentLibrary.BookLibrary.Common; +using Lumina.Domain.Core.BoundedContexts.WrittenContentLibraryBoundedContext.BookLibraryAggregate; +using System.Linq; +#endregion + +namespace Lumina.Application.Common.Mapping.MediaLibrary.WrittenContentLibrary.BookLibrary.Books; + +/// +/// Extension methods for converting . +/// +public static class BookMapping +{ + /// + /// Converts to . + /// + /// The domain entity to be converted. + /// The converted repository entity. + public static BookEntity ToRepositoryEntity(this Book domainEntity) + { + return new BookEntity + { + Id = domainEntity.Id.Value, + Title = domainEntity.Metadata.Title, + OriginalTitle = domainEntity.Metadata.OriginalTitle.HasValue ? domainEntity.Metadata.OriginalTitle.Value : null, + Description = domainEntity.Metadata.Description.HasValue ? domainEntity.Metadata.Description.Value : null, + OriginalReleaseDate = domainEntity.Metadata.ReleaseInfo.OriginalReleaseDate.HasValue ? domainEntity.Metadata.ReleaseInfo.OriginalReleaseDate.Value : null, + OriginalReleaseYear = domainEntity.Metadata.ReleaseInfo.OriginalReleaseYear.HasValue ? domainEntity.Metadata.ReleaseInfo.OriginalReleaseYear.Value : null, + ReReleaseDate = domainEntity.Metadata.ReleaseInfo.ReReleaseDate.HasValue ? domainEntity.Metadata.ReleaseInfo.ReReleaseDate.Value : null, + ReReleaseYear = domainEntity.Metadata.ReleaseInfo.ReReleaseYear.HasValue ? domainEntity.Metadata.ReleaseInfo.ReReleaseYear.Value : null, + ReleaseCountry = domainEntity.Metadata.ReleaseInfo.ReleaseCountry.HasValue ? domainEntity.Metadata.ReleaseInfo.ReleaseCountry.Value : null, + ReleaseVersion = domainEntity.Metadata.ReleaseInfo.ReleaseVersion.HasValue ? domainEntity.Metadata.ReleaseInfo.ReleaseVersion.Value : null, + LanguageCode = domainEntity.Metadata.Language.HasValue ? domainEntity.Metadata.Language.Value.LanguageCode : null, + LanguageName = domainEntity.Metadata.Language.HasValue ? domainEntity.Metadata.Language.Value.LanguageName : null, + LanguageNativeName = domainEntity.Metadata.Language.HasValue ? domainEntity.Metadata.Language.Value.NativeName.Value : null, + OriginalLanguageCode = domainEntity.Metadata.OriginalLanguage.HasValue ? domainEntity.Metadata.OriginalLanguage.Value.LanguageCode : null, + OriginalLanguageName = domainEntity.Metadata.OriginalLanguage.HasValue ? domainEntity.Metadata.OriginalLanguage.Value.LanguageName : null, + OriginalLanguageNativeName = domainEntity.Metadata.OriginalLanguage.HasValue ? domainEntity.Metadata.OriginalLanguage.Value.NativeName.Value : null, + Tags = domainEntity.Metadata.Tags.ToRepositoryEntities().ToHashSet(), + Genres = domainEntity.Metadata.Genres.ToRepositoryEntities().ToHashSet(), + Publisher = domainEntity.Metadata.Publisher.HasValue ? domainEntity.Metadata.Publisher.Value : null, + PageCount = domainEntity.Metadata.PageCount.HasValue ? domainEntity.Metadata.PageCount.Value : null, + Format = domainEntity.Format.HasValue ? domainEntity.Format.Value : null, + Edition = domainEntity.Edition.HasValue ? domainEntity.Edition.Value : null, + VolumeNumber = domainEntity.VolumeNumber.HasValue ? domainEntity.VolumeNumber.Value : null, + ASIN = domainEntity.ASIN.HasValue ? domainEntity.ASIN.Value : null, + GoodreadsId = domainEntity.GoodreadsId.HasValue ? domainEntity.GoodreadsId.Value : null, + LCCN = domainEntity.LCCN.HasValue ? domainEntity.LCCN.Value : null, + OCLCNumber = domainEntity.OCLCNumber.HasValue ? domainEntity.OCLCNumber.Value : null, + OpenLibraryId = domainEntity.OpenLibraryId.HasValue ? domainEntity.OpenLibraryId.Value : null, + LibraryThingId = domainEntity.LibraryThingId.HasValue ? domainEntity.LibraryThingId.Value : null, + GoogleBooksId = domainEntity.GoogleBooksId.HasValue ? domainEntity.GoogleBooksId.Value : null, + BarnesAndNobleId = domainEntity.BarnesAndNobleId.HasValue ? domainEntity.BarnesAndNobleId.Value : null, + AppleBooksId = domainEntity.AppleBooksId.HasValue ? domainEntity.AppleBooksId.Value : null, + ISBNs = domainEntity.ISBNs.ToRepositoryEntities().ToList(), + Ratings = domainEntity.Ratings.ToRepositoryEntities().ToList(), + Created = domainEntity.Created, + Updated = domainEntity.Updated.HasValue ? domainEntity.Updated : null + }; + } +} diff --git a/src/Lumina.Application/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Common/BookRatingDtoMapping.cs b/src/Lumina.Application/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Common/BookRatingDtoMapping.cs new file mode 100644 index 00000000..16616979 --- /dev/null +++ b/src/Lumina.Application/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Common/BookRatingDtoMapping.cs @@ -0,0 +1,42 @@ +#region ========================================================================= USING ===================================================================================== +using ErrorOr; +using Lumina.Contracts.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary; +using Lumina.Domain.Common.Enums.BookLibrary; +using Lumina.Domain.Common.Primitives; +using Lumina.Domain.Core.BoundedContexts.WrittenContentLibraryBoundedContext.BookLibraryAggregate.ValueObjects; +using System.Collections.Generic; +using System.Linq; +#endregion + +namespace Lumina.Application.Common.Mapping.MediaLibrary.WrittenContentLibrary.BookLibrary.Common; + +/// +/// Extension methods for converting . +/// +public static class BookRatingDtoMapping +{ + /// + /// Converts to . + /// + /// The DTO to be converted. + /// The converted domain entity. + public static ErrorOr ToDomainEntity(this BookRatingDto dto) + { + return BookRating.Create( + dto.Value ?? default, + dto.MaxValue ?? default, + Optional.FromNullable(dto.Source), + Optional.FromNullable(dto.VoteCount) + ); + } + + /// + /// Converts to a collection of . + /// + /// The DTOs to be converted. + /// The converted domain entities. + public static IEnumerable> ToDomainEntities(this IEnumerable dtos) + { + return dtos.Select(domainEntity => domainEntity.ToDomainEntity()); + } +} diff --git a/src/Lumina.Application/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Common/BookRatingEntityMapping.cs b/src/Lumina.Application/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Common/BookRatingEntityMapping.cs new file mode 100644 index 00000000..da176890 --- /dev/null +++ b/src/Lumina.Application/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Common/BookRatingEntityMapping.cs @@ -0,0 +1,68 @@ +#region ========================================================================= USING ===================================================================================== +using ErrorOr; +using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary; +using Lumina.Contracts.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary; +using Lumina.Domain.Common.Enums.BookLibrary; +using Lumina.Domain.Common.Primitives; +using Lumina.Domain.Core.BoundedContexts.WrittenContentLibraryBoundedContext.BookLibraryAggregate.ValueObjects; +using System.Collections.Generic; +using System.Linq; +#endregion + +namespace Lumina.Application.Common.Mapping.MediaLibrary.WrittenContentLibrary.BookLibrary.Common; + +/// +/// Extension methods for converting . +/// +public static class BookRatingEntityMapping +{ + /// + /// Converts to . + /// + /// The repository entity to be converted. + /// The converted DTO. + public static BookRatingDto ToResponse(this BookRatingEntity repositoryEntity) + { + return new BookRatingDto( + repositoryEntity.Value ?? default, + repositoryEntity.MaxValue ?? default, + repositoryEntity.Source, + repositoryEntity.VoteCount + ); + } + + /// + /// Converts to a collection of . + /// + /// The repository entities to be converted. + /// The converted DTOs. + public static IEnumerable ToResponses(this IEnumerable repositoryEntities) + { + return repositoryEntities.Select(responseEntity => responseEntity.ToResponse()); + } + + /// + /// Converts to . + /// + /// The repository entity to be converted. + /// The converted domain entity. + public static ErrorOr ToDomainEntity(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 entities to be converted. + /// The converted domain entities. + public static IEnumerable> ToDomainEntities(this IEnumerable repositoryEntities) + { + return repositoryEntities.Select(domainEntity => domainEntity.ToDomainEntity()); + } +} diff --git a/src/Lumina.Application/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Common/BookRatingMapping.cs b/src/Lumina.Application/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Common/BookRatingMapping.cs new file mode 100644 index 00000000..ec2c7f5b --- /dev/null +++ b/src/Lumina.Application/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Common/BookRatingMapping.cs @@ -0,0 +1,39 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary; +using Lumina.Domain.Core.BoundedContexts.WrittenContentLibraryBoundedContext.BookLibraryAggregate.ValueObjects; +using System.Collections.Generic; +using System.Linq; +#endregion + +namespace Lumina.Application.Common.Mapping.MediaLibrary.WrittenContentLibrary.BookLibrary.Common; + +/// +/// Extension methods for converting . +/// +public static class BookRatingMapping +{ + /// + /// Converts to . + /// + /// The domain entity to be converted. + /// The converted repository entity. + public static BookRatingEntity ToRepositoryEntity(this BookRating domainEntity) + { + return new BookRatingEntity( + domainEntity.Value, + domainEntity.MaxValue, + domainEntity.Source.HasValue ? domainEntity.Source.Value : null, + domainEntity.VoteCount.HasValue ? domainEntity.VoteCount.Value : null + ); + } + + /// + /// Converts to a collection of . + /// + /// The domain entities to be converted. + /// The converted repository entities. + public static IEnumerable ToRepositoryEntities(this IEnumerable domainEntities) + { + return domainEntities.Select(domainEntity => domainEntity.ToRepositoryEntity()); + } +} diff --git a/src/Lumina.Application/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Common/IsbnDtoMapping.cs b/src/Lumina.Application/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Common/IsbnDtoMapping.cs new file mode 100644 index 00000000..407edcb1 --- /dev/null +++ b/src/Lumina.Application/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Common/IsbnDtoMapping.cs @@ -0,0 +1,41 @@ +#region ========================================================================= USING ===================================================================================== +using ErrorOr; +using Lumina.Contracts.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary; +using Lumina.Domain.Common.Enums.BookLibrary; +using Lumina.Domain.Core.BoundedContexts.WrittenContentLibraryBoundedContext.BookLibraryAggregate.ValueObjects; +using System.Collections.Generic; +using System.Linq; +#endregion + +namespace Lumina.Application.Common.Mapping.MediaLibrary.WrittenContentLibrary.BookLibrary.Common; + +/// +/// Extension methods for converting . +/// +public static class IsbnDtoMapping +{ + /// + /// Converts to . + /// + /// The DTO to be converted. + /// + /// An containing either a successfully converted , or an error message. + /// + public static ErrorOr ToDomainEntity(this IsbnDto dto) + { + return Isbn.Create( + dto.Value, + dto.Format ?? IsbnFormat.Isbn13 + ); + } + + /// + /// Converts to a collection of . + /// + /// The DTOs to be converted. + /// The converted domain entities. + public static IEnumerable> ToDomainEntities(this IEnumerable dtos) + { + return dtos.Select(domainEntity => domainEntity.ToDomainEntity()); + } +} diff --git a/src/Lumina.Application/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Common/IsbnEntityMapping.cs b/src/Lumina.Application/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Common/IsbnEntityMapping.cs new file mode 100644 index 00000000..f889d41a --- /dev/null +++ b/src/Lumina.Application/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Common/IsbnEntityMapping.cs @@ -0,0 +1,62 @@ +#region ========================================================================= USING ===================================================================================== +using ErrorOr; +using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary; +using Lumina.Contracts.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary; +using Lumina.Domain.Core.BoundedContexts.WrittenContentLibraryBoundedContext.BookLibraryAggregate.ValueObjects; +using System.Collections.Generic; +using System.Linq; +#endregion + +namespace Lumina.Application.Common.Mapping.MediaLibrary.WrittenContentLibrary.BookLibrary.Common; + +/// +/// Extension methods for converting . +/// +public static class IsbnEntityMapping +{ + /// + /// Converts to . + /// + /// The repository entity to be converted. + /// The converted DTO. + public static IsbnDto ToResponse(this IsbnEntity repositoryEntity) + { + return new IsbnDto( + repositoryEntity.Value ?? default, + repositoryEntity.Format ?? null + ); + } + + /// + /// Converts to a collection of . + /// + /// The repository entities to be converted. + /// The converted DTOs. + public static IEnumerable ToResponses(this IEnumerable repositoryEntities) + { + return repositoryEntities.Select(responseEntity => responseEntity.ToResponse()); + } + + /// + /// Converts to . + /// + /// The repository entity to be converted. + /// The converted domain entity. + public static ErrorOr ToDomainEntity(this IsbnEntity repositoryEntity) + { + return Isbn.Create( + repositoryEntity.Value ?? default, + repositoryEntity.Format ?? default + ); + } + + /// + /// Converts to a collection of . + /// + /// The repository entities to be converted. + /// The converted domain entities. + public static IEnumerable> ToDomainEntities(this IEnumerable repositoryEntities) + { + return repositoryEntities.Select(domainEntity => domainEntity.ToDomainEntity()); + } +} diff --git a/src/Lumina.Application/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Common/IsbnMapping.cs b/src/Lumina.Application/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Common/IsbnMapping.cs new file mode 100644 index 00000000..a49b9728 --- /dev/null +++ b/src/Lumina.Application/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Common/IsbnMapping.cs @@ -0,0 +1,37 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary; +using Lumina.Domain.Core.BoundedContexts.WrittenContentLibraryBoundedContext.BookLibraryAggregate.ValueObjects; +using System.Collections.Generic; +using System.Linq; +#endregion + +namespace Lumina.Application.Common.Mapping.MediaLibrary.WrittenContentLibrary.BookLibrary.Common; + +/// +/// Extension methods for converting . +/// +public static class IsbnMapping +{ + /// + /// Converts to . + /// + /// The domain entity to be converted. + /// The converted repository entity. + public static IsbnEntity ToRepositoryEntity(this Isbn domainEntity) + { + return new IsbnEntity( + domainEntity.Value, + domainEntity.Format + ); + } + + /// + /// Converts to a collection of . + /// + /// The domain entities to be converted. + /// The converted repository entities. + public static IEnumerable ToRepositoryEntities(this IEnumerable domainEntities) + { + return domainEntities.Select(domainEntity => domainEntity.ToRepositoryEntity()); + } +} diff --git a/src/Lumina.Application/Common/Mapping/UsersManagement/Users/UserEntityMapping.cs b/src/Lumina.Application/Common/Mapping/UsersManagement/Users/UserEntityMapping.cs new file mode 100644 index 00000000..1eccd2c6 --- /dev/null +++ b/src/Lumina.Application/Common/Mapping/UsersManagement/Users/UserEntityMapping.cs @@ -0,0 +1,27 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Entities.UsersManagement; +using Lumina.Contracts.Responses.UsersManagement.Users; +#endregion + +namespace Lumina.Application.Common.Mapping.UsersManagement.Users; + +/// +/// Extension methods for converting . +/// +public static class UserEntityMapping +{ + /// + /// Converts to . + /// + /// The repository entity to be converted. + /// The converted response entity. + public static UserResponse ToResponse(this UserEntity repositoryEntity) + { + return new UserResponse( + repositoryEntity.Id, + repositoryEntity.Username, + repositoryEntity.Created, + repositoryEntity.Updated + ); + } +} diff --git a/src/Lumina.Application/Common/Mapping/UsersManagement/Users/UserMapping.cs b/src/Lumina.Application/Common/Mapping/UsersManagement/Users/UserMapping.cs new file mode 100644 index 00000000..9b8a6ad3 --- /dev/null +++ b/src/Lumina.Application/Common/Mapping/UsersManagement/Users/UserMapping.cs @@ -0,0 +1,29 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Entities.UsersManagement; +using Lumina.Domain.Core.BoundedContexts.UserManagementBoundedContext.UserAggregate; +#endregion + +namespace Lumina.Application.Common.Mapping.UsersManagement.Users; + +/// +/// Extension methods for converting . +/// +public static class UserMapping +{ + /// + /// Converts to . + /// + /// The domain entity to be converted. + /// The repository entity containing sensitive information not mapped to the Domain entity. + /// + /// Because Authentication and Authorization are Application Layer concerns, the members involved in those concerns are not mirrored in the Domain entity. + /// However, since Entity Framework updates an entire entity, when mapping from the Domain entity to the DAL entity, one still needs to provide the + /// values of the non-included members, such that they are not overriden with . Those values should come in the requested . + /// + /// The converted repository entity. + public static UserEntity ToRepositoryEntity(this User domainEntity, UserEntity repositoryEntity) + { + repositoryEntity.Username = domainEntity.Username; + return repositoryEntity; + } +} 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/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..ea47bb58 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.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Services; +using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Entities; 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 90% 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..ccc9782d 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.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.Application.Common.Mapping.FileSystemManagement.FileSystem; +using Lumina.Domain.Common.Enums.FileSystem; +using Lumina.Contracts.Responses.FileSystemManagement.Common; +using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate; +using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Entities; +using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Services; +using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.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..1e46d6a3 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.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Services; +using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Entities; 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..06591796 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.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate; +using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.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 83% 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..255cafcd 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.BoundedContexts.FileSystemManagementBoundedContext.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..57e79a1b 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.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Entities; +using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.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..6bbb0023 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.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Entities; +using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.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..6a3444c5 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.BoundedContexts.FileSystemManagementBoundedContext.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..ed8fd8c5 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.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Services; +using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.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 81% 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..7004ac97 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.BoundedContexts.FileSystemManagementBoundedContext.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..2f11a756 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.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Services; +using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.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..bfb44983 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.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Services; +using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.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 84% 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..e57fc0b9 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.BoundedContexts.FileSystemManagementBoundedContext.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 72% 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..3553ade7 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.BoundedContexts.FileSystemManagementBoundedContext.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..5475c23e 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.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Services; +using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.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/Maintenance/ApplicationSetup/Commands/SetupApplication/SetupApplicationCommand.cs b/src/Lumina.Application/Core/Maintenance/ApplicationSetup/Commands/SetupApplication/SetupApplicationCommand.cs new file mode 100644 index 00000000..8d9c161a --- /dev/null +++ b/src/Lumina.Application/Core/Maintenance/ApplicationSetup/Commands/SetupApplication/SetupApplicationCommand.cs @@ -0,0 +1,21 @@ +#region ========================================================================= USING ===================================================================================== +using ErrorOr; +using Lumina.Contracts.Responses.Authentication; +using Mediator; +#endregion + +namespace Lumina.Application.Core.Maintenance.ApplicationSetup.Commands.SetupApplication; + +/// +/// Command for the initial application setup. +/// +/// The username for the Admin account. +/// The password for the Admin account. +/// Confirmation of the password. +/// Indicates whether to enable two-factor authentication for the Admin account. +public record SetupApplicationCommand( + string? Username, + string? Password, + string? PasswordConfirm, + bool Use2fa +) : IRequest>; diff --git a/src/Lumina.Application/Core/Maintenance/ApplicationSetup/Commands/SetupApplication/SetupApplicationCommandHandler.cs b/src/Lumina.Application/Core/Maintenance/ApplicationSetup/Commands/SetupApplication/SetupApplicationCommandHandler.cs new file mode 100644 index 00000000..5f2ce8b7 --- /dev/null +++ b/src/Lumina.Application/Core/Maintenance/ApplicationSetup/Commands/SetupApplication/SetupApplicationCommandHandler.cs @@ -0,0 +1,99 @@ +#region ========================================================================= USING ===================================================================================== +using ErrorOr; +using Lumina.Application.Common.DataAccess.Entities.UsersManagement; +using Lumina.Application.Common.DataAccess.Repositories.Users; +using Lumina.Application.Common.DataAccess.UoW; +using Lumina.Application.Common.Errors; +using Lumina.Application.Common.Infrastructure.Authentication; +using Lumina.Application.Common.Infrastructure.Security; +using Lumina.Contracts.Responses.Authentication; +using Mediator; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Application.Core.Maintenance.ApplicationSetup.Commands.SetupApplication; + +/// +/// Handler for the command to perform the initial application setup. +/// +public class SetupApplicationCommandHandler : IRequestHandler> +{ + private readonly IUnitOfWork _unitOfWork; + private readonly IHashService _hashService; + private readonly ICryptographyService _cryptographyService; + private readonly ITotpTokenGenerator _totpTokenGenerator; + private readonly IQRCodeGenerator _qRCodeGenerator; + + /// + /// Initializes a new instance of the class. + /// + /// Injected unit of work for interacting with the data access layer repositories. + /// Injected service for password hashing functionality. + /// Injected service for cryptographic functionality. + /// Injected service for generating and validating TOTP tokens. + /// Injected service for generating QR codes. + public SetupApplicationCommandHandler( + IUnitOfWork unitOfWork, + IHashService hashService, + ICryptographyService cryptographyService, + ITotpTokenGenerator totpTokenGenerator, + IQRCodeGenerator qRCodeGenerator) + { + _unitOfWork = unitOfWork; + _hashService = hashService; + _cryptographyService = cryptographyService; + _totpTokenGenerator = totpTokenGenerator; + _qRCodeGenerator = qRCodeGenerator; + } + + /// + /// Handles the command to perform the initial application setup. + /// + /// The request to be handled. + /// Cancellation token that can be used to stop the execution. + /// + /// An containing either a successfully created , or an error message. + /// + public async ValueTask> Handle(SetupApplicationCommand request, CancellationToken cancellationToken) + { + // check if any users already exists (admin account is only set once!) + IUserRepository userRepository = _unitOfWork.GetRepository(); + ErrorOr> resultSelectUser = await userRepository.GetAllAsync(cancellationToken); + if (resultSelectUser.IsError) + return resultSelectUser.Errors; + else if (resultSelectUser.Value.Any()) + return Errors.Authorization.AdminAccountAlreadyCreated; + // no users are present, register the admin one + string? totpSecret = null; + UserEntity user = new() + { + Id = Guid.NewGuid(), + Username = request.Username!, + Password = Uri.EscapeDataString(_hashService.HashString(request.Password!)), + Created = DateTime.UtcNow, + Libraries = [] + }; + // if the user enabled two factor auth, include a QR with the totp secret + if (request.Use2fa) + { + // generate a TOTP secret + byte[] secret = _totpTokenGenerator.GenerateSecret(); + // convert the secret into a QR code for the user to scan + totpSecret = _qRCodeGenerator.GenerateQrCodeDataUri(request.Username!, secret); + // store the TOTP secret in the repository, encrypted + user.TotpSecret = _cryptographyService.Encrypt(Convert.ToBase64String(secret)); + } + // insert the user + ErrorOr resultInsertUser = await userRepository.InsertAsync(user, cancellationToken); + if (resultInsertUser.IsError) + return resultInsertUser.Errors; + await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false); + // TODO: insert the default admin profile preferences when they are implemented + // if 2FA was enabled, the TOTP secret needs to be delivered to the client unhashed, so it can be displayed + return new RegistrationResponse(user.Id, user.Username, totpSecret); + } +} diff --git a/src/Lumina.Application/Core/Maintenance/ApplicationSetup/Commands/SetupApplication/SetupApplicationCommandValidator.cs b/src/Lumina.Application/Core/Maintenance/ApplicationSetup/Commands/SetupApplication/SetupApplicationCommandValidator.cs new file mode 100644 index 00000000..b7d75b24 --- /dev/null +++ b/src/Lumina.Application/Core/Maintenance/ApplicationSetup/Commands/SetupApplication/SetupApplicationCommandValidator.cs @@ -0,0 +1,24 @@ +#region ========================================================================= USING ===================================================================================== +using FluentValidation; +using Lumina.Application.Common.Errors; +#endregion + +namespace Lumina.Application.Core.Maintenance.ApplicationSetup.Commands.SetupApplication; + +/// +/// Validates the needed validation rules for . +/// +public class SetupApplicationCommandValidator : AbstractValidator +{ + /// + /// Initializes a new instance of the class. + /// + public SetupApplicationCommandValidator() + { + RuleFor(x => x.Username).NotEmpty().WithMessage(Errors.Authentication.UsernameCannotBeEmpty.Description); + RuleFor(x => x.Password).NotEmpty().WithMessage(Errors.Authentication.PasswordCannotBeEmpty.Description) + .Matches("^(?=.*[A-Z])(?=.*[0-9])(?=.*[^a-zA-Z0-9]).{8,}$").WithMessage(Errors.Authentication.InvalidPassword.Description); + RuleFor(x => x.PasswordConfirm).NotEmpty().WithMessage(Errors.Authentication.PasswordConfirmCannotBeEmpty.Description); + RuleFor(x => x.Password).Equal(x => x.PasswordConfirm).WithMessage(Errors.Authentication.PasswordsNotMatch.Description); + } +} diff --git a/src/Lumina.Application/Core/Maintenance/ApplicationSetup/Queries/CheckInitialization/CheckInitializationQuery.cs b/src/Lumina.Application/Core/Maintenance/ApplicationSetup/Queries/CheckInitialization/CheckInitializationQuery.cs new file mode 100644 index 00000000..3400a137 --- /dev/null +++ b/src/Lumina.Application/Core/Maintenance/ApplicationSetup/Queries/CheckInitialization/CheckInitializationQuery.cs @@ -0,0 +1,11 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Contracts.Responses.UsersManagement; +using Mediator; +#endregion + +namespace Lumina.Application.Core.Maintenance.ApplicationSetup.Queries.CheckInitialization; + +/// +/// Query for checking the initialization of the application. +/// +public record CheckInitializationQuery() : IRequest; diff --git a/src/Lumina.Application/Core/Maintenance/ApplicationSetup/Queries/CheckInitialization/CheckInitializationQueryHandler.cs b/src/Lumina.Application/Core/Maintenance/ApplicationSetup/Queries/CheckInitialization/CheckInitializationQueryHandler.cs new file mode 100644 index 00000000..690c99d8 --- /dev/null +++ b/src/Lumina.Application/Core/Maintenance/ApplicationSetup/Queries/CheckInitialization/CheckInitializationQueryHandler.cs @@ -0,0 +1,50 @@ +#region ========================================================================= USING ===================================================================================== +using ErrorOr; +using Lumina.Application.Common.DataAccess.Entities.UsersManagement; +using Lumina.Application.Common.DataAccess.Repositories.Users; +using Lumina.Application.Common.DataAccess.UoW; +using Lumina.Contracts.Responses.FileSystemManagement.Path; +using Lumina.Contracts.Responses.UsersManagement; +using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Services; +using Mediator; +using System.Collections.Generic; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Application.Core.Maintenance.ApplicationSetup.Queries.CheckInitialization; + +/// +/// Handler for the query to check the initialization of the application. +/// +public class CheckInitializationQueryHandler : IRequestHandler +{ + private readonly IUnitOfWork _unitOfWork; + + /// + /// Initializes a new instance of the class. + /// + public CheckInitializationQueryHandler(IUnitOfWork unitOfWork) + { + _unitOfWork = unitOfWork; + } + + /// + /// Checks the initialization status of the application. + /// + /// The query containing the request. + /// Cancellation token that can be used to stop the execution. + /// + /// if the application is initialized (the admin account is created), otherwise. + /// + public async ValueTask Handle(CheckInitializationQuery request, CancellationToken cancellationToken) + { + IUserRepository userRepository = _unitOfWork.GetRepository(); + // if the repository reports an error, or there are no users, the application has not been initialized + ErrorOr> resultSelectUser = await userRepository.GetAllAsync(cancellationToken); + if (!resultSelectUser.IsError) + return new InitializationResponse(resultSelectUser.Value.Any()); + return new InitializationResponse(false); + } +} diff --git a/src/Lumina.Application/Core/MediaLibrary/Management/Commands/AddLibrary/AddLibraryCommand.cs b/src/Lumina.Application/Core/MediaLibrary/Management/Commands/AddLibrary/AddLibraryCommand.cs new file mode 100644 index 00000000..067a0519 --- /dev/null +++ b/src/Lumina.Application/Core/MediaLibrary/Management/Commands/AddLibrary/AddLibraryCommand.cs @@ -0,0 +1,25 @@ +#region ========================================================================= USING ===================================================================================== +using ErrorOr; +using Lumina.Domain.Common.Enums.MediaLibrary; +using Lumina.Contracts.Responses.MediaLibrary.Management; +using Mediator; +using System; +using System.Diagnostics; +#endregion + +namespace Lumina.Application.Core.MediaLibrary.Management.Commands.AddLibrary; + +/// +/// Command for adding a media library. +/// +/// The Id of the user owning the media library. +/// The type of the media library. +/// The file system paths of the directories where the media library elements are located. +/// The title of the media library. +[DebuggerDisplay("Title: {Title}")] +public record AddLibraryCommand( + Guid UserId, + string? Title, + LibraryType? LibraryType, + string[]? ContentLocations +) : IRequest>; diff --git a/src/Lumina.Application/Core/MediaLibrary/Management/Commands/AddLibrary/AddLibraryCommandHandler.cs b/src/Lumina.Application/Core/MediaLibrary/Management/Commands/AddLibrary/AddLibraryCommandHandler.cs new file mode 100644 index 00000000..1e51e519 --- /dev/null +++ b/src/Lumina.Application/Core/MediaLibrary/Management/Commands/AddLibrary/AddLibraryCommandHandler.cs @@ -0,0 +1,62 @@ +#region ========================================================================= USING ===================================================================================== +using ErrorOr; +using Lumina.Application.Common.DataAccess.Repositories.MediaLibrary; +using Lumina.Application.Common.DataAccess.UoW; +using Lumina.Application.Common.Mapping.MediaLibrary.Management; +using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management; +using Lumina.Domain.Common.Enums.MediaLibrary; +using Lumina.Contracts.Responses.MediaLibrary.Management; +using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate; +using Mediator; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Application.Core.MediaLibrary.Management.Commands.AddLibrary; + +/// +/// Handler for the command to add a media library. +/// +public class AddLibraryCommandHandler : IRequestHandler> +{ + private readonly IUnitOfWork _unitOfWork; + + /// + /// Initializes a new instance of the class. + /// + /// Injected unit of work for interacting with the data access layer repositories. + public AddLibraryCommandHandler(IUnitOfWork unitOfWork) + { + _unitOfWork = unitOfWork; + } + + /// + /// Handles the command to add a media library. + /// + /// The request to be handled. + /// Cancellation token that can be used to stop the execution. + /// + /// An containing either a successfully created , or an error message. + /// + public async ValueTask> Handle(AddLibraryCommand request, CancellationToken cancellationToken) + { + ErrorOr createLibraryResult = Library.Create( + request.UserId, + request.Title!, + request.LibraryType ?? LibraryType.Other, + request.ContentLocations! + ); + + if (createLibraryResult.IsError) + return createLibraryResult.Errors; + + ILibraryRepository libraryRepository = _unitOfWork.GetRepository(); + LibraryEntity persistenceLibrary = createLibraryResult.Value.ToRepositoryEntity(); + ErrorOr insertLibraryResult = await libraryRepository.InsertAsync(persistenceLibrary, cancellationToken).ConfigureAwait(false); + if (insertLibraryResult.IsError) + return insertLibraryResult.Errors; + await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false); + + return persistenceLibrary.ToResponse(); + } +} diff --git a/src/Lumina.Application/Core/MediaLibrary/Management/Commands/AddLibrary/AddLibraryCommandValidator.cs b/src/Lumina.Application/Core/MediaLibrary/Management/Commands/AddLibrary/AddLibraryCommandValidator.cs new file mode 100644 index 00000000..4d7d88a8 --- /dev/null +++ b/src/Lumina.Application/Core/MediaLibrary/Management/Commands/AddLibrary/AddLibraryCommandValidator.cs @@ -0,0 +1,39 @@ +#region ========================================================================= USING ===================================================================================== +using FluentValidation; +using Lumina.Domain.Common.Errors; +using System; +#endregion + +namespace Lumina.Application.Core.MediaLibrary.Management.Commands.AddLibrary; + +/// +/// Validates the needed validation rules for . +/// +public class AddLibraryCommandValidator : AbstractValidator +{ + /// + /// Initializes a new instance of the class. + /// + public AddLibraryCommandValidator() + { + RuleFor(x => x.UserId) + .NotEmpty().WithMessage(Errors.Library.UserIdCannotBeEmpty.Description) + .Must(id => id != Guid.Empty).WithMessage(Errors.Library.UserIdCannotBeEmpty.Description); + + RuleFor(x => x.LibraryType) + .NotNull().WithMessage(Errors.Library.LibraryTypeCannotBeNull.Description) + .IsInEnum().WithMessage(Errors.Library.UnknownLibraryType.Description); + + RuleFor(x => x.ContentLocations) + .NotNull().WithMessage(Errors.Library.PathsListCannotBeNull.Description) + .NotEmpty().WithMessage(Errors.Library.PathsListCannotBeEmpty.Description); + + RuleForEach(x => x.ContentLocations) + .NotEmpty().WithMessage(Errors.FileSystemManagement.PathCannotBeEmpty.Description) + .MaximumLength(260).WithMessage(Errors.FileSystemManagement.PathMustBeMaximum260CharactersLong.Description); + + RuleFor(x => x.Title) + .NotEmpty().WithMessage(Errors.Library.TitleCannotBeEmpty.Description) + .MaximumLength(255).WithMessage(Errors.Library.TitleMustBeMaximum255CharactersLong.Description); + } +} diff --git a/src/Lumina.Application/Core/WrittenContentLibrary/BooksLibrary/Books/Commands/AddBook/AddBookCommand.cs b/src/Lumina.Application/Core/MediaLibrary/WrittenContentLibrary/BooksLibrary/Books/Commands/AddBook/AddBookCommand.cs similarity index 75% rename from src/Lumina.Application/Core/WrittenContentLibrary/BooksLibrary/Books/Commands/AddBook/AddBookCommand.cs rename to src/Lumina.Application/Core/MediaLibrary/WrittenContentLibrary/BooksLibrary/Books/Commands/AddBook/AddBookCommand.cs index cff7a7b3..707d829f 100644 --- a/src/Lumina.Application/Core/WrittenContentLibrary/BooksLibrary/Books/Commands/AddBook/AddBookCommand.cs +++ b/src/Lumina.Application/Core/MediaLibrary/WrittenContentLibrary/BooksLibrary/Books/Commands/AddBook/AddBookCommand.cs @@ -1,15 +1,16 @@ #region ========================================================================= USING ===================================================================================== using ErrorOr; -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.Domain.Common.Enums.BookLibrary; +using Lumina.Contracts.Responses.MediaLibrary.WrittenContentLibrary.BookLibrary.Books; using Mediator; using System.Collections.Generic; +using System.Diagnostics; +using Lumina.Contracts.DTO.MediaContributors; +using Lumina.Contracts.DTO.MediaLibrary.WrittenContentLibrary; +using Lumina.Contracts.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary; #endregion -namespace Lumina.Application.Core.WrittenContentLibrary.BooksLibrary.Books.Commands.AddBook; +namespace Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BooksLibrary.Books.Commands.AddBook; /// /// Command for adding a book. @@ -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, + WrittenContentMetadataDto? Metadata, BookFormat? Format, string? Edition, int? VolumeNumber, - BookSeriesModel? Series, + BookSeriesDto? 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/MediaLibrary/WrittenContentLibrary/BooksLibrary/Books/Commands/AddBook/AddBookCommandHandler.cs similarity index 81% rename from src/Lumina.Application/Core/WrittenContentLibrary/BooksLibrary/Books/Commands/AddBook/AddBookCommandHandler.cs rename to src/Lumina.Application/Core/MediaLibrary/WrittenContentLibrary/BooksLibrary/Books/Commands/AddBook/AddBookCommandHandler.cs index 6134d50e..1e73d67a 100644 --- a/src/Lumina.Application/Core/WrittenContentLibrary/BooksLibrary/Books/Commands/AddBook/AddBookCommandHandler.cs +++ b/src/Lumina.Application/Core/MediaLibrary/WrittenContentLibrary/BooksLibrary/Books/Commands/AddBook/AddBookCommandHandler.cs @@ -2,43 +2,41 @@ using ErrorOr; using Lumina.Application.Common.DataAccess.Repositories.Books; using Lumina.Application.Common.DataAccess.UoW; -using Lumina.Contracts.Enums.BookLibrary; -using Lumina.Contracts.Models.MediaContributors; -using Lumina.Contracts.Models.WrittenContentLibrary.BookLibrary; +using Lumina.Application.Common.Mapping.MediaLibrary.WrittenContentLibrary.BookLibrary.Books; +using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary; +using Lumina.Domain.Common.Enums.BookLibrary; +using Lumina.Contracts.Responses.MediaLibrary.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 Lumina.Domain.Core.BoundedContexts.MediaContributorBoundedContext.MediaContributorAggregate.ValueObjects; +using Lumina.Domain.Core.BoundedContexts.WrittenContentLibraryBoundedContext.BookLibraryAggregate; +using Lumina.Domain.Core.BoundedContexts.WrittenContentLibraryBoundedContext.BookLibraryAggregate.Entities; +using Lumina.Domain.Core.BoundedContexts.WrittenContentLibraryBoundedContext.BookLibraryAggregate.ValueObjects; using Mediator; using System; using System.Collections.Generic; using System.Linq; using System.Threading; using System.Threading.Tasks; +using Lumina.Contracts.DTO.MediaContributors; #endregion -namespace Lumina.Application.Core.WrittenContentLibrary.BooksLibrary.Books.Commands.AddBook; +namespace Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BooksLibrary.Books.Commands.AddBook; /// /// 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; } /// @@ -47,13 +45,13 @@ public class AddBookCommandHandler : IRequestHandlerThe request to be handled. /// Cancellation token that can be used to stop the execution. /// - /// An containing either a successfully created , or an error message. + /// 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 (MediaContributorDto 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/MediaLibrary/WrittenContentLibrary/BooksLibrary/Books/Commands/AddBook/AddBookCommandValidator.cs similarity index 53% rename from src/Lumina.Application/Core/WrittenContentLibrary/BooksLibrary/Books/Commands/AddBook/AddBookCommandValidator.cs rename to src/Lumina.Application/Core/MediaLibrary/WrittenContentLibrary/BooksLibrary/Books/Commands/AddBook/AddBookCommandValidator.cs index 2b554f54..631c49ee 100644 --- a/src/Lumina.Application/Core/WrittenContentLibrary/BooksLibrary/Books/Commands/AddBook/AddBookCommandValidator.cs +++ b/src/Lumina.Application/Core/MediaLibrary/WrittenContentLibrary/BooksLibrary/Books/Commands/AddBook/AddBookCommandValidator.cs @@ -1,10 +1,10 @@ #region ========================================================================= USING ===================================================================================== using FluentValidation; -using Lumina.Contracts.Enums.BookLibrary; +using Lumina.Domain.Common.Enums.BookLibrary; using Lumina.Domain.Common.Errors; #endregion -namespace Lumina.Application.Core.WrittenContentLibrary.BooksLibrary.Books.Commands.AddBook; +namespace Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BooksLibrary.Books.Commands.AddBook; /// /// Validates the needed validation rules for . @@ -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/MediaLibrary/WrittenContentLibrary/BooksLibrary/Books/Queries/GetBooks/GetBooksQuery.cs b/src/Lumina.Application/Core/MediaLibrary/WrittenContentLibrary/BooksLibrary/Books/Queries/GetBooks/GetBooksQuery.cs new file mode 100644 index 00000000..85fe67f8 --- /dev/null +++ b/src/Lumina.Application/Core/MediaLibrary/WrittenContentLibrary/BooksLibrary/Books/Queries/GetBooks/GetBooksQuery.cs @@ -0,0 +1,13 @@ +#region ========================================================================= USING ===================================================================================== +using ErrorOr; +using Lumina.Contracts.Responses.MediaLibrary.WrittenContentLibrary.BookLibrary.Books; +using Mediator; +using System.Collections.Generic; +#endregion + +namespace Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BooksLibrary.Books.Queries.GetBooks; + +/// +/// Query for getting all books. +/// +public record class GetBooksQuery() : IRequest>>; diff --git a/src/Lumina.Application/Core/WrittenContentLibrary/BooksLibrary/Books/Queries/GetBooks/GetBooksQueryHandler.cs b/src/Lumina.Application/Core/MediaLibrary/WrittenContentLibrary/BooksLibrary/Books/Queries/GetBooks/GetBooksQueryHandler.cs similarity index 59% rename from src/Lumina.Application/Core/WrittenContentLibrary/BooksLibrary/Books/Queries/GetBooks/GetBooksQueryHandler.cs rename to src/Lumina.Application/Core/MediaLibrary/WrittenContentLibrary/BooksLibrary/Books/Queries/GetBooks/GetBooksQueryHandler.cs index 65d3b556..826ddac7 100644 --- a/src/Lumina.Application/Core/WrittenContentLibrary/BooksLibrary/Books/Queries/GetBooks/GetBooksQueryHandler.cs +++ b/src/Lumina.Application/Core/MediaLibrary/WrittenContentLibrary/BooksLibrary/Books/Queries/GetBooks/GetBooksQueryHandler.cs @@ -1,22 +1,22 @@ #region ========================================================================= USING ===================================================================================== using ErrorOr; +using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary; 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.MediaLibrary.WrittenContentLibrary.BookLibrary.Books; +using Lumina.Contracts.Responses.MediaLibrary.WrittenContentLibrary.BookLibrary.Books; using Mediator; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; #endregion -namespace Lumina.Application.Core.WrittenContentLibrary.BooksLibrary.Books.Queries.GetBooks; +namespace Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BooksLibrary.Books.Queries.GetBooks; /// /// 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/Core/UsersManagement/Authentication/Commands/ChangePassword/ChangePasswordCommand.cs b/src/Lumina.Application/Core/UsersManagement/Authentication/Commands/ChangePassword/ChangePasswordCommand.cs new file mode 100644 index 00000000..5bc40ef0 --- /dev/null +++ b/src/Lumina.Application/Core/UsersManagement/Authentication/Commands/ChangePassword/ChangePasswordCommand.cs @@ -0,0 +1,21 @@ +#region ========================================================================= USING ===================================================================================== +using ErrorOr; +using Lumina.Contracts.Responses.Authentication; +using Mediator; +#endregion + +namespace Lumina.Application.Core.UsersManagement.Authentication.Commands.ChangePassword; + +/// +/// Represents the request model for account password change. +/// +/// The username of the account for which to change the password. +/// The current password of the account for which to change the password. +/// The new password of the account for which to change the password. +/// The confirmation of the new password of the account for which to change the password. +public record ChangePasswordCommand( + string? Username, + string? CurrentPassword, + string? NewPassword, + string? NewPasswordConfirm +) : IRequest>; diff --git a/src/Lumina.Application/Core/UsersManagement/Authentication/Commands/ChangePassword/ChangePasswordCommandHandler.cs b/src/Lumina.Application/Core/UsersManagement/Authentication/Commands/ChangePassword/ChangePasswordCommandHandler.cs new file mode 100644 index 00000000..79cd59df --- /dev/null +++ b/src/Lumina.Application/Core/UsersManagement/Authentication/Commands/ChangePassword/ChangePasswordCommandHandler.cs @@ -0,0 +1,68 @@ +#region ========================================================================= USING ===================================================================================== +using ErrorOr; +using Lumina.Application.Common.DataAccess.Entities.UsersManagement; +using Lumina.Application.Common.DataAccess.Repositories.Users; +using Lumina.Application.Common.DataAccess.UoW; +using Lumina.Application.Common.Errors; +using Lumina.Application.Common.Infrastructure.Security; +using Lumina.Contracts.Responses.Authentication; +using Mediator; +using System; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Application.Core.UsersManagement.Authentication.Commands.ChangePassword; + +/// +/// Handler for the command to change the password of a user account. +/// +public class ChangePasswordCommandHandler : IRequestHandler> +{ + private readonly IUnitOfWork _unitOfWork; + private readonly IHashService _hashService; + + /// + /// Initializes a new instance of the class. + /// + /// Injected unit of work for interacting with the data access layer repositories. + /// Injected service for password hashing functionality. + public ChangePasswordCommandHandler( + IUnitOfWork unitOfWork, + IHashService hashService) + { + _unitOfWork = unitOfWork; + _hashService = hashService; + } + + /// + /// Handles the command to change the password of an account. + /// + /// The request to be handled. + /// Cancellation token that can be used to stop the execution. + /// + /// An containing either a successfully created , or an error message. + /// + public async ValueTask> Handle(ChangePasswordCommand request, CancellationToken cancellationToken) + { + IUserRepository userRepository = _unitOfWork.GetRepository(); + ErrorOr resultSelectUser = await userRepository.GetByUsernameAsync(request.Username!, cancellationToken); + if (resultSelectUser.IsError) + return resultSelectUser.Errors; + else if (resultSelectUser.Value is null) + return Errors.Authentication.UsernameDoesNotExist; + // validate if the current password is correct + if (!_hashService.CheckStringAgainstHash(request.CurrentPassword!, Uri.UnescapeDataString(resultSelectUser.Value.Password!))) + return Errors.Authentication.InvalidCurrentPassword; + resultSelectUser.Value.Password = Uri.EscapeDataString(_hashService.HashString(request.NewPassword!)); + // if the password change was initiated via a password reset, remote the temporary password that was generated in the process + resultSelectUser.Value.TempPassword = null; + resultSelectUser.Value.TempPasswordCreated = null; + // update the user + ErrorOr resultUpdateUser = await userRepository.UpdateAsync(resultSelectUser.Value, cancellationToken); + if (resultUpdateUser.IsError) + return resultUpdateUser.Errors; + await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false); + return new ChangePasswordResponse(true); + } +} diff --git a/src/Lumina.Application/Core/UsersManagement/Authentication/Commands/ChangePassword/ChangePasswordCommandValidator.cs b/src/Lumina.Application/Core/UsersManagement/Authentication/Commands/ChangePassword/ChangePasswordCommandValidator.cs new file mode 100644 index 00000000..a1168e39 --- /dev/null +++ b/src/Lumina.Application/Core/UsersManagement/Authentication/Commands/ChangePassword/ChangePasswordCommandValidator.cs @@ -0,0 +1,26 @@ +#region ========================================================================= USING ===================================================================================== +using FluentValidation; +using Lumina.Application.Common.Errors; +#endregion + +namespace Lumina.Application.Core.UsersManagement.Authentication.Commands.ChangePassword; + +/// +/// Validates the needed validation rules for . +/// +public class ChangePasswordCommandValidator : AbstractValidator +{ + /// + /// Initializes a new instance of the class. + /// + public ChangePasswordCommandValidator() + { + RuleFor(x => x.Username).NotEmpty().WithMessage(Errors.Authentication.UsernameCannotBeEmpty.Description); + RuleFor(x => x.CurrentPassword).NotEmpty().WithMessage(Errors.Authentication.CurrentPasswordCannotBeEmpty.Description) + .Matches("^(?=.*[A-Z])(?=.*[0-9])(?=.*[^a-zA-Z0-9]).{8,}$").WithMessage(Errors.Authentication.InvalidPassword.Description); + RuleFor(x => x.NewPassword).NotEmpty().WithMessage(Errors.Authentication.NewPasswordCannotBeEmpty.Description) + .Matches("^(?=.*[A-Z])(?=.*[0-9])(?=.*[^a-zA-Z0-9]).{8,}$").WithMessage(Errors.Authentication.InvalidPassword.Description); + RuleFor(x => x.NewPasswordConfirm).NotEmpty().WithMessage(Errors.Authentication.NewPasswordConfirmCannotBeEmpty.Description); + RuleFor(x => x.NewPassword).Equal(x => x.NewPasswordConfirm).WithMessage(Errors.Authentication.PasswordsNotMatch.Description); + } +} diff --git a/src/Lumina.Application/Core/UsersManagement/Authentication/Commands/RecoverPassword/RecoverPasswordCommand.cs b/src/Lumina.Application/Core/UsersManagement/Authentication/Commands/RecoverPassword/RecoverPasswordCommand.cs new file mode 100644 index 00000000..a4854a4e --- /dev/null +++ b/src/Lumina.Application/Core/UsersManagement/Authentication/Commands/RecoverPassword/RecoverPasswordCommand.cs @@ -0,0 +1,19 @@ +#region ========================================================================= USING ===================================================================================== +using ErrorOr; +using Lumina.Contracts.Responses.Authentication; +using Mediator; +using System.Diagnostics; +#endregion + +namespace Lumina.Application.Core.UsersManagement.Authentication.Commands.RecoverPassword; + +/// +/// Represents the request model for account password recovery. +/// +/// The username of the account for which to recover the password. +/// The TOTP (Time-Based One-Time Password) of the account for which to recover the password. +[DebuggerDisplay("Username: {Username}")] +public record class RecoverPasswordCommand( + string? Username, + string? TotpCode +) : IRequest>; diff --git a/src/Lumina.Application/Core/UsersManagement/Authentication/Commands/RecoverPassword/RecoverPasswordCommandHandler.cs b/src/Lumina.Application/Core/UsersManagement/Authentication/Commands/RecoverPassword/RecoverPasswordCommandHandler.cs new file mode 100644 index 00000000..6030c904 --- /dev/null +++ b/src/Lumina.Application/Core/UsersManagement/Authentication/Commands/RecoverPassword/RecoverPasswordCommandHandler.cs @@ -0,0 +1,85 @@ +#region ========================================================================= USING ===================================================================================== +using ErrorOr; +using Lumina.Application.Common.DataAccess.Entities.UsersManagement; +using Lumina.Application.Common.DataAccess.Repositories.Users; +using Lumina.Application.Common.DataAccess.UoW; +using Lumina.Application.Common.Errors; +using Lumina.Application.Common.Infrastructure.Authentication; +using Lumina.Application.Common.Infrastructure.Security; +using Lumina.Contracts.Responses.Authentication; +using Mediator; +using System; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Application.Core.UsersManagement.Authentication.Commands.RecoverPassword; + +/// +/// Handler for the command to recover the password of an account. +/// +public class RecoverPasswordCommandHandler : IRequestHandler> +{ + private readonly IUnitOfWork _unitOfWork; + private readonly IHashService _hashService; + private readonly ITotpTokenGenerator _totpTokenGenerator; + private readonly ICryptographyService _cryptographyService; + + /// + /// Initializes a new instance of the class. + /// + /// Injected unit of work for interacting with the data access layer repositories. + /// Injected service for password hashing functionality. + /// Injected service for generating and validating TOTP tokens. + /// Injected service for cryptographic functionality. + public RecoverPasswordCommandHandler( + IUnitOfWork unitOfWork, + IHashService hashService, + ITotpTokenGenerator totpTokenGenerator, + ICryptographyService cryptographyService) + { + _unitOfWork = unitOfWork; + _hashService = hashService; + _totpTokenGenerator = totpTokenGenerator; + _cryptographyService = cryptographyService; + } + + /// + /// Handles the command to recover the password of an account. + /// + /// The request to be handled. + /// Cancellation token that can be used to stop the execution. + /// + /// An containing either a successfully created , or an error message. + /// + public async ValueTask> Handle(RecoverPasswordCommand request, CancellationToken cancellationToken) + { + // check if any users already exists + IUserRepository userRepository = _unitOfWork.GetRepository(); + ErrorOr resultSelectUser = await userRepository.GetByUsernameAsync(request.Username!, cancellationToken); + if (resultSelectUser.IsError) + return resultSelectUser.Errors; + else if (resultSelectUser.Value is null) + return Errors.Authentication.UsernameDoesNotExist; + else if (resultSelectUser.Value.TempPassword is not null) // if a temp password is present, a password request was already requested + return Errors.Authentication.PasswordResetAlreadyRequested; + // check if the user uses TOTP + bool usesTotp = !string.IsNullOrEmpty(resultSelectUser.Value.TotpSecret); + if (!usesTotp) + return Errors.Authentication.InvalidTotpCode; + if (usesTotp && string.IsNullOrEmpty(request.TotpCode)) + return Errors.Authentication.InvalidTotpCode; + else if (usesTotp && !string.IsNullOrEmpty(request.TotpCode)) // and if they do, validate it + if (!_totpTokenGenerator.ValidateToken(Convert.FromBase64String(_cryptographyService.Decrypt(resultSelectUser.Value.TotpSecret!)), request.TotpCode)) + return Errors.Authentication.InvalidTotpCode; + // hash the new password and assign it to a temporary password that will be valid 15 minutes + resultSelectUser.Value.TempPassword = Uri.EscapeDataString(_hashService.HashString("Abcd123$")); // TODO: replace with random password generator + resultSelectUser.Value.TempPasswordCreated = DateTime.UtcNow; + // update the user + ErrorOr resultUpdateUser = await userRepository.UpdateAsync(resultSelectUser.Value, cancellationToken); + if (resultUpdateUser.IsError) + return resultUpdateUser.Errors; + await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false); + return new RecoverPasswordResponse(true); + } +} diff --git a/src/Lumina.Application/Core/UsersManagement/Authentication/Commands/RecoverPassword/RecoverPasswordCommandValidator.cs b/src/Lumina.Application/Core/UsersManagement/Authentication/Commands/RecoverPassword/RecoverPasswordCommandValidator.cs new file mode 100644 index 00000000..cb82c95e --- /dev/null +++ b/src/Lumina.Application/Core/UsersManagement/Authentication/Commands/RecoverPassword/RecoverPasswordCommandValidator.cs @@ -0,0 +1,23 @@ +#region ========================================================================= USING ===================================================================================== +using FluentValidation; +using Lumina.Application.Common.Errors; +#endregion + +namespace Lumina.Application.Core.UsersManagement.Authentication.Commands.RecoverPassword; + +/// +/// Validates the needed validation rules for . +/// +public class RecoverPasswordCommandValidator : AbstractValidator +{ + /// + /// Initializes a new instance of the class. + /// + public RecoverPasswordCommandValidator() + { + RuleFor(x => x.Username).NotEmpty().WithMessage(Errors.Authentication.UsernameCannotBeEmpty.Description); + RuleFor(x => x.TotpCode).NotEmpty().WithMessage(Errors.Authentication.TotpCannotBeEmpty.Description); + RuleFor(x => x.TotpCode).Length(6).WithMessage(Errors.Authentication.InvalidTotpCode.Description); + RuleFor(x => x.TotpCode).Matches(@"^[0-9]{6}$").WithMessage(Errors.Authentication.InvalidTotpCode.Description); + } +} diff --git a/src/Lumina.Application/Core/UsersManagement/Authentication/Commands/RegisterUser/RegisterUserCommand.cs b/src/Lumina.Application/Core/UsersManagement/Authentication/Commands/RegisterUser/RegisterUserCommand.cs new file mode 100644 index 00000000..d9e29c05 --- /dev/null +++ b/src/Lumina.Application/Core/UsersManagement/Authentication/Commands/RegisterUser/RegisterUserCommand.cs @@ -0,0 +1,21 @@ +#region ========================================================================= USING ===================================================================================== +using ErrorOr; +using Lumina.Contracts.Responses.Authentication; +using Mediator; +#endregion + +namespace Lumina.Application.Core.UsersManagement.Authentication.Commands.RegisterUser; + +/// +/// Command for registering a new account. +/// +/// The username for the new account. +/// The password for the new account. +/// Confirmation of the password. +/// Indicates whether to enable two-factor authentication for the new account. +public record RegisterUserCommand( + string? Username, + string? Password, + string? PasswordConfirm, + bool Use2fa +) : IRequest>; diff --git a/src/Lumina.Application/Core/UsersManagement/Authentication/Commands/RegisterUser/RegisterUserCommandHandler.cs b/src/Lumina.Application/Core/UsersManagement/Authentication/Commands/RegisterUser/RegisterUserCommandHandler.cs new file mode 100644 index 00000000..9db2c4c4 --- /dev/null +++ b/src/Lumina.Application/Core/UsersManagement/Authentication/Commands/RegisterUser/RegisterUserCommandHandler.cs @@ -0,0 +1,96 @@ +#region ========================================================================= USING ===================================================================================== +using ErrorOr; +using Lumina.Application.Common.DataAccess.Entities.UsersManagement; +using Lumina.Application.Common.DataAccess.Repositories.Users; +using Lumina.Application.Common.DataAccess.UoW; +using Lumina.Application.Common.Errors; +using Lumina.Application.Common.Infrastructure.Authentication; +using Lumina.Application.Common.Infrastructure.Security; +using Lumina.Contracts.Responses.Authentication; +using Mediator; +using System; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Application.Core.UsersManagement.Authentication.Commands.RegisterUser; + +/// +/// Handler for the command to register a new user account. +/// +public class RegisterUserCommandHandler : IRequestHandler> +{ + private readonly IUnitOfWork _unitOfWork; + private readonly IHashService _hashService; + private readonly ICryptographyService _cryptographyService; + private readonly ITotpTokenGenerator _totpTokenGenerator; + private readonly IQRCodeGenerator _qRCodeGenerator; + + /// + /// Initializes a new instance of the class. + /// + /// Injected unit of work for interacting with the data access layer repositories. + /// Injected service for password hashing functionality. + /// Injected service for cryptographic functionality. + /// Injected service for generating and validating TOTP tokens. + /// Injected service for generating QR codes. + public RegisterUserCommandHandler( + IUnitOfWork unitOfWork, + IHashService hashService, + ICryptographyService cryptographyService, + ITotpTokenGenerator totpTokenGenerator, + IQRCodeGenerator qRCodeGenerator) + { + _unitOfWork = unitOfWork; + _hashService = hashService; + _cryptographyService = cryptographyService; + _totpTokenGenerator = totpTokenGenerator; + _qRCodeGenerator = qRCodeGenerator; + } + + /// + /// Handles the command to register an account. + /// + /// The request to be handled. + /// Cancellation token that can be used to stop the execution. + /// + /// An containing either a successfully created , or an error message. + /// + public async ValueTask> Handle(RegisterUserCommand request, CancellationToken cancellationToken) + { + // check if any users already exists (admin account is only set once!) + IUserRepository userRepository = _unitOfWork.GetRepository(); + ErrorOr resultSelectUser = await userRepository.GetByUsernameAsync(request.Username!, cancellationToken); + if (resultSelectUser.IsError) + return resultSelectUser.Errors; + else if (resultSelectUser.Value is not null) + return Errors.Authentication.UsernameAlreadyExists; + string? totpSecret = null; + UserEntity user = new() + { + Id = Guid.NewGuid(), + Username = request.Username!, + Password = Uri.EscapeDataString(_hashService.HashString(request.Password!)), + Created = DateTime.UtcNow, + Libraries = [] + }; + // if the user enabled two factor auth, include a QR with the totp secret + if (request.Use2fa) + { + // generate a TOTP secret + byte[] secret = _totpTokenGenerator.GenerateSecret(); + // convert the secret into a QR code for the user to scan + totpSecret = _qRCodeGenerator.GenerateQrCodeDataUri(request.Username!, secret); + // store the TOTP secret in the repository, encrypted + user.TotpSecret = _cryptographyService.Encrypt(Convert.ToBase64String(secret)); + } + // insert the user + ErrorOr resultInsertUser = await userRepository.InsertAsync(user, cancellationToken); + if (resultInsertUser.IsError) + return resultInsertUser.Errors; + await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false); + // TODO: insert the default admin profile preferences when they are implemented + // if 2FA was enabled, the TOTP secret needs to be delivered to the client unhashed, so it can be displayed + return new RegistrationResponse(user.Id, user.Username, totpSecret); + } +} diff --git a/src/Lumina.Application/Core/UsersManagement/Authentication/Commands/RegisterUser/RegisterUserCommandValidator.cs b/src/Lumina.Application/Core/UsersManagement/Authentication/Commands/RegisterUser/RegisterUserCommandValidator.cs new file mode 100644 index 00000000..894432dc --- /dev/null +++ b/src/Lumina.Application/Core/UsersManagement/Authentication/Commands/RegisterUser/RegisterUserCommandValidator.cs @@ -0,0 +1,27 @@ +#region ========================================================================= USING ===================================================================================== +using FluentValidation; +using Lumina.Application.Common.Errors; +#endregion + +namespace Lumina.Application.Core.UsersManagement.Authentication.Commands.RegisterUser; + +/// +/// Validates the needed validation rules for . +/// +public class RegisterUserCommandValidator : AbstractValidator +{ + /// + /// Initializes a new instance of the class. + /// + public RegisterUserCommandValidator() + { + RuleFor(x => x.Username).NotEmpty().WithMessage(Errors.Authentication.UsernameCannotBeEmpty.Description) + .Length(3, 255).WithMessage(Errors.Authentication.UsernameMustBeBetween3And255CharactersLong.Description) + .Matches("^[a-zA-Z0-9][a-zA-Z0-9._-]*[a-zA-Z0-9]$") // only allow letters, numbers, dots, underscores and hyphens, and must start and end with letter or number + .WithMessage(Errors.Authentication.InvalidUsername.Description); + RuleFor(x => x.Password).NotEmpty().WithMessage(Errors.Authentication.PasswordCannotBeEmpty.Description) + .Matches("^(?=.*[A-Z])(?=.*[0-9])(?=.*[^a-zA-Z0-9]).{8,}$").WithMessage(Errors.Authentication.InvalidPassword.Description); + RuleFor(x => x.PasswordConfirm).NotEmpty().WithMessage(Errors.Authentication.PasswordConfirmCannotBeEmpty.Description); + RuleFor(x => x.Password).Equal(x => x.PasswordConfirm).WithMessage(Errors.Authentication.PasswordsNotMatch.Description); + } +} diff --git a/src/Lumina.Application/Core/UsersManagement/Authentication/Queries/LoginUser/LoginUserQuery.cs b/src/Lumina.Application/Core/UsersManagement/Authentication/Queries/LoginUser/LoginUserQuery.cs new file mode 100644 index 00000000..003e1fa1 --- /dev/null +++ b/src/Lumina.Application/Core/UsersManagement/Authentication/Queries/LoginUser/LoginUserQuery.cs @@ -0,0 +1,21 @@ +#region ========================================================================= USING ===================================================================================== +using ErrorOr; +using Lumina.Contracts.Responses.Authentication; +using Mediator; +using System.Diagnostics; +#endregion + +namespace Lumina.Application.Core.UsersManagement.Authentication.Queries.LoginUser; + +/// +/// Query for authenticating an account. +/// +/// The username of the account to authenticate. +/// The password of the account to authenticate. +/// The TOTP (Time-Based One-Time Password) of the account to authenticate. +[DebuggerDisplay("Path: {Path}")] +public record LoginUserQuery( + string? Username, + string? Password, + string? TotpCode = null +) : IRequest>; diff --git a/src/Lumina.Application/Core/UsersManagement/Authentication/Queries/LoginUser/LoginUserQueryHandler.cs b/src/Lumina.Application/Core/UsersManagement/Authentication/Queries/LoginUser/LoginUserQueryHandler.cs new file mode 100644 index 00000000..5ea0c600 --- /dev/null +++ b/src/Lumina.Application/Core/UsersManagement/Authentication/Queries/LoginUser/LoginUserQueryHandler.cs @@ -0,0 +1,103 @@ +#region ========================================================================= USING ===================================================================================== +using ErrorOr; +using Lumina.Application.Common.DataAccess.Entities.UsersManagement; +using Lumina.Application.Common.DataAccess.Repositories.Users; +using Lumina.Application.Common.DataAccess.UoW; +using Lumina.Application.Common.Errors; +using Lumina.Application.Common.Infrastructure.Authentication; +using Lumina.Application.Common.Infrastructure.Security; +using Lumina.Contracts.Responses.Authentication; +using Mediator; +using System; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Application.Core.UsersManagement.Authentication.Queries.LoginUser; + +/// +/// Handler for the query to authenticate an account. +/// +public class LoginUserQueryHandler : IRequestHandler> +{ + private readonly IUnitOfWork _unitOfWork; + private readonly IHashService _hashService; + private readonly IJwtTokenGenerator _jwtTokenGenerator; + private readonly ITotpTokenGenerator _totpTokenGenerator; + private readonly ICryptographyService _cryptographyService; + + /// + /// Initializes a new instance of the class. + /// + /// Injected unit of work for interacting with the data access layer repositories. + /// Injected service for password hashing functionality. + /// Injected service for generating JWT tokens. + /// Injected service for generating and validating TOTP tokens. + /// Injected service for cryptographic functionality. + public LoginUserQueryHandler( + IUnitOfWork unitOfWork, + IHashService hashService, + IJwtTokenGenerator jwtTokenGenerator, + ITotpTokenGenerator totpTokenGenerator, + ICryptographyService cryptographyService) + { + _unitOfWork = unitOfWork; + _hashService = hashService; + _jwtTokenGenerator = jwtTokenGenerator; + _totpTokenGenerator = totpTokenGenerator; + _cryptographyService = cryptographyService; + } + + /// + /// Handles the query to authenticate an account. + /// + /// The request to be handled. + /// Cancellation token that can be used to stop the execution. + /// + /// An containing either a successfully created , or an error message. + /// + public async ValueTask> Handle(LoginUserQuery request, CancellationToken cancellationToken) + { + // check if any users already exists + IUserRepository userRepository = _unitOfWork.GetRepository(); + ErrorOr resultSelectUser = await userRepository.GetByUsernameAsync(request.Username!, cancellationToken); + if (resultSelectUser.IsError) + return resultSelectUser.Errors; + else if (resultSelectUser.Value is null) + return Errors.Authentication.InvalidUsernameOrPassword; + // validate that the password is correct + if (!_hashService.CheckStringAgainstHash(request.Password!, Uri.UnescapeDataString(resultSelectUser.Value.Password!))) + { + // if a password reset was requested, a temp password is being used - if the hash check failed against the regular password, try against the temp one too + if (resultSelectUser.Value.TempPassword is not null) + { + // the temporary password should only be valid for 15 minutes, if its obsolete, remove it and return error + if (resultSelectUser.Value.TempPasswordCreated!.Value.AddMinutes(15) < DateTime.UtcNow) + { + resultSelectUser.Value.TempPassword = null; + resultSelectUser.Value.TempPasswordCreated = null; + await userRepository.UpdateAsync(resultSelectUser.Value, cancellationToken); + await _unitOfWork.SaveChangesAsync(cancellationToken); + return Errors.Authentication.TempPasswordExpired; + } + else // temporary password is still valid, validate password against it + { + if (!_hashService.CheckStringAgainstHash(request.Password!, Uri.UnescapeDataString(resultSelectUser.Value.TempPassword!))) + return Errors.Authentication.InvalidUsernameOrPassword; + } + } + else + return Errors.Authentication.InvalidUsernameOrPassword; + } + // create the JWT token + string token = _jwtTokenGenerator.GenerateToken(resultSelectUser.Value.Id.ToString(), resultSelectUser.Value.Username); + // check if the user uses TOTP + bool usesTotp = !string.IsNullOrEmpty(resultSelectUser.Value.TotpSecret); + if (usesTotp && string.IsNullOrEmpty(request.TotpCode)) + return Errors.Authentication.InvalidTotpCode; + else if (usesTotp && !string.IsNullOrEmpty(request.TotpCode)) // and if they do, validate it + if (!_totpTokenGenerator.ValidateToken(Convert.FromBase64String(_cryptographyService.Decrypt(resultSelectUser.Value.TotpSecret!)), request.TotpCode)) + return Errors.Authentication.InvalidTotpCode; + return new LoginResponse(resultSelectUser.Value.Id, resultSelectUser.Value.Username, token, usesTotp); + } +} diff --git a/src/Lumina.Application/Core/UsersManagement/Authentication/Queries/LoginUser/LoginUserQueryValidator.cs b/src/Lumina.Application/Core/UsersManagement/Authentication/Queries/LoginUser/LoginUserQueryValidator.cs new file mode 100644 index 00000000..90e4e4de --- /dev/null +++ b/src/Lumina.Application/Core/UsersManagement/Authentication/Queries/LoginUser/LoginUserQueryValidator.cs @@ -0,0 +1,33 @@ +#region ========================================================================= USING ===================================================================================== +using FluentValidation; +using Lumina.Application.Common.Errors; +using System.Linq; +#endregion + +namespace Lumina.Application.Core.UsersManagement.Authentication.Queries.LoginUser; + +/// +/// Validates the needed validation rules for . +/// +public class LoginUserQueryValidator : AbstractValidator +{ + /// + /// Initializes a new instance of the class. + /// + public LoginUserQueryValidator() + { + RuleFor(x => x.Username).NotEmpty().WithMessage(Errors.Authentication.UsernameCannotBeEmpty.Description); + RuleFor(x => x.Password).NotEmpty().WithMessage(Errors.Authentication.PasswordCannotBeEmpty.Description) + .Matches("^(?=.*[A-Z])(?=.*[0-9])(?=.*[^a-zA-Z0-9]).{8,}$").WithMessage(Errors.Authentication.InvalidPassword.Description); + RuleFor(m => m!.TotpCode) + .Custom((code, context) => + { + if (string.IsNullOrEmpty(code)) + return; + if (code.Length != 6) + context.AddFailure("TotpCode", Errors.Authentication.InvalidTotpCode.Description); + if (!code.All(char.IsDigit)) + context.AddFailure("TotpCode", Errors.Authentication.InvalidTotpCode.Description); + }); + } +} 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 deleted file mode 100644 index 8532c24c..00000000 --- a/src/Lumina.Application/Core/WrittenContentLibrary/BooksLibrary/Books/Queries/GetBooks/GetBooksQuery.cs +++ /dev/null @@ -1,13 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using ErrorOr; -using Lumina.Domain.Core.Aggregates.WrittenContentLibrary.BookLibraryAggregate; -using Mediator; -using System.Collections.Generic; -#endregion - -namespace Lumina.Application.Core.WrittenContentLibrary.BooksLibrary.Books.Queries.GetBooks; - -/// -/// Query for getting all books. -/// -public record class GetBooksQuery() : IRequest>>; \ No newline at end of file diff --git a/src/Lumina.Application/Lumina.Application.csproj b/src/Lumina.Application/Lumina.Application.csproj index 4e614fb6..eb1ee147 100644 --- a/src/Lumina.Application/Lumina.Application.csproj +++ b/src/Lumina.Application/Lumina.Application.csproj @@ -3,9 +3,10 @@ net9.0 disable enable - $(SolutionDir)..\bin\server\ + $(SolutionDir)..\bin\api\ false true + $(WarningsNotAsErrors);NU1901;NU1902;NU1903;NU1904 @@ -13,22 +14,19 @@ - - - runtime; build; native; contentfiles; analyzers; buildtransitive all - - + + diff --git a/src/Lumina.Contracts/Models/Common/GenreModel.cs b/src/Lumina.Contracts/DTO/Common/GenreDto.cs similarity index 68% rename from src/Lumina.Contracts/Models/Common/GenreModel.cs rename to src/Lumina.Contracts/DTO/Common/GenreDto.cs index 84ca2efc..2841eb1f 100644 --- a/src/Lumina.Contracts/Models/Common/GenreModel.cs +++ b/src/Lumina.Contracts/DTO/Common/GenreDto.cs @@ -2,13 +2,13 @@ using System.Diagnostics; #endregion -namespace Lumina.Contracts.Models.Common; +namespace Lumina.Contracts.DTO.Common; /// -/// Represents a request to get genre information. +/// Data transfer object for a genre. /// /// Gets the name of the genre. -[DebuggerDisplay("{Name}")] -public record GenreModel( +[DebuggerDisplay("Name: {Name}")] +public record GenreDto( string? Name -); \ No newline at end of file +); diff --git a/src/Lumina.Contracts/Models/Common/LanguageInfoModel.cs b/src/Lumina.Contracts/DTO/Common/LanguageInfoDto.cs similarity index 72% rename from src/Lumina.Contracts/Models/Common/LanguageInfoModel.cs rename to src/Lumina.Contracts/DTO/Common/LanguageInfoDto.cs index b3078fc5..173443c9 100644 --- a/src/Lumina.Contracts/Models/Common/LanguageInfoModel.cs +++ b/src/Lumina.Contracts/DTO/Common/LanguageInfoDto.cs @@ -2,17 +2,17 @@ using System.Diagnostics; #endregion -namespace Lumina.Contracts.Models.Common; +namespace Lumina.Contracts.DTO.Common; /// -/// Represents a request to get language information. +/// Data transfer object for 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 LanguageInfoDto( string? LanguageCode, string? LanguageName, string? NativeName -); \ No newline at end of file +); diff --git a/src/Lumina.Contracts/DTO/Common/RatingDto.cs b/src/Lumina.Contracts/DTO/Common/RatingDto.cs new file mode 100644 index 00000000..df956380 --- /dev/null +++ b/src/Lumina.Contracts/DTO/Common/RatingDto.cs @@ -0,0 +1,18 @@ +#region ========================================================================= USING ===================================================================================== +using System.Diagnostics; +#endregion + +namespace Lumina.Contracts.DTO.Common; + +/// +/// Data transfer object for a rating. +/// +/// Gets the rating value. +/// Gets the maximum possible rating value. +/// Gets the number of votes that contributed to the rating. +[DebuggerDisplay("{Value}/{MaxValue}")] +public abstract record RatingDto( + decimal? Value, + decimal? MaxValue, + int? VoteCount +); diff --git a/src/Lumina.Contracts/Models/Common/ReleaseInfoModel.cs b/src/Lumina.Contracts/DTO/Common/ReleaseInfoDto.cs similarity index 84% rename from src/Lumina.Contracts/Models/Common/ReleaseInfoModel.cs rename to src/Lumina.Contracts/DTO/Common/ReleaseInfoDto.cs index 1c8871b2..89c4b203 100644 --- a/src/Lumina.Contracts/Models/Common/ReleaseInfoModel.cs +++ b/src/Lumina.Contracts/DTO/Common/ReleaseInfoDto.cs @@ -3,10 +3,10 @@ using System; using System.Diagnostics; #endregion -namespace Lumina.Contracts.Models.Common; +namespace Lumina.Contracts.DTO.Common; /// -/// Represents a request to get release information. +/// Data transfer object for a release information. /// /// Gets the original release date of the content. /// Gets the original release year of the content. @@ -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 ReleaseInfoDto( 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/DTO/Common/TagDto.cs similarity index 68% rename from src/Lumina.Contracts/Models/Common/TagModel.cs rename to src/Lumina.Contracts/DTO/Common/TagDto.cs index 85d90520..b2d1e834 100644 --- a/src/Lumina.Contracts/Models/Common/TagModel.cs +++ b/src/Lumina.Contracts/DTO/Common/TagDto.cs @@ -2,13 +2,13 @@ using System.Diagnostics; #endregion -namespace Lumina.Contracts.Models.Common; +namespace Lumina.Contracts.DTO.Common; /// -/// Represents a request to get tag information. +/// Data transfer object for a tag. /// /// Gets the name of the tag. -[DebuggerDisplay("{Name}")] -public record TagModel( +[DebuggerDisplay("Name: {Name}")] +public record TagDto( string? Name -); \ No newline at end of file +); diff --git a/src/Lumina.Contracts/Models/FileManagement/FileSystemItemModel.cs b/src/Lumina.Contracts/DTO/FileSystemManagement/FileSystemItemDto.cs similarity index 77% rename from src/Lumina.Contracts/Models/FileManagement/FileSystemItemModel.cs rename to src/Lumina.Contracts/DTO/FileSystemManagement/FileSystemItemDto.cs index fa9ef765..9188267e 100644 --- a/src/Lumina.Contracts/Models/FileManagement/FileSystemItemModel.cs +++ b/src/Lumina.Contracts/DTO/FileSystemManagement/FileSystemItemDto.cs @@ -3,7 +3,7 @@ using System; using System.Diagnostics; #endregion -namespace Lumina.Contracts.Models.FileManagement; +namespace Lumina.Contracts.DTO.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 FileSystemItemDto( + string Path, + string Name, + DateTime DateCreated, DateTime DateModified ); diff --git a/src/Lumina.Contracts/DTO/MediaContributors/MediaContributorDto.cs b/src/Lumina.Contracts/DTO/MediaContributors/MediaContributorDto.cs new file mode 100644 index 00000000..bd81f133 --- /dev/null +++ b/src/Lumina.Contracts/DTO/MediaContributors/MediaContributorDto.cs @@ -0,0 +1,16 @@ +#region ========================================================================= USING ===================================================================================== +using System.Diagnostics; +#endregion + +namespace Lumina.Contracts.DTO.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 MediaContributorDto( + MediaContributorNameDto? Name, + MediaContributorRoleDto? Role +); diff --git a/src/Lumina.Contracts/DTO/MediaContributors/MediaContributorNameDto.cs b/src/Lumina.Contracts/DTO/MediaContributors/MediaContributorNameDto.cs new file mode 100644 index 00000000..674ae321 --- /dev/null +++ b/src/Lumina.Contracts/DTO/MediaContributors/MediaContributorNameDto.cs @@ -0,0 +1,16 @@ +#region ========================================================================= USING ===================================================================================== +using System.Diagnostics; +#endregion + +namespace Lumina.Contracts.DTO.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 MediaContributorNameDto( + string? DisplayName, + string? LegalName +); diff --git a/src/Lumina.Contracts/DTO/MediaContributors/MediaContributorRoleDto.cs b/src/Lumina.Contracts/DTO/MediaContributors/MediaContributorRoleDto.cs new file mode 100644 index 00000000..ddb48ef8 --- /dev/null +++ b/src/Lumina.Contracts/DTO/MediaContributors/MediaContributorRoleDto.cs @@ -0,0 +1,16 @@ +#region ========================================================================= USING ===================================================================================== +using System.Diagnostics; +#endregion + +namespace Lumina.Contracts.DTO.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 MediaContributorRoleDto( + string? Name, + string? Category +); diff --git a/src/Lumina.Contracts/DTO/MediaLibrary/Management/LibraryContentLocationDto.cs b/src/Lumina.Contracts/DTO/MediaLibrary/Management/LibraryContentLocationDto.cs new file mode 100644 index 00000000..1a164e95 --- /dev/null +++ b/src/Lumina.Contracts/DTO/MediaLibrary/Management/LibraryContentLocationDto.cs @@ -0,0 +1,17 @@ +#region ========================================================================= USING ===================================================================================== +using System.Diagnostics; +#endregion + +namespace Lumina.Contracts.DTO.MediaLibrary.Management; + +/// +/// Repository entity for a media library content location. +/// +[DebuggerDisplay("Path: {Path}")] +public class LibraryContentLocationDto +{ + /// + /// Gets or sets the path of the media library content location. + /// + public required string Path { get; set; } +} diff --git a/src/Lumina.Contracts/DTO/MediaLibrary/WrittenContentLibrary/BookLibrary/BookRatingDto.cs b/src/Lumina.Contracts/DTO/MediaLibrary/WrittenContentLibrary/BookLibrary/BookRatingDto.cs new file mode 100644 index 00000000..dcdd4c4f --- /dev/null +++ b/src/Lumina.Contracts/DTO/MediaLibrary/WrittenContentLibrary/BookLibrary/BookRatingDto.cs @@ -0,0 +1,22 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Contracts.DTO.Common; +using Lumina.Domain.Common.Enums.BookLibrary; +using System.Diagnostics; +#endregion + +namespace Lumina.Contracts.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary; + +/// +/// Data transfer object for 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 BookRatingDto( + decimal? Value, + decimal? MaxValue, + BookRatingSource? Source, + int? VoteCount +) : RatingDto(Value, MaxValue, VoteCount); diff --git a/src/Lumina.Contracts/DTO/MediaLibrary/WrittenContentLibrary/BookLibrary/BookSeriesDto.cs b/src/Lumina.Contracts/DTO/MediaLibrary/WrittenContentLibrary/BookLibrary/BookSeriesDto.cs new file mode 100644 index 00000000..012f51eb --- /dev/null +++ b/src/Lumina.Contracts/DTO/MediaLibrary/WrittenContentLibrary/BookLibrary/BookSeriesDto.cs @@ -0,0 +1,14 @@ +#region ========================================================================= USING ===================================================================================== +using System.Diagnostics; +#endregion + +namespace Lumina.Contracts.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary; + +/// +/// Data transfer object for book series. +/// +/// The title of the book series. +[DebuggerDisplay("Title: {Title}")] +public record BookSeriesDto( + string? Title +); diff --git a/src/Lumina.Contracts/DTO/MediaLibrary/WrittenContentLibrary/BookLibrary/IsbnDto.cs b/src/Lumina.Contracts/DTO/MediaLibrary/WrittenContentLibrary/BookLibrary/IsbnDto.cs new file mode 100644 index 00000000..da058c47 --- /dev/null +++ b/src/Lumina.Contracts/DTO/MediaLibrary/WrittenContentLibrary/BookLibrary/IsbnDto.cs @@ -0,0 +1,17 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Domain.Common.Enums.BookLibrary; +using System.Diagnostics; +#endregion + +namespace Lumina.Contracts.DTO.MediaLibrary.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 IsbnDto( + string? Value, + IsbnFormat? Format +); diff --git a/src/Lumina.Contracts/DTO/MediaLibrary/WrittenContentLibrary/WrittenContentMetadataDto.cs b/src/Lumina.Contracts/DTO/MediaLibrary/WrittenContentLibrary/WrittenContentMetadataDto.cs new file mode 100644 index 00000000..84099eb8 --- /dev/null +++ b/src/Lumina.Contracts/DTO/MediaLibrary/WrittenContentLibrary/WrittenContentMetadataDto.cs @@ -0,0 +1,34 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Contracts.DTO.Common; +using System.Collections.Generic; +using System.Diagnostics; +#endregion + +namespace Lumina.Contracts.DTO.MediaLibrary.WrittenContentLibrary; + +/// +/// Data transfer object 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 WrittenContentMetadataDto( + string? Title, + string? OriginalTitle, + string? Description, + ReleaseInfoDto? ReleaseInfo, + List? Genres, + List? Tags, + LanguageInfoDto? Language, + LanguageInfoDto? OriginalLanguage, + string? Publisher, + int? PageCount +); diff --git a/src/Lumina.Contracts/Enums/Library/LibraryType.cs b/src/Lumina.Contracts/Enums/Library/LibraryType.cs deleted file mode 100644 index 13362213..00000000 --- a/src/Lumina.Contracts/Enums/Library/LibraryType.cs +++ /dev/null @@ -1,32 +0,0 @@ -namespace Lumina.Contracts.Enums.Library; - -/// -/// Enumeration for the types of libraries. -/// -public enum LibraryType -{ - /// - /// Content that is written, such as books, articles, or other written works. - /// - WrittenContent, - - /// - /// Content that is video, such as movies, TV shows, or other video works. - /// - VideoContent, - - /// - /// Content that is audio, such as podcasts, radio shows, or other audio works. - /// - AudioContent, - - /// - /// Content that is visual, such as images, paintings, or other visual works. - /// - VisualContent, - - /// - /// Content that is miscellaneous, such as lyrics, movie posters, or other miscellaneous works. - /// - MiscellaneousContent, -} \ No newline at end of file diff --git a/src/Lumina.Contracts/Lumina.Contracts.csproj b/src/Lumina.Contracts/Lumina.Contracts.csproj index daa23099..19cb6d5f 100644 --- a/src/Lumina.Contracts/Lumina.Contracts.csproj +++ b/src/Lumina.Contracts/Lumina.Contracts.csproj @@ -3,9 +3,10 @@ net9.0 disable enable - $(SolutionDir)..\bin\server\ + $(SolutionDir)..\bin\api\ false true + $(WarningsNotAsErrors);NU1901;NU1902;NU1903;NU1904 @@ -13,6 +14,6 @@ - + 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/BookModel.cs b/src/Lumina.Contracts/Models/WrittenContentLibrary/BookLibrary/BookModel.cs deleted file mode 100644 index 1155fdb8..00000000 --- a/src/Lumina.Contracts/Models/WrittenContentLibrary/BookLibrary/BookModel.cs +++ /dev/null @@ -1,206 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using Lumina.Contracts.Models.Common; -using System; -using System.Collections.Generic; -using System.Diagnostics; -#endregion - -namespace Lumina.Contracts.Models.WrittenContentLibrary.BookLibrary; - -/// -/// Represents a book. -/// -[DebuggerDisplay("{Title}")] -public class BookModel : IStorageEntity -{ - /// - /// Gets the Id of the media item. - /// - public Guid Id { get; init; } - - /// - /// Gets the title of the media item. - /// - public string Title { get; init; } = null!; - - /// - /// Gets the original title of the media item. - /// - public string? OriginalTitle { get; init; } - - /// - /// Gets the optional description of the media item. - /// - public string? Description { get; init; } - - /// - /// Gets the optional original release date of the media item. - /// - public DateOnly? OriginalReleaseDate { get; init; } - - /// - /// Gets the optional original release year of the media item. - /// This is useful when only the year of original release is known. - /// - public int? OriginalReleaseYear { get; init; } - - /// - /// Gets the optional re-release or reissue date of the media item. - /// - public DateOnly? ReReleaseDate { get; init; } - - /// - /// Gets the optional re-release or reissue year of the media item. - /// - public int? ReReleaseYear { get; init; } - - /// - /// Gets the optional country or region of release. - /// - public string? ReleaseCountry { get; init; } - - /// - /// Gets the optional release version or edition. (e.g. "Original", "Director's Cut", "2.0") - /// - public string? ReleaseVersion { get; init; } - - /// - /// Gets the ISO 639-1 two-letter language code. - /// - public string? LanguageCode { get; init; } - - /// - /// Gets the full name of the language in English. - /// - public string? LanguageName { get; init; } - - /// - /// Gets an optional native name of the language. - /// - public string? LanguageNativeName { get; init; } - - /// - /// Gets the optional ISO 639-1 two-letter original language code. - /// - public string? OriginalLanguageCode { get; init; } - - /// - /// Gets the optional full name of the original language in English. - /// - public string? OriginalLanguageName { get; init; } - - /// - /// Gets an optional native name of the original language. - /// - public string? OriginalLanguageNativeName { get; init; } - - /// - /// Gets the list of tags associated with the media item. - /// - public HashSet Tags { get; set; } = []; - - /// - /// Gets the list of genres associated with the media item. - /// - public HashSet Genres { get; set; } = []; - - /// - /// Gets the publisher of the written content. - /// - public string? Publisher { get; init; } - - /// - /// Gets the number of pages in the written content. - /// - public int? PageCount { get; init; } - - /// - /// Gets the format of the book (e.g., Hardcover, Paperback), if applicable. - /// - public string Format { get; init; } = null!; - - /// - /// Gets the edition of the book, if applicable. - /// - public string? Edition { get; init; } - - /// - /// Gets the volume or book number in the series, if applicable. - /// - public int? VolumeNumber { get; init; } - - /// - /// Gets the series id, if the book is part of a series. - /// - //public Guid? BookSeriesId { get; init; } = null; - - /// - /// Gets the ASIN (Amazon Standard Identification Number) of the book. - /// - public string? ASIN { get; init; } = null!; - - /// - /// Gets the Goodreads ID of the book. - /// - public string? GoodreadsId { get; init; } = null!; - - /// - /// Gets the Library of Congress Control Number (LCCN) of the book. - /// - public string? LCCN { get; init; } = null!; - - /// - /// Gets the OCLC Number (WorldCat identifier) of the book. - /// - public string? OCLCNumber { get; init; } = null!; - - /// - /// Gets the Open Library ID of the book. - /// - public string? OpenLibraryId { get; init; } = null!; - - /// - /// Gets the LibraryThing ID of the book. - /// - public string? LibraryThingId { get; init; } = null!; - - /// - /// Gets the Google Books ID of the book. - /// - public string? GoogleBooksId { get; init; } = null!; - - /// - /// Gets the Barnes & Noble ID of the book. - /// - public string? BarnesAndNobleId { get; init; } = null!; - - /// - /// Gets the Apple Books ID of the book. - /// - public string? AppleBooksId { get; init; } = null!; - - /// - /// Gets the list of ISBN (International Standard Book Number) of the book. - /// - public List ISBNs { get; set; } = []; - - /// - /// Gets the list of media contributors (actors, directors, etc) starring in this book. - /// - //public List ContributorIds { get; init; } = []; - - /// - /// Gets the list of ratings for this book. - /// - public List Ratings { get; init; } = []; - - /// - /// Gets the time and date when the entity was added. - /// - public DateTime Created { get; set; } - - /// - /// 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/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/Authentication/ChangePasswordRequest.cs b/src/Lumina.Contracts/Requests/Authentication/ChangePasswordRequest.cs new file mode 100644 index 00000000..899092c8 --- /dev/null +++ b/src/Lumina.Contracts/Requests/Authentication/ChangePasswordRequest.cs @@ -0,0 +1,15 @@ +namespace Lumina.Contracts.Requests.Authentication; + +/// +/// Represents the request model for account password change. +/// +/// The username of the account. +/// The current password of the account. +/// The new password of the account. +/// The confirmation of the new password of the account. +public record ChangePasswordRequest( + string? Username, + string? CurrentPassword, + string? NewPassword, + string? NewPasswordConfirm +); diff --git a/src/Lumina.Contracts/Requests/Authentication/LoginRequest.cs b/src/Lumina.Contracts/Requests/Authentication/LoginRequest.cs new file mode 100644 index 00000000..ac24be8b --- /dev/null +++ b/src/Lumina.Contracts/Requests/Authentication/LoginRequest.cs @@ -0,0 +1,18 @@ +#region ========================================================================= USING ===================================================================================== +using System.Diagnostics; +#endregion + +namespace Lumina.Contracts.Requests.Authentication; + +/// +/// Represents the request model for user authentication. +/// +/// The username of the account to authenticate. +/// The password of the account to authenticate. +/// The TOTP (Time-Based One-Time Password) of the account to authenticate. +[DebuggerDisplay("Username: {Username}")] +public record LoginRequest( + string? Username, + string? Password, + string? TotpCode = null +); diff --git a/src/Lumina.Contracts/Requests/Authentication/RecoverPasswordRequest.cs b/src/Lumina.Contracts/Requests/Authentication/RecoverPasswordRequest.cs new file mode 100644 index 00000000..be02df67 --- /dev/null +++ b/src/Lumina.Contracts/Requests/Authentication/RecoverPasswordRequest.cs @@ -0,0 +1,16 @@ +#region ========================================================================= USING ===================================================================================== +using System.Diagnostics; +#endregion + +namespace Lumina.Contracts.Requests.Authentication; + +/// +/// Represents the request model for account password recovery. +/// +/// The username of the account for which to recover the password. +/// The TOTP (Time-Based One-Time Password) of the account for which to recover the password. +[DebuggerDisplay("Username: {Username}")] +public record RecoverPasswordRequest( + string? Username, + string? TotpCode +); diff --git a/src/Lumina.Contracts/Requests/Authentication/RegistrationRequest.cs b/src/Lumina.Contracts/Requests/Authentication/RegistrationRequest.cs new file mode 100644 index 00000000..f30762e4 --- /dev/null +++ b/src/Lumina.Contracts/Requests/Authentication/RegistrationRequest.cs @@ -0,0 +1,20 @@ +#region ========================================================================= USING ===================================================================================== +using System.Diagnostics; +#endregion + +namespace Lumina.Contracts.Requests.Authentication; + +/// +/// Represents the request model for user registration. +/// +/// The desired username for the new account. +/// The password for the new account. +/// The confirmation of the entered password, used to ensure consistency. +/// Indicates whether two-factor authentication (2FA) should be enabled for the new account. +[DebuggerDisplay("Username: {Username}")] +public record RegistrationRequest( + string? Username = null, + string? Password = null, + string? PasswordConfirm = null, + bool Use2fa = true +); 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/MediaLibrary/Management/AddLibraryRequest.cs b/src/Lumina.Contracts/Requests/MediaLibrary/Management/AddLibraryRequest.cs new file mode 100644 index 00000000..1bd437c9 --- /dev/null +++ b/src/Lumina.Contracts/Requests/MediaLibrary/Management/AddLibraryRequest.cs @@ -0,0 +1,22 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Domain.Common.Enums.MediaLibrary; +using System; +using System.Diagnostics; +#endregion + +namespace Lumina.Contracts.Requests.MediaLibrary.Management; + +/// +/// Represents a request to add a media library. +/// +/// The Id of the user owning the media library. +/// The title of the media library. +/// The type of the media library. +/// The file system paths of the directories where the media library elements are located. +[DebuggerDisplay("Title: {Title}")] +public record AddLibraryRequest( + Guid UserId, + string? Title, + LibraryType? LibraryType, + string[]? ContentLocations +); diff --git a/src/Lumina.Contracts/Requests/WrittenContentLibrary/BookLibrary/AddBookRequest.cs b/src/Lumina.Contracts/Requests/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/AddBookRequest.cs similarity index 79% rename from src/Lumina.Contracts/Requests/WrittenContentLibrary/BookLibrary/AddBookRequest.cs rename to src/Lumina.Contracts/Requests/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/AddBookRequest.cs index 806768e3..de10e15a 100644 --- a/src/Lumina.Contracts/Requests/WrittenContentLibrary/BookLibrary/AddBookRequest.cs +++ b/src/Lumina.Contracts/Requests/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/AddBookRequest.cs @@ -1,12 +1,13 @@ #region ========================================================================= USING ===================================================================================== -using Lumina.Contracts.Enums.BookLibrary; -using Lumina.Contracts.Models.MediaContributors; -using Lumina.Contracts.Models.WrittenContentLibrary; -using Lumina.Contracts.Models.WrittenContentLibrary.BookLibrary; +using Lumina.Contracts.DTO.MediaContributors; +using Lumina.Contracts.DTO.MediaLibrary.WrittenContentLibrary; +using Lumina.Contracts.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary; +using Lumina.Domain.Common.Enums.BookLibrary; using System.Collections.Generic; +using System.Diagnostics; #endregion -namespace Lumina.Contracts.Requests.WrittenContentLibrary.BookLibrary; +namespace Lumina.Contracts.Requests.MediaLibrary.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, + WrittenContentMetadataDto? Metadata, BookFormat? Format, string? Edition, int? VolumeNumber, - BookSeriesModel? Series, + BookSeriesDto? 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/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/GetBookRequest.cs b/src/Lumina.Contracts/Requests/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/GetBookRequest.cs new file mode 100644 index 00000000..4e02a50b --- /dev/null +++ b/src/Lumina.Contracts/Requests/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/GetBookRequest.cs @@ -0,0 +1,15 @@ +#region ========================================================================= USING ===================================================================================== +using System.Diagnostics; +using System.Text.Json.Serialization; +#endregion + +namespace Lumina.Contracts.Requests.MediaLibrary.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/Authentication/ChangePasswordResponse.cs b/src/Lumina.Contracts/Responses/Authentication/ChangePasswordResponse.cs new file mode 100644 index 00000000..c530b669 --- /dev/null +++ b/src/Lumina.Contracts/Responses/Authentication/ChangePasswordResponse.cs @@ -0,0 +1,14 @@ +#region ========================================================================= USING ===================================================================================== +using System.Diagnostics; +#endregion + +namespace Lumina.Contracts.Responses.Authentication; + +/// +/// Represents the response model for an account password change request. +/// +/// Whether the password was changed or not. +[DebuggerDisplay("IsPasswordChanged: {IsPasswordChanged}")] +public record ChangePasswordResponse( + bool IsPasswordChanged +); diff --git a/src/Lumina.Contracts/Responses/Authentication/LoginResponse.cs b/src/Lumina.Contracts/Responses/Authentication/LoginResponse.cs new file mode 100644 index 00000000..8fe6eef2 --- /dev/null +++ b/src/Lumina.Contracts/Responses/Authentication/LoginResponse.cs @@ -0,0 +1,21 @@ +#region ========================================================================= USING ===================================================================================== +using System; +using System.Diagnostics; +#endregion + +namespace Lumina.Contracts.Responses.Authentication; + +/// +/// Represents the response model for user authentication. +/// +/// The Id of the user to authenticate. +/// The username of the user to authenticate. +/// The authentication token used for subsequent requests. +/// Whether the user uses 2FA authentication, or not. +[DebuggerDisplay("Username: {Username}")] +public record LoginResponse( + Guid Id, + string Username, + string Token, + bool UsesTotp +); diff --git a/src/Lumina.Contracts/Responses/Authentication/RecoverPasswordResponse.cs b/src/Lumina.Contracts/Responses/Authentication/RecoverPasswordResponse.cs new file mode 100644 index 00000000..b85e7e61 --- /dev/null +++ b/src/Lumina.Contracts/Responses/Authentication/RecoverPasswordResponse.cs @@ -0,0 +1,14 @@ +#region ========================================================================= USING ===================================================================================== +using System.Diagnostics; +#endregion + +namespace Lumina.Contracts.Responses.Authentication; + +/// +/// Represents the response model for an account password reset request. +/// +/// Whether the password was reset or not. +[DebuggerDisplay("IsPasswordReset: {IsPasswordReset}")] +public record RecoverPasswordResponse( + bool IsPasswordReset +); diff --git a/src/Lumina.Contracts/Responses/Authentication/RegistrationResponse.cs b/src/Lumina.Contracts/Responses/Authentication/RegistrationResponse.cs new file mode 100644 index 00000000..46f1b394 --- /dev/null +++ b/src/Lumina.Contracts/Responses/Authentication/RegistrationResponse.cs @@ -0,0 +1,19 @@ +#region ========================================================================= USING ===================================================================================== +using System; +using System.Diagnostics; +#endregion + +namespace Lumina.Contracts.Responses.Authentication; + +/// +/// Represents the response model for user registration. +/// +/// The Id of the user. +/// The username of the user. +/// The TOTP (Time-Based One-Time Password) secret used for two-factor authentication. +[DebuggerDisplay("Username: {Username}")] +public record RegistrationResponse( + Guid Id, + string Username, + string? TotpSecret +); diff --git a/src/Lumina.Contracts/Responses/FileManagement/FileSystemTypeResponse.cs b/src/Lumina.Contracts/Responses/FileManagement/FileSystemTypeResponse.cs deleted file mode 100644 index 73477def..00000000 --- a/src/Lumina.Contracts/Responses/FileManagement/FileSystemTypeResponse.cs +++ /dev/null @@ -1,15 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using Lumina.Contracts.Enums.FileSystem; -using System.Diagnostics; -#endregion - -namespace Lumina.Contracts.Responses.FileManagement; - -/// -/// Represents a response containing the file system platform type. -/// -/// The returned file system platform type. -[DebuggerDisplay("{PlatformType}")] -public record FileSystemTypeResponse( - PlatformType PlatformType -); \ No newline at end of file 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 77% rename from src/Lumina.Contracts/Responses/FileManagement/FileSystemTreeNodeResponse.cs rename to src/Lumina.Contracts/Responses/FileSystemManagement/Common/FileSystemTreeNodeResponse.cs index d2ac28b4..36a42ce3 100644 --- a/src/Lumina.Contracts/Responses/FileManagement/FileSystemTreeNodeResponse.cs +++ b/src/Lumina.Contracts/Responses/FileSystemManagement/Common/FileSystemTreeNodeResponse.cs @@ -1,15 +1,15 @@ -#region ========================================================================= USING ===================================================================================== -using Lumina.Contracts.Enums.FileSystem; +#region ========================================================================= USING ===================================================================================== +using Lumina.Domain.Common.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 67% rename from src/Lumina.Contracts/Responses/FileManagement/DirectoryResponse.cs rename to src/Lumina.Contracts/Responses/FileSystemManagement/Directories/DirectoryResponse.cs index ef25f547..602c898d 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.DTO.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 +) : FileSystemItemDto(Path, Name, DateCreated, DateModified); diff --git a/src/Lumina.Contracts/Responses/FileSystemManagement/FileSystem/FileSystemTypeResponse.cs b/src/Lumina.Contracts/Responses/FileSystemManagement/FileSystem/FileSystemTypeResponse.cs new file mode 100644 index 00000000..78928e2a --- /dev/null +++ b/src/Lumina.Contracts/Responses/FileSystemManagement/FileSystem/FileSystemTypeResponse.cs @@ -0,0 +1,15 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Domain.Common.Enums.FileSystem; +using System.Diagnostics; +#endregion + +namespace Lumina.Contracts.Responses.FileSystemManagement.FileSystem; + +/// +/// Represents a response containing the file system platform type. +/// +/// The returned file system platform type. +[DebuggerDisplay("PlatformType: {PlatformType}")] +public record FileSystemTypeResponse( + PlatformType PlatformType +); diff --git a/src/Lumina.Contracts/Responses/FileManagement/FileResponse.cs b/src/Lumina.Contracts/Responses/FileSystemManagement/Files/FileResponse.cs similarity index 67% rename from src/Lumina.Contracts/Responses/FileManagement/FileResponse.cs rename to src/Lumina.Contracts/Responses/FileSystemManagement/Files/FileResponse.cs index 61fe82c3..0addc010 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.DTO.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); +) : FileSystemItemDto(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 73% rename from src/Lumina.Contracts/Responses/FileManagement/ThumbnailResponse.cs rename to src/Lumina.Contracts/Responses/FileSystemManagement/Thumbnails/ThumbnailResponse.cs index e1a68ca7..03588a7b 100644 --- a/src/Lumina.Contracts/Responses/FileManagement/ThumbnailResponse.cs +++ b/src/Lumina.Contracts/Responses/FileSystemManagement/Thumbnails/ThumbnailResponse.cs @@ -1,17 +1,17 @@ #region ========================================================================= USING ===================================================================================== -using Lumina.Contracts.Enums.PhotoLibrary; +using Lumina.Domain.Common.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/MediaLibrary/Management/LibraryResponse.cs b/src/Lumina.Contracts/Responses/MediaLibrary/Management/LibraryResponse.cs new file mode 100644 index 00000000..fc858b28 --- /dev/null +++ b/src/Lumina.Contracts/Responses/MediaLibrary/Management/LibraryResponse.cs @@ -0,0 +1,29 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Domain.Common.Enums.MediaLibrary; +using System; +using System.Collections.Generic; +using System.Diagnostics; +#endregion + +namespace Lumina.Contracts.Responses.MediaLibrary.Management; + +/// +/// Represents a media library response. +/// +/// The id of the media library. +/// The Id of the user owning the media library. +/// The title of the media library. +/// The type of the media library. +/// The file system paths of the directories where the media library elements are located. +/// The date and time when the library was created. +/// The optional date and time when the library was updated. +[DebuggerDisplay("Title: {Title}")] +public record LibraryResponse( + Guid Id, + Guid UserId, + string Title, + LibraryType LibraryType, + List ContentLocations, + DateTime Created, + DateTime? Updated +); diff --git a/src/Lumina.Contracts/Responses/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/BookResponse.cs b/src/Lumina.Contracts/Responses/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/BookResponse.cs new file mode 100644 index 00000000..a202bebd --- /dev/null +++ b/src/Lumina.Contracts/Responses/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/BookResponse.cs @@ -0,0 +1,58 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Contracts.DTO.MediaContributors; +using Lumina.Contracts.DTO.MediaLibrary.WrittenContentLibrary; +using Lumina.Contracts.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary; +using Lumina.Domain.Common.Enums.BookLibrary; +using System; +using System.Collections.Generic; +using System.Diagnostics; +#endregion + +namespace Lumina.Contracts.Responses.MediaLibrary.WrittenContentLibrary.BookLibrary.Books; + +/// +/// Represents a book response. +/// +/// The id of the 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. +/// The date and time when the book was created. +/// The optional date and time when the book was updated. +[DebuggerDisplay("Title: {Metadata.Title}")] +public record BookResponse( + Guid Id, + WrittenContentMetadataDto Metadata, + BookFormat? Format, + string? Edition, + int? VolumeNumber, + BookSeriesDto? Series, + string? ASIN, + string? GoodreadsId, + string? LCCN, + string? OCLCNumber, + string? OpenLibraryId, + string? LibraryThingId, + string? GoogleBooksId, + string? BarnesAndNobleId, + string? AppleBooksId, + List? ISBNs, + List? Contributors, + List? Ratings, + DateTime Created, + DateTime? Updated +); diff --git a/src/Lumina.Contracts/Responses/UsersManagement/InitializationResponse.cs b/src/Lumina.Contracts/Responses/UsersManagement/InitializationResponse.cs new file mode 100644 index 00000000..d837321d --- /dev/null +++ b/src/Lumina.Contracts/Responses/UsersManagement/InitializationResponse.cs @@ -0,0 +1,14 @@ +#region ========================================================================= USING ===================================================================================== +using System.Diagnostics; +#endregion + +namespace Lumina.Contracts.Responses.UsersManagement; + +/// +/// Represents a response for verifying the initialization status of the application. +/// +/// Indicates whether the application has been run before, and the super admin account has been created. +[DebuggerDisplay("IsInitialized: {IsInitialized}")] +public record InitializationResponse( + bool IsInitialized +); diff --git a/src/Lumina.Contracts/Responses/UsersManagement/Users/UserResponse.cs b/src/Lumina.Contracts/Responses/UsersManagement/Users/UserResponse.cs new file mode 100644 index 00000000..50bb8461 --- /dev/null +++ b/src/Lumina.Contracts/Responses/UsersManagement/Users/UserResponse.cs @@ -0,0 +1,21 @@ +#region ========================================================================= USING ===================================================================================== +using System; +using System.Diagnostics; +#endregion + +namespace Lumina.Contracts.Responses.UsersManagement.Users; + +/// +/// Represents a user response. +/// +/// The id of the user. +/// The username of the user. +/// The date and time when the user was created. +/// The optional date and time when the user was updated. +[DebuggerDisplay("Username: {Username}")] +public record UserResponse( + Guid Id, + string Username, + DateTime Created, + DateTime? Updated +); diff --git a/src/Lumina.DataAccess/Common/Configuration/BookConfiguration.cs b/src/Lumina.DataAccess/Common/Configuration/BookConfiguration.cs index 13f380ff..f961dc52 100644 --- a/src/Lumina.DataAccess/Common/Configuration/BookConfiguration.cs +++ b/src/Lumina.DataAccess/Common/Configuration/BookConfiguration.cs @@ -1,23 +1,24 @@ #region ========================================================================= USING ===================================================================================== -using Lumina.Contracts.Models.Common; -using Lumina.Contracts.Models.WrittenContentLibrary.BookLibrary; +using Lumina.Application.Common.DataAccess.Entities.Common; +using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Metadata.Builders; +using System; using System.Collections.Generic; #endregion 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); @@ -25,63 +26,114 @@ public class BookConfiguration : IEntityTypeConfiguration .ValueGeneratedNever() // because EF always tries to generate the value for the Id, and because we generate it as part of the aggregate root, we need to tell EF not to generate it .HasColumnOrder(0); - builder.Property(book => book.Title).IsRequired().HasMaxLength(255).HasColumnOrder(1); - builder.Property(book => book.OriginalTitle).HasMaxLength(255).HasColumnOrder(2); - builder.Property(book => book.Description).HasMaxLength(2000).HasColumnOrder(3); - builder.Property(book => book.OriginalReleaseDate).HasColumnOrder(4); - builder.Property(book => book.OriginalReleaseYear).HasColumnOrder(5); - builder.Property(book => book.ReReleaseDate).HasColumnOrder(6); - builder.Property(book => book.ReReleaseYear).HasColumnOrder(7); - builder.Property(book => book.ReleaseCountry).HasColumnOrder(8); - builder.Property(book => book.ReleaseVersion).HasColumnOrder(9); - builder.Property(book => book.LanguageCode).HasColumnOrder(10); - builder.Property(book => book.LanguageName).HasColumnOrder(11); - builder.Property(book => book.LanguageNativeName).HasColumnOrder(12); - builder.Property(book => book.OriginalLanguageCode).HasColumnOrder(13); - builder.Property(book => book.OriginalLanguageName).HasColumnOrder(14); - builder.Property(book => book.OriginalLanguageNativeName).HasColumnOrder(15); + builder.Property(book => book.Title) + .IsRequired() + .HasMaxLength(255) + .HasColumnOrder(1); + builder.Property(book => book.OriginalTitle) + .HasMaxLength(255) + .HasColumnOrder(2); + builder.Property(book => book.Description) + .HasMaxLength(2000) + .HasColumnOrder(3); + builder.Property(book => book.OriginalReleaseDate) + .HasColumnOrder(4); + builder.Property(book => book.OriginalReleaseYear) + .HasColumnOrder(5); + builder.Property(book => book.ReReleaseDate) + .HasColumnOrder(6); + builder.Property(book => book.ReReleaseYear) + .HasColumnOrder(7); + builder.Property(book => book.ReleaseCountry) + .HasColumnOrder(8); + builder.Property(book => book.ReleaseVersion) + .HasColumnOrder(9); + builder.Property(book => book.LanguageCode) + .HasColumnOrder(10); + builder.Property(book => book.LanguageName) + .HasColumnOrder(11); + builder.Property(book => book.LanguageNativeName) + .HasColumnOrder(12); + builder.Property(book => book.OriginalLanguageCode) + .HasColumnOrder(13); + builder.Property(book => book.OriginalLanguageName) + .HasColumnOrder(14); + builder.Property(book => book.OriginalLanguageNativeName) + .HasColumnOrder(15); // since Tag is a Domain ValueObject (no identity), but we also don't want to have duplicates, // we need to configure it as a many-to-many relationship, where the tag itself is the primary key builder.HasMany(book => book.Tags) - .WithMany() - .UsingEntity>( - "BookTags", - j => j.HasOne().WithMany().HasForeignKey("TagId"), - j => j.HasOne().WithMany().HasForeignKey("BookId"), - j => - { - j.HasKey("BookId", "TagId"); - j.ToTable("BookTags"); - }); + .WithMany() + .UsingEntity>( + "BookTags", + j => j.HasOne() + .WithMany() + .HasForeignKey("TagId"), + j => j.HasOne() + .WithMany() + .HasForeignKey("BookId"), + j => + { + j.HasKey("BookId", "TagId"); + j.ToTable("BookTags"); + }); builder.HasMany(book => book.Genres) - .WithMany() - .UsingEntity>( - "BookGenres", - j => j.HasOne().WithMany().HasForeignKey("GenreId"), - j => j.HasOne().WithMany().HasForeignKey("BookId"), - j => - { - j.HasKey("BookId", "GenreId"); - j.ToTable("BookGenres"); - }); + .WithMany() + .UsingEntity>( + "BookGenres", + j => j.HasOne() + .WithMany() + .HasForeignKey("GenreId"), + j => j.HasOne() + .WithMany() + .HasForeignKey("BookId"), + j => + { + j.HasKey("BookId", "GenreId"); + j.ToTable("BookGenres"); + }); - builder.Property(book => book.Publisher).HasMaxLength(100).HasColumnOrder(16); - builder.Property(book => book.PageCount).HasColumnOrder(17); - builder.Property(book => book.Format).HasColumnOrder(18); - builder.Property(book => book.Edition).HasMaxLength(50).HasColumnOrder(19); - builder.Property(book => book.VolumeNumber).HasColumnOrder(20); - builder.Property(book => book.ASIN).HasMaxLength(10).HasColumnOrder(21); - builder.Property(book => book.GoodreadsId).HasColumnOrder(22); - builder.Property(book => book.LCCN).HasColumnOrder(23); - builder.Property(book => book.OCLCNumber).HasColumnOrder(24); - builder.Property(book => book.OpenLibraryId).HasMaxLength(50).HasColumnOrder(25); - builder.Property(book => book.LibraryThingId).HasMaxLength(50).HasColumnOrder(26); - builder.Property(book => book.GoogleBooksId).HasMaxLength(12).HasColumnOrder(27); - builder.Property(book => book.BarnesAndNobleId).HasMaxLength(10).HasColumnOrder(28); - builder.Property(book => book.AppleBooksId).HasColumnOrder(29); - builder.Property(book => book.Created).HasColumnOrder(30); - builder.Property(book => book.Updated).HasColumnOrder(31); + builder.Property(book => book.Publisher) + .HasMaxLength(100) + .HasColumnOrder(16); + builder.Property(book => book.PageCount) + .HasColumnOrder(17); + builder.Property(book => book.Format) + .HasConversion() + .HasColumnOrder(18); + builder.Property(book => book.Edition) + .HasMaxLength(50) + .HasColumnOrder(19); + builder.Property(book => book.VolumeNumber) + .HasColumnOrder(20); + builder.Property(book => book.ASIN) + .HasMaxLength(10) + .HasColumnOrder(21); + builder.Property(book => book.GoodreadsId) + .HasColumnOrder(22); + builder.Property(book => book.LCCN) + .HasColumnOrder(23); + builder.Property(book => book.OCLCNumber) + .HasColumnOrder(24); + builder.Property(book => book.OpenLibraryId) + .HasMaxLength(50) + .HasColumnOrder(25); + builder.Property(book => book.LibraryThingId) + .HasMaxLength(50) + .HasColumnOrder(26); + builder.Property(book => book.GoogleBooksId) + .HasMaxLength(12) + .HasColumnOrder(27); + builder.Property(book => book.BarnesAndNobleId) + .HasMaxLength(10) + .HasColumnOrder(28); + builder.Property(book => book.AppleBooksId) + .HasColumnOrder(29); + builder.Property(book => book.Created) + .HasColumnOrder(30); + builder.Property(book => book.Updated) + .HasColumnOrder(31); //builder.HasMany() //.WithMany() @@ -108,8 +160,10 @@ public class BookConfiguration : IEntityTypeConfiguration builder.OwnsMany(book => book.Ratings, ratingBuilder => { ratingBuilder.ToTable("BookRatings"); - ratingBuilder.WithOwner().HasForeignKey("BookId"); - ratingBuilder.Property("Id").ValueGeneratedOnAdd(); + ratingBuilder.WithOwner() + .HasForeignKey("BookId"); + ratingBuilder.Property("Id") + .ValueGeneratedOnAdd(); ratingBuilder.HasKey("Id"); ratingBuilder.Property(rating => rating.Value) @@ -132,8 +186,10 @@ public class BookConfiguration : IEntityTypeConfiguration builder.OwnsMany(book => book.ISBNs, isbnBuilder => { isbnBuilder.ToTable("BookISBNs"); - isbnBuilder.WithOwner().HasForeignKey("BookId"); - isbnBuilder.Property("Id").ValueGeneratedOnAdd(); + isbnBuilder.WithOwner() + .HasForeignKey("BookId"); + isbnBuilder.Property("Id") + .ValueGeneratedOnAdd(); isbnBuilder.HasKey("Id"); isbnBuilder.Property(isbn => isbn.Value) @@ -157,4 +213,4 @@ public class BookConfiguration : IEntityTypeConfiguration // builder.HasKey(c => c.Id); // builder.Property(c => c.Id).ValueGeneratedNever(); // } -//} \ No newline at end of file +//} diff --git a/src/Lumina.DataAccess/Common/Configuration/GenreConfiguration.cs b/src/Lumina.DataAccess/Common/Configuration/GenreConfiguration.cs index 3a50847e..1b10395f 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.Application.Common.DataAccess.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/LibraryConfiguration.cs b/src/Lumina.DataAccess/Common/Configuration/LibraryConfiguration.cs new file mode 100644 index 00000000..bf5d8d63 --- /dev/null +++ b/src/Lumina.DataAccess/Common/Configuration/LibraryConfiguration.cs @@ -0,0 +1,60 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Metadata.Builders; +using System; +#endregion + +namespace Lumina.DataAccess.Common.Configuration; + +/// +/// Configures the entity mapping for the entity. +/// +public class LibraryConfiguration : IEntityTypeConfiguration +{ + /// + /// Configures the entity. + /// + /// The builder to be used to configure the entity. + public void Configure(EntityTypeBuilder builder) + { + builder.ToTable("Libraries"); + builder.HasKey(library => library.Id); + builder.Property(library => library.Id) + .ValueGeneratedNever() // because EF always tries to generate the value for the Id, and because we generate it as part of the aggregate root, we need to tell EF not to generate it + .HasColumnOrder(0); + + builder.Property(library => library.Title) + .IsRequired() + .HasMaxLength(255) + .HasColumnOrder(1); + + builder.Property(library => library.LibraryType) + .IsRequired() + .HasConversion() + .HasColumnOrder(2); + + // one user with many libraries + builder.HasOne(library => library.User) + .WithMany(user => user.Libraries) + .HasForeignKey(library => library.UserId) + .IsRequired(); + + // using OwnsMany because paths are domain Value Objects, thus they have no independent identity, and their lifecycle is bound to the Library + builder.OwnsMany(library => library.ContentLocations, contentLocationBuilder => + { + contentLocationBuilder.ToTable("LibraryContentLocations"); + contentLocationBuilder.WithOwner() + .HasForeignKey("LibraryId"); + + contentLocationBuilder.Property("Id") + .ValueGeneratedOnAdd(); + contentLocationBuilder.HasKey("Id"); + + contentLocationBuilder.Property(location => location.Path) + .HasColumnName("Path") + .HasMaxLength(260) + .IsRequired(); + }); + } +} diff --git a/src/Lumina.DataAccess/Common/Configuration/TagConfiguration.cs b/src/Lumina.DataAccess/Common/Configuration/TagConfiguration.cs index 5695a09b..836acfe5 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.Application.Common.DataAccess.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/Common/Configuration/UserConfiguration.cs b/src/Lumina.DataAccess/Common/Configuration/UserConfiguration.cs new file mode 100644 index 00000000..3cc33a73 --- /dev/null +++ b/src/Lumina.DataAccess/Common/Configuration/UserConfiguration.cs @@ -0,0 +1,56 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Entities.UsersManagement; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Metadata.Builders; +#endregion + +namespace Lumina.DataAccess.Common.Configuration; + +/// +/// Configures the entity mapping for the entity. +/// +public class UserConfiguration : IEntityTypeConfiguration +{ + /// + /// Configures the entity. + /// + /// The builder to be used to configure the entity. + public void Configure(EntityTypeBuilder builder) + { + builder.ToTable("Users"); + builder.HasKey(user => user.Id); + builder.Property(user => user.Id) + .ValueGeneratedNever() // because EF always tries to generate the value for the Id, and because we generate it as part of the aggregate root, we need to tell EF not to generate it + .HasColumnOrder(0); + + builder.Property(user => user.Username) + .IsRequired() + .HasMaxLength(255) + .HasColumnOrder(1); + + builder.Property(user => user.Password) + .IsRequired() + .HasColumnOrder(2); + + builder.Property(user => user.TempPassword) + .HasColumnOrder(3); + + builder.Property(user => user.TotpSecret) + .HasColumnOrder(4); + + builder.Property(user => user.VerificationToken) + .HasColumnOrder(5); + + builder.Property(user => user.VerificationTokenCreated) + .HasColumnOrder(6); + + builder.Property(user => user.TempPasswordCreated) + .HasColumnOrder(7); + + builder.HasMany(user => user.Libraries) + .WithOne(library => library.User) + .HasForeignKey(library => library.UserId) + .IsRequired() // a library must have a user + .OnDelete(DeleteBehavior.Cascade); + } +} diff --git a/src/Lumina.DataAccess/Common/DependencyInjection/DataAccessLayerServices.cs b/src/Lumina.DataAccess/Common/DependencyInjection/DataAccessLayerServices.cs index bc5fd532..53050eeb 100644 --- a/src/Lumina.DataAccess/Common/DependencyInjection/DataAccessLayerServices.cs +++ b/src/Lumina.DataAccess/Common/DependencyInjection/DataAccessLayerServices.cs @@ -7,6 +7,7 @@ using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.DependencyInjection; using System; using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; using System.IO; using System.Linq; using System.Reflection; @@ -17,6 +18,7 @@ namespace Lumina.DataAccess.Common.DependencyInjection; /// /// Contains all services of the DataAccess layer. /// +[ExcludeFromCodeCoverage] public static class DataAccessLayerServices { /// diff --git a/src/Lumina.DataAccess/Common/Migrations/20241103132414_AddUsersTable.Designer.cs b/src/Lumina.DataAccess/Common/Migrations/20241103132414_AddUsersTable.Designer.cs new file mode 100644 index 00000000..09243c42 --- /dev/null +++ b/src/Lumina.DataAccess/Common/Migrations/20241103132414_AddUsersTable.Designer.cs @@ -0,0 +1,366 @@ +// +using System; +using Lumina.DataAccess.Core.UoW; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Migrations; +using Microsoft.EntityFrameworkCore.Storage.ValueConversion; + +#nullable disable + +namespace Lumina.DataAccess.Common.Migrations +{ + [DbContext(typeof(LuminaDbContext))] + [Migration("20241103132414_AddUsersTable")] + partial class AddUsersTable + { + /// + protected override void BuildTargetModel(ModelBuilder modelBuilder) + { +#pragma warning disable 612, 618 + modelBuilder.HasAnnotation("ProductVersion", "8.0.10"); + + modelBuilder.Entity("BookGenres", b => + { + b.Property("BookId") + .HasColumnType("TEXT"); + + b.Property("GenreId") + .HasColumnType("TEXT"); + + b.HasKey("BookId", "GenreId"); + + b.HasIndex("GenreId"); + + b.ToTable("BookGenres", (string)null); + }); + + modelBuilder.Entity("BookTags", b => + { + b.Property("BookId") + .HasColumnType("TEXT"); + + b.Property("TagId") + .HasColumnType("TEXT"); + + b.HasKey("BookId", "TagId"); + + b.HasIndex("TagId"); + + b.ToTable("BookTags", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Common.GenreEntity", b => + { + b.Property("Name") + .HasMaxLength(50) + .HasColumnType("TEXT"); + + b.HasKey("Name"); + + b.ToTable("Genres", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Common.TagEntity", b => + { + b.Property("Name") + .HasMaxLength(50) + .HasColumnType("TEXT"); + + b.HasKey("Name"); + + b.ToTable("Tags", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.UsersManagement.UserEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("Created") + .HasColumnType("TEXT"); + + b.Property("Password") + .IsRequired() + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("TotpSecret") + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("Updated") + .HasColumnType("TEXT"); + + b.Property("Username") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("VerificationToken") + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("VerificationTokenCreated") + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.HasKey("Id"); + + b.ToTable("Users", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.WrittenContentLibrary.BookLibrary.BookEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("ASIN") + .HasMaxLength(10) + .HasColumnType("TEXT") + .HasColumnOrder(21); + + b.Property("AppleBooksId") + .HasColumnType("TEXT") + .HasColumnOrder(29); + + b.Property("BarnesAndNobleId") + .HasMaxLength(10) + .HasColumnType("TEXT") + .HasColumnOrder(28); + + b.Property("Created") + .HasColumnType("TEXT") + .HasColumnOrder(30); + + b.Property("Description") + .HasMaxLength(2000) + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("Edition") + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(19); + + b.Property("Format") + .IsRequired() + .HasColumnType("TEXT") + .HasColumnOrder(18); + + b.Property("GoodreadsId") + .HasColumnType("TEXT") + .HasColumnOrder(22); + + b.Property("GoogleBooksId") + .HasMaxLength(12) + .HasColumnType("TEXT") + .HasColumnOrder(27); + + b.Property("LCCN") + .HasColumnType("TEXT") + .HasColumnOrder(23); + + b.Property("LanguageCode") + .HasColumnType("TEXT") + .HasColumnOrder(10); + + b.Property("LanguageName") + .HasColumnType("TEXT") + .HasColumnOrder(11); + + b.Property("LanguageNativeName") + .HasColumnType("TEXT") + .HasColumnOrder(12); + + b.Property("LibraryThingId") + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(26); + + b.Property("OCLCNumber") + .HasColumnType("TEXT") + .HasColumnOrder(24); + + b.Property("OpenLibraryId") + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(25); + + b.Property("OriginalLanguageCode") + .HasColumnType("TEXT") + .HasColumnOrder(13); + + b.Property("OriginalLanguageName") + .HasColumnType("TEXT") + .HasColumnOrder(14); + + b.Property("OriginalLanguageNativeName") + .HasColumnType("TEXT") + .HasColumnOrder(15); + + b.Property("OriginalReleaseDate") + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("OriginalReleaseYear") + .HasColumnType("INTEGER") + .HasColumnOrder(5); + + b.Property("OriginalTitle") + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("PageCount") + .HasColumnType("INTEGER") + .HasColumnOrder(17); + + b.Property("Publisher") + .HasMaxLength(100) + .HasColumnType("TEXT") + .HasColumnOrder(16); + + b.Property("ReReleaseDate") + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("ReReleaseYear") + .HasColumnType("INTEGER") + .HasColumnOrder(7); + + b.Property("ReleaseCountry") + .HasColumnType("TEXT") + .HasColumnOrder(8); + + b.Property("ReleaseVersion") + .HasColumnType("TEXT") + .HasColumnOrder(9); + + b.Property("Title") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("Updated") + .HasColumnType("TEXT") + .HasColumnOrder(31); + + b.Property("VolumeNumber") + .HasColumnType("INTEGER") + .HasColumnOrder(20); + + b.HasKey("Id"); + + b.ToTable("Books", (string)null); + }); + + modelBuilder.Entity("BookGenres", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.WrittenContentLibrary.BookLibrary.BookEntity", null) + .WithMany() + .HasForeignKey("BookId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Lumina.Application.Common.DataAccess.Entities.Common.GenreEntity", null) + .WithMany() + .HasForeignKey("GenreId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BookTags", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.WrittenContentLibrary.BookLibrary.BookEntity", null) + .WithMany() + .HasForeignKey("BookId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Lumina.Application.Common.DataAccess.Entities.Common.TagEntity", null) + .WithMany() + .HasForeignKey("TagId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.WrittenContentLibrary.BookLibrary.BookEntity", b => + { + b.OwnsMany("Lumina.Application.Common.DataAccess.Entities.WrittenContentLibrary.BookLibrary.BookRatingEntity", "Ratings", b1 => + { + b1.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b1.Property("BookId") + .HasColumnType("TEXT"); + + b1.Property("MaxValue") + .IsRequired() + .HasColumnType("decimal(3,2)"); + + b1.Property("Source") + .IsRequired() + .HasMaxLength(50) + .HasColumnType("TEXT"); + + b1.Property("Value") + .IsRequired() + .HasColumnType("decimal(3,2)"); + + b1.Property("VoteCount") + .HasColumnType("INTEGER"); + + b1.HasKey("Id"); + + b1.HasIndex("BookId"); + + b1.ToTable("BookRatings", (string)null); + + b1.WithOwner() + .HasForeignKey("BookId"); + }); + + b.OwnsMany("Lumina.Application.Common.DataAccess.Entities.WrittenContentLibrary.BookLibrary.IsbnEntity", "ISBNs", b1 => + { + b1.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b1.Property("BookId") + .HasColumnType("TEXT"); + + b1.Property("Format") + .IsRequired() + .HasMaxLength(6) + .HasColumnType("TEXT"); + + b1.Property("Value") + .IsRequired() + .HasMaxLength(13) + .HasColumnType("TEXT") + .HasColumnName("ISBN"); + + b1.HasKey("Id"); + + b1.HasIndex("BookId"); + + b1.ToTable("BookISBNs", (string)null); + + b1.WithOwner() + .HasForeignKey("BookId"); + }); + + b.Navigation("ISBNs"); + + b.Navigation("Ratings"); + }); +#pragma warning restore 612, 618 + } + } +} diff --git a/src/Lumina.DataAccess/Common/Migrations/20241103132414_AddUsersTable.cs b/src/Lumina.DataAccess/Common/Migrations/20241103132414_AddUsersTable.cs new file mode 100644 index 00000000..713e1739 --- /dev/null +++ b/src/Lumina.DataAccess/Common/Migrations/20241103132414_AddUsersTable.cs @@ -0,0 +1,39 @@ +using System; +using Microsoft.EntityFrameworkCore.Migrations; + +#nullable disable + +namespace Lumina.DataAccess.Common.Migrations; + +/// +public partial class AddUsersTable : Migration +{ + /// + protected override void Up(MigrationBuilder migrationBuilder) + { + migrationBuilder.CreateTable( + name: "Users", + columns: table => new + { + Id = table.Column(type: "TEXT", nullable: false), + Username = table.Column(type: "TEXT", maxLength: 255, nullable: false), + Password = table.Column(type: "TEXT", nullable: false), + TotpSecret = table.Column(type: "TEXT", nullable: true), + VerificationToken = table.Column(type: "TEXT", nullable: true), + VerificationTokenCreated = table.Column(type: "TEXT", nullable: true), + Created = table.Column(type: "TEXT", nullable: false), + Updated = table.Column(type: "TEXT", nullable: true) + }, + constraints: table => + { + table.PrimaryKey("PK_Users", x => x.Id); + }); + } + + /// + protected override void Down(MigrationBuilder migrationBuilder) + { + migrationBuilder.DropTable( + name: "Users"); + } +} diff --git a/src/Lumina.DataAccess/Common/Migrations/20241103170430_AddLibrariesTable.Designer.cs b/src/Lumina.DataAccess/Common/Migrations/20241103170430_AddLibrariesTable.Designer.cs new file mode 100644 index 00000000..0ce82078 --- /dev/null +++ b/src/Lumina.DataAccess/Common/Migrations/20241103170430_AddLibrariesTable.Designer.cs @@ -0,0 +1,441 @@ +// +using System; +using Lumina.DataAccess.Core.UoW; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Migrations; +using Microsoft.EntityFrameworkCore.Storage.ValueConversion; + +#nullable disable + +namespace Lumina.DataAccess.Common.Migrations +{ + [DbContext(typeof(LuminaDbContext))] + [Migration("20241103170430_AddLibrariesTable")] + partial class AddLibrariesTable + { + /// + protected override void BuildTargetModel(ModelBuilder modelBuilder) + { +#pragma warning disable 612, 618 + modelBuilder.HasAnnotation("ProductVersion", "8.0.10"); + + modelBuilder.Entity("BookGenres", b => + { + b.Property("BookId") + .HasColumnType("TEXT"); + + b.Property("GenreId") + .HasColumnType("TEXT"); + + b.HasKey("BookId", "GenreId"); + + b.HasIndex("GenreId"); + + b.ToTable("BookGenres", (string)null); + }); + + modelBuilder.Entity("BookTags", b => + { + b.Property("BookId") + .HasColumnType("TEXT"); + + b.Property("TagId") + .HasColumnType("TEXT"); + + b.HasKey("BookId", "TagId"); + + b.HasIndex("TagId"); + + b.ToTable("BookTags", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Common.GenreEntity", b => + { + b.Property("Name") + .HasMaxLength(50) + .HasColumnType("TEXT"); + + b.HasKey("Name"); + + b.ToTable("Genres", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Common.TagEntity", b => + { + b.Property("Name") + .HasMaxLength(50) + .HasColumnType("TEXT"); + + b.HasKey("Name"); + + b.ToTable("Tags", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("Created") + .HasColumnType("TEXT"); + + b.Property("LibraryType") + .IsRequired() + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("Title") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("Updated") + .HasColumnType("TEXT"); + + b.Property("UserId") + .HasColumnType("TEXT"); + + b.HasKey("Id"); + + b.HasIndex("UserId"); + + b.ToTable("Libraries", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary.BookEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("ASIN") + .HasMaxLength(10) + .HasColumnType("TEXT") + .HasColumnOrder(21); + + b.Property("AppleBooksId") + .HasColumnType("TEXT") + .HasColumnOrder(29); + + b.Property("BarnesAndNobleId") + .HasMaxLength(10) + .HasColumnType("TEXT") + .HasColumnOrder(28); + + b.Property("Created") + .HasColumnType("TEXT") + .HasColumnOrder(30); + + b.Property("Description") + .HasMaxLength(2000) + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("Edition") + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(19); + + b.Property("Format") + .HasColumnType("TEXT") + .HasColumnOrder(18); + + b.Property("GoodreadsId") + .HasColumnType("TEXT") + .HasColumnOrder(22); + + b.Property("GoogleBooksId") + .HasMaxLength(12) + .HasColumnType("TEXT") + .HasColumnOrder(27); + + b.Property("LCCN") + .HasColumnType("TEXT") + .HasColumnOrder(23); + + b.Property("LanguageCode") + .HasColumnType("TEXT") + .HasColumnOrder(10); + + b.Property("LanguageName") + .HasColumnType("TEXT") + .HasColumnOrder(11); + + b.Property("LanguageNativeName") + .HasColumnType("TEXT") + .HasColumnOrder(12); + + b.Property("LibraryThingId") + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(26); + + b.Property("OCLCNumber") + .HasColumnType("TEXT") + .HasColumnOrder(24); + + b.Property("OpenLibraryId") + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(25); + + b.Property("OriginalLanguageCode") + .HasColumnType("TEXT") + .HasColumnOrder(13); + + b.Property("OriginalLanguageName") + .HasColumnType("TEXT") + .HasColumnOrder(14); + + b.Property("OriginalLanguageNativeName") + .HasColumnType("TEXT") + .HasColumnOrder(15); + + b.Property("OriginalReleaseDate") + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("OriginalReleaseYear") + .HasColumnType("INTEGER") + .HasColumnOrder(5); + + b.Property("OriginalTitle") + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("PageCount") + .HasColumnType("INTEGER") + .HasColumnOrder(17); + + b.Property("Publisher") + .HasMaxLength(100) + .HasColumnType("TEXT") + .HasColumnOrder(16); + + b.Property("ReReleaseDate") + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("ReReleaseYear") + .HasColumnType("INTEGER") + .HasColumnOrder(7); + + b.Property("ReleaseCountry") + .HasColumnType("TEXT") + .HasColumnOrder(8); + + b.Property("ReleaseVersion") + .HasColumnType("TEXT") + .HasColumnOrder(9); + + b.Property("Title") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("Updated") + .HasColumnType("TEXT") + .HasColumnOrder(31); + + b.Property("VolumeNumber") + .HasColumnType("INTEGER") + .HasColumnOrder(20); + + b.HasKey("Id"); + + b.ToTable("Books", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.UsersManagement.UserEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("Created") + .HasColumnType("TEXT"); + + b.Property("Password") + .IsRequired() + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("TotpSecret") + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("Updated") + .HasColumnType("TEXT"); + + b.Property("Username") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("VerificationToken") + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("VerificationTokenCreated") + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.HasKey("Id"); + + b.ToTable("Users", (string)null); + }); + + modelBuilder.Entity("BookGenres", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary.BookEntity", null) + .WithMany() + .HasForeignKey("BookId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Lumina.Application.Common.DataAccess.Entities.Common.GenreEntity", null) + .WithMany() + .HasForeignKey("GenreId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BookTags", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary.BookEntity", null) + .WithMany() + .HasForeignKey("BookId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Lumina.Application.Common.DataAccess.Entities.Common.TagEntity", null) + .WithMany() + .HasForeignKey("TagId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryEntity", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.UsersManagement.UserEntity", "User") + .WithMany("Libraries") + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.OwnsMany("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryContentLocationEntity", "ContentLocations", b1 => + { + b1.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b1.Property("LibraryId") + .HasColumnType("TEXT"); + + b1.Property("Path") + .IsRequired() + .HasMaxLength(260) + .HasColumnType("TEXT") + .HasColumnName("Path"); + + b1.HasKey("Id"); + + b1.HasIndex("LibraryId"); + + b1.ToTable("LibraryContentLocations", (string)null); + + b1.WithOwner() + .HasForeignKey("LibraryId"); + }); + + b.Navigation("ContentLocations"); + + b.Navigation("User"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary.BookEntity", b => + { + b.OwnsMany("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary.BookRatingEntity", "Ratings", b1 => + { + b1.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b1.Property("BookId") + .HasColumnType("TEXT"); + + b1.Property("MaxValue") + .IsRequired() + .HasColumnType("decimal(3,2)"); + + b1.Property("Source") + .IsRequired() + .HasMaxLength(50) + .HasColumnType("TEXT"); + + b1.Property("Value") + .IsRequired() + .HasColumnType("decimal(3,2)"); + + b1.Property("VoteCount") + .HasColumnType("INTEGER"); + + b1.HasKey("Id"); + + b1.HasIndex("BookId"); + + b1.ToTable("BookRatings", (string)null); + + b1.WithOwner() + .HasForeignKey("BookId"); + }); + + b.OwnsMany("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary.IsbnEntity", "ISBNs", b1 => + { + b1.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b1.Property("BookId") + .HasColumnType("TEXT"); + + b1.Property("Format") + .IsRequired() + .HasMaxLength(6) + .HasColumnType("TEXT"); + + b1.Property("Value") + .IsRequired() + .HasMaxLength(13) + .HasColumnType("TEXT") + .HasColumnName("ISBN"); + + b1.HasKey("Id"); + + b1.HasIndex("BookId"); + + b1.ToTable("BookISBNs", (string)null); + + b1.WithOwner() + .HasForeignKey("BookId"); + }); + + b.Navigation("ISBNs"); + + b.Navigation("Ratings"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.UsersManagement.UserEntity", b => + { + b.Navigation("Libraries"); + }); +#pragma warning restore 612, 618 + } + } +} diff --git a/src/Lumina.DataAccess/Common/Migrations/20241103170430_AddLibrariesTable.cs b/src/Lumina.DataAccess/Common/Migrations/20241103170430_AddLibrariesTable.cs new file mode 100644 index 00000000..e180f918 --- /dev/null +++ b/src/Lumina.DataAccess/Common/Migrations/20241103170430_AddLibrariesTable.cs @@ -0,0 +1,129 @@ +using System; +using Microsoft.EntityFrameworkCore.Migrations; + +#nullable disable + +namespace Lumina.DataAccess.Common.Migrations; + +/// +public partial class AddLibrariesTable : Migration +{ + /// + protected override void Up(MigrationBuilder migrationBuilder) + { + migrationBuilder.AlterColumn( + name: "Format", + table: "Books", + type: "TEXT", + nullable: true, + oldClrType: typeof(string), + oldType: "TEXT"); + + migrationBuilder.AlterColumn( + name: "Id", + table: "BookRatings", + type: "TEXT", + nullable: false, + oldClrType: typeof(int), + oldType: "INTEGER") + .OldAnnotation("Sqlite:Autoincrement", true); + + migrationBuilder.AlterColumn( + name: "Id", + table: "BookISBNs", + type: "TEXT", + nullable: false, + oldClrType: typeof(int), + oldType: "INTEGER") + .OldAnnotation("Sqlite:Autoincrement", true); + + migrationBuilder.CreateTable( + name: "Libraries", + columns: table => new + { + Id = table.Column(type: "TEXT", nullable: false), + Title = table.Column(type: "TEXT", maxLength: 255, nullable: false), + LibraryType = table.Column(type: "TEXT", nullable: false), + UserId = table.Column(type: "TEXT", nullable: false), + Created = table.Column(type: "TEXT", nullable: false), + Updated = table.Column(type: "TEXT", nullable: true) + }, + constraints: table => + { + table.PrimaryKey("PK_Libraries", x => x.Id); + table.ForeignKey( + name: "FK_Libraries_Users_UserId", + column: x => x.UserId, + principalTable: "Users", + principalColumn: "Id", + onDelete: ReferentialAction.Cascade); + }); + + migrationBuilder.CreateTable( + name: "LibraryContentLocations", + columns: table => new + { + Id = table.Column(type: "TEXT", nullable: false), + Path = table.Column(type: "TEXT", maxLength: 260, nullable: false), + LibraryId = table.Column(type: "TEXT", nullable: false) + }, + constraints: table => + { + table.PrimaryKey("PK_LibraryContentLocations", x => x.Id); + table.ForeignKey( + name: "FK_LibraryContentLocations_Libraries_LibraryId", + column: x => x.LibraryId, + principalTable: "Libraries", + principalColumn: "Id", + onDelete: ReferentialAction.Cascade); + }); + + migrationBuilder.CreateIndex( + name: "IX_Libraries_UserId", + table: "Libraries", + column: "UserId"); + + migrationBuilder.CreateIndex( + name: "IX_LibraryContentLocations_LibraryId", + table: "LibraryContentLocations", + column: "LibraryId"); + } + + /// + protected override void Down(MigrationBuilder migrationBuilder) + { + migrationBuilder.DropTable( + name: "LibraryContentLocations"); + + migrationBuilder.DropTable( + name: "Libraries"); + + migrationBuilder.AlterColumn( + name: "Format", + table: "Books", + type: "TEXT", + nullable: false, + defaultValue: "", + oldClrType: typeof(string), + oldType: "TEXT", + oldNullable: true); + + migrationBuilder.AlterColumn( + name: "Id", + table: "BookRatings", + type: "INTEGER", + nullable: false, + oldClrType: typeof(Guid), + oldType: "TEXT") + .Annotation("Sqlite:Autoincrement", true); + + migrationBuilder.AlterColumn( + name: "Id", + table: "BookISBNs", + type: "INTEGER", + nullable: false, + oldClrType: typeof(Guid), + oldType: "TEXT") + .Annotation("Sqlite:Autoincrement", true); + } +} diff --git a/src/Lumina.DataAccess/Common/Migrations/20241111183421_AddUsersTempPasswordColumn.Designer.cs b/src/Lumina.DataAccess/Common/Migrations/20241111183421_AddUsersTempPasswordColumn.Designer.cs new file mode 100644 index 00000000..d142660a --- /dev/null +++ b/src/Lumina.DataAccess/Common/Migrations/20241111183421_AddUsersTempPasswordColumn.Designer.cs @@ -0,0 +1,449 @@ +// +using System; +using Lumina.DataAccess.Core.UoW; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Migrations; +using Microsoft.EntityFrameworkCore.Storage.ValueConversion; + +#nullable disable + +namespace Lumina.DataAccess.Common.Migrations +{ + [DbContext(typeof(LuminaDbContext))] + [Migration("20241111183421_AddUsersTempPasswordColumn")] + partial class AddUsersTempPasswordColumn + { + /// + protected override void BuildTargetModel(ModelBuilder modelBuilder) + { +#pragma warning disable 612, 618 + modelBuilder.HasAnnotation("ProductVersion", "8.0.10"); + + modelBuilder.Entity("BookGenres", b => + { + b.Property("BookId") + .HasColumnType("TEXT"); + + b.Property("GenreId") + .HasColumnType("TEXT"); + + b.HasKey("BookId", "GenreId"); + + b.HasIndex("GenreId"); + + b.ToTable("BookGenres", (string)null); + }); + + modelBuilder.Entity("BookTags", b => + { + b.Property("BookId") + .HasColumnType("TEXT"); + + b.Property("TagId") + .HasColumnType("TEXT"); + + b.HasKey("BookId", "TagId"); + + b.HasIndex("TagId"); + + b.ToTable("BookTags", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Common.GenreEntity", b => + { + b.Property("Name") + .HasMaxLength(50) + .HasColumnType("TEXT"); + + b.HasKey("Name"); + + b.ToTable("Genres", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Common.TagEntity", b => + { + b.Property("Name") + .HasMaxLength(50) + .HasColumnType("TEXT"); + + b.HasKey("Name"); + + b.ToTable("Tags", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("Created") + .HasColumnType("TEXT"); + + b.Property("LibraryType") + .IsRequired() + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("Title") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("Updated") + .HasColumnType("TEXT"); + + b.Property("UserId") + .HasColumnType("TEXT"); + + b.HasKey("Id"); + + b.HasIndex("UserId"); + + b.ToTable("Libraries", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary.BookEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("ASIN") + .HasMaxLength(10) + .HasColumnType("TEXT") + .HasColumnOrder(21); + + b.Property("AppleBooksId") + .HasColumnType("TEXT") + .HasColumnOrder(29); + + b.Property("BarnesAndNobleId") + .HasMaxLength(10) + .HasColumnType("TEXT") + .HasColumnOrder(28); + + b.Property("Created") + .HasColumnType("TEXT") + .HasColumnOrder(30); + + b.Property("Description") + .HasMaxLength(2000) + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("Edition") + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(19); + + b.Property("Format") + .HasColumnType("TEXT") + .HasColumnOrder(18); + + b.Property("GoodreadsId") + .HasColumnType("TEXT") + .HasColumnOrder(22); + + b.Property("GoogleBooksId") + .HasMaxLength(12) + .HasColumnType("TEXT") + .HasColumnOrder(27); + + b.Property("LCCN") + .HasColumnType("TEXT") + .HasColumnOrder(23); + + b.Property("LanguageCode") + .HasColumnType("TEXT") + .HasColumnOrder(10); + + b.Property("LanguageName") + .HasColumnType("TEXT") + .HasColumnOrder(11); + + b.Property("LanguageNativeName") + .HasColumnType("TEXT") + .HasColumnOrder(12); + + b.Property("LibraryThingId") + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(26); + + b.Property("OCLCNumber") + .HasColumnType("TEXT") + .HasColumnOrder(24); + + b.Property("OpenLibraryId") + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(25); + + b.Property("OriginalLanguageCode") + .HasColumnType("TEXT") + .HasColumnOrder(13); + + b.Property("OriginalLanguageName") + .HasColumnType("TEXT") + .HasColumnOrder(14); + + b.Property("OriginalLanguageNativeName") + .HasColumnType("TEXT") + .HasColumnOrder(15); + + b.Property("OriginalReleaseDate") + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("OriginalReleaseYear") + .HasColumnType("INTEGER") + .HasColumnOrder(5); + + b.Property("OriginalTitle") + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("PageCount") + .HasColumnType("INTEGER") + .HasColumnOrder(17); + + b.Property("Publisher") + .HasMaxLength(100) + .HasColumnType("TEXT") + .HasColumnOrder(16); + + b.Property("ReReleaseDate") + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("ReReleaseYear") + .HasColumnType("INTEGER") + .HasColumnOrder(7); + + b.Property("ReleaseCountry") + .HasColumnType("TEXT") + .HasColumnOrder(8); + + b.Property("ReleaseVersion") + .HasColumnType("TEXT") + .HasColumnOrder(9); + + b.Property("Title") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("Updated") + .HasColumnType("TEXT") + .HasColumnOrder(31); + + b.Property("VolumeNumber") + .HasColumnType("INTEGER") + .HasColumnOrder(20); + + b.HasKey("Id"); + + b.ToTable("Books", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.UsersManagement.UserEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("Created") + .HasColumnType("TEXT"); + + b.Property("Password") + .IsRequired() + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("TempPassword") + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("TempPasswordCreated") + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.Property("TotpSecret") + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("Updated") + .HasColumnType("TEXT"); + + b.Property("Username") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("VerificationToken") + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("VerificationTokenCreated") + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.HasKey("Id"); + + b.ToTable("Users", (string)null); + }); + + modelBuilder.Entity("BookGenres", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary.BookEntity", null) + .WithMany() + .HasForeignKey("BookId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Lumina.Application.Common.DataAccess.Entities.Common.GenreEntity", null) + .WithMany() + .HasForeignKey("GenreId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BookTags", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary.BookEntity", null) + .WithMany() + .HasForeignKey("BookId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Lumina.Application.Common.DataAccess.Entities.Common.TagEntity", null) + .WithMany() + .HasForeignKey("TagId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryEntity", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.UsersManagement.UserEntity", "User") + .WithMany("Libraries") + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.OwnsMany("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryContentLocationEntity", "ContentLocations", b1 => + { + b1.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b1.Property("LibraryId") + .HasColumnType("TEXT"); + + b1.Property("Path") + .IsRequired() + .HasMaxLength(260) + .HasColumnType("TEXT") + .HasColumnName("Path"); + + b1.HasKey("Id"); + + b1.HasIndex("LibraryId"); + + b1.ToTable("LibraryContentLocations", (string)null); + + b1.WithOwner() + .HasForeignKey("LibraryId"); + }); + + b.Navigation("ContentLocations"); + + b.Navigation("User"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary.BookEntity", b => + { + b.OwnsMany("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary.BookRatingEntity", "Ratings", b1 => + { + b1.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b1.Property("BookId") + .HasColumnType("TEXT"); + + b1.Property("MaxValue") + .IsRequired() + .HasColumnType("decimal(3,2)"); + + b1.Property("Source") + .IsRequired() + .HasMaxLength(50) + .HasColumnType("TEXT"); + + b1.Property("Value") + .IsRequired() + .HasColumnType("decimal(3,2)"); + + b1.Property("VoteCount") + .HasColumnType("INTEGER"); + + b1.HasKey("Id"); + + b1.HasIndex("BookId"); + + b1.ToTable("BookRatings", (string)null); + + b1.WithOwner() + .HasForeignKey("BookId"); + }); + + b.OwnsMany("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary.IsbnEntity", "ISBNs", b1 => + { + b1.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b1.Property("BookId") + .HasColumnType("TEXT"); + + b1.Property("Format") + .IsRequired() + .HasMaxLength(6) + .HasColumnType("TEXT"); + + b1.Property("Value") + .IsRequired() + .HasMaxLength(13) + .HasColumnType("TEXT") + .HasColumnName("ISBN"); + + b1.HasKey("Id"); + + b1.HasIndex("BookId"); + + b1.ToTable("BookISBNs", (string)null); + + b1.WithOwner() + .HasForeignKey("BookId"); + }); + + b.Navigation("ISBNs"); + + b.Navigation("Ratings"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.UsersManagement.UserEntity", b => + { + b.Navigation("Libraries"); + }); +#pragma warning restore 612, 618 + } + } +} diff --git a/src/Lumina.DataAccess/Common/Migrations/20241111183421_AddUsersTempPasswordColumn.cs b/src/Lumina.DataAccess/Common/Migrations/20241111183421_AddUsersTempPasswordColumn.cs new file mode 100644 index 00000000..2b3f6fb8 --- /dev/null +++ b/src/Lumina.DataAccess/Common/Migrations/20241111183421_AddUsersTempPasswordColumn.cs @@ -0,0 +1,106 @@ +using System; +using Microsoft.EntityFrameworkCore.Migrations; + +#nullable disable + +namespace Lumina.DataAccess.Common.Migrations; + +/// +public partial class AddUsersTempPasswordColumn : Migration +{ + /// + protected override void Up(MigrationBuilder migrationBuilder) + { + migrationBuilder.AlterColumn( + name: "VerificationTokenCreated", + table: "Users", + type: "TEXT", + nullable: true, + oldClrType: typeof(DateTime), + oldType: "TEXT", + oldNullable: true) + .Annotation("Relational:ColumnOrder", 6) + .OldAnnotation("Relational:ColumnOrder", 5); + + migrationBuilder.AlterColumn( + name: "VerificationToken", + table: "Users", + type: "TEXT", + nullable: true, + oldClrType: typeof(string), + oldType: "TEXT", + oldNullable: true) + .Annotation("Relational:ColumnOrder", 5) + .OldAnnotation("Relational:ColumnOrder", 4); + + migrationBuilder.AlterColumn( + name: "TotpSecret", + table: "Users", + type: "TEXT", + nullable: true, + oldClrType: typeof(string), + oldType: "TEXT", + oldNullable: true) + .Annotation("Relational:ColumnOrder", 4) + .OldAnnotation("Relational:ColumnOrder", 3); + + migrationBuilder.AddColumn( + name: "TempPassword", + table: "Users", + type: "TEXT", + nullable: true) + .Annotation("Relational:ColumnOrder", 3); + + migrationBuilder.AddColumn( + name: "TempPasswordCreated", + table: "Users", + type: "TEXT", + nullable: true) + .Annotation("Relational:ColumnOrder", 7); + } + + /// + protected override void Down(MigrationBuilder migrationBuilder) + { + migrationBuilder.DropColumn( + name: "TempPassword", + table: "Users"); + + migrationBuilder.DropColumn( + name: "TempPasswordCreated", + table: "Users"); + + migrationBuilder.AlterColumn( + name: "VerificationTokenCreated", + table: "Users", + type: "TEXT", + nullable: true, + oldClrType: typeof(DateTime), + oldType: "TEXT", + oldNullable: true) + .Annotation("Relational:ColumnOrder", 5) + .OldAnnotation("Relational:ColumnOrder", 6); + + migrationBuilder.AlterColumn( + name: "VerificationToken", + table: "Users", + type: "TEXT", + nullable: true, + oldClrType: typeof(string), + oldType: "TEXT", + oldNullable: true) + .Annotation("Relational:ColumnOrder", 4) + .OldAnnotation("Relational:ColumnOrder", 5); + + migrationBuilder.AlterColumn( + name: "TotpSecret", + table: "Users", + type: "TEXT", + nullable: true, + oldClrType: typeof(string), + oldType: "TEXT", + oldNullable: true) + .Annotation("Relational:ColumnOrder", 3) + .OldAnnotation("Relational:ColumnOrder", 4); + } +} diff --git a/src/Lumina.DataAccess/Common/Migrations/LuminaDbContextModelSnapshot.cs b/src/Lumina.DataAccess/Common/Migrations/LuminaDbContextModelSnapshot.cs index 1c5bbaa3..5c6ec318 100644 --- a/src/Lumina.DataAccess/Common/Migrations/LuminaDbContextModelSnapshot.cs +++ b/src/Lumina.DataAccess/Common/Migrations/LuminaDbContextModelSnapshot.cs @@ -15,7 +15,7 @@ namespace Lumina.DataAccess.Common.Migrations protected override void BuildModel(ModelBuilder modelBuilder) { #pragma warning disable 612, 618 - modelBuilder.HasAnnotation("ProductVersion", "8.0.8"); + modelBuilder.HasAnnotation("ProductVersion", "8.0.10"); modelBuilder.Entity("BookGenres", b => { @@ -47,7 +47,62 @@ namespace Lumina.DataAccess.Common.Migrations b.ToTable("BookTags", (string)null); }); - modelBuilder.Entity("Lumina.Application.Common.Models.Books.BookModel", b => + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Common.GenreEntity", b => + { + b.Property("Name") + .HasMaxLength(50) + .HasColumnType("TEXT"); + + b.HasKey("Name"); + + b.ToTable("Genres", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Common.TagEntity", b => + { + b.Property("Name") + .HasMaxLength(50) + .HasColumnType("TEXT"); + + b.HasKey("Name"); + + b.ToTable("Tags", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("Created") + .HasColumnType("TEXT"); + + b.Property("LibraryType") + .IsRequired() + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("Title") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("Updated") + .HasColumnType("TEXT"); + + b.Property("UserId") + .HasColumnType("TEXT"); + + b.HasKey("Id"); + + b.HasIndex("UserId"); + + b.ToTable("Libraries", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary.BookEntity", b => { b.Property("Id") .HasColumnType("TEXT") @@ -82,7 +137,6 @@ namespace Lumina.DataAccess.Common.Migrations .HasColumnOrder(19); b.Property("Format") - .IsRequired() .HasColumnType("TEXT") .HasColumnOrder(18); @@ -194,37 +248,63 @@ namespace Lumina.DataAccess.Common.Migrations b.ToTable("Books", (string)null); }); - modelBuilder.Entity("Lumina.Application.Common.Models.Common.GenreModel", b => + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.UsersManagement.UserEntity", b => { - b.Property("Name") - .HasMaxLength(50) + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("Created") .HasColumnType("TEXT"); - b.HasKey("Name"); + b.Property("Password") + .IsRequired() + .HasColumnType("TEXT") + .HasColumnOrder(2); - b.ToTable("Genres", (string)null); - }); + b.Property("TempPassword") + .HasColumnType("TEXT") + .HasColumnOrder(3); - modelBuilder.Entity("Lumina.Application.Common.Models.Common.TagModel", b => - { - b.Property("Name") - .HasMaxLength(50) + b.Property("TempPasswordCreated") + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.Property("TotpSecret") + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("Updated") .HasColumnType("TEXT"); - b.HasKey("Name"); + b.Property("Username") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(1); - b.ToTable("Tags", (string)null); + b.Property("VerificationToken") + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("VerificationTokenCreated") + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.HasKey("Id"); + + b.ToTable("Users", (string)null); }); modelBuilder.Entity("BookGenres", b => { - b.HasOne("Lumina.Application.Common.Models.Books.BookModel", null) + b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary.BookEntity", null) .WithMany() .HasForeignKey("BookId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); - b.HasOne("Lumina.Application.Common.Models.Common.GenreModel", null) + b.HasOne("Lumina.Application.Common.DataAccess.Entities.Common.GenreEntity", null) .WithMany() .HasForeignKey("GenreId") .OnDelete(DeleteBehavior.Cascade) @@ -233,31 +313,70 @@ namespace Lumina.DataAccess.Common.Migrations modelBuilder.Entity("BookTags", b => { - b.HasOne("Lumina.Application.Common.Models.Books.BookModel", null) + b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary.BookEntity", null) .WithMany() .HasForeignKey("BookId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); - b.HasOne("Lumina.Application.Common.Models.Common.TagModel", null) + b.HasOne("Lumina.Application.Common.DataAccess.Entities.Common.TagEntity", null) .WithMany() .HasForeignKey("TagId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); }); - modelBuilder.Entity("Lumina.Application.Common.Models.Books.BookModel", b => + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryEntity", b => { - b.OwnsMany("Lumina.Application.Common.Models.Books.BookRatingModel", "Ratings", b1 => + b.HasOne("Lumina.Application.Common.DataAccess.Entities.UsersManagement.UserEntity", "User") + .WithMany("Libraries") + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.OwnsMany("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryContentLocationEntity", "ContentLocations", b1 => { - b1.Property("Id") + b1.Property("Id") .ValueGeneratedOnAdd() - .HasColumnType("INTEGER"); + .HasColumnType("TEXT"); + + b1.Property("LibraryId") + .HasColumnType("TEXT"); + + b1.Property("Path") + .IsRequired() + .HasMaxLength(260) + .HasColumnType("TEXT") + .HasColumnName("Path"); + + b1.HasKey("Id"); + + b1.HasIndex("LibraryId"); + + b1.ToTable("LibraryContentLocations", (string)null); + + b1.WithOwner() + .HasForeignKey("LibraryId"); + }); + + b.Navigation("ContentLocations"); + + b.Navigation("User"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary.BookEntity", b => + { + b.OwnsMany("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary.BookRatingEntity", "Ratings", b1 => + { + b1.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); b1.Property("BookId") .HasColumnType("TEXT"); - b1.Property("MaxValue") + b1.Property("MaxValue") + .IsRequired() .HasColumnType("decimal(3,2)"); b1.Property("Source") @@ -265,7 +384,8 @@ namespace Lumina.DataAccess.Common.Migrations .HasMaxLength(50) .HasColumnType("TEXT"); - b1.Property("Value") + b1.Property("Value") + .IsRequired() .HasColumnType("decimal(3,2)"); b1.Property("VoteCount") @@ -281,11 +401,11 @@ namespace Lumina.DataAccess.Common.Migrations .HasForeignKey("BookId"); }); - b.OwnsMany("Lumina.Application.Common.Models.Books.IsbnModel", "ISBNs", b1 => + b.OwnsMany("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary.IsbnEntity", "ISBNs", b1 => { - b1.Property("Id") + b1.Property("Id") .ValueGeneratedOnAdd() - .HasColumnType("INTEGER"); + .HasColumnType("TEXT"); b1.Property("BookId") .HasColumnType("TEXT"); @@ -315,6 +435,11 @@ namespace Lumina.DataAccess.Common.Migrations b.Navigation("Ratings"); }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.UsersManagement.UserEntity", b => + { + b.Navigation("Libraries"); + }); #pragma warning restore 612, 618 } } diff --git a/src/Lumina.DataAccess/Core/Repositories/Books/BookRepository.cs b/src/Lumina.DataAccess/Core/Repositories/Books/BookRepository.cs index db3d2cac..e1fa1799 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.Application.Common.DataAccess.Entities.Common; +using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.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) + bool bookExists = await _luminaDbContext.Books.AnyAsync(repositoryBook => repositoryBook.Id == book.Id, cancellationToken: cancellationToken).ConfigureAwait(false); + if (bookExists) 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/Repositories/Libraries/LibraryRepository.cs b/src/Lumina.DataAccess/Core/Repositories/Libraries/LibraryRepository.cs new file mode 100644 index 00000000..08e5f75c --- /dev/null +++ b/src/Lumina.DataAccess/Core/Repositories/Libraries/LibraryRepository.cs @@ -0,0 +1,45 @@ +#region ========================================================================= USING ===================================================================================== +using ErrorOr; +using Lumina.Application.Common.DataAccess.Repositories.MediaLibrary; +using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management; +using Lumina.DataAccess.Core.UoW; +using Lumina.Domain.Common.Errors; +using Microsoft.EntityFrameworkCore; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.DataAccess.Core.Repositories.Libraries; + +/// +/// Repository for media libraries. +/// +internal sealed class LibraryRepository : ILibraryRepository +{ + private readonly LuminaDbContext _luminaDbContext; + + /// + /// Initializes a new instance of the class. + /// + /// Injected Entity Framework DbContext. + public LibraryRepository(LuminaDbContext luminaDbContext) + { + _luminaDbContext = luminaDbContext; + } + + /// + /// Adds a new library. + /// + /// The library 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(LibraryEntity library, CancellationToken cancellationToken) + { + bool libraryExists = await _luminaDbContext.Libraries.AnyAsync(repositoryLibrary => repositoryLibrary.Id == library.Id, cancellationToken: cancellationToken).ConfigureAwait(false); + if (libraryExists) + return Errors.Library.LibraryAlreadyExists; + + _luminaDbContext.Libraries.Add(library); + return Result.Created; + } +} diff --git a/src/Lumina.DataAccess/Core/Repositories/Users/UserRepository.cs b/src/Lumina.DataAccess/Core/Repositories/Users/UserRepository.cs new file mode 100644 index 00000000..68b02bc1 --- /dev/null +++ b/src/Lumina.DataAccess/Core/Repositories/Users/UserRepository.cs @@ -0,0 +1,82 @@ +#region ========================================================================= USING ===================================================================================== +using ErrorOr; +using Lumina.Application.Common.DataAccess.Repositories.Users; +using Lumina.Application.Common.DataAccess.Entities.UsersManagement; +using Lumina.DataAccess.Core.UoW; +using Lumina.Domain.Common.Errors; +using Microsoft.EntityFrameworkCore; +using System.Threading; +using System.Threading.Tasks; +using System.Collections.Generic; +#endregion + +namespace Lumina.DataAccess.Core.Repositories.Users; + +/// +/// Repository for users. +/// +internal sealed class UserRepository : IUserRepository +{ + private readonly LuminaDbContext _luminaDbContext; + + /// + /// Initializes a new instance of the class. + /// + /// Injected Entity Framework DbContext. + public UserRepository(LuminaDbContext luminaDbContext) + { + _luminaDbContext = luminaDbContext; + } + + /// + /// Adds a new user. + /// + /// The user 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(UserEntity user, CancellationToken cancellationToken) + { + bool userExists = await _luminaDbContext.Users.AnyAsync(repositoryUser => repositoryUser.Id == user.Id, cancellationToken: cancellationToken).ConfigureAwait(false); + if (userExists) + return Errors.Users.UserAlreadyExists; + + _luminaDbContext.Users.Add(user); + return Result.Created; + } + + /// + /// Gets all users. + /// + /// 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) + { + return await _luminaDbContext.Users.ToListAsync(cancellationToken).ConfigureAwait(false); + } + + /// + /// Gets a username identified by from the repository, if it exists. + /// + /// The username of the user to get. + /// Cancellation token that can be used to stop the execution. + /// An containing either a if found, or an error. + public async Task> GetByUsernameAsync(string username, CancellationToken cancellationToken) + { + return await _luminaDbContext.Users.FirstOrDefaultAsync(user => user.Username == username, cancellationToken).ConfigureAwait(false); + } + + /// + /// Updates an user. + /// + /// Ther user to update. + /// Cancellation token that can be used to stop the execution. + /// An representing either a successfull operation, or an error. + public async Task> UpdateAsync(UserEntity data, CancellationToken cancellationToken) + { + UserEntity? foundUser = await _luminaDbContext.Users.FirstOrDefaultAsync(user => user.Username == data.Username, cancellationToken).ConfigureAwait(false); + if (foundUser is null) + return Errors.Users.UserDoesNotExist; + _luminaDbContext.Entry(foundUser).CurrentValues.SetValues(data); + return Result.Updated; + } +} diff --git a/src/Lumina.DataAccess/Core/UoW/LuminaDbContext.cs b/src/Lumina.DataAccess/Core/UoW/LuminaDbContext.cs index 75fe68d8..0c07678e 100644 --- a/src/Lumina.DataAccess/Core/UoW/LuminaDbContext.cs +++ b/src/Lumina.DataAccess/Core/UoW/LuminaDbContext.cs @@ -1,6 +1,8 @@ #region ========================================================================= USING ===================================================================================== -using Lumina.Contracts.Models.Common; -using Lumina.Contracts.Models.WrittenContentLibrary.BookLibrary; +using Lumina.Application.Common.DataAccess.Entities.Common; +using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management; +using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary; +using Lumina.Application.Common.DataAccess.Entities.UsersManagement; using Lumina.Domain.Common.Events; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.ChangeTracking; @@ -18,7 +20,9 @@ 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!; + public virtual DbSet Users { get; set; } = null!; + public virtual DbSet Libraries { get; set; } = null!; /// /// Initializes a new instance of the class. @@ -41,6 +45,8 @@ public class LuminaDbContext : DbContext base.OnModelCreating(modelBuilder); } + // TODO: implement async versions of SaveChanges + /// /// Overrides the SaveChanges method of the DbContext class to automatically set the Created and Updated properties of entities that implement the . /// @@ -49,8 +55,8 @@ public class LuminaDbContext : DbContext { // get all the entity entries that are either added or modified IEnumerable entries = ChangeTracker.Entries() - .Where(e => e.Entity is IStorageEntity && - (e.State is EntityState.Added or EntityState.Modified)); + .Where(entity => entity.Entity is IStorageEntity && + (entity.State is EntityState.Added or EntityState.Modified)); foreach (EntityEntry? entityEntry in entries) { // if the entity is in Added state, set the Created property to the current date and time diff --git a/src/Lumina.DataAccess/Lumina.DataAccess.csproj b/src/Lumina.DataAccess/Lumina.DataAccess.csproj index ff1e25dc..33a42c4b 100644 --- a/src/Lumina.DataAccess/Lumina.DataAccess.csproj +++ b/src/Lumina.DataAccess/Lumina.DataAccess.csproj @@ -3,9 +3,10 @@ net9.0 disable enable - $(SolutionDir)..\bin\server\ + $(SolutionDir)..\bin\api\ false true + $(WarningsNotAsErrors);NU1901;NU1902;NU1903;NU1904 @@ -17,15 +18,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..c81e80d0 100644 --- a/src/Lumina.Domain/Common/DependencyInjection/DomainLayerServices.cs +++ b/src/Lumina.Domain/Common/DependencyInjection/DomainLayerServices.cs @@ -1,12 +1,11 @@ #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.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Services; +using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Strategies.Environment; +using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Strategies.Path; +using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Strategies.Platform; using Microsoft.Extensions.DependencyInjection; -using System; +using System.Diagnostics.CodeAnalysis; using System.IO.Abstractions; -using System.Runtime.InteropServices; #endregion namespace Lumina.Domain.Common.DependencyInjection; @@ -14,6 +13,7 @@ namespace Lumina.Domain.Common.DependencyInjection; /// /// Contains all services of the Domain layer. /// +[ExcludeFromCodeCoverage] public static class DomainLayerServices { /// diff --git a/src/Lumina.Contracts/Enums/AudioLibrary/AudioContentType.cs b/src/Lumina.Domain/Common/Enums/AudioLibrary/AudioContentType.cs similarity index 96% rename from src/Lumina.Contracts/Enums/AudioLibrary/AudioContentType.cs rename to src/Lumina.Domain/Common/Enums/AudioLibrary/AudioContentType.cs index d73fe365..5d74b9d7 100644 --- a/src/Lumina.Contracts/Enums/AudioLibrary/AudioContentType.cs +++ b/src/Lumina.Domain/Common/Enums/AudioLibrary/AudioContentType.cs @@ -1,4 +1,4 @@ -namespace Lumina.Contracts.Enums.AudioLibrary; +namespace Lumina.Domain.Common.Enums.AudioLibrary; /// /// Enumeration for the types of audio content libraries. @@ -54,4 +54,4 @@ public enum AudioContentType /// A collection of music used as background sound for a movie, TV show, video game, or other media. /// Soundtrack, -} \ No newline at end of file +} diff --git a/src/Lumina.Contracts/Enums/AudioLibrary/AudioRatingSource.cs b/src/Lumina.Domain/Common/Enums/AudioLibrary/AudioRatingSource.cs similarity index 93% rename from src/Lumina.Contracts/Enums/AudioLibrary/AudioRatingSource.cs rename to src/Lumina.Domain/Common/Enums/AudioLibrary/AudioRatingSource.cs index 6662b15a..78bb4c9f 100644 --- a/src/Lumina.Contracts/Enums/AudioLibrary/AudioRatingSource.cs +++ b/src/Lumina.Domain/Common/Enums/AudioLibrary/AudioRatingSource.cs @@ -1,4 +1,4 @@ -namespace Lumina.Contracts.Enums.AudioLibrary; +namespace Lumina.Domain.Common.Enums.AudioLibrary; /// /// Enumeration for the various sources of audio ratings. diff --git a/src/Lumina.Contracts/Enums/BookLibrary/BookFormat.cs b/src/Lumina.Domain/Common/Enums/BookLibrary/BookFormat.cs similarity index 97% rename from src/Lumina.Contracts/Enums/BookLibrary/BookFormat.cs rename to src/Lumina.Domain/Common/Enums/BookLibrary/BookFormat.cs index 3f9354ff..32c98f60 100644 --- a/src/Lumina.Contracts/Enums/BookLibrary/BookFormat.cs +++ b/src/Lumina.Domain/Common/Enums/BookLibrary/BookFormat.cs @@ -1,4 +1,4 @@ -namespace Lumina.Contracts.Enums.BookLibrary; +namespace Lumina.Domain.Common.Enums.BookLibrary; /// /// Enumeration for various book formats. diff --git a/src/Lumina.Contracts/Enums/BookLibrary/BookRatingSource.cs b/src/Lumina.Domain/Common/Enums/BookLibrary/BookRatingSource.cs similarity index 93% rename from src/Lumina.Contracts/Enums/BookLibrary/BookRatingSource.cs rename to src/Lumina.Domain/Common/Enums/BookLibrary/BookRatingSource.cs index 2e2c50c4..fa3e2bca 100644 --- a/src/Lumina.Contracts/Enums/BookLibrary/BookRatingSource.cs +++ b/src/Lumina.Domain/Common/Enums/BookLibrary/BookRatingSource.cs @@ -1,4 +1,4 @@ -namespace Lumina.Contracts.Enums.BookLibrary; +namespace Lumina.Domain.Common.Enums.BookLibrary; /// /// Enumeration for the various sources of book ratings. diff --git a/src/Lumina.Contracts/Enums/BookLibrary/IsbnFormat.cs b/src/Lumina.Domain/Common/Enums/BookLibrary/IsbnFormat.cs similarity index 90% rename from src/Lumina.Contracts/Enums/BookLibrary/IsbnFormat.cs rename to src/Lumina.Domain/Common/Enums/BookLibrary/IsbnFormat.cs index 977b6ff1..b0d8e48e 100644 --- a/src/Lumina.Contracts/Enums/BookLibrary/IsbnFormat.cs +++ b/src/Lumina.Domain/Common/Enums/BookLibrary/IsbnFormat.cs @@ -1,4 +1,4 @@ -namespace Lumina.Contracts.Enums.BookLibrary; +namespace Lumina.Domain.Common.Enums.BookLibrary; /// /// Enumeration for the different ISBN (International Standard Book Number) formats. diff --git a/src/Lumina.Contracts/Enums/BookLibrary/WrittenContentType.cs b/src/Lumina.Domain/Common/Enums/BookLibrary/WrittenContentType.cs similarity index 96% rename from src/Lumina.Contracts/Enums/BookLibrary/WrittenContentType.cs rename to src/Lumina.Domain/Common/Enums/BookLibrary/WrittenContentType.cs index 329b3ed4..63d8a554 100644 --- a/src/Lumina.Contracts/Enums/BookLibrary/WrittenContentType.cs +++ b/src/Lumina.Domain/Common/Enums/BookLibrary/WrittenContentType.cs @@ -1,4 +1,4 @@ -namespace Lumina.Contracts.Enums.BookLibrary; +namespace Lumina.Domain.Common.Enums.BookLibrary; /// /// Enumeration for the types of written content libraries. diff --git a/src/Lumina.Contracts/Enums/FileSystem/FileAccessMode.cs b/src/Lumina.Domain/Common/Enums/FileSystem/FileAccessMode.cs similarity index 93% rename from src/Lumina.Contracts/Enums/FileSystem/FileAccessMode.cs rename to src/Lumina.Domain/Common/Enums/FileSystem/FileAccessMode.cs index 1861ac81..7a975756 100644 --- a/src/Lumina.Contracts/Enums/FileSystem/FileAccessMode.cs +++ b/src/Lumina.Domain/Common/Enums/FileSystem/FileAccessMode.cs @@ -1,4 +1,4 @@ -namespace Lumina.Contracts.Enums.FileSystem; +namespace Lumina.Domain.Common.Enums.FileSystem; /// /// Enumeration for file access mode types. diff --git a/src/Lumina.Contracts/Enums/FileSystem/FileSystemItemStatus.cs b/src/Lumina.Domain/Common/Enums/FileSystem/FileSystemItemStatus.cs similarity index 91% rename from src/Lumina.Contracts/Enums/FileSystem/FileSystemItemStatus.cs rename to src/Lumina.Domain/Common/Enums/FileSystem/FileSystemItemStatus.cs index 04cb3480..de6e7347 100644 --- a/src/Lumina.Contracts/Enums/FileSystem/FileSystemItemStatus.cs +++ b/src/Lumina.Domain/Common/Enums/FileSystem/FileSystemItemStatus.cs @@ -1,4 +1,4 @@ -namespace Lumina.Contracts.Enums.FileSystem; +namespace Lumina.Domain.Common.Enums.FileSystem; /// /// Enumeration for file system item statuses types. diff --git a/src/Lumina.Contracts/Enums/FileSystem/FileSystemItemType.cs b/src/Lumina.Domain/Common/Enums/FileSystem/FileSystemItemType.cs similarity index 91% rename from src/Lumina.Contracts/Enums/FileSystem/FileSystemItemType.cs rename to src/Lumina.Domain/Common/Enums/FileSystem/FileSystemItemType.cs index e34dad49..7acd64c4 100644 --- a/src/Lumina.Contracts/Enums/FileSystem/FileSystemItemType.cs +++ b/src/Lumina.Domain/Common/Enums/FileSystem/FileSystemItemType.cs @@ -1,4 +1,4 @@ -namespace Lumina.Contracts.Enums.FileSystem; +namespace Lumina.Domain.Common.Enums.FileSystem; /// /// Enumeration for the types of file system elements. diff --git a/src/Lumina.Contracts/Enums/FileSystem/PlatformType.cs b/src/Lumina.Domain/Common/Enums/FileSystem/PlatformType.cs similarity index 86% rename from src/Lumina.Contracts/Enums/FileSystem/PlatformType.cs rename to src/Lumina.Domain/Common/Enums/FileSystem/PlatformType.cs index 61857f54..4bded18c 100644 --- a/src/Lumina.Contracts/Enums/FileSystem/PlatformType.cs +++ b/src/Lumina.Domain/Common/Enums/FileSystem/PlatformType.cs @@ -1,4 +1,4 @@ -namespace Lumina.Contracts.Enums.FileSystem; +namespace Lumina.Domain.Common.Enums.FileSystem; /// /// Enumeration for platform types. diff --git a/src/Lumina.Domain/Common/Enums/MediaLibrary/LibraryType.cs b/src/Lumina.Domain/Common/Enums/MediaLibrary/LibraryType.cs new file mode 100644 index 00000000..7c917997 --- /dev/null +++ b/src/Lumina.Domain/Common/Enums/MediaLibrary/LibraryType.cs @@ -0,0 +1,187 @@ +namespace Lumina.Domain.Common.Enums.MediaLibrary; + +/// +/// Enumeration for the types of libraries. +/// +public enum LibraryType +{ + /// + /// Traditional printed books in physical format. + /// + Book, + + /// + /// Digital books in electronic format (e.g., PDF, EPUB, MOBI). + /// + EBook, + + /// + /// Comic books in digital or physical format. + /// + ComicBook, + + /// + /// Periodical publications containing articles and illustrations. + /// + Magazine, + + /// + /// Periodical publication containing news. + /// + Newspaper, + + /// + /// Japanese-style comics and graphic novels. + /// + Manga, + + /// + /// Extended comic-format narratives, typically containing a complete story. + /// + GraphicNovel, + + /// + /// Scholarly articles and research papers. + /// + AcademicPaper, + + /// + /// Musical notation and scores. + /// + SheetMusic, + + /// + /// Television series and episodic content. + /// + TvShow, + + /// + /// Feature-length films and motion pictures. + /// + Movie, + + /// + /// Non-fiction films presenting factual information. + /// + Documentary, + + /// + /// Japanese animation series and films. + /// + Anime, + + /// + /// Recorded live music performances and concerts. + /// + ConcertVideo, + + /// + /// Educational and instructional videos. + /// + TutorialVideo, + + /// + /// Personally recorded videos and family footage. + /// + HomeVideo, + + /// + /// Videos sourced from YouTube platform. + /// + YouTubeVideo, + + /// + /// Professional or amateur music video productions. + /// + MusicVideo, + + /// + /// Videos recorded during live performances or events. + /// + LiveRecordingVideo, + + /// + /// Recorded conversations and Q&A sessions in video format. + /// + InterviewVideo, + + /// + /// Videos of musical performances covering other artists' work. + /// + CoverSongVideo, + + /// + /// Video format podcasts and episodic content. + /// + PodcastVideo, + + /// + /// Audio recordings of musical content. + /// + Music, + + /// + /// Narrated books in audio format. + /// + Audiobook, + + /// + /// Audio recordings from live performances or events. + /// + LiveRecordingAudio, + + /// + /// Recorded conversations and Q&A sessions in audio format. + /// + InterviewAudio, + + /// + /// Audio recordings of musical performances covering other artists' work. + /// + CoverSongAudio, + + /// + /// Modified or reinterpreted versions of original musical recordings. + /// + Remix, + + /// + /// Audio clips used for sound design and production. + /// + SoundEffect, + + /// + /// Audio format podcasts and episodic content. + /// + PodcastAudio, + + /// + /// Digital images and photographs. + /// + Photo, + + /// + /// Curated sequences of media items. + /// + Playlist, + + /// + /// Grouped sets of related media items. + /// + Collection, + + /// + /// Text files containing dialogue translations for video content. + /// + Subtitles, + + /// + /// Text files containing words and timing for musical content. + /// + Lyrics, + + /// + /// A collection of media that does not fit into any other category. + /// + Other +} diff --git a/src/Lumina.Contracts/Enums/Library/MiscellaneousContentType.cs b/src/Lumina.Domain/Common/Enums/MediaLibrary/MiscellaneousContentType.cs similarity index 82% rename from src/Lumina.Contracts/Enums/Library/MiscellaneousContentType.cs rename to src/Lumina.Domain/Common/Enums/MediaLibrary/MiscellaneousContentType.cs index 6eaf688a..c6d40e05 100644 --- a/src/Lumina.Contracts/Enums/Library/MiscellaneousContentType.cs +++ b/src/Lumina.Domain/Common/Enums/MediaLibrary/MiscellaneousContentType.cs @@ -1,4 +1,4 @@ -namespace Lumina.Contracts.Enums.Library; +namespace Lumina.Domain.Common.Enums.MediaLibrary; /// /// Enumeration for the types of miscellaneous content libraries. @@ -9,4 +9,4 @@ public enum MiscellaneousContentType /// A collection of media that does not fit into any other category. /// Other, -} \ No newline at end of file +} diff --git a/src/Lumina.Contracts/Enums/PhotoLibrary/ImageType.cs b/src/Lumina.Domain/Common/Enums/PhotoLibrary/ImageType.cs similarity index 96% rename from src/Lumina.Contracts/Enums/PhotoLibrary/ImageType.cs rename to src/Lumina.Domain/Common/Enums/PhotoLibrary/ImageType.cs index 6ba8a7e9..1c63946c 100644 --- a/src/Lumina.Contracts/Enums/PhotoLibrary/ImageType.cs +++ b/src/Lumina.Domain/Common/Enums/PhotoLibrary/ImageType.cs @@ -1,4 +1,4 @@ -namespace Lumina.Contracts.Enums.PhotoLibrary; +namespace Lumina.Domain.Common.Enums.PhotoLibrary; /// /// Enumeration for known image types. diff --git a/src/Lumina.Contracts/Enums/PhotoLibrary/VisualContentType.cs b/src/Lumina.Domain/Common/Enums/PhotoLibrary/VisualContentType.cs similarity index 81% rename from src/Lumina.Contracts/Enums/PhotoLibrary/VisualContentType.cs rename to src/Lumina.Domain/Common/Enums/PhotoLibrary/VisualContentType.cs index 3e4e8707..9f749b5f 100644 --- a/src/Lumina.Contracts/Enums/PhotoLibrary/VisualContentType.cs +++ b/src/Lumina.Domain/Common/Enums/PhotoLibrary/VisualContentType.cs @@ -1,4 +1,4 @@ -namespace Lumina.Contracts.Enums.PhotoLibrary; +namespace Lumina.Domain.Common.Enums.PhotoLibrary; /// /// Enumeration for the types of visual content libraries. diff --git a/src/Lumina.Contracts/Enums/VideoLibrary/VideoContentType.cs b/src/Lumina.Domain/Common/Enums/VideoLibrary/VideoContentType.cs similarity index 96% rename from src/Lumina.Contracts/Enums/VideoLibrary/VideoContentType.cs rename to src/Lumina.Domain/Common/Enums/VideoLibrary/VideoContentType.cs index f6f5f57a..8341520f 100644 --- a/src/Lumina.Contracts/Enums/VideoLibrary/VideoContentType.cs +++ b/src/Lumina.Domain/Common/Enums/VideoLibrary/VideoContentType.cs @@ -1,4 +1,4 @@ -namespace Lumina.Contracts.Enums.VideoLibrary; +namespace Lumina.Domain.Common.Enums.VideoLibrary; /// /// Enumeration for the types of video content libraries. diff --git a/src/Lumina.Contracts/Enums/VideoLibrary/VideoRatingSource.cs b/src/Lumina.Domain/Common/Enums/VideoLibrary/VideoRatingSource.cs similarity index 94% rename from src/Lumina.Contracts/Enums/VideoLibrary/VideoRatingSource.cs rename to src/Lumina.Domain/Common/Enums/VideoLibrary/VideoRatingSource.cs index 05c81e4f..7778e2dd 100644 --- a/src/Lumina.Contracts/Enums/VideoLibrary/VideoRatingSource.cs +++ b/src/Lumina.Domain/Common/Enums/VideoLibrary/VideoRatingSource.cs @@ -1,4 +1,4 @@ -namespace Lumina.Contracts.Enums.VideoLibrary; +namespace Lumina.Domain.Common.Enums.VideoLibrary; /// /// Enumeration for the various sources of video ratings. diff --git a/src/Lumina.Domain/Common/Errors/Errors.FileManagement.cs b/src/Lumina.Domain/Common/Errors/Errors.FileManagement.cs deleted file mode 100644 index eeef6155..00000000 --- a/src/Lumina.Domain/Common/Errors/Errors.FileManagement.cs +++ /dev/null @@ -1,32 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using ErrorOr; -#endregion - -namespace Lumina.Domain.Common.Errors; - -/// -/// File management error types. -/// -public static partial class Errors -{ - public static class FileManagement - { - 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)); - } -} diff --git a/src/Lumina.Domain/Common/Errors/Errors.FileSystemManagement.cs b/src/Lumina.Domain/Common/Errors/Errors.FileSystemManagement.cs new file mode 100644 index 00000000..f7613977 --- /dev/null +++ b/src/Lumina.Domain/Common/Errors/Errors.FileSystemManagement.cs @@ -0,0 +1,33 @@ +#region ========================================================================= USING ===================================================================================== +using ErrorOr; +#endregion + +namespace Lumina.Domain.Common.Errors; + +/// +/// File management error types. +/// +public static partial class Errors +{ + public static class FileSystemManagement + { + public static Error ParentNodeCannotBeNull => Error.Failure(description: nameof(ParentNodeCannotBeNull)); + public static Error PathMustBeMaximum260CharactersLong => Error.Failure(description: nameof(PathMustBeMaximum260CharactersLong)); + 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.Library.cs b/src/Lumina.Domain/Common/Errors/Errors.Library.cs new file mode 100644 index 00000000..94b991ba --- /dev/null +++ b/src/Lumina.Domain/Common/Errors/Errors.Library.cs @@ -0,0 +1,23 @@ +#region ========================================================================= USING ===================================================================================== +using ErrorOr; +#endregion + +namespace Lumina.Domain.Common.Errors; + +/// +/// Media Library error types. +/// +public static partial class Errors +{ + public static class Library + { + public static Error UserIdCannotBeEmpty => Error.Forbidden(description: nameof(UserIdCannotBeEmpty)); + public static Error LibraryAlreadyExists => Error.Conflict(description: nameof(LibraryAlreadyExists)); + public static Error LibraryTypeCannotBeNull => Error.Validation(description: nameof(LibraryTypeCannotBeNull)); + public static Error UnknownLibraryType => Error.Unexpected(description: nameof(UnknownLibraryType)); + public static Error PathsListCannotBeNull => Error.Validation(description: nameof(PathsListCannotBeNull)); + public static Error PathsListCannotBeEmpty => Error.Validation(description: nameof(PathsListCannotBeEmpty)); + public static Error TitleCannotBeEmpty => Error.Validation(description: nameof(TitleCannotBeEmpty)); + public static Error TitleMustBeMaximum255CharactersLong => Error.Validation(description: nameof(TitleMustBeMaximum255CharactersLong)); + } +} 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.Users.cs b/src/Lumina.Domain/Common/Errors/Errors.Users.cs new file mode 100644 index 00000000..7e1da781 --- /dev/null +++ b/src/Lumina.Domain/Common/Errors/Errors.Users.cs @@ -0,0 +1,17 @@ +#region ========================================================================= USING ===================================================================================== +using ErrorOr; +#endregion + +namespace Lumina.Domain.Common.Errors; + +/// +/// Users error types. +/// +public static partial class Errors +{ + public static class Users + { + public static Error UserAlreadyExists => Error.Conflict(description: nameof(UserAlreadyExists)); + public static Error UserDoesNotExist => Error.Conflict(description: nameof(UserDoesNotExist)); + } +} 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/Strategies/Platform/IPlatformContext.cs b/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Strategies/Platform/IPlatformContext.cs deleted file mode 100644 index b285d2aa..00000000 --- a/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Strategies/Platform/IPlatformContext.cs +++ /dev/null @@ -1,22 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using Lumina.Contracts.Enums.FileSystem; -using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.Strategies.Path; -#endregion - -namespace Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.Strategies.Platform; - -/// -/// Interface for defining the contract of a platform-specific context. -/// -public interface IPlatformContext -{ - /// - /// Gets the platform for the current platform context. - /// - PlatformType Platform { get; } - - /// - /// 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/AudioLibrary/AudioLibraryAggregate/ValueObjects/AudioMetadata.cs b/src/Lumina.Domain/Core/BoundedContexts/AudioLibraryBoundedContext/AudioLibraryAggregate/ValueObjects/AudioMetadata.cs similarity index 98% rename from src/Lumina.Domain/Core/Aggregates/AudioLibrary/AudioLibraryAggregate/ValueObjects/AudioMetadata.cs rename to src/Lumina.Domain/Core/BoundedContexts/AudioLibraryBoundedContext/AudioLibraryAggregate/ValueObjects/AudioMetadata.cs index 90cd02ae..79848bc6 100644 --- a/src/Lumina.Domain/Core/Aggregates/AudioLibrary/AudioLibraryAggregate/ValueObjects/AudioMetadata.cs +++ b/src/Lumina.Domain/Core/BoundedContexts/AudioLibraryBoundedContext/AudioLibraryAggregate/ValueObjects/AudioMetadata.cs @@ -6,7 +6,7 @@ using System.Collections.Generic; using System.Diagnostics; #endregion -namespace Lumina.Domain.Core.Aggregates.AudioLibrary.AudioLibraryAggregate.ValueObjects; +namespace Lumina.Domain.Core.BoundedContexts.AudioLibraryBoundedContext.AudioLibraryAggregate.ValueObjects; /// /// Value Object for the audio metadata of a media element. @@ -150,4 +150,4 @@ public class AudioMetadata : BaseMetadata yield return AudioCodec; yield return Bitrate; } -} \ No newline at end of file +} diff --git a/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Entities/Directory.cs b/src/Lumina.Domain/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Entities/Directory.cs similarity index 93% rename from src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Entities/Directory.cs rename to src/Lumina.Domain/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Entities/Directory.cs index 26c725e2..49093099 100644 --- a/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Entities/Directory.cs +++ b/src/Lumina.Domain/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Entities/Directory.cs @@ -1,14 +1,15 @@ #region ========================================================================= USING ===================================================================================== using ErrorOr; -using Lumina.Contracts.Enums.FileSystem; +using Lumina.Domain.Common.Enums.FileSystem; using Lumina.Domain.Common.Primitives; -using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.ValueObjects; +using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate; +using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.ValueObjects; using System; using System.Collections.Generic; using System.Diagnostics; #endregion -namespace Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.Entities; +namespace Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.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/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Entities/File.cs similarity index 92% rename from src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Entities/File.cs rename to src/Lumina.Domain/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Entities/File.cs index b2a01e1f..832087d0 100644 --- a/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Entities/File.cs +++ b/src/Lumina.Domain/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Entities/File.cs @@ -1,14 +1,15 @@ #region ========================================================================= USING ===================================================================================== using ErrorOr; -using Lumina.Contracts.Enums.FileSystem; +using Lumina.Domain.Common.Enums.FileSystem; using Lumina.Domain.Common.Errors; using Lumina.Domain.Common.Primitives; -using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.ValueObjects; +using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate; +using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.ValueObjects; using System; using System.Diagnostics; #endregion -namespace Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.Entities; +namespace Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.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/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Entities/UnixRootItem.cs similarity index 76% rename from src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Entities/UnixRootItem.cs rename to src/Lumina.Domain/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Entities/UnixRootItem.cs index 80760fa3..c74bcfcd 100644 --- a/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Entities/UnixRootItem.cs +++ b/src/Lumina.Domain/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Entities/UnixRootItem.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.Common.Enums.FileSystem; +using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate; +using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.ValueObjects; using System.Collections.Generic; using System.Diagnostics; #endregion -namespace Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.Entities; +namespace Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Entities; /// /// Entity representing a file system root item on Unix platforms. @@ -38,15 +39,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/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Entities/WindowsRootItem.cs similarity index 89% rename from src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Entities/WindowsRootItem.cs rename to src/Lumina.Domain/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Entities/WindowsRootItem.cs index ac825e1b..66eb6214 100644 --- a/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Entities/WindowsRootItem.cs +++ b/src/Lumina.Domain/Core/BoundedContexts/FileSystemManagementBoundedContext/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.Common.Enums.FileSystem; +using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate; +using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.ValueObjects; using System.Collections.Generic; using System.Diagnostics; #endregion -namespace Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.Entities; +namespace Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.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/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/FileSystemItem.cs similarity index 82% rename from src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/FileSystemItem.cs rename to src/Lumina.Domain/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/FileSystemItem.cs index 3602546a..7687ce7b 100644 --- a/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/FileSystemItem.cs +++ b/src/Lumina.Domain/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/FileSystemItem.cs @@ -1,14 +1,14 @@ -#region ========================================================================= USING ===================================================================================== +#region ========================================================================= USING ===================================================================================== using ErrorOr; -using Lumina.Contracts.Enums.FileSystem; +using Lumina.Domain.Common.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.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.ValueObjects; using System.Diagnostics; #endregion -namespace Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate; +namespace Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.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/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Services/DirectoryProviderService.cs similarity index 95% rename from src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Services/DirectoryProviderService.cs rename to src/Lumina.Domain/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Services/DirectoryProviderService.cs index ae6580b2..0b0247f8 100644 --- a/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Services/DirectoryProviderService.cs +++ b/src/Lumina.Domain/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Services/DirectoryProviderService.cs @@ -1,9 +1,10 @@ #region ========================================================================= USING ===================================================================================== using ErrorOr; -using Lumina.Contracts.Enums.FileSystem; +using Lumina.Domain.Common.Enums.FileSystem; using Lumina.Domain.Common.Errors; using Lumina.Domain.Common.Primitives; -using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.ValueObjects; +using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Services; +using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.ValueObjects; using System; using System.Collections.Generic; using System.IO; @@ -11,7 +12,7 @@ using System.IO.Abstractions; using System.Linq; #endregion -namespace Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.Services; +namespace Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Services; /// /// Directory provider for local file systems. @@ -146,7 +147,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 +180,7 @@ internal class DirectoryProviderService : IDirectoryProviderService } catch { - return Errors.FileManagement.DirectoryCopyError; + return Errors.FileSystemManagement.DirectoryCopyError; } } @@ -209,7 +210,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 +222,7 @@ internal class DirectoryProviderService : IDirectoryProviderService } catch { - return Errors.FileManagement.DirectoryMoveError; + return Errors.FileSystemManagement.DirectoryMoveError; } } @@ -247,7 +248,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 +298,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/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Services/DirectoryService.cs similarity index 95% rename from src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Services/DirectoryService.cs rename to src/Lumina.Domain/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Services/DirectoryService.cs index 4069d457..7a98d2dd 100644 --- a/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Services/DirectoryService.cs +++ b/src/Lumina.Domain/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Services/DirectoryService.cs @@ -1,17 +1,17 @@ #region ========================================================================= USING ===================================================================================== using ErrorOr; -using Lumina.Contracts.Enums.FileSystem; +using Lumina.Domain.Common.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.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Strategies.Environment; +using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Strategies.Platform; +using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.ValueObjects; +using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Entities; using System; using System.Collections.Generic; #endregion -namespace Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.Services; +namespace Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.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/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Services/DriveService.cs similarity index 82% rename from src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Services/DriveService.cs rename to src/Lumina.Domain/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Services/DriveService.cs index 07fcfa43..1291f3f7 100644 --- a/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Services/DriveService.cs +++ b/src/Lumina.Domain/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Services/DriveService.cs @@ -1,14 +1,16 @@ #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.Common.Enums.FileSystem; +using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate; +using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Services; +using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Strategies.Platform; +using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Entities; using System.Collections.Generic; using System.IO.Abstractions; using System.Linq; #endregion -namespace Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.Services; +namespace Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Services; /// /// Service for handling drives. diff --git a/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Services/FileProviderService.cs b/src/Lumina.Domain/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Services/FileProviderService.cs similarity index 93% rename from src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Services/FileProviderService.cs rename to src/Lumina.Domain/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Services/FileProviderService.cs index 82746207..a16159a5 100644 --- a/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Services/FileProviderService.cs +++ b/src/Lumina.Domain/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Services/FileProviderService.cs @@ -1,9 +1,9 @@ #region ========================================================================= USING ===================================================================================== using ErrorOr; -using Lumina.Contracts.Enums.FileSystem; +using Lumina.Domain.Common.Enums.FileSystem; using Lumina.Domain.Common.Errors; using Lumina.Domain.Common.Primitives; -using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.ValueObjects; +using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.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.BoundedContexts.FileSystemManagementBoundedContext.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/BoundedContexts/FileSystemManagementBoundedContext/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/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Services/FileService.cs index 444f5dd5..a9f4a27e 100644 --- a/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Services/FileService.cs +++ b/src/Lumina.Domain/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Services/FileService.cs @@ -1,17 +1,17 @@ #region ========================================================================= USING ===================================================================================== using ErrorOr; -using Lumina.Contracts.Enums.FileSystem; +using Lumina.Domain.Common.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.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Strategies.Environment; +using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Strategies.Platform; +using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.ValueObjects; +using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Entities; using System; using System.Collections.Generic; #endregion -namespace Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.Services; +namespace Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.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/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Services/FileSystemPermissionsService.cs similarity index 60% rename from src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Services/FileSystemPermissionsService.cs rename to src/Lumina.Domain/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Services/FileSystemPermissionsService.cs index 0a24ba0f..93393e83 100644 --- a/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Services/FileSystemPermissionsService.cs +++ b/src/Lumina.Domain/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Services/FileSystemPermissionsService.cs @@ -1,9 +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 Mono.Unix; -using Mono.Unix.Native; +using Lumina.Domain.Common.Enums.FileSystem; +using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Strategies.Platform; +using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.ValueObjects; using System; using System.IO; using System.Runtime.Versioning; @@ -11,7 +9,7 @@ using System.Security.AccessControl; using System.Security.Principal; #endregion -namespace Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.Services; +namespace Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Services; /// /// Service for file system permissions. @@ -40,7 +38,7 @@ internal class FileSystemPermissionsService : IFileSystemPermissionsService // T { PlatformType platformType = _platformContextManager.GetCurrentContext().Platform; if (platformType == PlatformType.Unix) - return CanAccessPathLinux(path.Path, accessMode); + return CanAccessPathUnix(path.Path, accessMode); else if (platformType == PlatformType.Windows) #pragma warning disable CA1416 // Validate platform compatibility return CanAccessPathWindows(path.Path, accessMode, isFile); @@ -50,51 +48,99 @@ internal class FileSystemPermissionsService : IFileSystemPermissionsService // T } /// - /// Checks if a the current user has access permissions on Linux for , with . + /// Checks if a the current user has access permissions on Unix for , with . /// /// The path for which to check the access. /// The access mode in which to check that path access. /// if the current user has rights for the specified path and acccess mode, otherwise. - /// Thrown when trying to check access for a mode that is not supported - private static bool CanAccessPathLinux(string path, FileAccessMode accessMode) + /// Thrown when trying to check access for a mode that is not supported. + private static bool CanAccessPathUnix(string path, FileAccessMode accessMode) { - AccessModes modes; - UnixFileSystemInfo fileInfo = new UnixFileInfo(path); - switch (accessMode) + try { - case FileAccessMode.ReadProperties: - // we would typically need execute permissions on a directory, to list its contents or view file properties - if (fileInfo.FileType == FileTypes.Directory) - return fileInfo.CanAccess(AccessModes.X_OK); - // for files, just verifying existence might be sufficient for reading properties - return fileInfo.Exists; - case FileAccessMode.ReadContents: - return fileInfo.CanAccess(AccessModes.R_OK); - case FileAccessMode.Write: - modes = AccessModes.W_OK; - break; - case FileAccessMode.Execute: - modes = AccessModes.X_OK; - break; - case FileAccessMode.ListDirectory: - modes = AccessModes.F_OK; // check existence, not an exact match but the closest - break; - case FileAccessMode.Delete: - if (fileInfo.FileType == FileTypes.Directory) - return fileInfo.CanAccess(AccessModes.W_OK | AccessModes.X_OK); // to delete a directory, we need write and execute permissions on the directory itself - else - { - // to delete a file, we need write permission on the parent directory - string? parentDirectoryPath = Path.GetDirectoryName(path); - if (string.IsNullOrEmpty(parentDirectoryPath)) - return false; // if path is a root directory or has no parent, deletion is not possible - UnixDirectoryInfo parentDirectoryInfo = new(parentDirectoryPath); - return parentDirectoryInfo.CanAccess(AccessModes.W_OK); - } - default: - throw new ArgumentOutOfRangeException(nameof(accessMode), "Unknown FileAccessMode"); + switch (accessMode) + { + case FileAccessMode.ReadProperties: + // for properties, we only need to check if the path exists + return File.Exists(path) || Directory.Exists(path); + case FileAccessMode.ReadContents: + // attempt to open the file for reading to verify read access + if (File.Exists(path)) + { + FileStream fileStream = File.OpenRead(path); + fileStream.Dispose(); + return true; + } + return false; + case FileAccessMode.Write: + // attempt to open the file for writing or verify directory exists + if (File.Exists(path)) + { + FileStream fileStream = File.OpenWrite(path); + fileStream.Dispose(); + return true; + } + return Directory.Exists(path); + case FileAccessMode.Execute: + // check Unix execute permission bit + FileInfo fileInfo = new(path); + return (fileInfo.UnixFileMode & UnixFileMode.UserExecute) != 0; + case FileAccessMode.ListDirectory: + // attempt to list directory contents to verify access + if (Directory.Exists(path)) + { + string[] _ = Directory.GetFiles(path); + return true; + } + return false; + case FileAccessMode.Delete: + if (File.Exists(path)) + { + // for files, check if parent directory is writable + string? directoryPath = Path.GetDirectoryName(path); + return directoryPath != null && HasWriteAccessToDirectory(directoryPath); + } + // for directories, check if the directory itself is writable + return Directory.Exists(path) && HasWriteAccessToDirectory(path); + default: + throw new ArgumentOutOfRangeException(nameof(accessMode), "Unknown FileAccessMode"); + } + } + catch (UnauthorizedAccessException) + { + return false; // access denied by the operating system + } + catch (IOException) + { + return false; // IO operation failed, indicating no access + } + } + + /// + /// Verifies write access to a directory by attempting to create and delete a temporary file. + /// + /// The directory path to check for write access. + /// if write access is granted, otherwise. + private static bool HasWriteAccessToDirectory(string path) + { + try + { + // create a unique temporary filename + string temporaryFilePath = Path.Combine(path, string.Format(".test_{0}", Guid.NewGuid())); + // attempt to create and immediately delete a temporary file + FileStream testStream = File.Create(temporaryFilePath); + testStream.Dispose(); + File.Delete(temporaryFilePath); + return true; + } + catch (UnauthorizedAccessException) + { + return false; + } + catch (IOException) + { + return false; } - return new UnixDirectoryInfo(path).CanAccess(modes); } /// @@ -129,31 +175,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 +228,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/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Services/FileTypeService.cs similarity index 94% rename from src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Services/FileTypeService.cs rename to src/Lumina.Domain/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Services/FileTypeService.cs index 58b150a6..7b90341a 100644 --- a/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Services/FileTypeService.cs +++ b/src/Lumina.Domain/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Services/FileTypeService.cs @@ -1,10 +1,10 @@ #region ========================================================================= USING ===================================================================================== using ErrorOr; -using Lumina.Contracts.Enums.FileSystem; -using Lumina.Contracts.Enums.PhotoLibrary; +using Lumina.Domain.Common.Enums.FileSystem; +using Lumina.Domain.Common.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.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.ValueObjects; +using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Entities; 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.BoundedContexts.FileSystemManagementBoundedContext.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/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Services/IDirectoryProviderService.cs similarity index 92% rename from src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Services/IDirectoryProviderService.cs rename to src/Lumina.Domain/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Services/IDirectoryProviderService.cs index 3e176716..a3332339 100644 --- a/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Services/IDirectoryProviderService.cs +++ b/src/Lumina.Domain/Core/BoundedContexts/FileSystemManagementBoundedContext/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.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.ValueObjects; using System; using System.Collections.Generic; #endregion -namespace Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.Services; +namespace Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.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/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Services/IDirectoryService.cs similarity index 89% rename from src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Services/IDirectoryService.cs rename to src/Lumina.Domain/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Services/IDirectoryService.cs index b2c84dc6..48b4f5bb 100644 --- a/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Services/IDirectoryService.cs +++ b/src/Lumina.Domain/Core/BoundedContexts/FileSystemManagementBoundedContext/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.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.ValueObjects; +using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Entities; using System.Collections.Generic; #endregion -namespace Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.Services; +namespace Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.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/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Services/IDriveService.cs similarity index 50% rename from src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Services/IDriveService.cs rename to src/Lumina.Domain/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Services/IDriveService.cs index 240a5860..67333065 100644 --- a/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Services/IDriveService.cs +++ b/src/Lumina.Domain/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Services/IDriveService.cs @@ -1,9 +1,10 @@ -#region ========================================================================= USING ===================================================================================== +#region ========================================================================= USING ===================================================================================== using ErrorOr; +using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate; using System.Collections.Generic; #endregion -namespace Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.Services; +namespace Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.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/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Services/IFileProviderService.cs similarity index 92% rename from src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Services/IFileProviderService.cs rename to src/Lumina.Domain/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Services/IFileProviderService.cs index 6dce33bd..f75f7b41 100644 --- a/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Services/IFileProviderService.cs +++ b/src/Lumina.Domain/Core/BoundedContexts/FileSystemManagementBoundedContext/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.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.ValueObjects; using System; using System.Collections.Generic; #endregion -namespace Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.Services; +namespace Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.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/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Services/IFileService.cs similarity index 87% rename from src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Services/IFileService.cs rename to src/Lumina.Domain/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Services/IFileService.cs index 3d72da06..2cc9b5c7 100644 --- a/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Services/IFileService.cs +++ b/src/Lumina.Domain/Core/BoundedContexts/FileSystemManagementBoundedContext/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.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.ValueObjects; +using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Entities; using System.Collections.Generic; #endregion -namespace Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.Services; +namespace Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.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/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Services/IFileSystemPermissionsService.cs similarity index 60% rename from src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Services/IFileSystemPermissionsService.cs rename to src/Lumina.Domain/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Services/IFileSystemPermissionsService.cs index 1eb76f9c..478c209a 100644 --- a/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Services/IFileSystemPermissionsService.cs +++ b/src/Lumina.Domain/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Services/IFileSystemPermissionsService.cs @@ -1,9 +1,9 @@ -#region ========================================================================= USING ===================================================================================== -using Lumina.Contracts.Enums.FileSystem; -using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.ValueObjects; +#region ========================================================================= USING ===================================================================================== +using Lumina.Domain.Common.Enums.FileSystem; +using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.ValueObjects; #endregion -namespace Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.Services; +namespace Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.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/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Services/IFileTypeService.cs similarity index 78% rename from src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Services/IFileTypeService.cs rename to src/Lumina.Domain/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Services/IFileTypeService.cs index 19285cff..32f07d6a 100644 --- a/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Services/IFileTypeService.cs +++ b/src/Lumina.Domain/Core/BoundedContexts/FileSystemManagementBoundedContext/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.Common.Enums.PhotoLibrary; +using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.ValueObjects; +using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Entities; using System.Threading; using System.Threading.Tasks; #endregion -namespace Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.Services; +namespace Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.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/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Services/IPathService.cs similarity index 92% rename from src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Services/IPathService.cs rename to src/Lumina.Domain/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Services/IPathService.cs index ddfaa94f..a70aaf80 100644 --- a/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Services/IPathService.cs +++ b/src/Lumina.Domain/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Services/IPathService.cs @@ -1,10 +1,10 @@ #region ========================================================================= USING ===================================================================================== using ErrorOr; -using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.ValueObjects; +using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.ValueObjects; using System.Collections.Generic; #endregion -namespace Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.Services; +namespace Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.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/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Services/IThumbnailService.cs similarity index 87% rename from src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Services/IThumbnailService.cs rename to src/Lumina.Domain/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Services/IThumbnailService.cs index c48225d8..5f666995 100644 --- a/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Services/IThumbnailService.cs +++ b/src/Lumina.Domain/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Services/IThumbnailService.cs @@ -1,11 +1,11 @@ #region ========================================================================= USING ===================================================================================== using ErrorOr; -using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.ValueObjects; +using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.ValueObjects; using System.Threading; using System.Threading.Tasks; #endregion -namespace Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.Services; +namespace Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.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/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Services/PathService.cs similarity index 92% rename from src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Services/PathService.cs rename to src/Lumina.Domain/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Services/PathService.cs index 5ba130dd..f32a6423 100644 --- a/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Services/PathService.cs +++ b/src/Lumina.Domain/Core/BoundedContexts/FileSystemManagementBoundedContext/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.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Strategies.Platform; +using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.ValueObjects; using System.Collections.Generic; #endregion -namespace Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.Services; +namespace Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.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/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Services/ThumbnailService.cs similarity index 95% rename from src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Services/ThumbnailService.cs rename to src/Lumina.Domain/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Services/ThumbnailService.cs index 5e3bcee3..816e63ac 100644 --- a/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Services/ThumbnailService.cs +++ b/src/Lumina.Domain/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Services/ThumbnailService.cs @@ -1,9 +1,9 @@ #region ========================================================================= USING ===================================================================================== using ErrorOr; -using Lumina.Contracts.Enums.PhotoLibrary; +using Lumina.Domain.Common.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.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Strategies.Environment; +using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.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.BoundedContexts.FileSystemManagementBoundedContext.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/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Strategies/Environment/EnvironmentContext.cs similarity index 86% rename from src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Strategies/Environment/EnvironmentContext.cs rename to src/Lumina.Domain/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Strategies/Environment/EnvironmentContext.cs index 850fc5be..69156049 100644 --- a/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Strategies/Environment/EnvironmentContext.cs +++ b/src/Lumina.Domain/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Strategies/Environment/EnvironmentContext.cs @@ -1,8 +1,8 @@ #region ========================================================================= USING ===================================================================================== -using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.Services; +using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Services; #endregion -namespace Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.Strategies.Environment; +namespace Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.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/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Strategies/Environment/IEnvironmentContext.cs similarity index 61% rename from src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Strategies/Environment/IEnvironmentContext.cs rename to src/Lumina.Domain/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Strategies/Environment/IEnvironmentContext.cs index 4abd5b78..60561228 100644 --- a/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Strategies/Environment/IEnvironmentContext.cs +++ b/src/Lumina.Domain/Core/BoundedContexts/FileSystemManagementBoundedContext/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.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Services; #endregion -namespace Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.Strategies.Environment; +namespace Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.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/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Strategies/Path/IPathStrategy.cs similarity index 92% rename from src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Strategies/Path/IPathStrategy.cs rename to src/Lumina.Domain/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Strategies/Path/IPathStrategy.cs index fd41d7d9..fb9d417d 100644 --- a/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Strategies/Path/IPathStrategy.cs +++ b/src/Lumina.Domain/Core/BoundedContexts/FileSystemManagementBoundedContext/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.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.ValueObjects; using System.Collections.Generic; #endregion -namespace Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.Strategies.Path; +namespace Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.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/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Strategies/Path/IUnixPathStrategy.cs similarity index 56% rename from src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Strategies/Path/IUnixPathStrategy.cs rename to src/Lumina.Domain/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Strategies/Path/IUnixPathStrategy.cs index 74feabe5..a803c94c 100644 --- a/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Strategies/Path/IUnixPathStrategy.cs +++ b/src/Lumina.Domain/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Strategies/Path/IUnixPathStrategy.cs @@ -1,8 +1,8 @@ -namespace Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.Strategies.Path; +namespace Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.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/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Strategies/Path/IWindowsPathStrategy.cs similarity index 57% rename from src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Strategies/Path/IWindowsPathStrategy.cs rename to src/Lumina.Domain/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Strategies/Path/IWindowsPathStrategy.cs index 47599331..4bd41e39 100644 --- a/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Strategies/Path/IWindowsPathStrategy.cs +++ b/src/Lumina.Domain/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Strategies/Path/IWindowsPathStrategy.cs @@ -1,8 +1,8 @@ -namespace Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.Strategies.Path; +namespace Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.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/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Strategies/Path/UnixPathStrategy.cs similarity index 92% rename from src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Strategies/Path/UnixPathStrategy.cs rename to src/Lumina.Domain/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Strategies/Path/UnixPathStrategy.cs index cc858a6c..850f14e0 100644 --- a/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Strategies/Path/UnixPathStrategy.cs +++ b/src/Lumina.Domain/Core/BoundedContexts/FileSystemManagementBoundedContext/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.BoundedContexts.FileSystemManagementBoundedContext.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.BoundedContexts.FileSystemManagementBoundedContext.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/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Strategies/Path/WindowsPathStrategy.cs similarity index 88% rename from src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Strategies/Path/WindowsPathStrategy.cs rename to src/Lumina.Domain/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Strategies/Path/WindowsPathStrategy.cs index 8ab9d278..4f937462 100644 --- a/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Strategies/Path/WindowsPathStrategy.cs +++ b/src/Lumina.Domain/Core/BoundedContexts/FileSystemManagementBoundedContext/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.BoundedContexts.FileSystemManagementBoundedContext.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.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Strategies.Path; /// /// Service defining methods for handling path-related operations on Windows platforms. @@ -36,14 +36,14 @@ public class WindowsPathStrategy : IWindowsPathStrategy /// The path to be checked. /// if is a valid path, otherwise. public bool IsValidPath(FileSystemPathId path) - { + { // check for invalid path characters char[] invalidChars = GetInvalidPathCharsForPlatform(); if (path.Path.IndexOfAny(invalidChars) >= 0) return false; // regular expression to match valid absolute paths // this allows drive letters (e.g., C:\) and UNC paths (e.g., \\server\share) - const string PATH_PATTERN = @"^(?:[a-zA-Z]:\\|\\\\[a-zA-Z0-9\s()._\[\]-]+\\[a-zA-Z0-9\s()._\[\]-]+)(?:[a-zA-Z0-9\s()._\[\]-]+\\)*[a-zA-Z0-9\s()._\[\]-]*\\?$"; + const string PATH_PATTERN = @"^(?:[a-zA-Z]:\\|\\\\[a-zA-Z0-9\s()._&+,\[\]-]+\\[a-zA-Z0-9\s()._&+,\[\]-]+)(?:[a-zA-Z0-9\s()._&+,\[\]-]+\\)*[a-zA-Z0-9\s()._&+,\[\]-]*\\?$"; return Regex.IsMatch(path.Path, PATH_PATTERN); } @@ -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/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Strategies/Platform/IOperatingSystemInfo.cs similarity index 85% rename from src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Strategies/Platform/IOperatingSystemInfo.cs rename to src/Lumina.Domain/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Strategies/Platform/IOperatingSystemInfo.cs index 4fe05f69..afabc1b4 100644 --- a/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Strategies/Platform/IOperatingSystemInfo.cs +++ b/src/Lumina.Domain/Core/BoundedContexts/FileSystemManagementBoundedContext/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.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Strategies.Platform; /// /// Interface for checking the type of the current Operating System platform. diff --git a/src/Lumina.Domain/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Strategies/Platform/IPlatformContext.cs b/src/Lumina.Domain/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Strategies/Platform/IPlatformContext.cs new file mode 100644 index 00000000..500bda60 --- /dev/null +++ b/src/Lumina.Domain/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Strategies/Platform/IPlatformContext.cs @@ -0,0 +1,22 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Domain.Common.Enums.FileSystem; +using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Strategies.Path; +#endregion + +namespace Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Strategies.Platform; + +/// +/// Interface for defining the contract of a platform-specific context. +/// +public interface IPlatformContext +{ + /// + /// Gets the platform for the current platform context. + /// + PlatformType Platform { get; } + + /// + /// Gets the path strategy for the current platform context. + /// + IPathStrategy PathStrategy { get; } +} diff --git a/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Strategies/Platform/IPlatformContextFactory.cs b/src/Lumina.Domain/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Strategies/Platform/IPlatformContextFactory.cs similarity index 78% rename from src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Strategies/Platform/IPlatformContextFactory.cs rename to src/Lumina.Domain/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Strategies/Platform/IPlatformContextFactory.cs index 8ce72412..d5fd0dc5 100644 --- a/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Strategies/Platform/IPlatformContextFactory.cs +++ b/src/Lumina.Domain/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Strategies/Platform/IPlatformContextFactory.cs @@ -1,4 +1,4 @@ -namespace Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.Strategies.Platform; +namespace Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.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/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Strategies/Platform/IPlatformContextManager.cs similarity index 64% rename from src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Strategies/Platform/IPlatformContextManager.cs rename to src/Lumina.Domain/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Strategies/Platform/IPlatformContextManager.cs index d29df76a..2345f2df 100644 --- a/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Strategies/Platform/IPlatformContextManager.cs +++ b/src/Lumina.Domain/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Strategies/Platform/IPlatformContextManager.cs @@ -1,9 +1,9 @@ -#region ========================================================================= USING ===================================================================================== -using Lumina.Contracts.Enums.FileSystem; +#region ========================================================================= USING ===================================================================================== +using Lumina.Domain.Common.Enums.FileSystem; using System; #endregion -namespace Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.Strategies.Platform; +namespace Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.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/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Strategies/Platform/IUnixPlatformContext.cs similarity index 53% rename from src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Strategies/Platform/IUnixPlatformContext.cs rename to src/Lumina.Domain/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Strategies/Platform/IUnixPlatformContext.cs index 3331f7e6..29c5f9ad 100644 --- a/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Strategies/Platform/IUnixPlatformContext.cs +++ b/src/Lumina.Domain/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Strategies/Platform/IUnixPlatformContext.cs @@ -1,8 +1,8 @@ -namespace Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.Strategies.Platform; +namespace Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.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/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Strategies/Platform/IWindowsPlatformContext.cs similarity index 54% rename from src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Strategies/Platform/IWindowsPlatformContext.cs rename to src/Lumina.Domain/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Strategies/Platform/IWindowsPlatformContext.cs index de3e7239..077cd9f7 100644 --- a/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Strategies/Platform/IWindowsPlatformContext.cs +++ b/src/Lumina.Domain/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Strategies/Platform/IWindowsPlatformContext.cs @@ -1,8 +1,8 @@ -namespace Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.Strategies.Platform; +namespace Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.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/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Strategies/Platform/OperatingSystemInfo.cs similarity index 87% rename from src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Strategies/Platform/OperatingSystemInfo.cs rename to src/Lumina.Domain/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Strategies/Platform/OperatingSystemInfo.cs index 250af820..9f01740c 100644 --- a/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Strategies/Platform/OperatingSystemInfo.cs +++ b/src/Lumina.Domain/Core/BoundedContexts/FileSystemManagementBoundedContext/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.BoundedContexts.FileSystemManagementBoundedContext.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/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Strategies/Platform/PlatformContextFactory.cs similarity index 77% rename from src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Strategies/Platform/PlatformContextFactory.cs rename to src/Lumina.Domain/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Strategies/Platform/PlatformContextFactory.cs index 38620e2c..ac74531e 100644 --- a/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Strategies/Platform/PlatformContextFactory.cs +++ b/src/Lumina.Domain/Core/BoundedContexts/FileSystemManagementBoundedContext/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.BoundedContexts.FileSystemManagementBoundedContext.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/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Strategies/Platform/PlatformContextManager.cs similarity index 91% rename from src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Strategies/Platform/PlatformContextManager.cs rename to src/Lumina.Domain/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Strategies/Platform/PlatformContextManager.cs index e029129f..d1e4a766 100644 --- a/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Strategies/Platform/PlatformContextManager.cs +++ b/src/Lumina.Domain/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Strategies/Platform/PlatformContextManager.cs @@ -1,10 +1,10 @@ #region ========================================================================= USING ===================================================================================== -using Lumina.Contracts.Enums.FileSystem; +using Lumina.Domain.Common.Enums.FileSystem; using System; using System.Runtime.InteropServices; #endregion -namespace Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.Strategies.Platform; +namespace Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.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)) + if (_operatingSystemInfo.IsOSPlatform(OSPlatform.Linux) || _operatingSystemInfo.IsOSPlatform(OSPlatform.OSX)) 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/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Strategies/Platform/UnixPlatformContext.cs similarity index 76% rename from src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Strategies/Platform/UnixPlatformContext.cs rename to src/Lumina.Domain/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Strategies/Platform/UnixPlatformContext.cs index c7579366..e93499ba 100644 --- a/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Strategies/Platform/UnixPlatformContext.cs +++ b/src/Lumina.Domain/Core/BoundedContexts/FileSystemManagementBoundedContext/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.Common.Enums.FileSystem; +using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Strategies.Path; #endregion -namespace Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.Strategies.Platform; +namespace Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.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/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Strategies/Platform/WindowsPlatformContext.cs similarity index 77% rename from src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Strategies/Platform/WindowsPlatformContext.cs rename to src/Lumina.Domain/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Strategies/Platform/WindowsPlatformContext.cs index 837cbea5..2af18243 100644 --- a/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Strategies/Platform/WindowsPlatformContext.cs +++ b/src/Lumina.Domain/Core/BoundedContexts/FileSystemManagementBoundedContext/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.Common.Enums.FileSystem; +using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Strategies.Path; + #endregion -namespace Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.Strategies.Platform; +namespace Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.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/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/ValueObjects/FileSystemPathId.cs similarity index 89% rename from src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/ValueObjects/FileSystemPathId.cs rename to src/Lumina.Domain/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/ValueObjects/FileSystemPathId.cs index 8921ce95..97d5e626 100644 --- a/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/ValueObjects/FileSystemPathId.cs +++ b/src/Lumina.Domain/Core/BoundedContexts/FileSystemManagementBoundedContext/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.BoundedContexts.FileSystemManagementBoundedContext.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/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/ValueObjects/PathSegment.cs similarity index 92% rename from src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/ValueObjects/PathSegment.cs rename to src/Lumina.Domain/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/ValueObjects/PathSegment.cs index 1a05af70..3b3462ac 100644 --- a/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/ValueObjects/PathSegment.cs +++ b/src/Lumina.Domain/Core/BoundedContexts/FileSystemManagementBoundedContext/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.BoundedContexts.FileSystemManagementBoundedContext.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/BoundedContexts/FileSystemManagementBoundedContext/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/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/ValueObjects/StreamInfo.cs index 1d0ddd38..ae46567c 100644 --- a/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/ValueObjects/StreamInfo.cs +++ b/src/Lumina.Domain/Core/BoundedContexts/FileSystemManagementBoundedContext/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.BoundedContexts.FileSystemManagementBoundedContext.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/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/ValueObjects/Thumbnail.cs similarity index 75% rename from src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/ValueObjects/Thumbnail.cs rename to src/Lumina.Domain/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/ValueObjects/Thumbnail.cs index 581362d3..4612149c 100644 --- a/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/ValueObjects/Thumbnail.cs +++ b/src/Lumina.Domain/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/ValueObjects/Thumbnail.cs @@ -1,11 +1,11 @@ -#region ========================================================================= USING ===================================================================================== -using Lumina.Contracts.Enums.PhotoLibrary; +#region ========================================================================= USING ===================================================================================== +using Lumina.Domain.Common.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.BoundedContexts.FileSystemManagementBoundedContext.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/BoundedContexts/LibraryManagementBoundedContext/LibraryAggregate/Library.cs b/src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryAggregate/Library.cs new file mode 100644 index 00000000..626a0d5f --- /dev/null +++ b/src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryAggregate/Library.cs @@ -0,0 +1,133 @@ +#region ========================================================================= USING ===================================================================================== +using ErrorOr; +using Lumina.Domain.Common.Enums.MediaLibrary; +using Lumina.Domain.Common.Models.Core; +using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.ValueObjects; +using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects; +using Lumina.Domain.Core.BoundedContexts.UserManagementBoundedContext.UserAggregate.ValueObjects; +using System; +using System.Collections.Generic; +using System.Diagnostics; +#endregion + +namespace Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate; + +/// +/// Aggregate root for a media library. +/// +[DebuggerDisplay("Id: {Id} Title: {Title}")] +public class Library : AggregateRoot +{ + private readonly List _contentLocations; + + /// + /// Gets the id of the user owning this media library. + /// + public UserId UserId { get; private set; } + + /// + /// Gets the type of the media library (e.g., Book, TvShow). + /// + public LibraryType LibraryType { get; private set; } + + /// + /// Gets the title of the media library. + /// + public string Title { get; private set; } + + /// + /// Gets the list of file system paths that make up the media library. + /// + public IReadOnlyCollection ContentLocations => _contentLocations.AsReadOnly(); + + /// + /// Initializes a new instance of the class. + /// + /// The unique identifier of the media library. + /// The unique identifier of the user owning the media library. + /// The title of the media library. + /// The type of the media library (e.g., Book, TvShow). + /// The list of file system paths that make up the media library. + private Library( + LibraryId id, + UserId userId, + string title, + LibraryType libraryType, + List contentLocations) : base(id) + { + UserId = userId; + Title = title; + LibraryType = libraryType; + _contentLocations = contentLocations; + } + + /// + /// Creates a new instance of the class. + /// + /// The unique identifier of the user owning the media library. + /// The title of the media library. + /// The type of the media library (e.g., Book, TvShow). + /// The list of file system paths that make up the media library. + /// + /// An containing either a successfully created , or an error message. + /// + public static ErrorOr Create( + Guid userId, + string title, + LibraryType libraryType, + IEnumerable contentLocations) + { + List tempContentLocations = []; + // go through all the file system paths that make up the media library and create domain objects from them + foreach (string contentLocation in contentLocations) + { + ErrorOr contentLocationResult = FileSystemPathId.Create(contentLocation); + if (contentLocationResult.IsError) + return contentLocationResult.Errors; + tempContentLocations.Add(contentLocationResult.Value); + } + return new Library( + LibraryId.CreateUnique(), + UserId.Create(userId), + title, + libraryType, + tempContentLocations + ); + } + + /// + /// Creates a new instance of the , with a pre-existing . + /// + /// The object representing the id of the media library. + /// The object representing the id of the user owning the media library. + /// The title of the media library. + /// The type of the media library (e.g., Book, TvShow). + /// The list of file system paths that make up the media library. + /// + /// An containing either a successfully created , or an error message. + /// + public static ErrorOr Create( + LibraryId id, + Guid userId, + string title, + LibraryType libraryType, + IEnumerable contentLocations) + { + List tempContentLocations = []; + // go through all the file system paths that make up the media library and create domain objects from them + foreach (string contentLocation in contentLocations) + { + ErrorOr contentLocationResult = FileSystemPathId.Create(contentLocation); + if (contentLocationResult.IsError) + return contentLocationResult.Errors; + tempContentLocations.Add(contentLocationResult.Value); + } + return new Library( + id, + UserId.Create(userId), + title, + libraryType, + tempContentLocations + ); + } +} diff --git a/src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryAggregate/ValueObjects/LibraryId.cs b/src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryAggregate/ValueObjects/LibraryId.cs new file mode 100644 index 00000000..2ba28cb8 --- /dev/null +++ b/src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryAggregate/ValueObjects/LibraryId.cs @@ -0,0 +1,48 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Domain.Common.Models.Core; +using System; +using System.Collections.Generic; +using System.Diagnostics; +#endregion + +namespace Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects; + +/// +/// Value Object for the Id of a media library. +/// +[DebuggerDisplay("{Value}")] +public sealed class LibraryId : EntityId +{ + /// + /// Initializes a new instance of the class. + /// + /// The value representing this object. + private LibraryId(Guid value) : base(value) + { + } + + /// + /// Creates a new instance of the class. + /// + /// The created instance. + public static LibraryId CreateUnique() + { + return new LibraryId(Guid.NewGuid()); + } + + /// + /// Creates a new instance of the class, from a pre-existing . + /// + /// The value used to create the instance. + /// The created instance. + public static LibraryId Create(Guid value) + { + return new LibraryId(value); + } + + /// + public override IEnumerable GetEqualityComponents() + { + yield return Value; + } +} diff --git a/src/Lumina.Domain/Core/Aggregates/MediaContributor/MediaContributorAggregate/MediaContributor.cs b/src/Lumina.Domain/Core/BoundedContexts/MediaContributorBoundedContext/MediaContributorAggregate/MediaContributor.cs similarity index 93% rename from src/Lumina.Domain/Core/Aggregates/MediaContributor/MediaContributorAggregate/MediaContributor.cs rename to src/Lumina.Domain/Core/BoundedContexts/MediaContributorBoundedContext/MediaContributorAggregate/MediaContributor.cs index e00776d9..b02d15ac 100644 --- a/src/Lumina.Domain/Core/Aggregates/MediaContributor/MediaContributorAggregate/MediaContributor.cs +++ b/src/Lumina.Domain/Core/BoundedContexts/MediaContributorBoundedContext/MediaContributorAggregate/MediaContributor.cs @@ -2,13 +2,13 @@ using ErrorOr; using Lumina.Domain.Common.Models.Core; using Lumina.Domain.Common.Primitives; -using Lumina.Domain.Core.Aggregates.MediaContributor.MediaContributorAggregate.ValueObjects; +using Lumina.Domain.Core.BoundedContexts.MediaContributorBoundedContext.MediaContributorAggregate.ValueObjects; using System; using System.Diagnostics; #endregion -namespace Lumina.Domain.Core.Aggregates.MediaContributor.MediaContributorAggregate; +namespace Lumina.Domain.Core.BoundedContexts.MediaContributorBoundedContext.MediaContributorAggregate; /// /// Aggregate Root for a media contributor. @@ -90,4 +90,4 @@ public class MediaContributor : AggregateRoot { return new MediaContributor(id, name, role, dateOfBirth, dateOfDeath); } -} \ No newline at end of file +} diff --git a/src/Lumina.Domain/Core/Aggregates/MediaContributor/MediaContributorAggregate/ValueObjects/ContributorName.cs b/src/Lumina.Domain/Core/BoundedContexts/MediaContributorBoundedContext/MediaContributorAggregate/ValueObjects/ContributorName.cs similarity index 94% rename from src/Lumina.Domain/Core/Aggregates/MediaContributor/MediaContributorAggregate/ValueObjects/ContributorName.cs rename to src/Lumina.Domain/Core/BoundedContexts/MediaContributorBoundedContext/MediaContributorAggregate/ValueObjects/ContributorName.cs index a57342b4..902cc27e 100644 --- a/src/Lumina.Domain/Core/Aggregates/MediaContributor/MediaContributorAggregate/ValueObjects/ContributorName.cs +++ b/src/Lumina.Domain/Core/BoundedContexts/MediaContributorBoundedContext/MediaContributorAggregate/ValueObjects/ContributorName.cs @@ -6,7 +6,7 @@ using System.Collections.Generic; using System.Diagnostics; #endregion -namespace Lumina.Domain.Core.Aggregates.MediaContributor.MediaContributorAggregate.ValueObjects; +namespace Lumina.Domain.Core.BoundedContexts.MediaContributorBoundedContext.MediaContributorAggregate.ValueObjects; /// /// Value Object for the name of a person. @@ -53,4 +53,4 @@ public sealed class MediaContributorName : ValueObject yield return DisplayName; yield return LegalName; } -} \ No newline at end of file +} diff --git a/src/Lumina.Domain/Core/Aggregates/MediaContributor/MediaContributorAggregate/ValueObjects/MediaContributorId.cs b/src/Lumina.Domain/Core/BoundedContexts/MediaContributorBoundedContext/MediaContributorAggregate/ValueObjects/MediaContributorId.cs similarity index 93% rename from src/Lumina.Domain/Core/Aggregates/MediaContributor/MediaContributorAggregate/ValueObjects/MediaContributorId.cs rename to src/Lumina.Domain/Core/BoundedContexts/MediaContributorBoundedContext/MediaContributorAggregate/ValueObjects/MediaContributorId.cs index 500e7316..fc99490f 100644 --- a/src/Lumina.Domain/Core/Aggregates/MediaContributor/MediaContributorAggregate/ValueObjects/MediaContributorId.cs +++ b/src/Lumina.Domain/Core/BoundedContexts/MediaContributorBoundedContext/MediaContributorAggregate/ValueObjects/MediaContributorId.cs @@ -4,7 +4,7 @@ using System; using System.Collections.Generic; #endregion -namespace Lumina.Domain.Core.Aggregates.MediaContributor.MediaContributorAggregate.ValueObjects; +namespace Lumina.Domain.Core.BoundedContexts.MediaContributorBoundedContext.MediaContributorAggregate.ValueObjects; /// /// Value Object for the Id of a media contributor. diff --git a/src/Lumina.Domain/Core/Aggregates/MediaContributor/MediaContributorAggregate/ValueObjects/MediaContributorRole.cs b/src/Lumina.Domain/Core/BoundedContexts/MediaContributorBoundedContext/MediaContributorAggregate/ValueObjects/MediaContributorRole.cs similarity index 93% rename from src/Lumina.Domain/Core/Aggregates/MediaContributor/MediaContributorAggregate/ValueObjects/MediaContributorRole.cs rename to src/Lumina.Domain/Core/BoundedContexts/MediaContributorBoundedContext/MediaContributorAggregate/ValueObjects/MediaContributorRole.cs index 26c3a7d6..5956fba2 100644 --- a/src/Lumina.Domain/Core/Aggregates/MediaContributor/MediaContributorAggregate/ValueObjects/MediaContributorRole.cs +++ b/src/Lumina.Domain/Core/BoundedContexts/MediaContributorBoundedContext/MediaContributorAggregate/ValueObjects/MediaContributorRole.cs @@ -4,7 +4,7 @@ using System.Collections.Generic; using System.Diagnostics; #endregion -namespace Lumina.Domain.Core.Aggregates.MediaContributor.MediaContributorAggregate.ValueObjects; +namespace Lumina.Domain.Core.BoundedContexts.MediaContributorBoundedContext.MediaContributorAggregate.ValueObjects; /// /// Value Object for the role of a media contributor. diff --git a/src/Lumina.Domain/Core/BoundedContexts/UserManagementBoundedContext/UserAggregate/User.cs b/src/Lumina.Domain/Core/BoundedContexts/UserManagementBoundedContext/UserAggregate/User.cs new file mode 100644 index 00000000..953b6b96 --- /dev/null +++ b/src/Lumina.Domain/Core/BoundedContexts/UserManagementBoundedContext/UserAggregate/User.cs @@ -0,0 +1,64 @@ +#region ========================================================================= USING ===================================================================================== +using ErrorOr; +using Lumina.Domain.Common.Models.Core; +using Lumina.Domain.Core.BoundedContexts.UserManagementBoundedContext.UserAggregate.ValueObjects; +using System.Diagnostics; +#endregion + +namespace Lumina.Domain.Core.BoundedContexts.UserManagementBoundedContext.UserAggregate; + +/// +/// Aggregate root for a user aggregate. +/// +[DebuggerDisplay("{Id}: {Username}")] +public sealed class User : AggregateRoot +{ + /// + /// Gets or sets the username of the user. + /// + public string Username { get; private set; } + + /// + /// Initializes a new instance of the class. + /// + /// The unique identifier of the user. + /// The username of the user. + private User( + UserId id, + string username) : base(id) + { + Username = username; + } + + /// + /// Creates a new instance of the class. + /// + /// The username of the user. + /// + /// An containing either a successfully created , or an error message. + /// + public static ErrorOr Create( + string username) + { + return new User( + UserId.CreateUnique(), + username); + } + + /// + /// Creates a new instance of the , with a pre-existing . + /// + /// The object representing the id of the user. + /// The username of the user. + /// + /// An containing either a successfully created , or an error message. + /// + public static ErrorOr Create( + UserId id, + string username) + { + return new User( + id, + username); + } +} diff --git a/src/Lumina.Domain/Core/BoundedContexts/UserManagementBoundedContext/UserAggregate/ValueObjects/UserId.cs b/src/Lumina.Domain/Core/BoundedContexts/UserManagementBoundedContext/UserAggregate/ValueObjects/UserId.cs new file mode 100644 index 00000000..853648d8 --- /dev/null +++ b/src/Lumina.Domain/Core/BoundedContexts/UserManagementBoundedContext/UserAggregate/ValueObjects/UserId.cs @@ -0,0 +1,48 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Domain.Common.Models.Core; +using System; +using System.Collections.Generic; +using System.Diagnostics; +#endregion + +namespace Lumina.Domain.Core.BoundedContexts.UserManagementBoundedContext.UserAggregate.ValueObjects; + +/// +/// Value Object for the Id of a user. +/// +[DebuggerDisplay("{Value}")] +public sealed class UserId : EntityId +{ + /// + /// Initializes a new instance of the class. + /// + /// The value representing this object. + private UserId(Guid value) : base(value) + { + } + + /// + /// Creates a new instance of the class. + /// + /// The created instance. + public static UserId CreateUnique() + { + return new UserId(Guid.NewGuid()); + } + + /// + /// Creates a new instance of the class, from a pre-existing . + /// + /// The value used to create the instance. + /// The created instance. + public static UserId Create(Guid value) + { + return new UserId(value); + } + + /// + public override IEnumerable GetEqualityComponents() + { + yield return Value; + } +} diff --git a/src/Lumina.Domain/Core/Aggregates/VideoLibrary/MovieLibraryAggregate/Movie.cs b/src/Lumina.Domain/Core/BoundedContexts/VideoLibraryBoundedContext/MovieLibraryAggregate/Movie.cs similarity index 91% rename from src/Lumina.Domain/Core/Aggregates/VideoLibrary/MovieLibraryAggregate/Movie.cs rename to src/Lumina.Domain/Core/BoundedContexts/VideoLibraryBoundedContext/MovieLibraryAggregate/Movie.cs index e620a98a..784f7d9c 100644 --- a/src/Lumina.Domain/Core/Aggregates/VideoLibrary/MovieLibraryAggregate/Movie.cs +++ b/src/Lumina.Domain/Core/BoundedContexts/VideoLibraryBoundedContext/MovieLibraryAggregate/Movie.cs @@ -2,13 +2,13 @@ using ErrorOr; using Lumina.Domain.Common.Models.Core; using Lumina.Domain.Common.ValueObjects.Metadata; -using Lumina.Domain.Core.Aggregates.MediaContributor.MediaContributorAggregate.ValueObjects; -using Lumina.Domain.Core.Aggregates.VideoLibrary.MovieLibraryAggregate.ValueObjects; +using Lumina.Domain.Core.BoundedContexts.MediaContributorBoundedContext.MediaContributorAggregate.ValueObjects; +using Lumina.Domain.Core.BoundedContexts.VideoLibraryBoundedContext.MovieLibraryAggregate.ValueObjects; using System.Collections.Generic; using System.Diagnostics; #endregion -namespace Lumina.Domain.Core.Aggregates.VideoLibrary.MovieLibraryAggregate; +namespace Lumina.Domain.Core.BoundedContexts.VideoLibraryBoundedContext.MovieLibraryAggregate; /// /// Entity for a movie. @@ -85,4 +85,4 @@ public sealed class Movie : Entity // TODO: enforce invariants return new Movie(id, metadata, contributors, ratings); } -} \ No newline at end of file +} diff --git a/src/Lumina.Domain/Core/Aggregates/VideoLibrary/MovieLibraryAggregate/Services/IMovieLibraryService.cs b/src/Lumina.Domain/Core/BoundedContexts/VideoLibraryBoundedContext/MovieLibraryAggregate/Services/IMovieLibraryService.cs similarity index 82% rename from src/Lumina.Domain/Core/Aggregates/VideoLibrary/MovieLibraryAggregate/Services/IMovieLibraryService.cs rename to src/Lumina.Domain/Core/BoundedContexts/VideoLibraryBoundedContext/MovieLibraryAggregate/Services/IMovieLibraryService.cs index bfa5eb92..34fc2432 100644 --- a/src/Lumina.Domain/Core/Aggregates/VideoLibrary/MovieLibraryAggregate/Services/IMovieLibraryService.cs +++ b/src/Lumina.Domain/Core/BoundedContexts/VideoLibraryBoundedContext/MovieLibraryAggregate/Services/IMovieLibraryService.cs @@ -2,7 +2,7 @@ using System.Collections.Generic; #endregion -namespace Lumina.Domain.Core.Aggregates.VideoLibrary.MovieLibraryAggregate.Services; +namespace Lumina.Domain.Core.BoundedContexts.VideoLibraryBoundedContext.MovieLibraryAggregate.Services; /// /// Interface for the service for managing movie libraries. @@ -13,4 +13,4 @@ public interface IMovieLibraryService /// Gets the collection of movies in the library. /// public ICollection Movies { get; } -} \ No newline at end of file +} diff --git a/src/Lumina.Domain/Core/Aggregates/VideoLibrary/MovieLibraryAggregate/Services/MovieLibraryService.cs b/src/Lumina.Domain/Core/BoundedContexts/VideoLibraryBoundedContext/MovieLibraryAggregate/Services/MovieLibraryService.cs similarity index 83% rename from src/Lumina.Domain/Core/Aggregates/VideoLibrary/MovieLibraryAggregate/Services/MovieLibraryService.cs rename to src/Lumina.Domain/Core/BoundedContexts/VideoLibraryBoundedContext/MovieLibraryAggregate/Services/MovieLibraryService.cs index ebef3153..d8415b3d 100644 --- a/src/Lumina.Domain/Core/Aggregates/VideoLibrary/MovieLibraryAggregate/Services/MovieLibraryService.cs +++ b/src/Lumina.Domain/Core/BoundedContexts/VideoLibraryBoundedContext/MovieLibraryAggregate/Services/MovieLibraryService.cs @@ -3,7 +3,7 @@ using System; using System.Collections.Generic; #endregion -namespace Lumina.Domain.Core.Aggregates.VideoLibrary.MovieLibraryAggregate.Services; +namespace Lumina.Domain.Core.BoundedContexts.VideoLibraryBoundedContext.MovieLibraryAggregate.Services; /// /// Service for managing movie libraries. diff --git a/src/Lumina.Domain/Core/Aggregates/VideoLibrary/MovieLibraryAggregate/ValueObjects/MovieId.cs b/src/Lumina.Domain/Core/BoundedContexts/VideoLibraryBoundedContext/MovieLibraryAggregate/ValueObjects/MovieId.cs similarity index 93% rename from src/Lumina.Domain/Core/Aggregates/VideoLibrary/MovieLibraryAggregate/ValueObjects/MovieId.cs rename to src/Lumina.Domain/Core/BoundedContexts/VideoLibraryBoundedContext/MovieLibraryAggregate/ValueObjects/MovieId.cs index 05a04a60..3b6c4b59 100644 --- a/src/Lumina.Domain/Core/Aggregates/VideoLibrary/MovieLibraryAggregate/ValueObjects/MovieId.cs +++ b/src/Lumina.Domain/Core/BoundedContexts/VideoLibraryBoundedContext/MovieLibraryAggregate/ValueObjects/MovieId.cs @@ -5,7 +5,7 @@ using System.Collections.Generic; using System.Diagnostics; #endregion -namespace Lumina.Domain.Core.Aggregates.VideoLibrary.MovieLibraryAggregate.ValueObjects; +namespace Lumina.Domain.Core.BoundedContexts.VideoLibraryBoundedContext.MovieLibraryAggregate.ValueObjects; /// /// Value Object for the Id of a movie. @@ -47,4 +47,4 @@ public sealed class MovieId : EntityId { yield return Value; } -} \ No newline at end of file +} diff --git a/src/Lumina.Domain/Core/Aggregates/VideoLibrary/MovieLibraryAggregate/ValueObjects/VideoMetadata.cs b/src/Lumina.Domain/Core/BoundedContexts/VideoLibraryBoundedContext/MovieLibraryAggregate/ValueObjects/VideoMetadata.cs similarity index 98% rename from src/Lumina.Domain/Core/Aggregates/VideoLibrary/MovieLibraryAggregate/ValueObjects/VideoMetadata.cs rename to src/Lumina.Domain/Core/BoundedContexts/VideoLibraryBoundedContext/MovieLibraryAggregate/ValueObjects/VideoMetadata.cs index 478a3d73..23eff432 100644 --- a/src/Lumina.Domain/Core/Aggregates/VideoLibrary/MovieLibraryAggregate/ValueObjects/VideoMetadata.cs +++ b/src/Lumina.Domain/Core/BoundedContexts/VideoLibraryBoundedContext/MovieLibraryAggregate/ValueObjects/VideoMetadata.cs @@ -7,7 +7,7 @@ using System.Collections.Generic; using System.Diagnostics; #endregion -namespace Lumina.Domain.Core.Aggregates.VideoLibrary.MovieLibraryAggregate.ValueObjects; +namespace Lumina.Domain.Core.BoundedContexts.VideoLibraryBoundedContext.MovieLibraryAggregate.ValueObjects; /// /// Value Object for the video metadata of a media element. diff --git a/src/Lumina.Domain/Core/Aggregates/VideoLibrary/Services/IVideoLibraryService.cs b/src/Lumina.Domain/Core/BoundedContexts/VideoLibraryBoundedContext/Services/IVideoLibraryService.cs similarity index 68% rename from src/Lumina.Domain/Core/Aggregates/VideoLibrary/Services/IVideoLibraryService.cs rename to src/Lumina.Domain/Core/BoundedContexts/VideoLibraryBoundedContext/Services/IVideoLibraryService.cs index ea56bf38..758a51a8 100644 --- a/src/Lumina.Domain/Core/Aggregates/VideoLibrary/Services/IVideoLibraryService.cs +++ b/src/Lumina.Domain/Core/BoundedContexts/VideoLibraryBoundedContext/Services/IVideoLibraryService.cs @@ -1,9 +1,9 @@ #region ========================================================================= USING ===================================================================================== -using Lumina.Domain.Core.Aggregates.VideoLibrary.MovieLibraryAggregate.Services; -using Lumina.Domain.Core.Aggregates.VideoLibrary.TvShowLibraryAggregate.Services; +using Lumina.Domain.Core.BoundedContexts.VideoLibraryBoundedContext.MovieLibraryAggregate.Services; +using Lumina.Domain.Core.BoundedContexts.VideoLibraryBoundedContext.TvShowLibraryAggregate.Services; #endregion -namespace Lumina.Domain.Core.Aggregates.VideoLibrary.Services; +namespace Lumina.Domain.Core.BoundedContexts.VideoLibraryBoundedContext.Services; /// /// Interface for the service for managing video content. @@ -19,4 +19,4 @@ public interface IVideoLibraryService /// Gets the service for managing a TV shows library. /// public ITvShowLibraryService TvShowLibraryService { get; } -} \ No newline at end of file +} diff --git a/src/Lumina.Domain/Core/Aggregates/VideoLibrary/Services/VideoLibraryService.cs b/src/Lumina.Domain/Core/BoundedContexts/VideoLibraryBoundedContext/Services/VideoLibraryService.cs similarity index 80% rename from src/Lumina.Domain/Core/Aggregates/VideoLibrary/Services/VideoLibraryService.cs rename to src/Lumina.Domain/Core/BoundedContexts/VideoLibraryBoundedContext/Services/VideoLibraryService.cs index da52db32..3bfe300b 100644 --- a/src/Lumina.Domain/Core/Aggregates/VideoLibrary/Services/VideoLibraryService.cs +++ b/src/Lumina.Domain/Core/BoundedContexts/VideoLibraryBoundedContext/Services/VideoLibraryService.cs @@ -1,9 +1,9 @@ #region ========================================================================= USING ===================================================================================== -using Lumina.Domain.Core.Aggregates.VideoLibrary.MovieLibraryAggregate.Services; -using Lumina.Domain.Core.Aggregates.VideoLibrary.TvShowLibraryAggregate.Services; +using Lumina.Domain.Core.BoundedContexts.VideoLibraryBoundedContext.MovieLibraryAggregate.Services; +using Lumina.Domain.Core.BoundedContexts.VideoLibraryBoundedContext.TvShowLibraryAggregate.Services; #endregion -namespace Lumina.Domain.Core.Aggregates.VideoLibrary.Services; +namespace Lumina.Domain.Core.BoundedContexts.VideoLibraryBoundedContext.Services; /// /// Service for managing video content. diff --git a/src/Lumina.Domain/Core/Aggregates/VideoLibrary/TvShowLibraryAggregate/Entities/Episode.cs b/src/Lumina.Domain/Core/BoundedContexts/VideoLibraryBoundedContext/TvShowLibraryAggregate/Entities/Episode.cs similarity index 65% rename from src/Lumina.Domain/Core/Aggregates/VideoLibrary/TvShowLibraryAggregate/Entities/Episode.cs rename to src/Lumina.Domain/Core/BoundedContexts/VideoLibraryBoundedContext/TvShowLibraryAggregate/Entities/Episode.cs index 373e9252..21682dff 100644 --- a/src/Lumina.Domain/Core/Aggregates/VideoLibrary/TvShowLibraryAggregate/Entities/Episode.cs +++ b/src/Lumina.Domain/Core/BoundedContexts/VideoLibraryBoundedContext/TvShowLibraryAggregate/Entities/Episode.cs @@ -1,10 +1,10 @@ #region ========================================================================= USING ===================================================================================== using Lumina.Domain.Common.Models.Core; -using Lumina.Domain.Core.Aggregates.VideoLibrary.TvShowLibraryAggregate.ValueObjects; +using Lumina.Domain.Core.BoundedContexts.VideoLibraryBoundedContext.TvShowLibraryAggregate.ValueObjects; using System.Diagnostics; #endregion -namespace Lumina.Domain.Core.Aggregates.VideoLibrary.TvShowLibraryAggregate.Entities; +namespace Lumina.Domain.Core.BoundedContexts.VideoLibraryBoundedContext.TvShowLibraryAggregate.Entities; /// /// Entity for an episode. @@ -13,4 +13,4 @@ namespace Lumina.Domain.Core.Aggregates.VideoLibrary.TvShowLibraryAggregate.Enti public sealed class Episode : Entity { -} \ No newline at end of file +} diff --git a/src/Lumina.Domain/Core/Aggregates/VideoLibrary/TvShowLibraryAggregate/Entities/Season.cs b/src/Lumina.Domain/Core/BoundedContexts/VideoLibraryBoundedContext/TvShowLibraryAggregate/Entities/Season.cs similarity index 65% rename from src/Lumina.Domain/Core/Aggregates/VideoLibrary/TvShowLibraryAggregate/Entities/Season.cs rename to src/Lumina.Domain/Core/BoundedContexts/VideoLibraryBoundedContext/TvShowLibraryAggregate/Entities/Season.cs index 61053207..b8e838fe 100644 --- a/src/Lumina.Domain/Core/Aggregates/VideoLibrary/TvShowLibraryAggregate/Entities/Season.cs +++ b/src/Lumina.Domain/Core/BoundedContexts/VideoLibraryBoundedContext/TvShowLibraryAggregate/Entities/Season.cs @@ -1,10 +1,10 @@ #region ========================================================================= USING ===================================================================================== using Lumina.Domain.Common.Models.Core; -using Lumina.Domain.Core.Aggregates.VideoLibrary.TvShowLibraryAggregate.ValueObjects; +using Lumina.Domain.Core.BoundedContexts.VideoLibraryBoundedContext.TvShowLibraryAggregate.ValueObjects; using System.Diagnostics; #endregion -namespace Lumina.Domain.Core.Aggregates.VideoLibrary.TvShowLibraryAggregate.Entities; +namespace Lumina.Domain.Core.BoundedContexts.VideoLibraryBoundedContext.TvShowLibraryAggregate.Entities; /// /// Entity for a season. diff --git a/src/Lumina.Domain/Core/Aggregates/VideoLibrary/TvShowLibraryAggregate/Services/ITvShowLibraryService.cs b/src/Lumina.Domain/Core/BoundedContexts/VideoLibraryBoundedContext/TvShowLibraryAggregate/Services/ITvShowLibraryService.cs similarity index 82% rename from src/Lumina.Domain/Core/Aggregates/VideoLibrary/TvShowLibraryAggregate/Services/ITvShowLibraryService.cs rename to src/Lumina.Domain/Core/BoundedContexts/VideoLibraryBoundedContext/TvShowLibraryAggregate/Services/ITvShowLibraryService.cs index 386134c3..311df28e 100644 --- a/src/Lumina.Domain/Core/Aggregates/VideoLibrary/TvShowLibraryAggregate/Services/ITvShowLibraryService.cs +++ b/src/Lumina.Domain/Core/BoundedContexts/VideoLibraryBoundedContext/TvShowLibraryAggregate/Services/ITvShowLibraryService.cs @@ -2,7 +2,7 @@ using System.Collections.Generic; #endregion -namespace Lumina.Domain.Core.Aggregates.VideoLibrary.TvShowLibraryAggregate.Services; +namespace Lumina.Domain.Core.BoundedContexts.VideoLibraryBoundedContext.TvShowLibraryAggregate.Services; /// /// Interface for the service for managing TV show libraries. @@ -13,4 +13,4 @@ public interface ITvShowLibraryService /// Gets the collection of TV shows in the library. /// public ICollection TvShows { get; } -} \ No newline at end of file +} diff --git a/src/Lumina.Domain/Core/Aggregates/VideoLibrary/TvShowLibraryAggregate/Services/TvShowLibraryService.cs b/src/Lumina.Domain/Core/BoundedContexts/VideoLibraryBoundedContext/TvShowLibraryAggregate/Services/TvShowLibraryService.cs similarity index 83% rename from src/Lumina.Domain/Core/Aggregates/VideoLibrary/TvShowLibraryAggregate/Services/TvShowLibraryService.cs rename to src/Lumina.Domain/Core/BoundedContexts/VideoLibraryBoundedContext/TvShowLibraryAggregate/Services/TvShowLibraryService.cs index a3dd7d4f..b62ef2ed 100644 --- a/src/Lumina.Domain/Core/Aggregates/VideoLibrary/TvShowLibraryAggregate/Services/TvShowLibraryService.cs +++ b/src/Lumina.Domain/Core/BoundedContexts/VideoLibraryBoundedContext/TvShowLibraryAggregate/Services/TvShowLibraryService.cs @@ -3,7 +3,7 @@ using System; using System.Collections.Generic; #endregion -namespace Lumina.Domain.Core.Aggregates.VideoLibrary.TvShowLibraryAggregate.Services; +namespace Lumina.Domain.Core.BoundedContexts.VideoLibraryBoundedContext.TvShowLibraryAggregate.Services; /// /// Service for managing TV show libraries. diff --git a/src/Lumina.Domain/Core/Aggregates/VideoLibrary/TvShowLibraryAggregate/TvShow.cs b/src/Lumina.Domain/Core/BoundedContexts/VideoLibraryBoundedContext/TvShowLibraryAggregate/TvShow.cs similarity index 65% rename from src/Lumina.Domain/Core/Aggregates/VideoLibrary/TvShowLibraryAggregate/TvShow.cs rename to src/Lumina.Domain/Core/BoundedContexts/VideoLibraryBoundedContext/TvShowLibraryAggregate/TvShow.cs index 747b4906..a186f6f7 100644 --- a/src/Lumina.Domain/Core/Aggregates/VideoLibrary/TvShowLibraryAggregate/TvShow.cs +++ b/src/Lumina.Domain/Core/BoundedContexts/VideoLibraryBoundedContext/TvShowLibraryAggregate/TvShow.cs @@ -1,10 +1,10 @@ #region ========================================================================= USING ===================================================================================== using Lumina.Domain.Common.Models.Core; -using Lumina.Domain.Core.Aggregates.VideoLibrary.TvShowLibraryAggregate.ValueObjects; +using Lumina.Domain.Core.BoundedContexts.VideoLibraryBoundedContext.TvShowLibraryAggregate.ValueObjects; using System.Diagnostics; #endregion -namespace Lumina.Domain.Core.Aggregates.VideoLibrary.TvShowLibraryAggregate; +namespace Lumina.Domain.Core.BoundedContexts.VideoLibraryBoundedContext.TvShowLibraryAggregate; /// /// Entity for a TV show. @@ -13,4 +13,4 @@ namespace Lumina.Domain.Core.Aggregates.VideoLibrary.TvShowLibraryAggregate; public sealed class TvShow : Entity { -} \ No newline at end of file +} diff --git a/src/Lumina.Domain/Core/Aggregates/VideoLibrary/TvShowLibraryAggregate/ValueObjects/EpisodeId.cs b/src/Lumina.Domain/Core/BoundedContexts/VideoLibraryBoundedContext/TvShowLibraryAggregate/ValueObjects/EpisodeId.cs similarity index 93% rename from src/Lumina.Domain/Core/Aggregates/VideoLibrary/TvShowLibraryAggregate/ValueObjects/EpisodeId.cs rename to src/Lumina.Domain/Core/BoundedContexts/VideoLibraryBoundedContext/TvShowLibraryAggregate/ValueObjects/EpisodeId.cs index f390a3c6..50df2cd6 100644 --- a/src/Lumina.Domain/Core/Aggregates/VideoLibrary/TvShowLibraryAggregate/ValueObjects/EpisodeId.cs +++ b/src/Lumina.Domain/Core/BoundedContexts/VideoLibraryBoundedContext/TvShowLibraryAggregate/ValueObjects/EpisodeId.cs @@ -4,7 +4,7 @@ using System; using System.Collections.Generic; #endregion -namespace Lumina.Domain.Core.Aggregates.VideoLibrary.TvShowLibraryAggregate.ValueObjects; +namespace Lumina.Domain.Core.BoundedContexts.VideoLibraryBoundedContext.TvShowLibraryAggregate.ValueObjects; /// /// Value Object for the Id of an episode. @@ -45,4 +45,4 @@ public sealed class EpisodeId : EntityId { yield return Value; } -} \ No newline at end of file +} diff --git a/src/Lumina.Domain/Core/Aggregates/VideoLibrary/TvShowLibraryAggregate/ValueObjects/SeasonId.cs b/src/Lumina.Domain/Core/BoundedContexts/VideoLibraryBoundedContext/TvShowLibraryAggregate/ValueObjects/SeasonId.cs similarity index 93% rename from src/Lumina.Domain/Core/Aggregates/VideoLibrary/TvShowLibraryAggregate/ValueObjects/SeasonId.cs rename to src/Lumina.Domain/Core/BoundedContexts/VideoLibraryBoundedContext/TvShowLibraryAggregate/ValueObjects/SeasonId.cs index b2a732ec..ed7bd3e1 100644 --- a/src/Lumina.Domain/Core/Aggregates/VideoLibrary/TvShowLibraryAggregate/ValueObjects/SeasonId.cs +++ b/src/Lumina.Domain/Core/BoundedContexts/VideoLibraryBoundedContext/TvShowLibraryAggregate/ValueObjects/SeasonId.cs @@ -4,7 +4,7 @@ using System; using System.Collections.Generic; #endregion -namespace Lumina.Domain.Core.Aggregates.VideoLibrary.TvShowLibraryAggregate.ValueObjects; +namespace Lumina.Domain.Core.BoundedContexts.VideoLibraryBoundedContext.TvShowLibraryAggregate.ValueObjects; /// /// Value Object for the Id of a season. diff --git a/src/Lumina.Domain/Core/Aggregates/VideoLibrary/TvShowLibraryAggregate/ValueObjects/TvShowId.cs b/src/Lumina.Domain/Core/BoundedContexts/VideoLibraryBoundedContext/TvShowLibraryAggregate/ValueObjects/TvShowId.cs similarity index 93% rename from src/Lumina.Domain/Core/Aggregates/VideoLibrary/TvShowLibraryAggregate/ValueObjects/TvShowId.cs rename to src/Lumina.Domain/Core/BoundedContexts/VideoLibraryBoundedContext/TvShowLibraryAggregate/ValueObjects/TvShowId.cs index c37f5ef2..2fa124da 100644 --- a/src/Lumina.Domain/Core/Aggregates/VideoLibrary/TvShowLibraryAggregate/ValueObjects/TvShowId.cs +++ b/src/Lumina.Domain/Core/BoundedContexts/VideoLibraryBoundedContext/TvShowLibraryAggregate/ValueObjects/TvShowId.cs @@ -4,7 +4,7 @@ using System; using System.Collections.Generic; #endregion -namespace Lumina.Domain.Core.Aggregates.VideoLibrary.TvShowLibraryAggregate.ValueObjects; +namespace Lumina.Domain.Core.BoundedContexts.VideoLibraryBoundedContext.TvShowLibraryAggregate.ValueObjects; /// /// Value Object for the Id of a TV show. diff --git a/src/Lumina.Domain/Core/Aggregates/WrittenContentLibrary/BookLibraryAggregate/Book.cs b/src/Lumina.Domain/Core/BoundedContexts/WrittenContentLibraryBoundedContext/BookLibraryAggregate/Book.cs similarity index 95% rename from src/Lumina.Domain/Core/Aggregates/WrittenContentLibrary/BookLibraryAggregate/Book.cs rename to src/Lumina.Domain/Core/BoundedContexts/WrittenContentLibraryBoundedContext/BookLibraryAggregate/Book.cs index faa4dbcd..a0f2e22a 100644 --- a/src/Lumina.Domain/Core/Aggregates/WrittenContentLibrary/BookLibraryAggregate/Book.cs +++ b/src/Lumina.Domain/Core/BoundedContexts/WrittenContentLibraryBoundedContext/BookLibraryAggregate/Book.cs @@ -1,22 +1,22 @@ #region ========================================================================= USING ===================================================================================== using ErrorOr; -using Lumina.Contracts.Enums.BookLibrary; +using Lumina.Domain.Common.Enums.BookLibrary; using Lumina.Domain.Common.Models.Core; using Lumina.Domain.Common.Primitives; -using Lumina.Domain.Core.Aggregates.MediaContributor.MediaContributorAggregate.ValueObjects; -using Lumina.Domain.Core.Aggregates.WrittenContentLibrary.BookLibraryAggregate.Entities; -using Lumina.Domain.Core.Aggregates.WrittenContentLibrary.BookLibraryAggregate.ValueObjects; +using Lumina.Domain.Core.BoundedContexts.MediaContributorBoundedContext.MediaContributorAggregate.ValueObjects; +using Lumina.Domain.Core.BoundedContexts.WrittenContentLibraryBoundedContext.BookLibraryAggregate.Entities; +using Lumina.Domain.Core.BoundedContexts.WrittenContentLibraryBoundedContext.BookLibraryAggregate.ValueObjects; using System; using System.Collections.Generic; using System.Diagnostics; #endregion -namespace Lumina.Domain.Core.Aggregates.WrittenContentLibrary.BookLibraryAggregate; +namespace Lumina.Domain.Core.BoundedContexts.WrittenContentLibraryBoundedContext.BookLibraryAggregate; /// /// Aggregate root for a book. /// -[DebuggerDisplay("{Id}: {Title}")] +[DebuggerDisplay("Id: {Id} Title: {Title}")] public sealed class Book : AggregateRoot { private readonly List _contributors; @@ -248,7 +248,8 @@ public sealed class Book : AggregateRoot default, isbns, contributors, - ratings); + ratings + ); } /// @@ -320,6 +321,7 @@ public sealed class Book : AggregateRoot updated, isbns, contributors, - ratings); + ratings + ); } -} \ No newline at end of file +} diff --git a/src/Lumina.Domain/Core/Aggregates/WrittenContentLibrary/BookLibraryAggregate/Entities/BookSeries.cs b/src/Lumina.Domain/Core/BoundedContexts/WrittenContentLibraryBoundedContext/BookLibraryAggregate/Entities/BookSeries.cs similarity index 95% rename from src/Lumina.Domain/Core/Aggregates/WrittenContentLibrary/BookLibraryAggregate/Entities/BookSeries.cs rename to src/Lumina.Domain/Core/BoundedContexts/WrittenContentLibraryBoundedContext/BookLibraryAggregate/Entities/BookSeries.cs index ef21a589..649fdf88 100644 --- a/src/Lumina.Domain/Core/Aggregates/WrittenContentLibrary/BookLibraryAggregate/Entities/BookSeries.cs +++ b/src/Lumina.Domain/Core/BoundedContexts/WrittenContentLibraryBoundedContext/BookLibraryAggregate/Entities/BookSeries.cs @@ -2,12 +2,12 @@ using ErrorOr; using Lumina.Domain.Common.Errors; using Lumina.Domain.Common.Models.Core; -using Lumina.Domain.Core.Aggregates.WrittenContentLibrary.BookLibraryAggregate.ValueObjects; +using Lumina.Domain.Core.BoundedContexts.WrittenContentLibraryBoundedContext.BookLibraryAggregate.ValueObjects; using System.Collections.Generic; using System.Diagnostics; #endregion -namespace Lumina.Domain.Core.Aggregates.WrittenContentLibrary.BookLibraryAggregate.Entities; +namespace Lumina.Domain.Core.BoundedContexts.WrittenContentLibraryBoundedContext.BookLibraryAggregate.Entities; /// /// Entity for a book series. @@ -120,4 +120,4 @@ public sealed class BookSeries : Entity _books.Remove(book); return Result.Deleted; } -} \ No newline at end of file +} diff --git a/src/Lumina.Domain/Core/Aggregates/WrittenContentLibrary/BookLibraryAggregate/Services/BookLibraryService.cs b/src/Lumina.Domain/Core/BoundedContexts/WrittenContentLibraryBoundedContext/BookLibraryAggregate/Services/BookLibraryService.cs similarity index 82% rename from src/Lumina.Domain/Core/Aggregates/WrittenContentLibrary/BookLibraryAggregate/Services/BookLibraryService.cs rename to src/Lumina.Domain/Core/BoundedContexts/WrittenContentLibraryBoundedContext/BookLibraryAggregate/Services/BookLibraryService.cs index 27be5efe..bf64219b 100644 --- a/src/Lumina.Domain/Core/Aggregates/WrittenContentLibrary/BookLibraryAggregate/Services/BookLibraryService.cs +++ b/src/Lumina.Domain/Core/BoundedContexts/WrittenContentLibraryBoundedContext/BookLibraryAggregate/Services/BookLibraryService.cs @@ -3,7 +3,7 @@ using System; using System.Collections.Generic; #endregion -namespace Lumina.Domain.Core.Aggregates.WrittenContentLibrary.BookLibraryAggregate.Services; +namespace Lumina.Domain.Core.BoundedContexts.WrittenContentLibraryBoundedContext.BookLibraryAggregate.Services; /// /// Service for managing book libraries. @@ -14,4 +14,4 @@ public sealed class BookLibraryService : IBookLibraryService /// Gets the collection of books in the library. /// public ICollection Books => throw new NotImplementedException(); -} \ No newline at end of file +} diff --git a/src/Lumina.Domain/Core/Aggregates/WrittenContentLibrary/BookLibraryAggregate/Services/IBookLibraryService.cs b/src/Lumina.Domain/Core/BoundedContexts/WrittenContentLibraryBoundedContext/BookLibraryAggregate/Services/IBookLibraryService.cs similarity index 87% rename from src/Lumina.Domain/Core/Aggregates/WrittenContentLibrary/BookLibraryAggregate/Services/IBookLibraryService.cs rename to src/Lumina.Domain/Core/BoundedContexts/WrittenContentLibraryBoundedContext/BookLibraryAggregate/Services/IBookLibraryService.cs index ee05ac0e..91368260 100644 --- a/src/Lumina.Domain/Core/Aggregates/WrittenContentLibrary/BookLibraryAggregate/Services/IBookLibraryService.cs +++ b/src/Lumina.Domain/Core/BoundedContexts/WrittenContentLibraryBoundedContext/BookLibraryAggregate/Services/IBookLibraryService.cs @@ -2,7 +2,7 @@ using System.Collections.Generic; #endregion -namespace Lumina.Domain.Core.Aggregates.WrittenContentLibrary.BookLibraryAggregate.Services; +namespace Lumina.Domain.Core.BoundedContexts.WrittenContentLibraryBoundedContext.BookLibraryAggregate.Services; /// /// Interface for the service for managing book libraries. diff --git a/src/Lumina.Domain/Core/Aggregates/WrittenContentLibrary/BookLibraryAggregate/ValueObjects/BookId.cs b/src/Lumina.Domain/Core/BoundedContexts/WrittenContentLibraryBoundedContext/BookLibraryAggregate/ValueObjects/BookId.cs similarity index 92% rename from src/Lumina.Domain/Core/Aggregates/WrittenContentLibrary/BookLibraryAggregate/ValueObjects/BookId.cs rename to src/Lumina.Domain/Core/BoundedContexts/WrittenContentLibraryBoundedContext/BookLibraryAggregate/ValueObjects/BookId.cs index 49585405..0e568056 100644 --- a/src/Lumina.Domain/Core/Aggregates/WrittenContentLibrary/BookLibraryAggregate/ValueObjects/BookId.cs +++ b/src/Lumina.Domain/Core/BoundedContexts/WrittenContentLibraryBoundedContext/BookLibraryAggregate/ValueObjects/BookId.cs @@ -5,7 +5,7 @@ using System.Collections.Generic; using System.Diagnostics; #endregion -namespace Lumina.Domain.Core.Aggregates.WrittenContentLibrary.BookLibraryAggregate.ValueObjects; +namespace Lumina.Domain.Core.BoundedContexts.WrittenContentLibraryBoundedContext.BookLibraryAggregate.ValueObjects; /// /// Value Object for the Id of a book. @@ -45,4 +45,4 @@ public sealed class BookId : EntityId { yield return Value; } -} \ No newline at end of file +} diff --git a/src/Lumina.Domain/Core/Aggregates/WrittenContentLibrary/BookLibraryAggregate/ValueObjects/BookLibraryId.cs b/src/Lumina.Domain/Core/BoundedContexts/WrittenContentLibraryBoundedContext/BookLibraryAggregate/ValueObjects/BookLibraryId.cs similarity index 89% rename from src/Lumina.Domain/Core/Aggregates/WrittenContentLibrary/BookLibraryAggregate/ValueObjects/BookLibraryId.cs rename to src/Lumina.Domain/Core/BoundedContexts/WrittenContentLibraryBoundedContext/BookLibraryAggregate/ValueObjects/BookLibraryId.cs index f6940acc..4d855c5a 100644 --- a/src/Lumina.Domain/Core/Aggregates/WrittenContentLibrary/BookLibraryAggregate/ValueObjects/BookLibraryId.cs +++ b/src/Lumina.Domain/Core/BoundedContexts/WrittenContentLibraryBoundedContext/BookLibraryAggregate/ValueObjects/BookLibraryId.cs @@ -6,13 +6,13 @@ using System.Collections.Generic; using System.Diagnostics; #endregion -namespace Lumina.Domain.Core.Aggregates.WrittenContentLibrary.BookLibraryAggregate.ValueObjects; +namespace Lumina.Domain.Core.BoundedContexts.WrittenContentLibraryBoundedContext.BookLibraryAggregate.ValueObjects; /// /// Value Object for the Id of a book library. /// [DebuggerDisplay("{Value}")] -public sealed class BookLibraryId : EntityId +public sealed class BookLibraryId : EntityId // TODO: to be removed { /// /// Initializes a new instance of the class. @@ -48,4 +48,4 @@ public sealed class BookLibraryId : EntityId { yield return Value; } -} \ No newline at end of file +} diff --git a/src/Lumina.Domain/Core/Aggregates/WrittenContentLibrary/BookLibraryAggregate/ValueObjects/BookRating.cs b/src/Lumina.Domain/Core/BoundedContexts/WrittenContentLibraryBoundedContext/BookLibraryAggregate/ValueObjects/BookRating.cs similarity index 94% rename from src/Lumina.Domain/Core/Aggregates/WrittenContentLibrary/BookLibraryAggregate/ValueObjects/BookRating.cs rename to src/Lumina.Domain/Core/BoundedContexts/WrittenContentLibraryBoundedContext/BookLibraryAggregate/ValueObjects/BookRating.cs index 6fd5ed35..9bd0af3d 100644 --- a/src/Lumina.Domain/Core/Aggregates/WrittenContentLibrary/BookLibraryAggregate/ValueObjects/BookRating.cs +++ b/src/Lumina.Domain/Core/BoundedContexts/WrittenContentLibraryBoundedContext/BookLibraryAggregate/ValueObjects/BookRating.cs @@ -1,6 +1,6 @@ #region ========================================================================= USING ===================================================================================== using ErrorOr; -using Lumina.Contracts.Enums.BookLibrary; +using Lumina.Domain.Common.Enums.BookLibrary; using Lumina.Domain.Common.Errors; using Lumina.Domain.Common.Primitives; using Lumina.Domain.Common.ValueObjects.Metadata; @@ -8,7 +8,7 @@ using System.Collections.Generic; using System.Diagnostics; #endregion -namespace Lumina.Domain.Core.Aggregates.WrittenContentLibrary.BookLibraryAggregate.ValueObjects; +namespace Lumina.Domain.Core.BoundedContexts.WrittenContentLibraryBoundedContext.BookLibraryAggregate.ValueObjects; /// /// Value Object for the rating of a media element. diff --git a/src/Lumina.Domain/Core/Aggregates/WrittenContentLibrary/BookLibraryAggregate/ValueObjects/BookSeriesId.cs b/src/Lumina.Domain/Core/BoundedContexts/WrittenContentLibraryBoundedContext/BookLibraryAggregate/ValueObjects/BookSeriesId.cs similarity index 93% rename from src/Lumina.Domain/Core/Aggregates/WrittenContentLibrary/BookLibraryAggregate/ValueObjects/BookSeriesId.cs rename to src/Lumina.Domain/Core/BoundedContexts/WrittenContentLibraryBoundedContext/BookLibraryAggregate/ValueObjects/BookSeriesId.cs index ea40e631..f8086a6c 100644 --- a/src/Lumina.Domain/Core/Aggregates/WrittenContentLibrary/BookLibraryAggregate/ValueObjects/BookSeriesId.cs +++ b/src/Lumina.Domain/Core/BoundedContexts/WrittenContentLibraryBoundedContext/BookLibraryAggregate/ValueObjects/BookSeriesId.cs @@ -5,7 +5,7 @@ using System.Collections.Generic; using System.Diagnostics; #endregion -namespace Lumina.Domain.Core.Aggregates.WrittenContentLibrary.BookLibraryAggregate.ValueObjects; +namespace Lumina.Domain.Core.BoundedContexts.WrittenContentLibraryBoundedContext.BookLibraryAggregate.ValueObjects; /// /// Value Object for the Id of a book series. diff --git a/src/Lumina.Domain/Core/Aggregates/WrittenContentLibrary/BookLibraryAggregate/ValueObjects/Isbn.cs b/src/Lumina.Domain/Core/BoundedContexts/WrittenContentLibraryBoundedContext/BookLibraryAggregate/ValueObjects/Isbn.cs similarity index 94% rename from src/Lumina.Domain/Core/Aggregates/WrittenContentLibrary/BookLibraryAggregate/ValueObjects/Isbn.cs rename to src/Lumina.Domain/Core/BoundedContexts/WrittenContentLibraryBoundedContext/BookLibraryAggregate/ValueObjects/Isbn.cs index aa6dfa1b..ad4a7c17 100644 --- a/src/Lumina.Domain/Core/Aggregates/WrittenContentLibrary/BookLibraryAggregate/ValueObjects/Isbn.cs +++ b/src/Lumina.Domain/Core/BoundedContexts/WrittenContentLibraryBoundedContext/BookLibraryAggregate/ValueObjects/Isbn.cs @@ -1,6 +1,6 @@ #region ========================================================================= USING ===================================================================================== using ErrorOr; -using Lumina.Contracts.Enums.BookLibrary; +using Lumina.Domain.Common.Enums.BookLibrary; using Lumina.Domain.Common.Errors; using Lumina.Domain.Common.Models.Core; using System.Collections.Generic; @@ -8,7 +8,7 @@ using System.Diagnostics; using System.Text.RegularExpressions; #endregion -namespace Lumina.Domain.Core.Aggregates.WrittenContentLibrary.BookLibraryAggregate.ValueObjects; +namespace Lumina.Domain.Core.BoundedContexts.WrittenContentLibraryBoundedContext.BookLibraryAggregate.ValueObjects; /// /// Value Object for the ISBN of a book. @@ -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/BoundedContexts/WrittenContentLibraryBoundedContext/BookLibraryAggregate/ValueObjects/WrittenContentMetadata.cs similarity index 86% rename from src/Lumina.Domain/Core/Aggregates/WrittenContentLibrary/BookLibraryAggregate/ValueObjects/WrittenContentMetadata.cs rename to src/Lumina.Domain/Core/BoundedContexts/WrittenContentLibraryBoundedContext/BookLibraryAggregate/ValueObjects/WrittenContentMetadata.cs index 19383cd1..04c7c429 100644 --- a/src/Lumina.Domain/Core/Aggregates/WrittenContentLibrary/BookLibraryAggregate/ValueObjects/WrittenContentMetadata.cs +++ b/src/Lumina.Domain/Core/BoundedContexts/WrittenContentLibraryBoundedContext/BookLibraryAggregate/ValueObjects/WrittenContentMetadata.cs @@ -7,7 +7,7 @@ using System.Collections.Generic; using System.Diagnostics; #endregion -namespace Lumina.Domain.Core.Aggregates.WrittenContentLibrary.BookLibraryAggregate.ValueObjects; +namespace Lumina.Domain.Core.BoundedContexts.WrittenContentLibraryBoundedContext.BookLibraryAggregate.ValueObjects; /// /// Value Object for the metadata of a written media element. @@ -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.Domain/Core/Aggregates/WrittenContentLibrary/MagazineLibraryAggregate/Magazine.cs b/src/Lumina.Domain/Core/BoundedContexts/WrittenContentLibraryBoundedContext/MagazineLibraryAggregate/Magazine.cs similarity index 100% rename from src/Lumina.Domain/Core/Aggregates/WrittenContentLibrary/MagazineLibraryAggregate/Magazine.cs rename to src/Lumina.Domain/Core/BoundedContexts/WrittenContentLibraryBoundedContext/MagazineLibraryAggregate/Magazine.cs diff --git a/src/Lumina.Domain/Core/Aggregates/WrittenContentLibrary/Services/IWrittenContentLibraryService.cs b/src/Lumina.Domain/Core/BoundedContexts/WrittenContentLibraryBoundedContext/Services/IWrittenContentLibraryService.cs similarity index 70% rename from src/Lumina.Domain/Core/Aggregates/WrittenContentLibrary/Services/IWrittenContentLibraryService.cs rename to src/Lumina.Domain/Core/BoundedContexts/WrittenContentLibraryBoundedContext/Services/IWrittenContentLibraryService.cs index 64cb6df6..e7e0c8ae 100644 --- a/src/Lumina.Domain/Core/Aggregates/WrittenContentLibrary/Services/IWrittenContentLibraryService.cs +++ b/src/Lumina.Domain/Core/BoundedContexts/WrittenContentLibraryBoundedContext/Services/IWrittenContentLibraryService.cs @@ -1,8 +1,8 @@ #region ========================================================================= USING ===================================================================================== -using Lumina.Domain.Core.Aggregates.WrittenContentLibrary.BookLibraryAggregate.Services; +using Lumina.Domain.Core.BoundedContexts.WrittenContentLibraryBoundedContext.BookLibraryAggregate.Services; #endregion -namespace Lumina.Domain.Core.Aggregates.WrittenContentLibrary.Services; +namespace Lumina.Domain.Core.BoundedContexts.WrittenContentLibraryBoundedContext.Services; /// /// Interface for the service for managing written content. @@ -13,4 +13,4 @@ public interface IWrittenContentLibraryService /// Gets the service for managing book libraries. /// public IBookLibraryService BookLibraryService { get; } -} \ No newline at end of file +} diff --git a/src/Lumina.Domain/Core/Aggregates/WrittenContentLibrary/Services/WrittenContentLibraryService.cs b/src/Lumina.Domain/Core/BoundedContexts/WrittenContentLibraryBoundedContext/Services/WrittenContentLibraryService.cs similarity index 81% rename from src/Lumina.Domain/Core/Aggregates/WrittenContentLibrary/Services/WrittenContentLibraryService.cs rename to src/Lumina.Domain/Core/BoundedContexts/WrittenContentLibraryBoundedContext/Services/WrittenContentLibraryService.cs index 44ae2570..241c3535 100644 --- a/src/Lumina.Domain/Core/Aggregates/WrittenContentLibrary/Services/WrittenContentLibraryService.cs +++ b/src/Lumina.Domain/Core/BoundedContexts/WrittenContentLibraryBoundedContext/Services/WrittenContentLibraryService.cs @@ -1,8 +1,8 @@ #region ========================================================================= USING ===================================================================================== -using Lumina.Domain.Core.Aggregates.WrittenContentLibrary.BookLibraryAggregate.Services; +using Lumina.Domain.Core.BoundedContexts.WrittenContentLibraryBoundedContext.BookLibraryAggregate.Services; #endregion -namespace Lumina.Domain.Core.Aggregates.WrittenContentLibrary.Services; +namespace Lumina.Domain.Core.BoundedContexts.WrittenContentLibraryBoundedContext.Services; /// /// Service for managing written content. diff --git a/src/Lumina.Domain/Core/Services/IMediaLibraryService.cs b/src/Lumina.Domain/Core/Services/IMediaLibraryService.cs index ca64be06..ca9574ff 100644 --- a/src/Lumina.Domain/Core/Services/IMediaLibraryService.cs +++ b/src/Lumina.Domain/Core/Services/IMediaLibraryService.cs @@ -1,6 +1,6 @@ #region ========================================================================= USING ===================================================================================== -using Lumina.Domain.Core.Aggregates.VideoLibrary.Services; -using Lumina.Domain.Core.Aggregates.WrittenContentLibrary.Services; +using Lumina.Domain.Core.BoundedContexts.VideoLibraryBoundedContext.Services; +using Lumina.Domain.Core.BoundedContexts.WrittenContentLibraryBoundedContext.Services; #endregion namespace Lumina.Domain.Core.Services; diff --git a/src/Lumina.Domain/Core/Services/MediaLibraryService.cs b/src/Lumina.Domain/Core/Services/MediaLibraryService.cs index 7004acbe..8cbdf521 100644 --- a/src/Lumina.Domain/Core/Services/MediaLibraryService.cs +++ b/src/Lumina.Domain/Core/Services/MediaLibraryService.cs @@ -1,6 +1,6 @@ #region ========================================================================= USING ===================================================================================== -using Lumina.Domain.Core.Aggregates.VideoLibrary.Services; -using Lumina.Domain.Core.Aggregates.WrittenContentLibrary.Services; +using Lumina.Domain.Core.BoundedContexts.VideoLibraryBoundedContext.Services; +using Lumina.Domain.Core.BoundedContexts.WrittenContentLibraryBoundedContext.Services; #endregion namespace Lumina.Domain.Core.Services; @@ -8,7 +8,7 @@ namespace Lumina.Domain.Core.Services; /// /// Service for managing media libraries. /// -public class MediaLibraryService : IMediaLibraryService +public class MediaLibraryService : IMediaLibraryService // TODO: perhaps a better naming would be IMediaLibraryFacade (same for injected facades here) { /// /// Gets the service for managing a video library. @@ -30,4 +30,4 @@ public class MediaLibraryService : IMediaLibraryService VideoLibraryService = videoLibraryService; WrittenContentLibraryService = writtenContentLibraryService; } -} \ No newline at end of file +} diff --git a/src/Lumina.Domain/Lumina.Domain.csproj b/src/Lumina.Domain/Lumina.Domain.csproj index 241719c2..46d926bd 100644 --- a/src/Lumina.Domain/Lumina.Domain.csproj +++ b/src/Lumina.Domain/Lumina.Domain.csproj @@ -3,9 +3,10 @@ net9.0 disable enable - $(SolutionDir)..\bin\server\ + $(SolutionDir)..\bin\api\ false true + $(WarningsNotAsErrors);NU1901;NU1902;NU1903;NU1904 @@ -14,14 +15,10 @@ - + - + - - - - diff --git a/src/Lumina.Infrastructure/Common/DependencyInjection/InfrastructureLayerServices.cs b/src/Lumina.Infrastructure/Common/DependencyInjection/InfrastructureLayerServices.cs index 1e1d0ce0..13c0096f 100644 --- a/src/Lumina.Infrastructure/Common/DependencyInjection/InfrastructureLayerServices.cs +++ b/src/Lumina.Infrastructure/Common/DependencyInjection/InfrastructureLayerServices.cs @@ -1,6 +1,13 @@ #region ========================================================================= USING ===================================================================================== using FluentValidation; +using Lumina.Application.Common.Infrastructure.Authentication; +using Lumina.Application.Common.Infrastructure.Security; +using Lumina.Application.Common.Infrastructure.Time; +using Lumina.Infrastructure.Core.Authentication; +using Lumina.Infrastructure.Core.Security; +using Lumina.Infrastructure.Core.Time; using Microsoft.Extensions.DependencyInjection; +using System.Diagnostics.CodeAnalysis; using System.Reflection; #endregion @@ -9,6 +16,7 @@ namespace Lumina.Infrastructure.Common.DependencyInjection; /// /// Contains all services of the Infrastructure layer. /// +[ExcludeFromCodeCoverage] public static class InfrastructureLayerServices { /// @@ -21,6 +29,14 @@ public static class InfrastructureLayerServices // scan the current assembly for validators and add them to the DI container services.AddValidatorsFromAssembly(Assembly.GetExecutingAssembly(), ServiceLifetime.Singleton); + services.AddSingleton(); + services.AddSingleton(); + services.AddSingleton(); + services.AddSingleton(); + services.AddSingleton(); + services.AddSingleton(); + services.AddSingleton(); + return services; } -} \ No newline at end of file +} diff --git a/src/Lumina.Infrastructure/Common/DependencyInjection/SharedConfiguration.cs b/src/Lumina.Infrastructure/Common/DependencyInjection/SharedConfiguration.cs index 3229546d..430d8cfe 100644 --- a/src/Lumina.Infrastructure/Common/DependencyInjection/SharedConfiguration.cs +++ b/src/Lumina.Infrastructure/Common/DependencyInjection/SharedConfiguration.cs @@ -3,6 +3,7 @@ using Lumina.Infrastructure.Common.Models.Configuration; using Lumina.Infrastructure.Common.Utilities; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; +using System.Diagnostics.CodeAnalysis; using System.IO; using System.Reflection; #endregion @@ -12,6 +13,7 @@ namespace Lumina.Infrastructure.Common.DependencyInjection; /// /// Class containing the shared configuration bindings of the application. /// +[ExcludeFromCodeCoverage] public static class SharedConfiguration { /// @@ -42,6 +44,22 @@ public static class SharedConfiguration .Bind(configuration.GetRequiredSection(DatabaseSettingsModel.SECTION_NAME)) .ValidateFluently() .ValidateOnStart(); + + services.AddOptions() + .Bind(configuration.GetRequiredSection(MediaSettingsModel.SECTION_NAME)) + .ValidateFluently() + .ValidateOnStart(); + + services.AddOptions() + .Bind(configuration.GetRequiredSection(JwtSettingsModel.SECTION_NAME)) + .ValidateFluently() + .ValidateOnStart(); + + services.AddOptions() + .Bind(configuration.GetRequiredSection(EncryptionSettingsModel.SECTION_NAME)) + .ValidateFluently() + .ValidateOnStart(); + return services; } -} \ No newline at end of file +} diff --git a/src/Lumina.Infrastructure/Common/Errors/Errors.Configuration.cs b/src/Lumina.Infrastructure/Common/Errors/Errors.Configuration.cs index ff34f4b3..94fb3220 100644 --- a/src/Lumina.Infrastructure/Common/Errors/Errors.Configuration.cs +++ b/src/Lumina.Infrastructure/Common/Errors/Errors.Configuration.cs @@ -11,7 +11,15 @@ 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)); + public static Error MediaRootDirectoryCannotBeEmpty => Error.Validation(description: nameof(MediaRootDirectoryCannotBeEmpty)); + public static Error EncryptionSecretKeyCannotBeEmpty => Error.Validation(description: nameof(EncryptionSecretKeyCannotBeEmpty)); + public static Error EncryptionSecretKeyMustBeABase64String => Error.Validation(description: nameof(EncryptionSecretKeyMustBeABase64String)); + public static Error JwtSecretKeyCannotBeEmpty => Error.Validation(description: nameof(JwtSecretKeyCannotBeEmpty)); + public static Error JwtSecretKeyTooShort => Error.Validation(description: nameof(JwtSecretKeyTooShort)); + public static Error JwtExpiryMinutesMustBePositive => Error.Validation(description: nameof(JwtExpiryMinutesMustBePositive)); + public static Error JwtIssuerCannotBeEmpty => Error.Validation(description: nameof(JwtIssuerCannotBeEmpty)); + public static Error JwtAudienceCannotBeEmpty => Error.Validation(description: nameof(JwtAudienceCannotBeEmpty)); } } diff --git a/src/Lumina.Infrastructure/Common/Models/Configuration/EncryptionSettingsModel.cs b/src/Lumina.Infrastructure/Common/Models/Configuration/EncryptionSettingsModel.cs new file mode 100644 index 00000000..5a672e71 --- /dev/null +++ b/src/Lumina.Infrastructure/Common/Models/Configuration/EncryptionSettingsModel.cs @@ -0,0 +1,19 @@ +#region ========================================================================= USING ===================================================================================== +using System.Diagnostics; +#endregion + +namespace Lumina.Infrastructure.Common.Models.Configuration; + +/// +/// Model for deserializing media settings. +/// +[DebuggerDisplay("{SECTION_NAME}")] +public class EncryptionSettingsModel +{ + public const string SECTION_NAME = "EncryptionSettings"; + + /// + /// Gets or sets the root directory where media files are stored. + /// + public required string SecretKey { get; init; } +} diff --git a/src/Lumina.Infrastructure/Common/Models/Configuration/JwtSettingsModel.cs b/src/Lumina.Infrastructure/Common/Models/Configuration/JwtSettingsModel.cs new file mode 100644 index 00000000..0ac5f6ff --- /dev/null +++ b/src/Lumina.Infrastructure/Common/Models/Configuration/JwtSettingsModel.cs @@ -0,0 +1,34 @@ +#region ========================================================================= USING ===================================================================================== +using System.Diagnostics; +#endregion + +namespace Lumina.Infrastructure.Common.Models.Configuration; + +/// +/// Model for deserializing media settings. +/// +[DebuggerDisplay("{SECTION_NAME}")] +public class JwtSettingsModel +{ + public const string SECTION_NAME = "JwtSettings"; + + /// + /// The secret key used to sign the JWT. This should be a strong, securely stored key. + /// + public required string SecretKey { get; init; } + + /// + /// The duration (in minutes) for which the JWT is valid. + /// + public required int ExpiryMinutes { get; init; } + + /// + /// The issuer of the JWT, typically the application or service generating the token. + /// + public required string Issuer { get; init; } + + /// + /// The intended audience for the JWT, usually representing the clients that can consume the token. + /// + public required string Audience { get; init; } +} diff --git a/src/Lumina.Infrastructure/Common/Models/Configuration/MediaSettingsModel.cs b/src/Lumina.Infrastructure/Common/Models/Configuration/MediaSettingsModel.cs new file mode 100644 index 00000000..f00b484b --- /dev/null +++ b/src/Lumina.Infrastructure/Common/Models/Configuration/MediaSettingsModel.cs @@ -0,0 +1,19 @@ +#region ========================================================================= USING ===================================================================================== +using System.Diagnostics; +#endregion + +namespace Lumina.Infrastructure.Common.Models.Configuration; + +/// +/// Model for deserializing media settings. +/// +[DebuggerDisplay("{SECTION_NAME}")] +public class MediaSettingsModel +{ + public const string SECTION_NAME = "MediaSettings"; + + /// + /// Gets or sets the root directory where media files are stored. + /// + public required string RootDirectory { get; init; } +} 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/Common/Validators/EncryptionSettingsModelValidator.cs b/src/Lumina.Infrastructure/Common/Validators/EncryptionSettingsModelValidator.cs new file mode 100644 index 00000000..b95344fe --- /dev/null +++ b/src/Lumina.Infrastructure/Common/Validators/EncryptionSettingsModelValidator.cs @@ -0,0 +1,24 @@ +#region ========================================================================= USING ===================================================================================== +using FluentValidation; +using Lumina.Infrastructure.Common.Models.Configuration; +using System; +using System.Buffers.Text; +#endregion + +namespace Lumina.Infrastructure.Common.Validators; + +/// +/// Validates the needed validation rules for the EncryptionSettings application configuration settings section. +/// +public class EncryptionSettingsModelValidator : AbstractValidator +{ + /// + /// Initializes a new instance of the class. + /// + public EncryptionSettingsModelValidator() + { + RuleFor(x => x.SecretKey) + .NotEmpty().WithMessage(Errors.Errors.Configuration.EncryptionSecretKeyCannotBeEmpty.Description) + .Must(value => Base64.IsValid(value.AsSpan())).WithMessage(Errors.Errors.Configuration.EncryptionSecretKeyMustBeABase64String.Description); + } +} diff --git a/src/Lumina.Infrastructure/Common/Validators/JwtSettingsModelValidator.cs b/src/Lumina.Infrastructure/Common/Validators/JwtSettingsModelValidator.cs new file mode 100644 index 00000000..47201c97 --- /dev/null +++ b/src/Lumina.Infrastructure/Common/Validators/JwtSettingsModelValidator.cs @@ -0,0 +1,36 @@ +#region ========================================================================= USING ===================================================================================== +using FluentValidation; +using Lumina.Infrastructure.Common.Models.Configuration; +#endregion + +namespace Lumina.Infrastructure.Common.Validators; + +/// +/// Validates the needed validation rules for the JwtSettings application configuration settings section. +/// +public class JwtSettingsModelValidator : AbstractValidator +{ + /// + /// Initializes a new instance of the class. + /// + public JwtSettingsModelValidator() + { + RuleFor(x => x.SecretKey) + .NotEmpty() + .WithMessage(Errors.Errors.Configuration.JwtSecretKeyCannotBeEmpty.Description) + .MinimumLength(32) + .WithMessage(Errors.Errors.Configuration.JwtSecretKeyTooShort.Description); + + RuleFor(x => x.ExpiryMinutes) + .GreaterThan(0) + .WithMessage(Errors.Errors.Configuration.JwtExpiryMinutesMustBePositive.Description); + + RuleFor(x => x.Issuer) + .NotEmpty() + .WithMessage(Errors.Errors.Configuration.JwtIssuerCannotBeEmpty.Description); + + RuleFor(x => x.Audience) + .NotEmpty() + .WithMessage(Errors.Errors.Configuration.JwtAudienceCannotBeEmpty.Description); + } +} diff --git a/src/Lumina.Infrastructure/Common/Validators/MediaSettingsModelValidator.cs b/src/Lumina.Infrastructure/Common/Validators/MediaSettingsModelValidator.cs new file mode 100644 index 00000000..caf6d52e --- /dev/null +++ b/src/Lumina.Infrastructure/Common/Validators/MediaSettingsModelValidator.cs @@ -0,0 +1,20 @@ +#region ========================================================================= USING ===================================================================================== +using FluentValidation; +using Lumina.Infrastructure.Common.Models.Configuration; +#endregion + +namespace Lumina.Infrastructure.Common.Validators; + +/// +/// Validates the needed validation rules for the MediaSettings application configuration settings section. +/// +public class MediaSettingsModelValidator : AbstractValidator +{ + /// + /// Initializes a new instance of the class. + /// + public MediaSettingsModelValidator() + { + RuleFor(x => x.RootDirectory).NotEmpty().WithMessage(Errors.Errors.Configuration.MediaRootDirectoryCannotBeEmpty.Description); + } +} diff --git a/src/Lumina.Infrastructure/Core/Authentication/JwtTokenGenerator.cs b/src/Lumina.Infrastructure/Core/Authentication/JwtTokenGenerator.cs new file mode 100644 index 00000000..f50effc4 --- /dev/null +++ b/src/Lumina.Infrastructure/Core/Authentication/JwtTokenGenerator.cs @@ -0,0 +1,57 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.Infrastructure.Authentication; +using Lumina.Application.Common.Infrastructure.Time; +using Lumina.Infrastructure.Common.Models.Configuration; +using Microsoft.Extensions.Options; +using Microsoft.IdentityModel.Tokens; +using System.IdentityModel.Tokens.Jwt; +using System.Security.Claims; +using System.Text; +#endregion + +namespace Lumina.Infrastructure.Core.Authentication; + +/// +/// Class for generating JWT tokens. +/// +public class JwtTokenGenerator : IJwtTokenGenerator +{ + private readonly IDateTimeProvider _dateTimeProvider; + private readonly JwtSettingsModel _jwtSettingsModel; + + /// + /// Initializes a new instance of the class. + /// + /// Injected service for time related functionality. + /// Injected service for retrieving . + public JwtTokenGenerator(IDateTimeProvider dateTimeProvider, IOptions jwtSettingsModelOptions) + { + _dateTimeProvider = dateTimeProvider; + _jwtSettingsModel = jwtSettingsModelOptions.Value; + } + + /// + /// Generates a new JWT token. + /// + /// The id of the user for which to generate the token. + /// The username of the user for which to generate the token. + /// The generated JWT token. + public string GenerateToken(string id, string username) + { + // use a symmetric key approach + SigningCredentials signingCredentials = new(new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_jwtSettingsModel.SecretKey)), SecurityAlgorithms.HmacSha256); + Claim[] claims = + [ + new Claim(JwtRegisteredClaimNames.Sub, id), + new Claim(JwtRegisteredClaimNames.UniqueName, username), + new Claim(JwtRegisteredClaimNames.Jti, id.ToString()) + ]; + JwtSecurityToken securityToken = new( + issuer: _jwtSettingsModel.Issuer, + audience: _jwtSettingsModel.Audience, + expires: _dateTimeProvider.UtcNow.AddMinutes(_jwtSettingsModel.ExpiryMinutes), + claims: claims, + signingCredentials: signingCredentials); + return new JwtSecurityTokenHandler().WriteToken(securityToken); + } +} diff --git a/src/Lumina.Infrastructure/Core/Authentication/QRCodeGenerator.cs b/src/Lumina.Infrastructure/Core/Authentication/QRCodeGenerator.cs new file mode 100644 index 00000000..b192fbf7 --- /dev/null +++ b/src/Lumina.Infrastructure/Core/Authentication/QRCodeGenerator.cs @@ -0,0 +1,38 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.Infrastructure.Authentication; +using OtpNet; +using QRCoder; +using System; +#endregion + +namespace Lumina.Infrastructure.Core.Authentication; + +/// +/// Service for generating QR codes for TOTP. +/// +public class QRCodeGenerator : IQRCodeGenerator +{ + private const string ISSUER = "Lumina"; + + /// + /// Generates a QR code Data URI for the specified TOTP secret. + /// + /// User's username or unique identifier. + /// The TOTP secret for which the QR code should be generated. + /// Data URI for the QR code. + public string GenerateQrCodeDataUri(string username, byte[] secret) + { + // convert secret to Base32 + string base32Secret = Base32Encoding.ToString(secret); + // build the otpauth URI + string otpauthString = $"otpauth://totp/{ISSUER}:{Uri.EscapeDataString(username)}?secret={base32Secret}&issuer={ISSUER}"; + // generate QR Code + QRCoder.QRCodeGenerator qrGenerator = new(); + QRCodeData qrData = qrGenerator.CreateQrCode(otpauthString, QRCoder.QRCodeGenerator.ECCLevel.Q); + PngByteQRCode qrCode = new(qrData); + // convert QR Code to Data URI + byte[] pngBytes = qrCode.GetGraphic(20); // specify a pixel size if needed + string dataUri = "data:image/png;base64," + Convert.ToBase64String(pngBytes); + return dataUri; + } +} diff --git a/src/Lumina.Infrastructure/Core/Authentication/TokenGenerator.cs b/src/Lumina.Infrastructure/Core/Authentication/TokenGenerator.cs new file mode 100644 index 00000000..d3fb139a --- /dev/null +++ b/src/Lumina.Infrastructure/Core/Authentication/TokenGenerator.cs @@ -0,0 +1,27 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.Infrastructure.Authentication; +using System; +using System.Security.Cryptography; +#endregion + +namespace Lumina.Infrastructure.Core.Authentication; + +/// +/// Service for the service for generating secure tokens for accounts confirmation or recovery. +/// +public class TokenGenerator : ITokenGenerator +{ + /// + /// Generates a secure token. + /// + /// A secure token. + public string GenerateToken() + { + // allocate an array for the token data + byte[] tokenData = new byte[32]; + // fill the array with a cryptographically strong sequence of random values + RandomNumberGenerator.Fill(tokenData); + // convert to a Base64 string, but replace URL-unsafe characters '+' and '/' with '-' and '_', and remove padding characters ('=') + return Convert.ToBase64String(tokenData).Replace('+', '-').Replace('/', '_').TrimEnd('='); + } +} diff --git a/src/Lumina.Infrastructure/Core/Authentication/TotpTokenGenerator.cs b/src/Lumina.Infrastructure/Core/Authentication/TotpTokenGenerator.cs new file mode 100644 index 00000000..4bc8e8cc --- /dev/null +++ b/src/Lumina.Infrastructure/Core/Authentication/TotpTokenGenerator.cs @@ -0,0 +1,34 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.Infrastructure.Authentication; +using OtpNet; +#endregion + +namespace Lumina.Infrastructure.Core.Authentication; + +/// +/// Service for generating and validating TOTP tokens. +/// +public class TotpTokenGenerator : ITotpTokenGenerator +{ + /// + /// Generates a new TOTP secret for a user. + /// + /// The generated TOTP secret. + public byte[] GenerateSecret() + { + return KeyGeneration.GenerateRandomKey(); // generate a random key for TOTP + } + + /// + /// Validates a TOTP token against the stored secret. + /// + /// The user's TOTP secret. + /// The token to validate. + /// if valid, otherwise. + public bool ValidateToken(byte[] secret, string token) + { + Totp totp = new(secret); + // verify the TOTP token, allowing for slight time drifts between server and client + return totp.VerifyTotp(token, out _, VerificationWindow.RfcSpecifiedNetworkDelay); + } +} diff --git a/src/Lumina.Infrastructure/Core/Security/CryptographyService.cs b/src/Lumina.Infrastructure/Core/Security/CryptographyService.cs new file mode 100644 index 00000000..c45c5c3b --- /dev/null +++ b/src/Lumina.Infrastructure/Core/Security/CryptographyService.cs @@ -0,0 +1,103 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.Infrastructure.Security; +using Lumina.Infrastructure.Common.Models.Configuration; +using Microsoft.Extensions.Options; +using System; +using System.Security.Cryptography; +using System.Text; +#endregion + +namespace Lumina.Infrastructure.Core.Security; + +/// +/// Service for cryptographic concerns. +/// +public sealed class CryptographyService : ICryptographyService, IDisposable +{ + private readonly byte[] _key; + + /// + /// Initializes a new instance of the class. + /// + /// Injected service for retrieving . + public CryptographyService(IOptions encryptionSettingsModelOptions) + { + _key = Convert.FromBase64String(encryptionSettingsModelOptions.Value.SecretKey); + } + + /// + /// Encrypts a plaintext string using AES encryption with a randomly generated initialization vector (IV). + /// + /// The plaintext string to encrypt. + /// A Base64-encoded string of the combined IV and encrypted ciphertext. + /// Thrown when is or empty. + public string Encrypt(string plaintext) + { + if (string.IsNullOrEmpty(plaintext)) + throw new ArgumentException("Value cannot be null or empty", nameof(plaintext)); + + // generate a new, random 16-byte IV for each encryption to ensure unique ciphertexts + byte[] iv = new byte[16]; + using (RandomNumberGenerator rng = RandomNumberGenerator.Create()) + rng.GetBytes(iv); + + using Aes aes = Aes.Create(); + aes.Key = _key; + aes.IV = iv; + aes.Mode = CipherMode.CBC; + aes.Padding = PaddingMode.PKCS7; + + using ICryptoTransform encryptor = aes.CreateEncryptor(); + byte[] plaintextBytes = Encoding.UTF8.GetBytes(plaintext); + byte[] ciphertext = encryptor.TransformFinalBlock(plaintextBytes, 0, plaintextBytes.Length); + + // combine IV and ciphertext + byte[] combined = new byte[iv.Length + ciphertext.Length]; + Buffer.BlockCopy(iv, 0, combined, 0, iv.Length); + Buffer.BlockCopy(ciphertext, 0, combined, iv.Length, ciphertext.Length); + + return Convert.ToBase64String(combined); + } + + /// + /// Decrypts a Base64-encoded string that contains both the IV and ciphertext. + /// + /// The Base64-encoded string containing both IV and ciphertext. + /// The decrypted plaintext string. + /// Thrown when is , empty, or invalid. + public string Decrypt(string ciphertext) + { + if (string.IsNullOrEmpty(ciphertext)) + throw new ArgumentException("Value cannot be null or empty", nameof(ciphertext)); + + // decode the combined data (IV + ciphertext) from Base64 + byte[] combined = Convert.FromBase64String(ciphertext); + + if (combined.Length < 16) + throw new ArgumentException("Invalid ciphertext"); + + // extract IV and ciphertext + byte[] iv = new byte[16]; + byte[] encryptedData = new byte[combined.Length - 16]; + Buffer.BlockCopy(combined, 0, iv, 0, 16); + Buffer.BlockCopy(combined, 16, encryptedData, 0, encryptedData.Length); + + using Aes aes = Aes.Create(); + aes.Key = _key; + aes.IV = iv; + aes.Mode = CipherMode.CBC; + aes.Padding = PaddingMode.PKCS7; + + using ICryptoTransform decryptor = aes.CreateDecryptor(); + byte[] decrypted = decryptor.TransformFinalBlock(encryptedData, 0, encryptedData.Length); + return Encoding.UTF8.GetString(decrypted); + } + + /// + /// Clears sensitive key data when the service is disposed. + /// + public void Dispose() + { + Array.Clear(_key, 0, _key.Length); + } +} diff --git a/src/Lumina.Infrastructure/Core/Security/HashService.cs b/src/Lumina.Infrastructure/Core/Security/HashService.cs new file mode 100644 index 00000000..e1079cf6 --- /dev/null +++ b/src/Lumina.Infrastructure/Core/Security/HashService.cs @@ -0,0 +1,82 @@ +#region ========================================================================= USING ===================================================================================== +using Konscious.Security.Cryptography; +using Lumina.Application.Common.Infrastructure.Security; +using System; +using System.Security.Cryptography; +using System.Text; +#endregion + +namespace Lumina.Infrastructure.Core.Security; + +/// +/// Service for hashing passwords. +/// +public sealed class HashService : IHashService +{ + // OWASP recommended parameters for Argon2id + private const int MEMORY_SIZE = 19456; // 19 MiB (19 * 1024 = 19456) + private const int ITERATIONS = 2; + private const int DEGREE_OF_PARALLELISM = 1; + private const int HASH_SIZE = 32; // 256 bits + private const int SALT_SIZE = 16; // 128 bits + + /// + /// Creates a hash from a string. + /// + /// The string to be hashed. + /// The hashed string. + public string HashString(string password) + { + byte[] salt = new byte[SALT_SIZE]; + using (RandomNumberGenerator rng = RandomNumberGenerator.Create()) + rng.GetBytes(salt); // generate a random salt + + byte[] hashBytes; + using (Argon2id hasher = new(Encoding.UTF8.GetBytes(password))) + { + hasher.Salt = salt; + hasher.DegreeOfParallelism = DEGREE_OF_PARALLELISM; + hasher.MemorySize = MEMORY_SIZE; + hasher.Iterations = ITERATIONS; + hashBytes = hasher.GetBytes(HASH_SIZE); + } + // concatenate salt and hash and return as a Base64 string + byte[] hashWithSaltBytes = new byte[SALT_SIZE + HASH_SIZE]; + Buffer.BlockCopy(salt, 0, hashWithSaltBytes, 0, SALT_SIZE); + Buffer.BlockCopy(hashBytes, 0, hashWithSaltBytes, SALT_SIZE, HASH_SIZE); + return Convert.ToBase64String(hashWithSaltBytes); + } + + /// + /// Verifies a password against a hash. + /// + /// The string to be checked. + /// The hashed representation of the string to be checked. + /// if and the de-hashed versions of are equal, otherwise. + public bool CheckStringAgainstHash(string password, string hashedPassword) + { + // convert the Base64 string back into a byte array + byte[] hashWithSaltBytes = Convert.FromBase64String(hashedPassword); + // validate the length too + if (hashWithSaltBytes.Length != SALT_SIZE + HASH_SIZE) + return false; + + byte[] saltBytes = new byte[SALT_SIZE]; + Buffer.BlockCopy(hashWithSaltBytes, 0, saltBytes, 0, SALT_SIZE); + + byte[] hashBytes; + using (Argon2id hasher = new(Encoding.UTF8.GetBytes(password))) + { + hasher.Salt = saltBytes; + hasher.DegreeOfParallelism = DEGREE_OF_PARALLELISM; + hasher.MemorySize = MEMORY_SIZE; + hasher.Iterations = ITERATIONS; + hashBytes = hasher.GetBytes(HASH_SIZE); + } + // get the stored hash from the stored hashed password + byte[] storedHashBytes = new byte[HASH_SIZE]; + Buffer.BlockCopy(hashWithSaltBytes, SALT_SIZE, storedHashBytes, 0, HASH_SIZE); + // use constant-time comparison to prevent timing attacks + return CryptographicOperations.FixedTimeEquals(hashBytes, storedHashBytes); + } +} diff --git a/src/Lumina.Infrastructure/Core/Time/DateTimeProvider.cs b/src/Lumina.Infrastructure/Core/Time/DateTimeProvider.cs new file mode 100644 index 00000000..2334c5aa --- /dev/null +++ b/src/Lumina.Infrastructure/Core/Time/DateTimeProvider.cs @@ -0,0 +1,19 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.Infrastructure.Time; +using System; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Infrastructure.Core.Time; + +/// +/// Service for time related concerns +/// +[ExcludeFromCodeCoverage] +public class DateTimeProvider : IDateTimeProvider +{ + /// + /// The current UTC time. + /// + public DateTime UtcNow => DateTime.UtcNow; +} diff --git a/src/Lumina.Infrastructure/Lumina.Infrastructure.csproj b/src/Lumina.Infrastructure/Lumina.Infrastructure.csproj index e74eeea5..d2edaf63 100644 --- a/src/Lumina.Infrastructure/Lumina.Infrastructure.csproj +++ b/src/Lumina.Infrastructure/Lumina.Infrastructure.csproj @@ -3,9 +3,10 @@ net9.0 disable enable - $(SolutionDir)..\bin\server\ + $(SolutionDir)..\bin\api\ false true + $(WarningsNotAsErrors);NU1901;NU1902;NU1903;NU1904 @@ -14,18 +15,22 @@ - - - - - + + + + + + + + + PreserveNewest - + PreserveNewest appsettings.shared.json diff --git a/src/Lumina.Infrastructure/appsettings.shared.json b/src/Lumina.Infrastructure/appsettings.shared.json index 64b489af..366d50a5 100644 --- a/src/Lumina.Infrastructure/appsettings.shared.json +++ b/src/Lumina.Infrastructure/appsettings.shared.json @@ -1,9 +1,12 @@ { + "MediaSettings": { + "RootDirectory": "wwwroot/media" + }, "CommonSettings": { "Theme": "LuminaDark" }, "ConnectionStrings": { - "DefaultConnection": "Server=localhost;Database=Lumina;User Id=sa;Password=Password123;" + "DefaultConnection": "Server=;Database=;User Id=;Password=;" }, "Serilog": { "MinimumLevel": { @@ -18,4 +21,4 @@ "WithThreadId" ] } -} \ No newline at end of file +} 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/PresentationApiLayerConfiguration.cs b/src/Lumina.Presentation.Api/Common/DependencyInjection/PresentationApiLayerConfiguration.cs index 2ffb81cc..148e42f4 100644 --- a/src/Lumina.Presentation.Api/Common/DependencyInjection/PresentationApiLayerConfiguration.cs +++ b/src/Lumina.Presentation.Api/Common/DependencyInjection/PresentationApiLayerConfiguration.cs @@ -1,6 +1,7 @@ #region ========================================================================= USING ===================================================================================== using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; +using System.Diagnostics.CodeAnalysis; using System.IO; using System.Reflection; #endregion @@ -10,6 +11,7 @@ namespace Lumina.Presentation.Api.Common.DependencyInjection; /// /// Class containing the configuration bindings of the Presentation API layer. /// +[ExcludeFromCodeCoverage] internal static class PresentationApiLayerConfiguration { /// @@ -30,4 +32,4 @@ internal static class PresentationApiLayerConfiguration return services; } -} \ 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..620ee5a5 100644 --- a/src/Lumina.Presentation.Api/Common/DependencyInjection/PresentationApiLayerServices.cs +++ b/src/Lumina.Presentation.Api/Common/DependencyInjection/PresentationApiLayerServices.cs @@ -1,13 +1,20 @@ #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.Authentication.JwtBearer; +using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Http.Json; +using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; +using Microsoft.IdentityModel.Tokens; +using Serilog; +using System; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +using System.Text; using System.Text.Json.Serialization; +using System.Threading.RateLimiting; #endregion namespace Lumina.Presentation.Api.Common.DependencyInjection; @@ -15,15 +22,149 @@ namespace Lumina.Presentation.Api.Common.DependencyInjection; /// /// Contains all services of the Presentation API layer. /// +[ExcludeFromCodeCoverage] public static class PresentationApiLayerServices { /// /// Registers the services of the Presentation API layer into the dependency injection container. /// /// The service collection to add the services to. + /// Application configuration properties. /// The updated . - public static IServiceCollection AddPresentationApiLayerServices(this IServiceCollection services) + public static IServiceCollection AddPresentationApiLayerServices(this IServiceCollection services, IConfiguration configuration) { + services.AddMemoryCache(); // used for the tracking involved in authentication rate limiting + services.AddProblemDetails(); + + 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 + }); + + // TODO: also implement account locking after a number of failed login attempts + services.AddRateLimiter(options => + { + options.RejectionStatusCode = StatusCodes.Status429TooManyRequests; + options.OnRejected = async (context, cancellationToken) => + { + ILogger logger = context.HttpContext.RequestServices.GetRequiredService(); + + string clientIp = context.HttpContext.Request.Headers["X-Forwarded-For"] + .FirstOrDefault()?.Split(',')[0].Trim() + ?? context.HttpContext.Connection.RemoteIpAddress?.ToString() + ?? "unknown"; + Log.Warning( + "Rate limit exceeded. IP: {IpAddress}, Route: {Route}, Lease Acquired: {IsAcquired}", + clientIp, + context.HttpContext.Request.Path, + context.Lease.IsAcquired); // when False, the request was rejected because it exceeded rate limits + + context.HttpContext.Response.StatusCode = StatusCodes.Status429TooManyRequests; + context.HttpContext.Response.ContentType = "application/problem+json"; + + // set standard rate limit headers + if (context.Lease.TryGetMetadata(MetadataName.RetryAfter, out TimeSpan retryAfter)) + context.HttpContext.Response.Headers.RetryAfter = ((int)retryAfter.TotalSeconds).ToString(); + + // set custom rate limit headers + context.HttpContext.Response.Headers["X-RateLimit-Limit"] = "10"; + context.HttpContext.Response.Headers["X-RateLimit-Remaining"] = "0"; + context.HttpContext.Response.Headers["X-RateLimit-Reset"] = DateTimeOffset.UtcNow.AddMinutes(15).ToUnixTimeSeconds().ToString(); + + var problem = new + { + type = "https://tools.ietf.org/html/rfc7231#section-6.5.29", + title = "TooManyRequests", // TODO: implement translation? + status = StatusCodes.Status429TooManyRequests, + detail = "Too many attempts. Please try again later.", + retryAfter = "15" + }; + + await context.HttpContext.Response.WriteAsJsonAsync(problem, cancellationToken); + }; + options.AddPolicy("authenticationPolicy", httpContext => + { + string clientIp = httpContext.Request.Headers["X-Forwarded-For"] // first check forwarded headers, in case this is behind a reverse proxy + .FirstOrDefault()?.Split(',')[0].Trim() // take first IP, if multiple available, to avoid IP spoofing attempts + ?? httpContext.Connection.RemoteIpAddress?.ToString() // then try RemoteIpAddress + ?? "unknown"; // fallback if both are null + return RateLimitPartition.GetFixedWindowLimiter( + partitionKey: $"auth_{clientIp}", + factory: _ => new FixedWindowRateLimiterOptions + { + PermitLimit = 10, // allow 10 attempts + Window = TimeSpan.FromMinutes(15), // within 15 minute window + QueueLimit = 0, // don't queue requests + AutoReplenishment = true // automatically reset rate limiter tokens + }); + }); + }); + + // add authentication and specify the JWT scheme to check tokens against + services.AddAuthentication(defaultScheme: JwtBearerDefaults.AuthenticationScheme) + .AddJwtBearer(options => + { + options.TokenValidationParameters = new TokenValidationParameters() + { + ValidateIssuer = true, + ValidateAudience = true, + ValidateLifetime = true, + ValidateIssuerSigningKey = true, + ValidIssuer = configuration["JwtSettings:Issuer"], + ValidAudience = configuration["JwtSettings:Audience"], + IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(configuration["JwtSettings:SecretKey"]!)), + }; + + options.Events = new JwtBearerEvents + { + OnChallenge = context => // event triggered when authentication is not successful for whatever reason + { + context.HandleResponse(); // prevent the default 401 response + // set the response status code to 401 Unauthorized + context.Response.StatusCode = StatusCodes.Status401Unauthorized; + context.Response.ContentType = "application/problem+json"; + + IProblemDetailsService problemDetailsService = context.HttpContext.RequestServices.GetRequiredService(); + return context.Response.WriteAsJsonAsync(new + { + type = "https://tools.ietf.org/html/rfc7235#section-3.1", + status = StatusCodes.Status401Unauthorized, + title = "Unauthorized", + detail = "You are not authorized", + instance = context.HttpContext.Request.Path + }); + } + }; + }); + + 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 +174,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/Http/HttpContextItemKeys.cs b/src/Lumina.Presentation.Api/Common/Http/HttpContextItemKeys.cs index 1ce72009..bcc445d3 100644 --- a/src/Lumina.Presentation.Api/Common/Http/HttpContextItemKeys.cs +++ b/src/Lumina.Presentation.Api/Common/Http/HttpContextItemKeys.cs @@ -1,6 +1,4 @@ -#region ========================================================================= USING ===================================================================================== namespace Lumina.Presentation.Api.Common.Http; -#endregion /// /// Constants shared by HttpContext across a HTTP request (avoid magic strings). @@ -8,4 +6,4 @@ namespace Lumina.Presentation.Api.Common.Http; public static class HttpContextItemKeys { public const string ERRORS = "errors"; -} \ No newline at end of file +} 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/Library/Management/ApiRoutes.Libraries.cs b/src/Lumina.Presentation.Api/Common/Routes/Library/Management/ApiRoutes.Libraries.cs new file mode 100644 index 00000000..c1c20675 --- /dev/null +++ b/src/Lumina.Presentation.Api/Common/Routes/Library/Management/ApiRoutes.Libraries.cs @@ -0,0 +1,17 @@ +namespace Lumina.Presentation.Api.Common.Routes.Library.Management; + +/// +/// Class for the collection of routes defined in this API. +/// +public static partial class ApiRoutes +{ + /// + /// Routes for the Libraries route. + /// + public static class Libraries + { + public const string GET_LIBRARY_BY_ID = "/libraries/{id}"; + public const string GET_LIBRARIES = "/libraries"; + public const string ADD_LIBRARY = "/libraries"; + } +} diff --git a/src/Lumina.Presentation.Api/Common/Routes/Library/WrittenContentLibrary/BookLibrary/ApiRoutes.Books.cs b/src/Lumina.Presentation.Api/Common/Routes/Library/WrittenContentLibrary/BookLibrary/ApiRoutes.Books.cs new file mode 100644 index 00000000..4c356ef1 --- /dev/null +++ b/src/Lumina.Presentation.Api/Common/Routes/Library/WrittenContentLibrary/BookLibrary/ApiRoutes.Books.cs @@ -0,0 +1,17 @@ +namespace Lumina.Presentation.Api.Common.Routes.Library.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/Common/Routes/Maintenance/ApiRoutes.Health.cs b/src/Lumina.Presentation.Api/Common/Routes/Maintenance/ApiRoutes.Health.cs new file mode 100644 index 00000000..bad03b91 --- /dev/null +++ b/src/Lumina.Presentation.Api/Common/Routes/Maintenance/ApiRoutes.Health.cs @@ -0,0 +1,15 @@ +namespace Lumina.Presentation.Api.Common.Routes.Maintenance; + +/// +/// 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/Maintenance/ApiRoutes.Initialization.cs b/src/Lumina.Presentation.Api/Common/Routes/Maintenance/ApiRoutes.Initialization.cs new file mode 100644 index 00000000..86e190c0 --- /dev/null +++ b/src/Lumina.Presentation.Api/Common/Routes/Maintenance/ApiRoutes.Initialization.cs @@ -0,0 +1,16 @@ +namespace Lumina.Presentation.Api.Common.Routes.Maintenance; + +/// +/// Class for the collection of routes defined in this API. +/// +public static partial class ApiRoutes +{ + /// + /// Routes for the Initialization route. + /// + public static class Initialization + { + public const string SETUP_APPLICATION = "/initialization"; + public const string CHECK_INITIALIZATION = "/initialization"; + } +} diff --git a/src/Lumina.Presentation.Api/Common/Routes/UsersManagement/ApiRoutes.Authentication.cs b/src/Lumina.Presentation.Api/Common/Routes/UsersManagement/ApiRoutes.Authentication.cs new file mode 100644 index 00000000..e2827ea1 --- /dev/null +++ b/src/Lumina.Presentation.Api/Common/Routes/UsersManagement/ApiRoutes.Authentication.cs @@ -0,0 +1,18 @@ +namespace Lumina.Presentation.Api.Common.Routes.UsersManagement; + +/// +/// Class for the collection of routes defined in this API. +/// +public static partial class ApiRoutes +{ + /// + /// Routes for the Authentication route. + /// + public static class Authentication + { + public const string REGISTER_ACCOUNT = "/auth/register"; + public const string LOGIN_ACCOUNT = "/auth/login"; + public const string RECOVER_PASSWORD = "/auth/recover-password"; + public const string CHANGE_PASSWORD = "/auth/change-password"; + } +} diff --git a/src/Lumina.Presentation.Api/Common/Routes/UsersManagement/ApiRoutes.Users.cs b/src/Lumina.Presentation.Api/Common/Routes/UsersManagement/ApiRoutes.Users.cs new file mode 100644 index 00000000..c06527fd --- /dev/null +++ b/src/Lumina.Presentation.Api/Common/Routes/UsersManagement/ApiRoutes.Users.cs @@ -0,0 +1,15 @@ +namespace Lumina.Presentation.Api.Common.Routes.UsersManagement; + +/// +/// Class for the collection of routes defined in this API. +/// +public static partial class ApiRoutes +{ + /// + /// Routes for the Users route. + /// + public static class Users + { + public const string GET_USER_BY_ID = "/users/{id}"; + } +} diff --git a/src/Lumina.Presentation.Api/Common/Utilities/MimeTypes.cs b/src/Lumina.Presentation.Api/Common/Utilities/MimeTypes.cs index 17299f81..4e284be2 100644 --- a/src/Lumina.Presentation.Api/Common/Utilities/MimeTypes.cs +++ b/src/Lumina.Presentation.Api/Common/Utilities/MimeTypes.cs @@ -1,5 +1,5 @@ #region ========================================================================= USING ===================================================================================== -using Lumina.Contracts.Enums.PhotoLibrary; +using Lumina.Domain.Common.Enums.PhotoLibrary; using System.Collections.Frozen; using System.Collections.Generic; #endregion 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..d6a33427 --- /dev/null +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Common/BaseEndpoint.cs @@ -0,0 +1,104 @@ +#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.Validation => StatusCodes.Status400BadRequest, + ErrorType.Unauthorized => StatusCodes.Status403Forbidden, // DO NOT return Status401Unauthorized, that actually means lack of valid authentication credentials (not logged in) + ErrorType.Failure => StatusCodes.Status403Forbidden, + ErrorType.Forbidden => StatusCodes.Status403Forbidden, + ErrorType.NotFound => StatusCodes.Status404NotFound, + ErrorType.Conflict => StatusCodes.Status409Conflict, + _ => 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.", // TODO: implement translation? + 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..23c84f93 --- /dev/null +++ b/src/Lumina.Presentation.Api/Core/Endpoints/FileSystemManagement/Directories/GetDirectories/GetDirectoriesEndpointSummary.cs @@ -0,0 +1,31 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Contracts.Requests.FileSystemManagement.Directories; +using Lumina.Contracts.Responses.FileSystemManagement.Directories; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Presentation.Api.Core.Endpoints.FileSystemManagement.Directories.GetDirectories; + +/// +/// Class used for providing a textual description for the API endpoint, for Swagger. +/// +[ExcludeFromCodeCoverage] +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..da5e6175 --- /dev/null +++ b/src/Lumina.Presentation.Api/Core/Endpoints/FileSystemManagement/Directories/GetDirectoryTree/GetDirectoryTreeEndpointSummary.cs @@ -0,0 +1,32 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Contracts.Requests.FileSystemManagement.Directories; +using Lumina.Contracts.Responses.FileSystemManagement.Common; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Presentation.Api.Core.Endpoints.FileSystemManagement.Directories.GetDirectoryTree; + +/// +/// Class used for providing a textual description for the API endpoint, for Swagger. +/// +[ExcludeFromCodeCoverage] +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..434d3740 --- /dev/null +++ b/src/Lumina.Presentation.Api/Core/Endpoints/FileSystemManagement/Directories/GetTreeDirectories/GetTreeDirectoriesEndpointSummary.cs @@ -0,0 +1,31 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Contracts.Requests.FileSystemManagement.Directories; +using Lumina.Contracts.Responses.FileSystemManagement.Common; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Presentation.Api.Core.Endpoints.FileSystemManagement.Directories.GetTreeDirectories; + +/// +/// Class used for providing a textual description for the API endpoint, for Swagger. +/// +[ExcludeFromCodeCoverage] +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..d6b5ddbc --- /dev/null +++ b/src/Lumina.Presentation.Api/Core/Endpoints/FileSystemManagement/Drives/GetDrives/GetDrivesEndpointSummary.cs @@ -0,0 +1,26 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Contracts.Responses.FileSystemManagement.Common; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Presentation.Api.Core.Endpoints.FileSystemManagement.Drives.GetDrives; + +/// +/// Class used for providing a textual description for the API endpoint, for Swagger. +/// +[ExcludeFromCodeCoverage] +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..7aaf65bb --- /dev/null +++ b/src/Lumina.Presentation.Api/Core/Endpoints/FileSystemManagement/FileSystem/GetType/GetTypeEndpointSummary.cs @@ -0,0 +1,25 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Contracts.Responses.FileSystemManagement.FileSystem; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Presentation.Api.Core.Endpoints.FileSystemManagement.FileSystem.GetType; + +/// +/// Class used for providing a textual description for the API endpoint, for Swagger. +/// +[ExcludeFromCodeCoverage] +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..831d31c8 --- /dev/null +++ b/src/Lumina.Presentation.Api/Core/Endpoints/FileSystemManagement/Files/GetFiles/GetFilesEndpointSummary.cs @@ -0,0 +1,31 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Contracts.Requests.FileSystemManagement.Files; +using Lumina.Contracts.Responses.FileSystemManagement.Common; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Presentation.Api.Core.Endpoints.FileSystemManagement.Files.GetFiles; + +/// +/// Class used for providing a textual description for the API endpoint, for Swagger. +/// +[ExcludeFromCodeCoverage] +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..49be978e --- /dev/null +++ b/src/Lumina.Presentation.Api/Core/Endpoints/FileSystemManagement/Files/GetTreeFiles/GetTreeFilesEndpointSummary.cs @@ -0,0 +1,31 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Contracts.Requests.FileSystemManagement.Files; +using Lumina.Contracts.Responses.FileSystemManagement.Common; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Presentation.Api.Core.Endpoints.FileSystemManagement.Files.GetTreeFiles; + +/// +/// Class used for providing a textual description for the API endpoint, for Swagger. +/// +[ExcludeFromCodeCoverage] +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..c8a159e1 --- /dev/null +++ b/src/Lumina.Presentation.Api/Core/Endpoints/FileSystemManagement/Path/CheckPathExists/CheckPathExistsEndpointSummary.cs @@ -0,0 +1,31 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using FastEndpoints.Swagger; +using Lumina.Contracts.Requests.FileSystemManagement.Path; +using Lumina.Contracts.Responses.FileSystemManagement.Path; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Presentation.Api.Core.Endpoints.FileSystemManagement.Path.CheckPathExists; + +/// +/// Class used for providing a textual description for the API endpoint, for Swagger. +/// +[ExcludeFromCodeCoverage] +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..3babebc1 --- /dev/null +++ b/src/Lumina.Presentation.Api/Core/Endpoints/FileSystemManagement/Path/CombinePath/CombinePathEndpointSummary.cs @@ -0,0 +1,30 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Contracts.Requests.FileSystemManagement.Path; +using Lumina.Contracts.Responses.FileSystemManagement.Path; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Presentation.Api.Core.Endpoints.FileSystemManagement.Path.CombinePath; + +/// +/// Class used for providing a textual description for the API endpoint, for Swagger. +/// +[ExcludeFromCodeCoverage] +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..44e2d177 --- /dev/null +++ b/src/Lumina.Presentation.Api/Core/Endpoints/FileSystemManagement/Path/GetPathParent/GetPathParentEndpointSummary.cs @@ -0,0 +1,30 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Contracts.Requests.FileSystemManagement.Path; +using Lumina.Contracts.Responses.FileSystemManagement.Path; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Presentation.Api.Core.Endpoints.FileSystemManagement.Path.GetPathParent; + +/// +/// Class used for providing a textual description for the API endpoint, for Swagger. +/// +[ExcludeFromCodeCoverage] +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..57e558b4 --- /dev/null +++ b/src/Lumina.Presentation.Api/Core/Endpoints/FileSystemManagement/Path/GetPathRoot/GetPathRootEndpointSummary.cs @@ -0,0 +1,29 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Contracts.Requests.FileSystemManagement.Path; +using Lumina.Contracts.Responses.FileSystemManagement.Path; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Presentation.Api.Core.Endpoints.FileSystemManagement.Path.GetPathRoot; + +/// +/// Class used for providing a textual description for the API endpoint, for Swagger. +/// +[ExcludeFromCodeCoverage] +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..28aa7765 --- /dev/null +++ b/src/Lumina.Presentation.Api/Core/Endpoints/FileSystemManagement/Path/GetPathSeparator/GetPathSeparatorEndpointSummary.cs @@ -0,0 +1,25 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Contracts.Responses.FileSystemManagement.Path; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Presentation.Api.Core.Endpoints.FileSystemManagement.Path.GetPathSeparator; + +/// +/// Class used for providing a textual description for the API endpoint, for Swagger. +/// +[ExcludeFromCodeCoverage] +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..f0df92ec --- /dev/null +++ b/src/Lumina.Presentation.Api/Core/Endpoints/FileSystemManagement/Path/SplitPath/SplitPathEndpointSummary.cs @@ -0,0 +1,30 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Contracts.Requests.FileSystemManagement.Path; +using Lumina.Contracts.Responses.FileSystemManagement.Path; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Presentation.Api.Core.Endpoints.FileSystemManagement.Path.SplitPath; + +/// +/// Class used for providing a textual description for the API endpoint, for Swagger. +/// +[ExcludeFromCodeCoverage] +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..011ccc4c --- /dev/null +++ b/src/Lumina.Presentation.Api/Core/Endpoints/FileSystemManagement/Path/ValidatePath/ValidatePathEndpointSummary.cs @@ -0,0 +1,29 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Contracts.Requests.FileSystemManagement.Path; +using Lumina.Contracts.Responses.FileSystemManagement.Path; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Presentation.Api.Core.Endpoints.FileSystemManagement.Path.ValidatePath; + +/// +/// Class used for providing a textual description for the API endpoint, for Swagger. +/// +[ExcludeFromCodeCoverage] +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..cbaad9ef --- /dev/null +++ b/src/Lumina.Presentation.Api/Core/Endpoints/FileSystemManagement/Thumbnails/GetThumbnail/GetThumbnailEndpointSummary.cs @@ -0,0 +1,29 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Contracts.Requests.FileSystemManagement.Thumbnails; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Presentation.Api.Core.Endpoints.FileSystemManagement.Thumbnails.GetThumbnail; + +/// +/// Class used for providing a textual description for the API endpoint, for Swagger. +/// +[ExcludeFromCodeCoverage] +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/Library/WrittenContentLibrary/BookLibrary/Books/AddBook/AddBookEndpoint.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/AddBook/AddBookEndpoint.cs new file mode 100644 index 00000000..5c5ae48a --- /dev/null +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/AddBook/AddBookEndpoint.cs @@ -0,0 +1,55 @@ +#region ========================================================================= USING ===================================================================================== +using ErrorOr; +using FastEndpoints; +using Lumina.Application.Common.Mapping.MediaLibrary.WrittenContentLibrary.BookLibrary.Books; +using Lumina.Contracts.Requests.MediaLibrary.WrittenContentLibrary.BookLibrary.Books; +using Lumina.Contracts.Responses.MediaLibrary.WrittenContentLibrary.BookLibrary.Books; +using Lumina.Presentation.Api.Common.Routes.Library.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.Library.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/Library/WrittenContentLibrary/BookLibrary/Books/AddBook/AddBookEndpointSummary.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/AddBook/AddBookEndpointSummary.cs new file mode 100644 index 00000000..3df13595 --- /dev/null +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/AddBook/AddBookEndpointSummary.cs @@ -0,0 +1,53 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Contracts.Requests.MediaLibrary.WrittenContentLibrary.BookLibrary.Books; +using Lumina.Contracts.Responses.MediaLibrary.WrittenContentLibrary.BookLibrary.Books; +using System.Diagnostics.CodeAnalysis; + +#endregion + +namespace Lumina.Presentation.Api.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.Books.AddBook; + +/// +/// Class used for providing a textual description for the API endpoint, for Swagger. +/// +[ExcludeFromCodeCoverage] +public class AddLibraryEndpointSummary : Summary +{ + /// + /// Initializes a new instance of the class. + /// + public AddLibraryEndpointSummary() + { + 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/Library/WrittenContentLibrary/BookLibrary/Books/GetBooks/GetBooksEndpoint.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/GetBooks/GetBooksEndpoint.cs new file mode 100644 index 00000000..e89bd44a --- /dev/null +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/GetBooks/GetBooksEndpoint.cs @@ -0,0 +1,54 @@ +#region ========================================================================= USING ===================================================================================== +using ErrorOr; +using FastEndpoints; +using Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BooksLibrary.Books.Queries.GetBooks; +using Lumina.Contracts.Responses.MediaLibrary.WrittenContentLibrary.BookLibrary.Books; +using Lumina.Presentation.Api.Common.Routes.Library.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.Library.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/Library/WrittenContentLibrary/BookLibrary/Books/GetBooks/GetBooksEndpointSummary.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/GetBooks/GetBooksEndpointSummary.cs new file mode 100644 index 00000000..49a7af53 --- /dev/null +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/GetBooks/GetBooksEndpointSummary.cs @@ -0,0 +1,26 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Contracts.Responses.MediaLibrary.WrittenContentLibrary.BookLibrary.Books; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Presentation.Api.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.Books.GetBooks; + +/// +/// Class used for providing a textual description for the API endpoint, for Swagger. +/// +[ExcludeFromCodeCoverage] +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/Library/WrittenContentLibrary/BookLibrary/GetBook/GetBookEndpoint.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/GetBook/GetBookEndpoint.cs new file mode 100644 index 00000000..108d4ebd --- /dev/null +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/GetBook/GetBookEndpoint.cs @@ -0,0 +1,53 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Contracts.Requests.MediaLibrary.WrittenContentLibrary.BookLibrary.Books; +using Lumina.Presentation.Api.Common.Routes.Library.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.Library.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/Core/Endpoints/Library/WrittenContentLibrary/Management/AddLibrary/AddLibraryEndpoint.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Library/WrittenContentLibrary/Management/AddLibrary/AddLibraryEndpoint.cs new file mode 100644 index 00000000..3bdee2a2 --- /dev/null +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Library/WrittenContentLibrary/Management/AddLibrary/AddLibraryEndpoint.cs @@ -0,0 +1,55 @@ +#region ========================================================================= USING ===================================================================================== +using ErrorOr; +using FastEndpoints; +using Lumina.Application.Common.Mapping.MediaLibrary.Management; +using Lumina.Contracts.Requests.MediaLibrary.Management; +using Lumina.Contracts.Responses.MediaLibrary.Management; +using Lumina.Presentation.Api.Common.Routes.Library.Management; +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.Library.WrittenContentLibrary.Management.AddLibrary; + +/// +/// API endpoint for the /library route. +/// +public class AddLibraryEndpoint : BaseEndpoint +{ + private readonly ISender _sender; + + /// + /// Initializes a new instance of the class. + /// + /// Injected service for mediating commands and queries. + public AddLibraryEndpoint(ISender sender) + { + _sender = sender; + } + + /// + /// Configures the API endpoint. + /// + public override void Configure() + { + Verbs(Http.POST); + Routes(ApiRoutes.Libraries.ADD_LIBRARY); + Version(1); + AllowAnonymous(); + DontCatchExceptions(); + } + + /// + /// Adds a media library stored in . + /// + /// The request containing the media library to be added. + /// Cancellation token that can be used to stop the execution. + public override async Task ExecuteAsync(AddLibraryRequest request, CancellationToken cancellationToken) + { + ErrorOr result = await _sender.Send(request.ToCommand(), cancellationToken).ConfigureAwait(false); + return result.Match(success => TypedResults.Created($"{BaseURL}api/v1{ApiRoutes.Libraries.ADD_LIBRARY}/{result.Value.Id}", result.Value), Problem); + } +} diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Library/WrittenContentLibrary/Management/AddLibrary/AddLibraryEndpointSummary.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Library/WrittenContentLibrary/Management/AddLibrary/AddLibraryEndpointSummary.cs new file mode 100644 index 00000000..b5519fe2 --- /dev/null +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Library/WrittenContentLibrary/Management/AddLibrary/AddLibraryEndpointSummary.cs @@ -0,0 +1,41 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Contracts.Requests.MediaLibrary.Management; +using Lumina.Contracts.Responses.MediaLibrary.Management; +using System.Diagnostics.CodeAnalysis; + + +#endregion + +namespace Lumina.Presentation.Api.Core.Endpoints.Library.WrittenContentLibrary.Management.AddLibrary; + +/// +/// Class used for providing a textual description for the API endpoint, for Swagger. +/// +[ExcludeFromCodeCoverage] +public class AddLibraryEndpointSummary : Summary +{ + /// + /// Initializes a new instance of the class. + /// + public AddLibraryEndpointSummary() + { + Summary = "Adds a new media library."; + Description = "Creates a new media library and returns its details, including the location of the newly created resource."; + + RequestParam(r => r.UserId, "The Id of the user owning the media library."); + RequestParam(r => r.Title, "The title of the media library."); + RequestParam(r => r.LibraryType, "The type of the media library."); + RequestParam(r => r.ContentLocations, ">The file system paths of the directories where the media library elements are located."); + + ResponseParam(r => r.Id, "The unique identifier of the entity."); + ResponseParam(r => r.UserId, "The Id of the user owning the media library."); + ResponseParam(r => r.Title, "The title of the media library."); + ResponseParam(r => r.LibraryType, "The type of the media library."); + ResponseParam(r => r.ContentLocations, "The file system paths of the directories where the media library elements are located."); + 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."); + Response(201, "The media library 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/Maintenance/ApplicationSetup/CheckInitializationEndpoint.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Maintenance/ApplicationSetup/CheckInitializationEndpoint.cs new file mode 100644 index 00000000..0ac46c2d --- /dev/null +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Maintenance/ApplicationSetup/CheckInitializationEndpoint.cs @@ -0,0 +1,52 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Application.Core.Maintenance.ApplicationSetup.Queries.CheckInitialization; +using Lumina.Contracts.Responses.UsersManagement; +using Lumina.Presentation.Api.Common.Routes.Maintenance; +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.Maintenance.ApplicationSetup; + +/// +/// API endpoint for the /initialization route. +/// +public class CheckInitializationEndpoint : BaseEndpoint +{ + private readonly ISender _sender; + + /// + /// Initializes a new instance of the class. + /// + /// Injected service for mediating commands and queries. + public CheckInitializationEndpoint(ISender sender) + { + _sender = sender; + } + + /// + /// Configures the API endpoint. + /// + public override void Configure() + { + Verbs(Http.GET); + Routes(ApiRoutes.Initialization.CHECK_INITIALIZATION); + Version(1); + AllowAnonymous(); + DontCatchExceptions(); + } + + /// + /// Checks the initialization status of the application (if the Admin account exists). + /// + /// Cancellation token that can be used to stop the execution. + public override async Task ExecuteAsync(EmptyRequest _, CancellationToken cancellationToken) + { + InitializationResponse result = await _sender.Send(new CheckInitializationQuery(), cancellationToken).ConfigureAwait(false); + return await Task.FromResult(TypedResults.Ok(result)); + } +} diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Maintenance/ApplicationSetup/CheckInitializationEndpointSummary.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Maintenance/ApplicationSetup/CheckInitializationEndpointSummary.cs new file mode 100644 index 00000000..56ffe275 --- /dev/null +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Maintenance/ApplicationSetup/CheckInitializationEndpointSummary.cs @@ -0,0 +1,25 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Contracts.Responses.UsersManagement; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Presentation.Api.Core.Endpoints.Maintenance.ApplicationSetup; + +/// +/// Class used for providing a textual description for the API endpoint, for Swagger. +/// +[ExcludeFromCodeCoverage] +public class CheckInitializationEndpointSummary : Summary +{ + /// + /// Initializes a new instance of the class. + /// + public CheckInitializationEndpointSummary() + { + Summary = "Checks the initialization status of the application."; + Description = "Checks the initialization status of the application (if the Admin account exists)."; + + Response(200, "The application initialization status is returned."); + } +} diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Maintenance/ApplicationSetup/SetupApplicationEndpoint.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Maintenance/ApplicationSetup/SetupApplicationEndpoint.cs new file mode 100644 index 00000000..c7b79cf6 --- /dev/null +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Maintenance/ApplicationSetup/SetupApplicationEndpoint.cs @@ -0,0 +1,55 @@ +#region ========================================================================= USING ===================================================================================== +using ErrorOr; +using FastEndpoints; +using Lumina.Contracts.Requests.Authentication; +using Lumina.Contracts.Responses.Authentication; +using Lumina.Application.Common.Mapping.Authentication; +using Lumina.Presentation.Api.Core.Endpoints.Common; +using Mediator; +using Microsoft.AspNetCore.Http; +using System.Threading; +using System.Threading.Tasks; +using Lumina.Presentation.Api.Common.Routes.Maintenance; +#endregion + +namespace Lumina.Presentation.Api.Core.Endpoints.Maintenance.ApplicationSetup; + +/// +/// API endpoint for the /initialization route. +/// +public class SetupApplicationEndpoint : BaseEndpoint +{ + private readonly ISender _sender; + + /// + /// Initializes a new instance of the class. + /// + /// Injected service for mediating commands and queries. + public SetupApplicationEndpoint(ISender sender) + { + _sender = sender; + } + + /// + /// Configures the API endpoint. + /// + public override void Configure() + { + Verbs(Http.POST); + Routes(ApiRoutes.Initialization.SETUP_APPLICATION); + Version(1); + AllowAnonymous(); + DontCatchExceptions(); + } + + /// + /// Performs the initial application setup, including creating the Admin account. + /// + /// The request containing the Admin user to be added. + /// Cancellation token that can be used to stop the execution. + public override async Task ExecuteAsync(RegistrationRequest request, CancellationToken cancellationToken) + { + ErrorOr result = await _sender.Send(request.ToSetupCommand(), cancellationToken).ConfigureAwait(false); + return result.Match(success => TypedResults.Created($"{BaseURL}api/v1{Api.Common.Routes.UsersManagement.ApiRoutes.Users.GET_USER_BY_ID.Replace("{id}", success.Id.ToString())}", result.Value), Problem); + } +} diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Maintenance/ApplicationSetup/SetupApplicationEndpointSummary.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Maintenance/ApplicationSetup/SetupApplicationEndpointSummary.cs new file mode 100644 index 00000000..1c08943b --- /dev/null +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Maintenance/ApplicationSetup/SetupApplicationEndpointSummary.cs @@ -0,0 +1,31 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Contracts.Requests.Authentication; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Presentation.Api.Core.Endpoints.Maintenance.ApplicationSetup; + +/// +/// Class used for providing a textual description for the API endpoint, for Swagger. +/// +[ExcludeFromCodeCoverage] +public class SetupApplicationEndpointSummary : Summary +{ + /// + /// Initializes a new instance of the class. + /// + public SetupApplicationEndpointSummary() + { + Summary = "Performs the initial application setup."; + Description = "Performs the initial application setup, including creating the Admin account."; + + RequestParam(r => r.Username, "The desired username for the new account."); + RequestParam(r => r.Password, "The password for the new account."); + RequestParam(r => r.PasswordConfirm, "The confirmation of the entered password, used to ensure consistency."); + RequestParam(r => r.Use2fa, "Indicates whether two-factor authentication (2FA) should be enabled for the new account."); + + Response(200, "The Admin account of the application 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..fd622095 --- /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.Maintenance; +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/UsersManagement/Authentication/ChangePassword/ChangePasswordEndpoint.cs b/src/Lumina.Presentation.Api/Core/Endpoints/UsersManagement/Authentication/ChangePassword/ChangePasswordEndpoint.cs new file mode 100644 index 00000000..72eb7a55 --- /dev/null +++ b/src/Lumina.Presentation.Api/Core/Endpoints/UsersManagement/Authentication/ChangePassword/ChangePasswordEndpoint.cs @@ -0,0 +1,54 @@ +#region ========================================================================= USING ===================================================================================== +using ErrorOr; +using FastEndpoints; +using Lumina.Application.Common.Mapping.Authentication; +using Lumina.Contracts.Requests.Authentication; +using Lumina.Contracts.Responses.Authentication; +using Lumina.Presentation.Api.Common.Routes.UsersManagement; +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.UsersManagement.Authentication.ChangePassword; + +/// +/// API endpoint for the /auth/change-password route. +/// +public class ChangePasswordEndpoint : BaseEndpoint +{ + private readonly ISender _sender; + + /// + /// Initializes a new instance of the class. + /// + /// Injected service for mediating commands and queries. + public ChangePasswordEndpoint(ISender sender) + { + _sender = sender; + } + + /// + /// Configures the API endpoint. + /// + public override void Configure() + { + Verbs(Http.POST); + Routes(ApiRoutes.Authentication.CHANGE_PASSWORD); + Version(1); + DontCatchExceptions(); + } + + /// + /// Changes the password of an account. + /// + /// The request containing the account for which to change the password. + /// Cancellation token that can be used to stop the execution. + public override async Task ExecuteAsync(ChangePasswordRequest 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/UsersManagement/Authentication/ChangePassword/ChangePasswordEndpointSummary.cs b/src/Lumina.Presentation.Api/Core/Endpoints/UsersManagement/Authentication/ChangePassword/ChangePasswordEndpointSummary.cs new file mode 100644 index 00000000..24a4eb2f --- /dev/null +++ b/src/Lumina.Presentation.Api/Core/Endpoints/UsersManagement/Authentication/ChangePassword/ChangePasswordEndpointSummary.cs @@ -0,0 +1,30 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Contracts.Requests.Authentication; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Presentation.Api.Core.Endpoints.UsersManagement.Authentication.ChangePassword; + +/// +/// Class used for providing a textual description for the API endpoint, for Swagger. +/// +[ExcludeFromCodeCoverage] +public class ChangePasswordEndpointSummary : Summary +{ + /// + /// Initializes a new instance of the class. + /// + public ChangePasswordEndpointSummary() + { + Summary = "Changes the password of an account."; + Description = "Changes the password of an account by reseting its password, after verifying TOTP code associated with the account."; + + RequestParam(r => r.CurrentPassword, "The current password of the account for which to change the password."); + RequestParam(r => r.NewPassword, "The new password of the account for which to change the password."); + RequestParam(r => r.NewPasswordConfirm, "The confirmation of the new password of the account for which to change the password."); + + Response(200, "The password of the account is changed."); + Response(422, "The request did not pass validation checks.", "application/problem+json"); + } +} diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/UsersManagement/Authentication/Login/LoginEndpoint.cs b/src/Lumina.Presentation.Api/Core/Endpoints/UsersManagement/Authentication/Login/LoginEndpoint.cs new file mode 100644 index 00000000..cad0554d --- /dev/null +++ b/src/Lumina.Presentation.Api/Core/Endpoints/UsersManagement/Authentication/Login/LoginEndpoint.cs @@ -0,0 +1,60 @@ +#region ========================================================================= USING ===================================================================================== +using ErrorOr; +using FastEndpoints; +using Lumina.Application.Common.Errors; +using Lumina.Application.Common.Mapping.Authentication; +using Lumina.Contracts.Requests.Authentication; +using Lumina.Contracts.Responses.Authentication; +using Lumina.Presentation.Api.Common.Routes.UsersManagement; +using Lumina.Presentation.Api.Core.Endpoints.Common; +using Mediator; +using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Http; +using Microsoft.Extensions.Caching.Memory; +using System; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Api.Core.Endpoints.UsersManagement.Authentication.Login; + +/// +/// API endpoint for the /auth/login route. +/// +public class LoginEndpoint : BaseEndpoint +{ + private readonly ISender _sender; + + /// + /// Initializes a new instance of the class. + /// + /// Injected service for mediating commands and queries. + public LoginEndpoint(ISender sender) + { + _sender = sender; + } + + /// + /// Configures the API endpoint. + /// + public override void Configure() + { + Verbs(Http.POST); + Routes(ApiRoutes.Authentication.LOGIN_ACCOUNT); + Version(1); + AllowAnonymous(); + DontCatchExceptions(); + Options(x => x.RequireRateLimiting("authenticationPolicy")); + } + + /// + /// Authenticates an account. + /// + /// The request containing the account to be authenticated. + /// Cancellation token that can be used to stop the execution. + public override async Task ExecuteAsync(LoginRequest 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/UsersManagement/Authentication/Login/LoginEndpointSummary.cs b/src/Lumina.Presentation.Api/Core/Endpoints/UsersManagement/Authentication/Login/LoginEndpointSummary.cs new file mode 100644 index 00000000..8ba72585 --- /dev/null +++ b/src/Lumina.Presentation.Api/Core/Endpoints/UsersManagement/Authentication/Login/LoginEndpointSummary.cs @@ -0,0 +1,30 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Contracts.Requests.Authentication; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Presentation.Api.Core.Endpoints.UsersManagement.Authentication.Login; + +/// +/// Class used for providing a textual description for the API endpoint, for Swagger. +/// +[ExcludeFromCodeCoverage] +public class LoginEndpointSummary : Summary +{ + /// + /// Initializes a new instance of the class. + /// + public LoginEndpointSummary() + { + Summary = "Authenticates an account."; + Description = "Authenticates an application account."; + + RequestParam(r => r.Username, "The username of the account to authenticate."); + RequestParam(r => r.Password, "The password of the account to authenticate."); + RequestParam(r => r.TotpCode, "The TOTP (Time-Based One-Time Password) of the account to authenticate."); + + Response(200, "The JWT authentication token is returned."); + Response(422, "The request did not pass validation checks.", "application/problem+json"); + } +} diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/UsersManagement/Authentication/RecoverPassword/RecoverPasswordEndpoint.cs b/src/Lumina.Presentation.Api/Core/Endpoints/UsersManagement/Authentication/RecoverPassword/RecoverPasswordEndpoint.cs new file mode 100644 index 00000000..4686e25e --- /dev/null +++ b/src/Lumina.Presentation.Api/Core/Endpoints/UsersManagement/Authentication/RecoverPassword/RecoverPasswordEndpoint.cs @@ -0,0 +1,57 @@ +#region ========================================================================= USING ===================================================================================== +using ErrorOr; +using FastEndpoints; +using Lumina.Application.Common.Mapping.Authentication; +using Lumina.Contracts.Requests.Authentication; +using Lumina.Contracts.Responses.Authentication; +using Lumina.Presentation.Api.Common.Routes.UsersManagement; +using Lumina.Presentation.Api.Core.Endpoints.Common; +using Mediator; +using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Http; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Api.Core.Endpoints.UsersManagement.Authentication.RecoverPassword; + +/// +/// API endpoint for the /auth/recover-password route. +/// +public class RecoverPasswordEndpoint : BaseEndpoint +{ + private readonly ISender _sender; + + /// + /// Initializes a new instance of the class. + /// + /// Injected service for mediating commands and queries. + public RecoverPasswordEndpoint(ISender sender) + { + _sender = sender; + } + + /// + /// Configures the API endpoint. + /// + public override void Configure() + { + Verbs(Http.POST); + Routes(ApiRoutes.Authentication.RECOVER_PASSWORD); + Version(1); + AllowAnonymous(); + DontCatchExceptions(); + Options(x => x.RequireRateLimiting("authenticationPolicy")); + } + + /// + /// Recovers the password of an account. + /// + /// The request containing the account for which to recover the password. + /// Cancellation token that can be used to stop the execution. + public override async Task ExecuteAsync(RecoverPasswordRequest 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/UsersManagement/Authentication/RecoverPassword/RecoverPasswordEndpointSummary.cs b/src/Lumina.Presentation.Api/Core/Endpoints/UsersManagement/Authentication/RecoverPassword/RecoverPasswordEndpointSummary.cs new file mode 100644 index 00000000..af3f3afe --- /dev/null +++ b/src/Lumina.Presentation.Api/Core/Endpoints/UsersManagement/Authentication/RecoverPassword/RecoverPasswordEndpointSummary.cs @@ -0,0 +1,29 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Contracts.Requests.Authentication; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Presentation.Api.Core.Endpoints.UsersManagement.Authentication.RecoverPassword; + +/// +/// Class used for providing a textual description for the API endpoint, for Swagger. +/// +[ExcludeFromCodeCoverage] +public class RecoverPasswordEndpointSummary : Summary +{ + /// + /// Initializes a new instance of the class. + /// + public RecoverPasswordEndpointSummary() + { + Summary = "Recovers the password of an account."; + Description = "Recovers the password of an account by reseting its password, after verifying TOTP code associated with the account."; + + RequestParam(r => r.Username, "The username of the account for which to recover the password."); + RequestParam(r => r.TotpCode, "The TOTP (Time-Based One-Time Password) of the account for which to recover the password."); + + Response(200, "The password of the account is reset."); + Response(422, "The request did not pass validation checks.", "application/problem+json"); + } +} diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/UsersManagement/Authentication/Register/RegisterEndpoint.cs b/src/Lumina.Presentation.Api/Core/Endpoints/UsersManagement/Authentication/Register/RegisterEndpoint.cs new file mode 100644 index 00000000..95351ca1 --- /dev/null +++ b/src/Lumina.Presentation.Api/Core/Endpoints/UsersManagement/Authentication/Register/RegisterEndpoint.cs @@ -0,0 +1,57 @@ +#region ========================================================================= USING ===================================================================================== +using ErrorOr; +using FastEndpoints; +using Lumina.Application.Common.Mapping.Authentication; +using Lumina.Contracts.Requests.Authentication; +using Lumina.Contracts.Responses.Authentication; +using Lumina.Presentation.Api.Common.Routes.UsersManagement; +using Lumina.Presentation.Api.Core.Endpoints.Common; +using Mediator; +using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Http; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Api.Core.Endpoints.UsersManagement.Authentication.Register; + +/// +/// API endpoint for the /auth/register route. +/// +public class RegisterEndpoint : BaseEndpoint +{ + private readonly ISender _sender; + + /// + /// Initializes a new instance of the class. + /// + /// Injected service for mediating commands and queries. + public RegisterEndpoint(ISender sender) + { + _sender = sender; + } + + /// + /// Configures the API endpoint. + /// + public override void Configure() + { + Verbs(Http.POST); + Routes(ApiRoutes.Authentication.REGISTER_ACCOUNT); + Version(1); + AllowAnonymous(); + DontCatchExceptions(); + Options(x => x.RequireRateLimiting("authenticationPolicy")); + } + + /// + /// Registers a new account. + /// + /// The request containing the account to be added. + /// Cancellation token that can be used to stop the execution. + public override async Task ExecuteAsync(RegistrationRequest request, CancellationToken cancellationToken) + { + ErrorOr result = await _sender.Send(request.ToCommand(), cancellationToken).ConfigureAwait(false); + return result.Match(success => TypedResults.Created($"{BaseURL}api/v1{ApiRoutes.Users.GET_USER_BY_ID.Replace("{id}", success.Id.ToString())}", result.Value), Problem); + } +} diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/UsersManagement/Authentication/Register/RegisterEndpointSummary.cs b/src/Lumina.Presentation.Api/Core/Endpoints/UsersManagement/Authentication/Register/RegisterEndpointSummary.cs new file mode 100644 index 00000000..04f87c13 --- /dev/null +++ b/src/Lumina.Presentation.Api/Core/Endpoints/UsersManagement/Authentication/Register/RegisterEndpointSummary.cs @@ -0,0 +1,31 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Contracts.Requests.Authentication; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Presentation.Api.Core.Endpoints.UsersManagement.Authentication.Register; + +/// +/// Class used for providing a textual description for the API endpoint, for Swagger. +/// +[ExcludeFromCodeCoverage] +public class RegisterEndpointSummary : Summary +{ + /// + /// Initializes a new instance of the class. + /// + public RegisterEndpointSummary() + { + Summary = "Registers a new account."; + Description = "Registes a new application account."; + + RequestParam(r => r.Username, "The desired username for the new account."); + RequestParam(r => r.Password, "The password for the new account."); + RequestParam(r => r.PasswordConfirm, "The confirmation of the entered password, used to ensure consistency."); + RequestParam(r => r.Use2fa, "Indicates whether two-factor authentication (2FA) should be enabled for the new account."); + + Response(200, "The new account of the application is returned."); + Response(422, "The request did not pass validation checks.", "application/problem+json"); + } +} diff --git a/src/Lumina.Presentation.Api/Dockerfile b/src/Lumina.Presentation.Api/Dockerfile index 8d78a4ec..c84bbb52 100644 --- a/src/Lumina.Presentation.Api/Dockerfile +++ b/src/Lumina.Presentation.Api/Dockerfile @@ -1,5 +1,6 @@ # This stage is used when running from VS in fast mode (Default for Debug configuration) FROM mcr.microsoft.com/dotnet/aspnet:8.0 AS base +RUN mkdir /logs && chown -R app:app /logs USER app WORKDIR /app EXPOSE 5214 @@ -53,4 +54,4 @@ EXPOSE 5214 ENTRYPOINT ["dotnet", "Lumina.Presentation.Api.dll"] # to build this Docker image, run the following command from the root of the project (location of the .sln file): -# docker build --no-cache -t lumina-server -f Lumina.Presentation.Api/Dockerfile . \ No newline at end of file +# docker build --no-cache -t lumina-api -f Lumina.Presentation.Api/Dockerfile . diff --git a/src/Lumina.Presentation.Api/Lumina.Presentation.Api.csproj b/src/Lumina.Presentation.Api/Lumina.Presentation.Api.csproj index 52d20123..cf75db3a 100644 --- a/src/Lumina.Presentation.Api/Lumina.Presentation.Api.csproj +++ b/src/Lumina.Presentation.Api/Lumina.Presentation.Api.csproj @@ -3,13 +3,14 @@ net9.0 enable disable - $(SolutionDir)..\bin\server\ + $(SolutionDir)..\bin\api\ false true + $(WarningsNotAsErrors);NU1901;NU1902;NU1903;NU1904 37d55c87-4374-4971-82e9-012fcaad1853 Linux - lumina-server - lumina-server + lumina-api + lumina-api ..\docker-compose.dcproj @@ -18,31 +19,34 @@ - - + + runtime; build; native; contentfiles; analyzers; buildtransitive all - - - + - - + all runtime; build; native; contentfiles; analyzers; buildtransitive + + + + + + PreserveNewest - + PreserveNewest - appsettings.shared.json + appsettings.json @@ -53,7 +57,7 @@ - + $(NoWarn);CS0436 diff --git a/src/Lumina.Presentation.Api/Program.cs b/src/Lumina.Presentation.Api/Program.cs index e70d334d..72ba4875 100644 --- a/src/Lumina.Presentation.Api/Program.cs +++ b/src/Lumina.Presentation.Api/Program.cs @@ -1,11 +1,22 @@ #region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using FastEndpoints.Swagger; using Lumina.Application.Common.DependencyInjection; using Lumina.DataAccess.Common.DependencyInjection; +using Lumina.DataAccess.Core.UoW; 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 Microsoft.AspNetCore.Hosting; +using Microsoft.EntityFrameworkCore; +using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.FileProviders; +using Serilog; +using System; +using System.Diagnostics.CodeAnalysis; +using System.IO; using System.Threading.Tasks; #endregion @@ -14,6 +25,7 @@ namespace Lumina.Presentation.Api; /// /// Application entry point, contains the composition root module, wires up all dependencies of the application. /// +[ExcludeFromCodeCoverage] public class Program { /// @@ -27,28 +39,86 @@ public class Program builder.Services.BindSharedConfiguration(builder.Configuration); builder.Services.BindPresentationApiLayerConfiguration(builder.Configuration); - builder.Services.AddPresentationApiLayerServices(); + builder.Services.AddPresentationApiLayerServices(builder.Configuration); builder.Services.AddApplicationLayerServices(); builder.Services.AddInfrastructureLayerServices(); builder.Services.AddDataAccessLayerServices(); builder.Services.AddDomainLayerServices(); + // determine log path based on environment + string logPath; + if (Environment.GetEnvironmentVariable("DOTNET_RUNNING_IN_CONTAINER") == "true") + { + logPath = Environment.GetEnvironmentVariable("LOG_PATH") ?? "/logs"; // use docker volume path + builder.WebHost.ConfigureKestrel(options => + { + options.ListenAnyIP(5214); // HTTP only + }); + } + else + logPath = Path.Combine(AppContext.BaseDirectory, "logs"); // use local binary path + Directory.CreateDirectory(logPath); + if (!logPath.EndsWith(Path.DirectorySeparatorChar.ToString())) + logPath = logPath += Path.DirectorySeparatorChar; + // set environment variable for Serilog configuration + Environment.SetEnvironmentVariable("LOG_PATH", logPath); + + builder.Host.UseSerilog((context, services, configuration) => + { + configuration.ReadFrom.Configuration(context.Configuration) + .ReadFrom.Services(services) + .Enrich.FromLogContext(); + }); WebApplication app = builder.Build(); + app.UseSerilogRequestLogging(); + + // apply any pending migrations + using (IServiceScope scope = app.Services.CreateScope()) + { + IServiceProvider services = scope.ServiceProvider; + try + { + LuminaDbContext context = services.GetRequiredService(); + await context.Database.MigrateAsync(); + } + catch (Exception ex) + { + ILogger logger = services.GetRequiredService(); + logger.Fatal(ex, "Failed to run database migrations"); + } + } + 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.UseRateLimiter(); + + 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(); + + string mediaRootDirectoryPathSetting = app.Configuration.GetValue("MediaSettings:RootDirectory") ?? string.Empty; + string mediaRootPath = Path.Combine(AppContext.BaseDirectory, mediaRootDirectoryPathSetting); + + if (!Directory.Exists(mediaRootPath)) + Directory.CreateDirectory(mediaRootPath); + + app.UseStaticFiles(new StaticFileOptions + { + FileProvider = new PhysicalFileProvider(mediaRootPath), + RequestPath = "/media" + }); await app.RunAsync().ConfigureAwait(false); } diff --git a/src/Lumina.Presentation.Api/Properties/launchSettings.json b/src/Lumina.Presentation.Api/Properties/launchSettings.json index 5b8aa36c..76a5b1d5 100644 --- a/src/Lumina.Presentation.Api/Properties/launchSettings.json +++ b/src/Lumina.Presentation.Api/Properties/launchSettings.json @@ -17,16 +17,7 @@ }, "dotnetRunMessages": true, "applicationUrl": "https://localhost:7057;http://localhost:5214" - }, - "Container (Dockerfile)": { - "commandName": "Docker", - "launchUrl": "{Scheme}://{ServiceHost}:{ServicePort}", - "environmentVariables": { - "ASPNETCORE_HTTP_PORTS": "5214" - }, - "publishAllPorts": true, - "useSSL": true } }, "$schema": "http://json.schemastore.org/launchsettings.json" -} \ No newline at end of file +} diff --git a/src/Lumina.Presentation.Api/appsettings.json b/src/Lumina.Presentation.Api/appsettings.json index 2585bf1a..2db1c53f 100644 --- a/src/Lumina.Presentation.Api/appsettings.json +++ b/src/Lumina.Presentation.Api/appsettings.json @@ -1,21 +1,55 @@ { - "Serilog": { - "WriteTo": [ - { - "Name": "Debug" - }, - { - "Name": "Console" - }, - { - "Name": "File", - "Args": { - "path": "Logs/lumina_api_.log", - "rollingInterval": "Day", - "outputTemplate": "{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz} [{Level:u3}] {Message:lj}{NewLine}{Exception}" + "JwtSettings": { + "SecretKey": "", + "ExpiryMinutes": 60, + "Issuer": "Lumina", + "Audience": "Lumina" + }, + "EncryptionSettings": { + "SecretKey": "" // base64 string + }, + "Serilog": { + "Using": [ "Serilog.Sinks.Console", "Serilog.Sinks.File" ], + "MinimumLevel": { + "Default": "Information", + "Override": { + "Microsoft": "Warning", + "System": "Warning", + "Microsoft.AspNetCore": "Warning", + "Microsoft.Hosting.Lifetime": "Information" + } + }, + "WriteTo": [ + { + "Name": "Console", + "Args": { + "theme": "Serilog.Sinks.SystemConsole.Themes.AnsiConsoleTheme::Literate, Serilog.Sinks.Console", + "outputTemplate": "[{Timestamp:HH:mm:ss} {Level:u3}] {Message:lj}{NewLine}{Exception}" + } + }, + { + "Name": "File", + "Args": { + "path": "%LOG_PATH%lumina_api_.log", + "rollingInterval": "Day", + "outputTemplate": "{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz} [{Level:u3}] {Message:lj}{NewLine}{Exception}", + "retainedFileCountLimit": 7, + "fileSizeLimitBytes": 10485760, + "rollOnFileSizeLimit": true, + "shared": true, + "flushToDiskInterval": "00:00:01" + } + } + ], + "Enrich": [ + "FromLogContext", + "WithMachineName", + "WithThreadId", + "WithEnvironmentName" + ], + "Properties": { + "Application": "LuminaApi" } - } - ] - }, - "AllowedHosts": "*" + }, + "AllowedHosts": "*" } diff --git a/src/Lumina.Presentation.Web/Common/Api/ApiHttpClient.cs b/src/Lumina.Presentation.Web/Common/Api/ApiHttpClient.cs index 2db649d7..2805fd39 100644 --- a/src/Lumina.Presentation.Web/Common/Api/ApiHttpClient.cs +++ b/src/Lumina.Presentation.Web/Common/Api/ApiHttpClient.cs @@ -2,7 +2,8 @@ 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.AspNetCore.Http; using Microsoft.Extensions.Options; using System; using System.Collections.Generic; @@ -25,16 +26,19 @@ namespace Lumina.Presentation.Web.Common.Api; public class ApiHttpClient : IApiHttpClient { private readonly HttpClient _httpClient; + private readonly HttpContext? _httpContext; private readonly JsonSerializerOptions _jsonOptions; /// /// Initializes a new instance of the class. /// /// Injected HttpClient for interacting with the API. + /// Injected service for providing the current HTTP context. /// Injected server configuration application settings. - public ApiHttpClient(HttpClient httpClient, IOptionsSnapshot serverConfigurationOptions) + public ApiHttpClient(HttpClient httpClient, IHttpContextAccessor httpContextAccessor, IOptionsSnapshot serverConfigurationOptions) { _httpClient = httpClient; + _httpContext = httpContextAccessor.HttpContext; // read the API server configuration values from the configuration, and assign them to the injected client ServerConfigurationModel serverConfigurationModel = serverConfigurationOptions.Value; httpClient.BaseAddress = new Uri($"{serverConfigurationModel.BaseAddress}:{serverConfigurationModel.Port}/api/v{serverConfigurationModel.ApiVersion}/"); @@ -52,14 +56,14 @@ public class ApiHttpClient : IApiHttpClient /// /// The expected type of the response content. /// The API endpoint where the request is being sent. - /// The token used for authentication with the API. /// Cancellation token that can be used to stop the execution. /// The deserialized response containing the result of the GET request. - public async Task GetAsync(string endpoint, string? token = null, CancellationToken cancellationToken = default) + public async Task GetAsync(string endpoint, CancellationToken cancellationToken = default) { using HttpRequestMessage request = new(HttpMethod.Get, endpoint); - if (!string.IsNullOrEmpty(token)) - request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", token); + AuthenticationHeaderValue? authenticationHeader = GetAuthenticationHeader(); + if (authenticationHeader is not null) + request.Headers.Authorization = authenticationHeader; return await SendRequestAsync(request, cancellationToken).ConfigureAwait(false); } @@ -68,14 +72,14 @@ public class ApiHttpClient : IApiHttpClient /// /// The expected type of the response content. /// The API endpoint where the request is being sent. - /// The token used for authentication with the API. /// Cancellation token that can be used to stop the execution. /// An object, which allows for asynchronous iteration over the deserialized items. - public async IAsyncEnumerable GetAsyncEnumerable(string endpoint, string? token = null, [EnumeratorCancellation] CancellationToken cancellationToken = default) + public async IAsyncEnumerable GetAsyncEnumerable(string endpoint, [EnumeratorCancellation] CancellationToken cancellationToken = default) { - using HttpRequestMessage request = new(HttpMethod.Get, endpoint); - if (!string.IsNullOrEmpty(token)) - request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", token); + using HttpRequestMessage request = new(HttpMethod.Get, endpoint); + AuthenticationHeaderValue? authenticationHeader = GetAuthenticationHeader(); + if (authenticationHeader is not null) + request.Headers.Authorization = authenticationHeader; // send the request and expect only headers initially - this prevents the client from buffering the entire response using HttpResponseMessage response = await _httpClient.SendAsync(request, HttpCompletionOption.ResponseHeadersRead, cancellationToken).ConfigureAwait(false); response.EnsureSuccessStatusCode(); @@ -93,14 +97,14 @@ public class ApiHttpClient : IApiHttpClient /// Sends a GET request to the specified as an asynchronous operation and returns the result. /// /// The API endpoint where the request is being sent. - /// The token used for authentication with the API. /// Cancellation token that can be used to stop the execution. /// A model containing the deserialized blob. - public async Task GetBlobAsync(string endpoint, string? token = null, CancellationToken cancellationToken = default) + public async Task GetBlobAsync(string endpoint, CancellationToken cancellationToken = default) { using HttpRequestMessage request = new(HttpMethod.Get, endpoint); - if (!string.IsNullOrEmpty(token)) - request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", token); + AuthenticationHeaderValue? authenticationHeader = GetAuthenticationHeader(); + if (authenticationHeader is not null) + request.Headers.Authorization = authenticationHeader; using HttpResponseMessage response = await _httpClient.SendAsync(request, cancellationToken).ConfigureAwait(false); if (!response.IsSuccessStatusCode) { @@ -125,14 +129,14 @@ public class ApiHttpClient : IApiHttpClient /// /// The expected type of the response content. /// The API endpoint where the request is being sent. - /// The token used for authentication with the API. /// Cancellation token that can be used to stop the execution. /// The deserialized response containing the result of the DELETE request. - public async Task DeleteAsync(string endpoint, string? token = null, CancellationToken cancellationToken = default) + public async Task DeleteAsync(string endpoint, CancellationToken cancellationToken = default) { using HttpRequestMessage request = new(HttpMethod.Delete, endpoint); - if (!string.IsNullOrEmpty(token)) - _httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token); + AuthenticationHeaderValue? authenticationHeader = GetAuthenticationHeader(); + if (authenticationHeader is not null) + request.Headers.Authorization = authenticationHeader; return await SendRequestAsync(request, cancellationToken).ConfigureAwait(false); } @@ -143,14 +147,14 @@ public class ApiHttpClient : IApiHttpClient /// The expected type of the payload content. /// The API endpoint where the request is being sent. /// The data to be serialized and send to the API. - /// The token used for authentication with the API. /// Cancellation token that can be used to stop the execution. /// The deserialized response containing the result of the PUT request. - public async Task PutAsync(string endpoint, TModel data, string? token = null, CancellationToken cancellationToken = default) + public async Task PutAsync(string endpoint, TModel data, CancellationToken cancellationToken = default) { using HttpRequestMessage request = new(HttpMethod.Put, endpoint); - if (!string.IsNullOrEmpty(token)) - _httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token); + AuthenticationHeaderValue? authenticationHeader = GetAuthenticationHeader(); + if (authenticationHeader is not null) + request.Headers.Authorization = authenticationHeader; request.Content = new StringContent(JsonSerializer.Serialize(data, _jsonOptions), Encoding.UTF8, "application/json"); return await SendRequestAsync(request, cancellationToken).ConfigureAwait(false); } @@ -162,14 +166,14 @@ public class ApiHttpClient : IApiHttpClient /// The expected type of the payload content. /// The API endpoint where the request is being sent. /// The data to be serialized and sent to the API. - /// The token used for authentication with the API. /// Cancellation token that can be used to stop the execution. /// The deserialized response containing the result of the POST request. - public async Task PostAsync(string endpoint, TModel data, string? token = null, CancellationToken cancellationToken = default) + public async Task PostAsync(string endpoint, TModel data, CancellationToken cancellationToken = default) { using HttpRequestMessage request = new(HttpMethod.Post, endpoint); - if (!string.IsNullOrEmpty(token)) - _httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token); + AuthenticationHeaderValue? authenticationHeader = GetAuthenticationHeader(); + if (authenticationHeader is not null) + request.Headers.Authorization = authenticationHeader; request.Content = new StringContent(JsonSerializer.Serialize(data, _jsonOptions), Encoding.UTF8, "application/json"); return await SendRequestAsync(request, cancellationToken).ConfigureAwait(false); } @@ -203,4 +207,16 @@ public class ApiHttpClient : IApiHttpClient throw new ApiException(problemDetails, response.StatusCode); } } + + /// + /// Retrieves the authentication header for the current user, if available. + /// + /// + /// An with a Bearer token if the user's token is found, otherwise. + /// + private AuthenticationHeaderValue? GetAuthenticationHeader() + { + string? token = _httpContext?.User?.FindFirst("Token")?.Value; + return !string.IsNullOrEmpty(token) ? new AuthenticationHeaderValue("Bearer", token) : null; + } } diff --git a/src/Lumina.Presentation.Web/Common/Api/IApiHttpClient.cs b/src/Lumina.Presentation.Web/Common/Api/IApiHttpClient.cs index 7304556f..a5d8f3c7 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; +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Common.Models.FileSystemManagement; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; @@ -17,39 +17,35 @@ public interface IApiHttpClient /// /// The expected type of the response content. /// The API endpoint where the request is being sent. - /// The token used for authentication with the API. /// Cancellation token that can be used to stop the execution. /// The deserialized response containing the result of the GET request. - Task GetAsync(string endpoint, string? token = null, CancellationToken cancellationToken = default); + Task GetAsync(string endpoint, CancellationToken cancellationToken = default); /// /// Sends a GET request to the specified as an asynchronous operation and returns the result as a streamable response. /// /// The expected type of the response content. /// The API endpoint where the request is being sent. - /// The token used for authentication with the API. /// Cancellation token that can be used to stop the execution. /// An object, which allows for asynchronous iteration over the deserialized items. - IAsyncEnumerable GetAsyncEnumerable(string endpoint, string? token = null, CancellationToken cancellationToken = default); + IAsyncEnumerable GetAsyncEnumerable(string endpoint, CancellationToken cancellationToken = default); /// /// Sends a GET request to the specified as an asynchronous operation and returns the result. /// /// The API endpoint where the request is being sent. - /// The token used for authentication with the API. /// Cancellation token that can be used to stop the execution. /// A model containing the deserialized blob. - Task GetBlobAsync(string endpoint, string? token = null, CancellationToken cancellationToken = default); + Task GetBlobAsync(string endpoint, CancellationToken cancellationToken = default); /// /// Sends a DELETE request to the specified as an asynchronous operation and returns the result. /// /// The expected type of the response content. /// The API endpoint where the request is being sent. - /// The token used for authentication with the API. /// Cancellation token that can be used to stop the execution. /// The deserialized response containing the result of the DELETE request. - Task DeleteAsync(string endpoint, string? token = null, CancellationToken cancellationToken = default); + Task DeleteAsync(string endpoint, CancellationToken cancellationToken = default); /// /// Sends a PUT request to the specified as an asynchronous operation and returns the result. @@ -58,10 +54,9 @@ public interface IApiHttpClient /// The expected type of the payload content. /// The API endpoint where the request is being sent. /// The data to be serialized and send to the API. - /// The token used for authentication with the API. /// Cancellation token that can be used to stop the execution. /// The deserialized response containing the result of the PUT request. - Task PutAsync(string endpoint, TModel data, string? token = null, CancellationToken cancellationToken = default); + Task PutAsync(string endpoint, TModel data, CancellationToken cancellationToken = default); /// /// Sends a POST request to the specified as an asynchronous operation and returns the result. @@ -70,8 +65,7 @@ public interface IApiHttpClient /// The expected type of the payload content. /// The API endpoint where the request is being sent. /// The data to be serialized and sent to the API. - /// The token used for authentication with the API. /// Cancellation token that can be used to stop the execution. /// The deserialized response containing the result of the POST request. - Task PostAsync(string endpoint, TModel data, string? token = null, CancellationToken cancellationToken = default); -} \ No newline at end of file + Task PostAsync(string endpoint, TModel data, CancellationToken cancellationToken = default); +} diff --git a/src/Lumina.Presentation.Web/Common/Authorization/InitializationHandler.cs b/src/Lumina.Presentation.Web/Common/Authorization/InitializationHandler.cs new file mode 100644 index 00000000..8e15a798 --- /dev/null +++ b/src/Lumina.Presentation.Web/Common/Authorization/InitializationHandler.cs @@ -0,0 +1,51 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Common.Api; +using Lumina.Presentation.Web.Common.Http; +using Lumina.Presentation.Web.Common.Models.UsersManagement; +using Microsoft.AspNetCore.Authorization; +using Microsoft.AspNetCore.Http; +using Microsoft.Extensions.Caching.Memory; +using System; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.Common.Authorization; + +/// +/// Handles the to ensure that the application is initialized before allowing authorization. +/// +public class InitializationHandler : AuthorizationHandler +{ + private readonly IApiHttpClient _apiHttpClient; + private readonly IMemoryCache _cache; + + /// + /// Initializes a new instance of the class. + /// + /// Injected HTTP typed client for interactions with the API. + /// Cache for storing the initialization status. + public InitializationHandler(IApiHttpClient apiHttpClient, IMemoryCache cache) + { + _apiHttpClient = apiHttpClient; + _cache = cache; + } + + /// + /// Checks the application initialization status and authorizes the requirement if initialized. + /// + /// The authorization context. + /// The initialization requirement to be evaluated. + protected override async Task HandleRequirementAsync(AuthorizationHandlerContext context, InitializationRequirement requirement) + { + InitializationModel result = await _apiHttpClient.GetAsync("initialization/"); + HttpContext? httpContext = context.Resource as HttpContext; + if (result.IsInitialized) + { + // admin account was registered, remove this requirement from the session + httpContext?.Session.Remove(HttpContextItemKeys.PENDING_SUPER_ADMIN_SETUP); + context.Succeed(requirement); + } + else // store in session that super admin setup is needed + httpContext?.Session.SetString(HttpContextItemKeys.PENDING_SUPER_ADMIN_SETUP, "true"); + } +} diff --git a/src/Lumina.Presentation.Web/Common/Authorization/InitializationRequirement.cs b/src/Lumina.Presentation.Web/Common/Authorization/InitializationRequirement.cs new file mode 100644 index 00000000..78a0f6d9 --- /dev/null +++ b/src/Lumina.Presentation.Web/Common/Authorization/InitializationRequirement.cs @@ -0,0 +1,25 @@ +#region ========================================================================= USING ===================================================================================== +using Microsoft.AspNetCore.Authorization; +#endregion + +namespace Lumina.Presentation.Web.Common.Authorization; + +/// +/// Defines a requirement for initialization status in the authorization process. +/// +public class InitializationRequirement : IAuthorizationRequirement +{ + /// + /// Gets the timeout duration, in minutes, for caching the initialization check. + /// + public int CacheTimeoutMinutes { get; } + + /// + /// Initializes a new instance of the class. + /// + /// The cache timeout in minutes for the initialization status. + public InitializationRequirement(int cacheTimeoutMinutes = 5) + { + CacheTimeoutMinutes = cacheTimeoutMinutes; + } +} diff --git a/src/Lumina.Presentation.Web/Common/DependencyInjection/PresentationWebLayerConfiguration.cs b/src/Lumina.Presentation.Web/Common/DependencyInjection/PresentationWebLayerConfiguration.cs index a99da909..e949c91d 100644 --- a/src/Lumina.Presentation.Web/Common/DependencyInjection/PresentationWebLayerConfiguration.cs +++ b/src/Lumina.Presentation.Web/Common/DependencyInjection/PresentationWebLayerConfiguration.cs @@ -1,13 +1,17 @@ +#region ========================================================================= USING ===================================================================================== using Lumina.Presentation.Web.Common.Models.Configuration; using Lumina.Presentation.Web.Common.Utilities; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; +using System.Diagnostics.CodeAnalysis; +#endregion namespace Lumina.Presentation.Web.Common.DependencyInjection; /// /// Class containing the configuration bindings of the Lumina.Presentation.Web project. /// +[ExcludeFromCodeCoverage] internal static class PresentationWebLayerConfiguration { /// @@ -26,6 +30,12 @@ internal static class PresentationWebLayerConfiguration .Bind(configuration.GetRequiredSection(ServerConfigurationModel.SECTION_NAME)) .ValidateFluently() .ValidateOnStart(); + + serviceCollection.AddOptions() + .Bind(configuration.GetRequiredSection(EncryptionSettingsModel.SECTION_NAME)) + .ValidateFluently() + .ValidateOnStart(); + return serviceCollection; } } diff --git a/src/Lumina.Presentation.Web/Common/DependencyInjection/PresentationWebLayerServices.cs b/src/Lumina.Presentation.Web/Common/DependencyInjection/PresentationWebLayerServices.cs index 16761764..f21ac11c 100644 --- a/src/Lumina.Presentation.Web/Common/DependencyInjection/PresentationWebLayerServices.cs +++ b/src/Lumina.Presentation.Web/Common/DependencyInjection/PresentationWebLayerServices.cs @@ -1,18 +1,27 @@ #region ========================================================================= USING ===================================================================================== using FluentValidation; using Lumina.Presentation.Web.Common.Api; +using Lumina.Presentation.Web.Common.Authorization; using Lumina.Presentation.Web.Common.Exceptions; using Lumina.Presentation.Web.Common.Filters; +using Lumina.Presentation.Web.Common.Security; using Lumina.Presentation.Web.Common.Services; +using Microsoft.AspNetCore.Authentication.Cookies; +using Microsoft.AspNetCore.Authorization; +using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.HttpOverrides; using Microsoft.Extensions.DependencyInjection; using Polly; using Polly.CircuitBreaker; using Polly.Retry; using Polly.Wrap; using System; +using System.Diagnostics.CodeAnalysis; using System.Net; using System.Net.Http; using System.Text.Json.Serialization; +using System.Threading.Tasks; #endregion namespace Lumina.Presentation.Web.Common.DependencyInjection; @@ -20,6 +29,7 @@ namespace Lumina.Presentation.Web.Common.DependencyInjection; /// /// Contains all services of the Presentation Web layer. /// +[ExcludeFromCodeCoverage] public static class PresentationWebLayerServices { /// @@ -30,13 +40,73 @@ public static class PresentationWebLayerServices public static IServiceCollection AddPresentationWebLayerServices(this IServiceCollection services) { services.AddControllersWithViews(options => options.Filters.Add(typeof(ApiExceptionFilter))) - .AddJsonOptions(options => + .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()); }); + // configure cookie-based authentication + services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme) + .AddCookie(options => + { + // basic path configuration + options.LoginPath = "/auth/login"; + options.LogoutPath = "/auth/logout"; + options.AccessDeniedPath = "/auth/access-denied"; + + // Cookie configuration + options.Cookie = new CookieBuilder + { + Name = ".Lumina.Auth", // unique name to avoid conflicts + HttpOnly = true, // prevent JavaScript access + SameSite = SameSiteMode.Lax, // balance between security and functionality + SecurePolicy = CookieSecurePolicy.Always, // require HTTPS + Path = "/", // make cookie available for all paths + IsEssential = true // mark as essential for GDPR + }; + + // security settings + options.ExpireTimeSpan = TimeSpan.FromHours(24); // TODO: perhaps make it configurable by user? + options.SlidingExpiration = true; + + // handle validation to support various deployment scenarios + options.Events = new CookieAuthenticationEvents + { + // handle redirects to work with different base paths + OnRedirectToLogin = context => + { + // preserve any base path or subdirectory + string redirectPath = context.RedirectUri; + if (context.Request.PathBase.HasValue) + redirectPath = context.Request.PathBase + options.LoginPath + new QueryString("?returnUrl=") + Uri.EscapeDataString(context.Request.PathBase + context.Request.Path); + context.Response.Redirect(redirectPath); + return Task.CompletedTask; + } + }; + }); + + // add an authorization policy that ensures application is initialized with super admin account before allowing access + services.AddAuthorizationBuilder() + .AddPolicy("RequireInitialization", policy => policy.Requirements.Add(new InitializationRequirement())); + + // add forwarded headers middleware to handle reverse proxy scenarios + services.Configure(options => + { + options.ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto | ForwardedHeaders.XForwardedHost; + options.KnownNetworks.Clear(); + options.KnownProxies.Clear(); + }); + + // configure session management to maintain user-specific data across requests + services.AddSession(options => + { + options.IdleTimeout = TimeSpan.FromMinutes(30); // session expires after 30 minutes of inactivity + options.Cookie.HttpOnly = true; // prevent JavaScript access to session cookie, for security + options.Cookie.IsEssential = true; // mark session cookie as essential, for GDPR compliance + }); + // scan the current assembly for validators and register them to the DI container services.AddValidatorsFromAssemblyContaining(ServiceLifetime.Singleton); @@ -57,13 +127,18 @@ public static class PresentationWebLayerServices AsyncPolicyWrap policy = Policy.WrapAsync(retryPolicy, circuitBreakerPolicy); - // register the typed client used for the API interaction + // register the HTTP typed client used for the API interaction services.AddHttpClient() .AddPolicyHandler(retryPolicy) .AddPolicyHandler(circuitBreakerPolicy); - services.AddScoped(); + // enable access to the current HTTP context in non-controller classes + services.AddHttpContextAccessor(); + services.AddScoped(); + services.AddScoped(); + services.AddSingleton(); + services.AddSingleton(); return services; } diff --git a/src/Lumina.Presentation.Web/Common/Enums/BookLibrary/WrittenContentType.cs b/src/Lumina.Presentation.Web/Common/Enums/BookLibrary/WrittenContentType.cs index 4f257b4d..673d70c4 100644 --- a/src/Lumina.Presentation.Web/Common/Enums/BookLibrary/WrittenContentType.cs +++ b/src/Lumina.Presentation.Web/Common/Enums/BookLibrary/WrittenContentType.cs @@ -1,9 +1,9 @@ -namespace Lumina.Presentation.Web.Common.Enums.BookLibrary; +namespace Lumina.Presentation.Web.Common.Enums.BookLibrary; /// /// Enumeration for the types of written content libraries. /// -public enum WrittenContentType +public enum WrittenContentType // TODO: to be removed? { /// /// A printed or written literary work. @@ -35,6 +35,11 @@ public enum WrittenContentType /// Magazine, + /// + /// Periodical publication containing news. + /// + Newspaper, + /// /// A style of Japanese comic books and graphic novels. /// @@ -59,4 +64,4 @@ public enum WrittenContentType /// A script for a film, television program, or other visual media. /// Screenplay, -} \ No newline at end of file +} diff --git a/src/Lumina.Presentation.Web/Common/Enums/Library/LibraryType.cs b/src/Lumina.Presentation.Web/Common/Enums/Library/LibraryType.cs index 763a2b66..26eb34d2 100644 --- a/src/Lumina.Presentation.Web/Common/Enums/Library/LibraryType.cs +++ b/src/Lumina.Presentation.Web/Common/Enums/Library/LibraryType.cs @@ -1,4 +1,4 @@ -namespace Lumina.Presentation.Web.Common.Enums.Library; +namespace Lumina.Presentation.Web.Common.Enums.Library; /// /// Enumeration for the types of libraries. @@ -6,27 +6,182 @@ public enum LibraryType { /// - /// Content that is written, such as books, articles, or other written works. + /// Traditional printed books in physical format. /// - WrittenContent, + Book, /// - /// Content that is video, such as movies, TV shows, or other video works. + /// Digital books in electronic format (e.g., PDF, EPUB, MOBI). /// - VideoContent, + EBook, /// - /// Content that is audio, such as podcasts, radio shows, or other audio works. + /// Comic books in digital or physical format. /// - AudioContent, + ComicBook, /// - /// Content that is visual, such as images, paintings, or other visual works. + /// Periodical publications containing articles and illustrations. /// - VisualContent, + Magazine, /// - /// Content that is miscellaneous, such as lyrics, movie posters, or other miscellaneous works. + /// Periodical publication containing news. /// - MiscellaneousContent, -} \ No newline at end of file + Newspaper, + + /// + /// Japanese-style comics and graphic novels. + /// + Manga, + + /// + /// Extended comic-format narratives, typically containing a complete story. + /// + GraphicNovel, + + /// + /// Scholarly articles and research papers. + /// + AcademicPaper, + + /// + /// Musical notation and scores. + /// + SheetMusic, + + /// + /// Television series and episodic content. + /// + TvShow, + + /// + /// Feature-length films and motion pictures. + /// + Movie, + + /// + /// Non-fiction films presenting factual information. + /// + Documentary, + + /// + /// Japanese animation series and films. + /// + Anime, + + /// + /// Recorded live music performances and concerts. + /// + ConcertVideo, + + /// + /// Educational and instructional videos. + /// + TutorialVideo, + + /// + /// Personally recorded videos and family footage. + /// + HomeVideo, + + /// + /// Videos sourced from YouTube platform. + /// + YouTubeVideo, + + /// + /// Professional or amateur music video productions. + /// + MusicVideo, + + /// + /// Videos recorded during live performances or events. + /// + LiveRecordingVideo, + + /// + /// Recorded conversations and Q&A sessions in video format. + /// + InterviewVideo, + + /// + /// Videos of musical performances covering other artists' work. + /// + CoverSongVideo, + + /// + /// Video format podcasts and episodic content. + /// + PodcastVideo, + + /// + /// Audio recordings of musical content. + /// + Music, + + /// + /// Narrated books in audio format. + /// + Audiobook, + + /// + /// Audio recordings from live performances or events. + /// + LiveRecordingAudio, + + /// + /// Recorded conversations and Q&A sessions in audio format. + /// + InterviewAudio, + + /// + /// Audio recordings of musical performances covering other artists' work. + /// + CoverSongAudio, + + /// + /// Modified or reinterpreted versions of original musical recordings. + /// + Remix, + + /// + /// Audio clips used for sound design and production. + /// + SoundEffect, + + /// + /// Audio format podcasts and episodic content. + /// + PodcastAudio, + + /// + /// Digital images and photographs. + /// + Photo, + + /// + /// Curated sequences of media items. + /// + Playlist, + + /// + /// Grouped sets of related media items. + /// + Collection, + + /// + /// Text files containing dialogue translations for video content. + /// + Subtitles, + + /// + /// Text files containing words and timing for musical content. + /// + Lyrics, + + /// + /// A collection of media that does not fit into any other category. + /// + Other +} diff --git a/src/Lumina.Presentation.Web/Common/Filters/ApiExceptionFilter.cs b/src/Lumina.Presentation.Web/Common/Filters/ApiExceptionFilter.cs index 9014c48d..307d933d 100644 --- a/src/Lumina.Presentation.Web/Common/Filters/ApiExceptionFilter.cs +++ b/src/Lumina.Presentation.Web/Common/Filters/ApiExceptionFilter.cs @@ -31,7 +31,7 @@ public class ApiExceptionFilter : IExceptionFilter if (context.Exception is ApiException apiException) { // handle unauthorized errors by prompting the user to re-login - if (apiException.HttpStatusCode == HttpStatusCode.Unauthorized) + if (apiException.HttpStatusCode == HttpStatusCode.Unauthorized) // HTTP 401 Unauthorized actually means lack of valid authentication credentials (not logged in) { SignOutSynchronously(context.HttpContext); string currentUrl = context.HttpContext.Request.GetDisplayUrl(); diff --git a/src/Lumina.Presentation.Web/Common/Filters/InitializationCheckAttribute.cs b/src/Lumina.Presentation.Web/Common/Filters/InitializationCheckAttribute.cs new file mode 100644 index 00000000..f7543734 --- /dev/null +++ b/src/Lumina.Presentation.Web/Common/Filters/InitializationCheckAttribute.cs @@ -0,0 +1,26 @@ +#region ========================================================================= USING ===================================================================================== +using Microsoft.AspNetCore.Authorization; +using Microsoft.AspNetCore.Mvc.Filters; +using Microsoft.Extensions.DependencyInjection; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.Common.Filters; + +/// +/// Attribute that enforces application initialization checks on controller actions. +/// +public class InitializationCheckAttribute : ActionFilterAttribute +{ + /// + /// Asynchronously executes the initialization check before the action executes. + /// + /// The context for the action being executed. + /// Delegate to execute the next action filter in the pipeline. + public override async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next) + { + IAuthorizationService authorizationService = context.HttpContext.RequestServices.GetRequiredService(); + await authorizationService.AuthorizeAsync(context.HttpContext.User, context.HttpContext, "RequireInitialization"); + await next(); + } +} diff --git a/src/Lumina.Presentation.Web/Common/Http/HttpContextItemKeys.cs b/src/Lumina.Presentation.Web/Common/Http/HttpContextItemKeys.cs new file mode 100644 index 00000000..f47a0ec7 --- /dev/null +++ b/src/Lumina.Presentation.Web/Common/Http/HttpContextItemKeys.cs @@ -0,0 +1,10 @@ +namespace Lumina.Presentation.Web.Common.Http; + +/// +/// Constants shared by HttpContext across a HTTP request (avoid magic strings). +/// +public static class HttpContextItemKeys +{ + public const string ERRORS = "errors"; + public const string PENDING_SUPER_ADMIN_SETUP = "PendingSuperAdminSetup"; +} diff --git a/src/Lumina.Presentation.Web/Common/Models/Configuration/EncryptionSettingsModel.cs b/src/Lumina.Presentation.Web/Common/Models/Configuration/EncryptionSettingsModel.cs new file mode 100644 index 00000000..7f8ebbbf --- /dev/null +++ b/src/Lumina.Presentation.Web/Common/Models/Configuration/EncryptionSettingsModel.cs @@ -0,0 +1,19 @@ +#region ========================================================================= USING ===================================================================================== +using System.Diagnostics; +#endregion + +namespace Lumina.Presentation.Web.Common.Models.Configuration; + +/// +/// Model for deserializing media settings. +/// +[DebuggerDisplay("{SECTION_NAME}")] +public class EncryptionSettingsModel +{ + public const string SECTION_NAME = "EncryptionSettings"; + + /// + /// Gets or sets the root directory where media files are stored. + /// + public required string SecretKey { get; init; } +} 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/Common/Models/MediaContributors/MediaContributorModel.cs b/src/Lumina.Presentation.Web/Common/Models/MediaContributors/MediaContributorModel.cs index ef1c9c38..c1e3a418 100644 --- a/src/Lumina.Presentation.Web/Common/Models/MediaContributors/MediaContributorModel.cs +++ b/src/Lumina.Presentation.Web/Common/Models/MediaContributors/MediaContributorModel.cs @@ -1,6 +1,5 @@ #region ========================================================================= USING ===================================================================================== using System.Diagnostics; - #endregion namespace Lumina.Presentation.Web.Common.Models.MediaContributors; @@ -20,4 +19,4 @@ public class MediaContributorModel /// Gets the role of the contributor. /// public MediaContributorRoleModel? Role { get; set; } -} \ No newline at end of file +} diff --git a/src/Lumina.Presentation.Web/Common/Models/UI/ComboboxItem.cs b/src/Lumina.Presentation.Web/Common/Models/UI/ComboboxItem.cs deleted file mode 100644 index 0168e431..00000000 --- a/src/Lumina.Presentation.Web/Common/Models/UI/ComboboxItem.cs +++ /dev/null @@ -1,28 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using System.Diagnostics; -#endregion - -namespace Lumina.Presentation.Web.Common.Models.UI; - -/// -/// Represents an item in a combobox. -/// -/// The type used for the property of the item. -[DebuggerDisplay("{Text}")] -public class ComboboxItem -{ - /// - /// Gets or sets the text of the item, that is visible to the user. - /// - public string? Text { get; set; } - - /// - /// Gets or sets the value of the item, that is used by the application. - /// - public TValue? Value { get; set; } - - /// - /// Gets or sets the property indicating whether this element can be selected or not. - /// - public bool IsEnabled { get; set; } = true; -} \ No newline at end of file diff --git a/src/Lumina.Presentation.Web/Common/Models/UsersManagement/ChangePasswordRequestModel.cs b/src/Lumina.Presentation.Web/Common/Models/UsersManagement/ChangePasswordRequestModel.cs new file mode 100644 index 00000000..85b51598 --- /dev/null +++ b/src/Lumina.Presentation.Web/Common/Models/UsersManagement/ChangePasswordRequestModel.cs @@ -0,0 +1,15 @@ +namespace Lumina.Presentation.Web.Common.Models.UsersManagement; + +/// +/// Represents the request model for account password change. +/// +/// The username of the account. +/// The current password of the account. +/// The new password of the account. +/// The confirmation of the new password of the account. +public record ChangePasswordRequestModel( + string? Username, + string? CurrentPassword, + string? NewPassword, + string? NewPasswordConfirm +); diff --git a/src/Lumina.Presentation.Web/Common/Models/UsersManagement/ChangePasswordResponseModel.cs b/src/Lumina.Presentation.Web/Common/Models/UsersManagement/ChangePasswordResponseModel.cs new file mode 100644 index 00000000..4befdb83 --- /dev/null +++ b/src/Lumina.Presentation.Web/Common/Models/UsersManagement/ChangePasswordResponseModel.cs @@ -0,0 +1,14 @@ +#region ========================================================================= USING ===================================================================================== +using System.Diagnostics; +#endregion + +namespace Lumina.Presentation.Web.Common.Models.UsersManagement; + +/// +/// Represents the response model for an account password change request. +/// +/// Whether the password was changed or not. +[DebuggerDisplay("IsPasswordChanged: {IsPasswordChanged}")] +public record ChangePasswordResponseModel( + bool IsPasswordChanged +); diff --git a/src/Lumina.Presentation.Web/Common/Models/UsersManagement/InitializationModel.cs b/src/Lumina.Presentation.Web/Common/Models/UsersManagement/InitializationModel.cs new file mode 100644 index 00000000..68a0dc52 --- /dev/null +++ b/src/Lumina.Presentation.Web/Common/Models/UsersManagement/InitializationModel.cs @@ -0,0 +1,17 @@ +#region ========================================================================= USING ===================================================================================== +using System.Diagnostics; +#endregion + +namespace Lumina.Presentation.Web.Common.Models.UsersManagement; + +/// +/// Model for verifying the initialization status of the application. +/// +[DebuggerDisplay("IsInitialized: {IsInitialized}")] +public class InitializationModel +{ + /// + /// Gets or sets a value indicating whether the application has been run before, and the super admin account has been created. + /// + public bool IsInitialized { get; set; } +} diff --git a/src/Lumina.Presentation.Web/Common/Models/UsersManagement/LoginRequestModel.cs b/src/Lumina.Presentation.Web/Common/Models/UsersManagement/LoginRequestModel.cs new file mode 100644 index 00000000..d84581b9 --- /dev/null +++ b/src/Lumina.Presentation.Web/Common/Models/UsersManagement/LoginRequestModel.cs @@ -0,0 +1,18 @@ +#region ========================================================================= USING ===================================================================================== +using System.Diagnostics; +#endregion + +namespace Lumina.Presentation.Web.Common.Models.UsersManagement; + +/// +/// Represents the request model for user authentication. +/// +/// The username used to authenticate. +/// The password used to authenticate. +/// The TOTP (Time-Based One-Time Password) code used for two-factor authentication. +[DebuggerDisplay("Username: {Username}")] +public record LoginRequestModel( + string? Username = null, + string? Password = null, + string? TotpCode = null +); diff --git a/src/Lumina.Presentation.Web/Common/Models/UsersManagement/LoginResponseModel.cs b/src/Lumina.Presentation.Web/Common/Models/UsersManagement/LoginResponseModel.cs new file mode 100644 index 00000000..a5662424 --- /dev/null +++ b/src/Lumina.Presentation.Web/Common/Models/UsersManagement/LoginResponseModel.cs @@ -0,0 +1,21 @@ +#region ========================================================================= USING ===================================================================================== +using System; +using System.Diagnostics; +#endregion + +namespace Lumina.Presentation.Web.Common.Models.UsersManagement; + +/// +/// Represents the response model for a user authentication. +/// +/// The Id of the logged in user. +/// The username of the logged in user. +/// The JWT authentication token, if authentication failed or TOTP is required. +/// Indicates whether the user has Two-Factor Authentication enabled, or not. +[DebuggerDisplay("Username: {Username}")] +public record LoginResponseModel( + Guid Id, + string? Username, + string? Token, + bool UsesTotp +); diff --git a/src/Lumina.Presentation.Web/Common/Models/UsersManagement/RecoverPasswordRequestModel.cs b/src/Lumina.Presentation.Web/Common/Models/UsersManagement/RecoverPasswordRequestModel.cs new file mode 100644 index 00000000..1668a464 --- /dev/null +++ b/src/Lumina.Presentation.Web/Common/Models/UsersManagement/RecoverPasswordRequestModel.cs @@ -0,0 +1,16 @@ +#region ========================================================================= USING ===================================================================================== +using System.Diagnostics; +#endregion + +namespace Lumina.Presentation.Web.Common.Models.UsersManagement; + +/// +/// Represents the request model for account password recovery. +/// +/// The username of the account for which to recover the password. +/// The TOTP (Time-Based One-Time Password) code used to recover the password. +[DebuggerDisplay("Username: {Username}")] +public record RecoverPasswordRequestModel( + string? Username, + string? TotpCode +); diff --git a/src/Lumina.Presentation.Web/Common/Models/UsersManagement/RecoverPasswordResponseModel.cs b/src/Lumina.Presentation.Web/Common/Models/UsersManagement/RecoverPasswordResponseModel.cs new file mode 100644 index 00000000..4a5703f1 --- /dev/null +++ b/src/Lumina.Presentation.Web/Common/Models/UsersManagement/RecoverPasswordResponseModel.cs @@ -0,0 +1,14 @@ +#region ========================================================================= USING ===================================================================================== +using System.Diagnostics; +#endregion + +namespace Lumina.Presentation.Web.Common.Models.UsersManagement; + +/// +/// Represents the response model for an account password reset request. +/// +/// Whether the password was reset or not. +[DebuggerDisplay("IsPasswordReset: {IsPasswordReset}")] +public record RecoverPasswordResponseModel( + bool IsPasswordReset +); diff --git a/src/Lumina.Presentation.Web/Common/Models/UsersManagement/RegisterRequestModel.cs b/src/Lumina.Presentation.Web/Common/Models/UsersManagement/RegisterRequestModel.cs new file mode 100644 index 00000000..082b8108 --- /dev/null +++ b/src/Lumina.Presentation.Web/Common/Models/UsersManagement/RegisterRequestModel.cs @@ -0,0 +1,22 @@ +#region ========================================================================= USING ===================================================================================== +using System.Diagnostics; +#endregion + +namespace Lumina.Presentation.Web.Common.Models.UsersManagement; + +/// +/// Represents the request model for user registration. +/// +/// The desired username for the new account. +/// The password for the new account. +/// The confirmation of the entered password, used to ensure consistency. +/// Specifies the type of registration, e.g., "Admin" or "User". +/// Indicates whether two-factor authentication (2FA) should be enabled for the new account. +[DebuggerDisplay("Username: {Username}")] +public record RegisterRequestModel( + string? Username, + string? Password, + string? PasswordConfirm, + string? RegistrationType, + bool Use2fa = true +); diff --git a/src/Lumina.Presentation.Web/Common/Models/UsersManagement/RegisterResponseModel.cs b/src/Lumina.Presentation.Web/Common/Models/UsersManagement/RegisterResponseModel.cs new file mode 100644 index 00000000..7a43ba88 --- /dev/null +++ b/src/Lumina.Presentation.Web/Common/Models/UsersManagement/RegisterResponseModel.cs @@ -0,0 +1,17 @@ +#region ========================================================================= USING ===================================================================================== +using System; +using System.Diagnostics; +#endregion + +namespace Lumina.Presentation.Web.Common.Models.UsersManagement; + +/// +/// Represents the response model for a successful registration. +/// +/// The username of the registered user. +/// The TOTP (Time-Based One-Time Password) secret used for two-factor authentication. +[DebuggerDisplay("Username: {Username}")] +public record RegisterResponseModel( + string? Username, + string? TotpSecret +); diff --git a/src/Lumina.Contracts/Models/WrittenContentLibrary/BookLibrary/BookSeriesModel.cs b/src/Lumina.Presentation.Web/Common/Models/WrittenContentLibrary/BookLibrary/BooksModel.cs similarity index 52% rename from src/Lumina.Contracts/Models/WrittenContentLibrary/BookLibrary/BookSeriesModel.cs rename to src/Lumina.Presentation.Web/Common/Models/WrittenContentLibrary/BookLibrary/BooksModel.cs index a8b23fe0..96565d6e 100644 --- a/src/Lumina.Contracts/Models/WrittenContentLibrary/BookLibrary/BookSeriesModel.cs +++ b/src/Lumina.Presentation.Web/Common/Models/WrittenContentLibrary/BookLibrary/BooksModel.cs @@ -1,14 +1,16 @@ #region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Common.Models.Common; +using System; +using System.Collections.Generic; using System.Diagnostics; #endregion -namespace Lumina.Contracts.Models.WrittenContentLibrary.BookLibrary; +namespace Lumina.Presentation.Web.Common.Models.WrittenContentLibrary.BookLibrary; /// -/// Represents a request to get book series information. +/// Represents a book. /// -/// Gets the title of the book series. [DebuggerDisplay("{Title}")] -public record BookSeriesModel( - string? Title -); \ No newline at end of file +public class BooksModel +{ +} diff --git a/src/Lumina.Presentation.Web/Common/Models/WrittenContentLibrary/BookLibrary/LightBookModel.cs b/src/Lumina.Presentation.Web/Common/Models/WrittenContentLibrary/BookLibrary/LightBookModel.cs new file mode 100644 index 00000000..0da7e882 --- /dev/null +++ b/src/Lumina.Presentation.Web/Common/Models/WrittenContentLibrary/BookLibrary/LightBookModel.cs @@ -0,0 +1,33 @@ +#region ========================================================================= USING ===================================================================================== +using System; +using System.Diagnostics; +#endregion + +namespace Lumina.Presentation.Web.Common.Models.WrittenContentLibrary.BookLibrary; + +/// +/// Represents a preview of important properties of a book. +/// +[DebuggerDisplay("{Title}")] +public class LightBookModel +{ + /// + /// Gets the Id of the media item. + /// + public required Guid Id { get; init; } + + /// + /// Gets the title of the media item. + /// + public required string Title { get; init; } + + /// + /// Gets the optional release year (either re-release year, if available, or original release year, if known) of the media item. + /// + public int? ReleaseYear { get; init; } + + /// + /// Gets the optional path of the image representing the cover of this book. + /// + public string? CoverPath { get; init; } +} diff --git a/src/Lumina.Presentation.Web/Common/Requests/WrittenContentLibrary/BookLibrary/AddBookRequest.cs b/src/Lumina.Presentation.Web/Common/Requests/WrittenContentLibrary/BookLibrary/AddBookRequest.cs deleted file mode 100644 index 8af7c595..00000000 --- a/src/Lumina.Presentation.Web/Common/Requests/WrittenContentLibrary/BookLibrary/AddBookRequest.cs +++ /dev/null @@ -1,100 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using Lumina.Presentation.Web.Common.Enums.BookLibrary; -using Lumina.Presentation.Web.Common.Models.MediaContributors; -using Lumina.Presentation.Web.Common.Models.WrittenContentLibrary; -using Lumina.Presentation.Web.Common.Models.WrittenContentLibrary.BookLibrary; -using System.Collections.Generic; -#endregion - -namespace Lumina.Presentation.Web.Common.Requests.WrittenContentLibrary.BookLibrary; - -/// -/// Represents a request to add a book. -/// -public class AddBookRequest -{ - /// - /// Gets or sets the written content metadata of the book. - /// - public WrittenContentMetadataModel? Metadata { get; set; } - - /// - /// Gets or sets the format of the book (e.g., Hardcover, Paperback), if applicable. - /// - public BookFormat? Format { get; set; } - - /// - /// Gets or sets the edition of the book, if applicable. - /// - public string? Edition { get; set; } - - /// - /// Gets or sets the volume or book number in the series, if applicable. - /// - public int? VolumeNumber { get; set; } - - /// - /// Gets or sets the series name, if the book is part of a series. - /// - public BookSeriesModel? Series { get; set; } - - /// - /// Gets or sets the ASIN (Amazon Standard Identification Number) of the book, if applicable. - /// - public string? ASIN { get; set; } - - /// - /// Gets or sets the Goodreads ID of the book, if applicable. - /// - public string? GoodreadsId { get; set; } - - /// - /// Gets or sets the Library of Congress Control Number (LCCN) of the book, if applicable. - /// - public string? LCCN { get; set; } - - /// - /// Gets or sets the OCLC Number (WorldCat identifier) of the book, if applicable. - /// - public string? OCLCNumber { get; set; } - - /// - /// Gets or sets the Open Library ID of the book, if applicable. - /// - public string? OpenLibraryId { get; set; } - - /// - /// Gets or sets the LibraryThing ID of the book, if applicable. - /// - public string? LibraryThingId { get; set; } - - /// - /// Gets or sets the Google Books ID of the book, if applicable. - /// - public string? GoogleBooksId { get; set; } - - /// - /// Gets or sets the Barnes & Noble ID of the book, if applicable. - /// - public string? BarnesAndNobleId { get; set; } - - /// - /// Gets or sets the Apple Books ID of the book, if applicable. - /// - public string? AppleBooksId { get; set; } - - /// - /// Gets or sets the list of ISBN (International Standard Book Number) of the book. - /// - public List? ISBNs { get; set; } - - /// - /// Gets or sets the list of media contributors (actors, directors, etc) starring in this book. - /// - public List? Contributors { get; set; } - - /// - /// Gets or sets the list of ratings for this book. - /// - public List? Ratings { get; set; } -} \ No newline at end of file diff --git a/src/Lumina.Presentation.Web/Common/Security/CryptographyService.cs b/src/Lumina.Presentation.Web/Common/Security/CryptographyService.cs new file mode 100644 index 00000000..b8480404 --- /dev/null +++ b/src/Lumina.Presentation.Web/Common/Security/CryptographyService.cs @@ -0,0 +1,102 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Common.Models.Configuration; +using Microsoft.Extensions.Options; +using System; +using System.Security.Cryptography; +using System.Text; +#endregion + +namespace Lumina.Presentation.Web.Common.Security; + +/// +/// Service for cryptographic concerns. +/// +public sealed class CryptographyService : ICryptographyService, IDisposable +{ + private readonly byte[] _key; + + /// + /// Initializes a new instance of the class. + /// + /// Injected service for retrieving . + public CryptographyService(IOptions encryptionSettingsModelOptions) + { + _key = Convert.FromBase64String(encryptionSettingsModelOptions.Value.SecretKey); + } + + /// + /// Encrypts a plaintext string using AES encryption with a randomly generated initialization vector (IV). + /// + /// The plaintext string to encrypt. + /// A Base64-encoded string of the combined IV and encrypted ciphertext. + /// Thrown when is or empty. + public string Encrypt(string plaintext) + { + if (string.IsNullOrEmpty(plaintext)) + throw new ArgumentException("Value cannot be null or empty", nameof(plaintext)); + + // generate a new, random 16-byte IV for each encryption to ensure unique ciphertexts + byte[] iv = new byte[16]; + using (RandomNumberGenerator rng = RandomNumberGenerator.Create()) + rng.GetBytes(iv); + + using Aes aes = Aes.Create(); + aes.Key = _key; + aes.IV = iv; + aes.Mode = CipherMode.CBC; + aes.Padding = PaddingMode.PKCS7; + + using ICryptoTransform encryptor = aes.CreateEncryptor(); + byte[] plaintextBytes = Encoding.UTF8.GetBytes(plaintext); + byte[] ciphertext = encryptor.TransformFinalBlock(plaintextBytes, 0, plaintextBytes.Length); + + // combine IV and ciphertext + byte[] combined = new byte[iv.Length + ciphertext.Length]; + Buffer.BlockCopy(iv, 0, combined, 0, iv.Length); + Buffer.BlockCopy(ciphertext, 0, combined, iv.Length, ciphertext.Length); + + return Convert.ToBase64String(combined); + } + + /// + /// Decrypts a Base64-encoded string that contains both the IV and ciphertext. + /// + /// The Base64-encoded string containing both IV and ciphertext. + /// The decrypted plaintext string. + /// Thrown when is , empty, or invalid. + public string Decrypt(string ciphertext) + { + if (string.IsNullOrEmpty(ciphertext)) + throw new ArgumentException("Value cannot be null or empty", nameof(ciphertext)); + + // decode the combined data (IV + ciphertext) from Base64 + byte[] combined = Convert.FromBase64String(ciphertext); + + if (combined.Length < 16) + throw new ArgumentException("Invalid ciphertext"); + + // extract IV and ciphertext + byte[] iv = new byte[16]; + byte[] encryptedData = new byte[combined.Length - 16]; + Buffer.BlockCopy(combined, 0, iv, 0, 16); + Buffer.BlockCopy(combined, 16, encryptedData, 0, encryptedData.Length); + + using Aes aes = Aes.Create(); + aes.Key = _key; + aes.IV = iv; + aes.Mode = CipherMode.CBC; + aes.Padding = PaddingMode.PKCS7; + + using ICryptoTransform decryptor = aes.CreateDecryptor(); + byte[] decrypted = decryptor.TransformFinalBlock(encryptedData, 0, encryptedData.Length); + return Encoding.UTF8.GetString(decrypted); + } + + /// + /// Clears sensitive key data when the service is disposed. + /// + public void Dispose() + { + Array.Clear(_key, 0, _key.Length); + } +} diff --git a/src/Lumina.Presentation.Web/Common/Security/ICryptographyService.cs b/src/Lumina.Presentation.Web/Common/Security/ICryptographyService.cs new file mode 100644 index 00000000..ecfdbccf --- /dev/null +++ b/src/Lumina.Presentation.Web/Common/Security/ICryptographyService.cs @@ -0,0 +1,27 @@ +#region ========================================================================= USING ===================================================================================== +using System; +#endregion + +namespace Lumina.Presentation.Web.Common.Security; + +/// +/// Interface for the service for cryptographic concerns. +/// +public interface ICryptographyService +{ + /// + /// Encrypts a plaintext string using AES encryption with a randomly generated initialization vector (IV). + /// + /// The plaintext string to encrypt. + /// A Base64-encoded string of the combined IV and encrypted ciphertext. + /// Thrown when is or empty. + string Encrypt(string plaintext); + + /// + /// Decrypts a Base64-encoded string that contains both the IV and ciphertext. + /// + /// The Base64-encoded string containing both IV and ciphertext. + /// The decrypted plaintext string. + /// Thrown when is , empty, or invalid. + string Decrypt(string ciphertext); +} diff --git a/src/Lumina.Presentation.Web/Common/Services/INotificationService.cs b/src/Lumina.Presentation.Web/Common/Services/INotificationService.cs deleted file mode 100644 index d5b896d3..00000000 --- a/src/Lumina.Presentation.Web/Common/Services/INotificationService.cs +++ /dev/null @@ -1,22 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using Lumina.Presentation.Web.Common.Enums.Notifications; -using Lumina.Presentation.Web.Common.Models.Common; -using System; -#endregion - -namespace Lumina.Presentation.Web.Common.Services; - -/// -/// Interface for the service for showing notifications. -/// -public interface INotificationService -{ - event Action? OnNotification; - - /// - /// Shows a notification. - /// - /// The message of the notification. - /// The type of the notification. - void Show(string message, NotificationType type); -} \ No newline at end of file diff --git a/src/Lumina.Presentation.Web/Common/Services/IUrlService.cs b/src/Lumina.Presentation.Web/Common/Services/IUrlService.cs new file mode 100644 index 00000000..f28f6696 --- /dev/null +++ b/src/Lumina.Presentation.Web/Common/Services/IUrlService.cs @@ -0,0 +1,12 @@ +namespace Lumina.Presentation.Web.Common.Services; + +public interface IUrlService +{ + /// + /// Generates an absolute URL for the specified controller action. + /// + /// The action name within the controller. + /// The controller name. + /// An absolute URL to the specified action. + string? GetAbsoluteUrl(string action, string controller); +} diff --git a/src/Lumina.Presentation.Web/Common/Services/NotificationService.cs b/src/Lumina.Presentation.Web/Common/Services/NotificationService.cs deleted file mode 100644 index 2313c776..00000000 --- a/src/Lumina.Presentation.Web/Common/Services/NotificationService.cs +++ /dev/null @@ -1,25 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using Lumina.Presentation.Web.Common.Enums.Notifications; -using Lumina.Presentation.Web.Common.Models.Common; -using System; -#endregion - -namespace Lumina.Presentation.Web.Common.Services; - -/// -/// Service for showing notifications. -/// -public class NotificationService : INotificationService -{ - public event Action? OnNotification; - - /// - /// Shows a notification. - /// - /// The message of the notification. - /// The type of the notification. - public void Show(string message, NotificationType type) - { - OnNotification?.Invoke(new NotificationModel { Message = message, Type = type, Id = Guid.NewGuid() }); - } -} \ No newline at end of file diff --git a/src/Lumina.Presentation.Web/Common/Services/UrlService.cs b/src/Lumina.Presentation.Web/Common/Services/UrlService.cs new file mode 100644 index 00000000..2f8ed3b5 --- /dev/null +++ b/src/Lumina.Presentation.Web/Common/Services/UrlService.cs @@ -0,0 +1,38 @@ +#region ========================================================================= USING ===================================================================================== +using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Routing; +#endregion + +namespace Lumina.Presentation.Web.Common.Services; + +/// +/// Service for generating URLs from action and controller names. +/// +public class UrlService : IUrlService +{ + private readonly LinkGenerator _linkGenerator; + private readonly IHttpContextAccessor _httpContextAccessor; + + /// + /// Initializes a new instance of the class. + /// + /// The ASP.NET Core link generator service. + /// Provides access to the current HTTP context. + public UrlService(LinkGenerator linkGenerator, IHttpContextAccessor httpContextAccessor) + { + _linkGenerator = linkGenerator; + _httpContextAccessor = httpContextAccessor; + } + + /// + /// Generates an absolute URL for the specified controller action. + /// + /// The action name within the controller. + /// The controller name. + /// An absolute URL to the specified action. + public string? GetAbsoluteUrl(string action, string controller) + { + string? scheme = _httpContextAccessor.HttpContext?.Request.Scheme; + return _linkGenerator.GetUriByAction(_httpContextAccessor.HttpContext!, action: action, controller: controller, values: null, scheme: scheme); + } +} diff --git a/src/Lumina.Presentation.Web/Common/Validators/EncryptionSettingsModelValidator.cs b/src/Lumina.Presentation.Web/Common/Validators/EncryptionSettingsModelValidator.cs new file mode 100644 index 00000000..b05311bc --- /dev/null +++ b/src/Lumina.Presentation.Web/Common/Validators/EncryptionSettingsModelValidator.cs @@ -0,0 +1,24 @@ +#region ========================================================================= USING ===================================================================================== +using FluentValidation; +using Lumina.Presentation.Web.Common.Models.Configuration; +using System; +using System.Buffers.Text; +#endregion + +namespace Lumina.Presentation.Web.Common.Validators; + +/// +/// Validates the needed validation rules for the EncryptionSettings application configuration settings section. +/// +public class EncryptionSettingsModelValidator : AbstractValidator +{ + /// + /// Initializes a new instance of the class. + /// + public EncryptionSettingsModelValidator() + { + RuleFor(x => x.SecretKey) + .NotEmpty().WithMessage("Encryption secret key cannot be empty!") + .Must(value => Base64.IsValid(value.AsSpan())).WithMessage("Encryption secret key must be a base64 string!"); + } +} diff --git a/src/Lumina.Presentation.Web/Controllers/FileManagement/DirectoriesController.cs b/src/Lumina.Presentation.Web/Controllers/FileSystemManagement/DirectoriesController.cs similarity index 71% rename from src/Lumina.Presentation.Web/Controllers/FileManagement/DirectoriesController.cs rename to src/Lumina.Presentation.Web/Controllers/FileSystemManagement/DirectoriesController.cs index 8dbb6fc7..9de82e2e 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. @@ -35,16 +35,11 @@ public class DirectoriesController : Controller /// 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] string path, [FromQuery] bool includeHiddenElements, [EnumeratorCancellation] CancellationToken cancellationToken) + public async Task GetDirectories([FromQuery] string path, [FromQuery] bool includeHiddenElements, CancellationToken cancellationToken) { - IAsyncEnumerable response = _apiHttpClient.GetAsyncEnumerable( + IEnumerable response = await _apiHttpClient.GetAsync( $"directories/get-directories?path={Uri.EscapeDataString(path)}&includeHiddenElements={includeHiddenElements}", cancellationToken: cancellationToken); - await foreach (DirectoryModel? directory in response) - { - if (cancellationToken.IsCancellationRequested) - yield break; - yield return directory; - } + return Json(new { success = true, data = response }); } /// @@ -54,16 +49,11 @@ public class DirectoriesController : Controller /// 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] string path, [FromQuery] bool includeHiddenElements, [EnumeratorCancellation] CancellationToken cancellationToken) + public async Task GetTreeDirectories([FromQuery] string path, [FromQuery] bool includeHiddenElements, CancellationToken cancellationToken) { - IAsyncEnumerable response = _apiHttpClient.GetAsyncEnumerable( + IEnumerable response = await _apiHttpClient.GetAsync( $"directories/get-tree-directories?path={Uri.EscapeDataString(path)}&includeHiddenElements={includeHiddenElements}", cancellationToken: cancellationToken); - await foreach (FileSystemTreeNodeModel? directory in response) - { - if (cancellationToken.IsCancellationRequested) - yield break; - yield return directory; - } + return Json(new { success = true, data = response }); } /// @@ -76,6 +66,6 @@ public class DirectoriesController : Controller public async Task GetDirectoryTree([FromQuery] string path, [FromQuery] bool includeFiles, [FromQuery] bool includeHiddenElements, CancellationToken cancellationToken) { FileSystemTreeNodeModel[] response = await _apiHttpClient.GetAsync($"directories/get-directory-tree?path={Uri.EscapeDataString(path)}&includeFiles={includeFiles}&includeHiddenElements={includeHiddenElements}", cancellationToken: cancellationToken); - return Json(new { success = true, data = new { tree = response } }); + return Json(new { success = true, data = response }); } } 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 64% rename from src/Lumina.Presentation.Web/Controllers/FileManagement/FilesController.cs rename to src/Lumina.Presentation.Web/Controllers/FileSystemManagement/FilesController.cs index ed263306..e327ef23 100644 --- a/src/Lumina.Presentation.Web/Controllers/FileManagement/FilesController.cs +++ b/src/Lumina.Presentation.Web/Controllers/FileSystemManagement/FilesController.cs @@ -1,14 +1,15 @@ #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; using System.Runtime.CompilerServices; 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 files. @@ -34,16 +35,11 @@ public class FilesController : Controller /// 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] string path, [FromQuery] bool includeHiddenElements, [EnumeratorCancellation] CancellationToken cancellationToken) + public async Task GetTreeFiles([FromQuery] string path, [FromQuery] bool includeHiddenElements, CancellationToken cancellationToken) { - IAsyncEnumerable response = _apiHttpClient.GetAsyncEnumerable( + IEnumerable response = await _apiHttpClient.GetAsync( $"files/get-tree-files?path={Uri.EscapeDataString(path)}&includeHiddenElements={includeHiddenElements}", cancellationToken: cancellationToken); - await foreach (FileSystemTreeNodeModel? file in response) - { - if (cancellationToken.IsCancellationRequested) - yield break; - yield return file; - } + return Json(new { success = true, data = response }); } /// @@ -53,15 +49,10 @@ public class FilesController : Controller /// 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] string path, [FromQuery] bool includeHiddenElements, [EnumeratorCancellation] CancellationToken cancellationToken) + public async Task GetFiles([FromQuery] string path, [FromQuery] bool includeHiddenElements, CancellationToken cancellationToken) { - IAsyncEnumerable response = _apiHttpClient.GetAsyncEnumerable( + IEnumerable response = await _apiHttpClient.GetAsync( $"files/get-files?path={Uri.EscapeDataString(path)}&includeHiddenElements={includeHiddenElements}", cancellationToken: cancellationToken); - await foreach (FileModel? file in response) - { - if (cancellationToken.IsCancellationRequested) - yield break; - yield return file; - } + return Json(new { success = true, data = response }); } } 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/Controllers/HomeController.cs b/src/Lumina.Presentation.Web/Controllers/HomeController.cs index cbc920fe..939bebe2 100644 --- a/src/Lumina.Presentation.Web/Controllers/HomeController.cs +++ b/src/Lumina.Presentation.Web/Controllers/HomeController.cs @@ -1,14 +1,17 @@ using Lumina.Presentation.Web.Models; +using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; -using Microsoft.Extensions.Logging; +using Serilog; using System.Diagnostics; namespace Lumina.Presentation.Web.Controllers; + +[Authorize] public class HomeController : Controller { - private readonly ILogger _logger; + private readonly ILogger _logger; - public HomeController(ILogger logger) + public HomeController(ILogger logger) { _logger = logger; } diff --git a/src/Lumina.Presentation.Web/Controllers/Library/Management/LibraryManagementController.cs b/src/Lumina.Presentation.Web/Controllers/Library/Management/LibraryManagementController.cs new file mode 100644 index 00000000..cc77f34e --- /dev/null +++ b/src/Lumina.Presentation.Web/Controllers/Library/Management/LibraryManagementController.cs @@ -0,0 +1,50 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Common.Api; +using Lumina.Presentation.Web.Common.Enums.Library; +using Lumina.Presentation.Web.Common.Models.Libraries; +using Microsoft.AspNetCore.Mvc; +using Microsoft.AspNetCore.Mvc.Formatters; +using System; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.Controllers.Library.Management; + +[Route("/library/manage/")] +public class LibraryManagementController : Controller +{ + private readonly IApiHttpClient _apiHttpClient; + + public LibraryManagementController(IApiHttpClient apiHttpClient) + { + _apiHttpClient = apiHttpClient; + } + + [HttpGet("")] + public IActionResult Index() + { + return View("/Views/Library/Management/Index.cshtml"); + } + + [HttpGet("item/{id?}")] + public IActionResult EditLibrary(Guid? id = null) + { + LibraryModel libraryModel = new() + { + Id = id, + LibraryType = LibraryType.Book, + Paths = ["a", "b", "c"], + Title = "" + }; + return View("/Views/Library/Management/Item.cshtml", libraryModel); + } + + [HttpPost("item")] + public async Task SaveLibraryAsync([FromBody] LibraryModel model) + { + LibraryModel response = model.Id.HasValue + ? await _apiHttpClient.PutAsync($"libraries/{model.Id}", model) + : await _apiHttpClient.PostAsync("libraries", model); + return Json(new { success = true }); + } +} diff --git a/src/Lumina.Presentation.Web/Controllers/Library/WrittenContentLibrary/BookLibrary/BooksController.cs b/src/Lumina.Presentation.Web/Controllers/Library/WrittenContentLibrary/BookLibrary/BooksController.cs new file mode 100644 index 00000000..0cd52639 --- /dev/null +++ b/src/Lumina.Presentation.Web/Controllers/Library/WrittenContentLibrary/BookLibrary/BooksController.cs @@ -0,0 +1,20 @@ +using Microsoft.AspNetCore.Mvc; +using System; + +namespace Lumina.Presentation.Web.Controllers.Library.WrittenContentLibrary.BookLibrary; + +[Route("/library/written-content-library/books-library/books/")] +public class BooksController : Controller +{ + [HttpGet("")] + public IActionResult Index() + { + return View("/Views/Library/WrittenContentLibrary/BookLibrary/Books/Index.cshtml"); + } + + [HttpGet("{id}")] + public IActionResult EditBook(Guid id) + { + return View("/Views/Library/WrittenContentLibrary/BookLibrary/Books/Item.cshtml"); + } +} diff --git a/src/Lumina.Presentation.Web/Controllers/UsersManagement/AuthController.cs b/src/Lumina.Presentation.Web/Controllers/UsersManagement/AuthController.cs new file mode 100644 index 00000000..4845a986 --- /dev/null +++ b/src/Lumina.Presentation.Web/Controllers/UsersManagement/AuthController.cs @@ -0,0 +1,218 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Common.Api; +using Lumina.Presentation.Web.Common.Exceptions; +using Lumina.Presentation.Web.Common.Filters; +using Lumina.Presentation.Web.Common.Http; +using Lumina.Presentation.Web.Common.Models.UsersManagement; +using Lumina.Presentation.Web.Common.Security; +using Microsoft.AspNetCore.Authentication; +using Microsoft.AspNetCore.Authentication.Cookies; +using Microsoft.AspNetCore.Authorization; +using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Mvc; +using System; +using System.Collections.Generic; +using System.Security.Claims; +using System.Text.Json; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.Controllers.UsersManagement; + +/// +/// Controller for authentication related operations. +/// +[Authorize] +[Route("/auth/")] +public class AuthController : Controller +{ + private readonly IApiHttpClient _apiHttpClient; + private readonly ICryptographyService _cryptographyService; + + /// + /// Initializes a new instance of the class. + /// + /// Injected service for interactions with the API. + /// Injected service for cryptographic functionality. + public AuthController(IApiHttpClient apiHttpClient, ICryptographyService cryptographyService) + { + _apiHttpClient = apiHttpClient; + _cryptographyService = cryptographyService; + } + + /// + /// Displays the view for registering a new account. + /// + [AllowAnonymous] + [InitializationCheck] + [HttpGet("register")] + public IActionResult Register() + { + // check if this is the initial super admin setup + string? isPendingSuperAdminSetup = HttpContext.Session.GetString(HttpContextItemKeys.PENDING_SUPER_ADMIN_SETUP); + ViewData["RegistrationType"] = isPendingSuperAdminSetup == "true" ? "Admin" : "User"; + return View(); + } + + /// + /// Displays the view for logging in. + /// + /// The url to return to, after login (if any). + [AllowAnonymous] + [InitializationCheck] + [HttpGet("login/{returnUrl?}")] + public IActionResult Login(string? returnUrl = null) + { + ViewData["ReturnUrl"] = returnUrl; + // if the user is already logged in, redirect them to the home page + if (User?.Identity?.IsAuthenticated == true) + return RedirectToAction("Index", "Home"); + // check if the application is initialized (does contain at least the super user account); if it's not, redirect to registration view + string? isPendingSuperAdminSetup = HttpContext.Session.GetString(HttpContextItemKeys.PENDING_SUPER_ADMIN_SETUP); + if (isPendingSuperAdminSetup == "true") + // TODO: should be: + // return View("~/Views/Auth/Register", new RegisterRequestDto()); + // but doesn't work because of an ASP.NET bug: https://github.com/dotnet/AspNetCore.Docs/issues/25157 + return RedirectToAction("Register", "Auth"); + return View(new LoginRequestModel()); + } + + /// + /// Displays the view for recovering the password of an account. + /// + [AllowAnonymous] + [InitializationCheck] + [HttpGet("recover-password")] + public IActionResult RecoverPassword() + { + // if the user is already logged in, redirect them to the home page + if (User?.Identity?.IsAuthenticated == true) + return RedirectToAction("Index", "Home"); + return View(); + } + + /// + /// Displays the view for changing the password of an account. + /// + [HttpGet("change-password")] + public IActionResult ChangePassword() + { + return View(); + } + + /// + /// Displays the view for registering a new account. + /// + [HttpGet("profile")] + public IActionResult Profile() + { + return View(); + } + + /// + /// Registers a new account. + /// + /// User credentials used for registration. + [AllowAnonymous] + [ValidateAntiForgeryToken] + [HttpPost("register")] + public async Task Register([FromBody] RegisterRequestModel data) + { + // call different endpoints based on the view hidden field - registration for normal users, or initial application admin account setup + string endpoint = data.RegistrationType == "Admin" ? "initialization" : "auth/register"; + // attempt API registration + RegisterResponseModel response = await _apiHttpClient.PostAsync(endpoint, data); + return Json(new { success = true, data = response }); + } + + /// + /// Logs in an account. + /// + /// User credentials used for login. + /// The url to return to, after login (if any). + [AllowAnonymous] + [ValidateAntiForgeryToken] + [HttpPost("login")] + public async Task Login([FromBody] LoginRequestModel data, string? returnUrl = null) + { + try + { + // attempt API registration + LoginResponseModel response = await _apiHttpClient.PostAsync("auth/login", data); + // store the received token in a secure cookie + Response.Cookies.Delete("Token"); + Response.Cookies.Append("Token", _cryptographyService.Encrypt(response.Token!), new CookieOptions + { + Expires = DateTimeOffset.UtcNow.AddMonths(1), + Path = "/", + HttpOnly = true, + Secure = true + }); + // tell asp.net we are logged in + List claims = + [ + new Claim(ClaimTypes.Name, response.Username!), + new Claim(ClaimTypes.NameIdentifier, response.Id.ToString()!), + new Claim("Token", response.Token!), + ]; + ClaimsIdentity claimsIdentity = new(claims, CookieAuthenticationDefaults.AuthenticationScheme); + await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, new ClaimsPrincipal(claimsIdentity)); + // return success status and redirect URL + return Json(new { success = true, data = string.IsNullOrEmpty(returnUrl) || !Url.IsLocalUrl(returnUrl) ? Url.Content("~/") : Url.Content(returnUrl) }); + } + catch (ApiException ex) + { + // in this particular case, we DO NOT want to let the ApiExceptionFilter take care of this exception, because when the user has 2FA enabled, the first auth step involves sending + // only the username and password, in which case the server API will respond with a validation error, that TOTP code is not valid (empty); it is then that we catch this error here + // and display the form that asks the user for the TOTP code + if (ex.ProblemDetails is not null && ex.ProblemDetails.Extensions?.Count > 0 && ex.ProblemDetails.Extensions.TryGetValue("errors", out JsonElement errorsObj)) + if (errorsObj is JsonElement jsonElement && jsonElement.ValueKind == JsonValueKind.Object) + foreach (JsonProperty error in jsonElement.EnumerateObject()) + if (error.Value.ValueKind == JsonValueKind.Array) + foreach (JsonElement errorValue in error.Value.EnumerateArray()) + if (errorValue.ValueKind == JsonValueKind.String && errorValue.GetString() == "InvalidTotpCode" && string.IsNullOrEmpty(data.TotpCode)) + return Json(new { success = true, data = new { isTotpRequired = true } }); // only get here when user did not enter a TOTP code at all, otherwise rethrow the validation error + throw; + } + } + + /// + /// Logs out an account and redirects to the login page. + /// + [HttpGet("logout")] + public async Task Logout() + { + // if the user is not logged in, redirect them to the home page + if (User?.Identity?.IsAuthenticated == false) + return RedirectToAction("Index", "Home"); + Response.Cookies.Delete("Token"); + await HttpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme); + return RedirectToAction("Login", "Auth"); + } + + /// + /// Recovers the password of an account. + /// + /// User credentials used for password recovery. + [AllowAnonymous] + [ValidateAntiForgeryToken] + [HttpPost("recover-password")] + public async Task RecoverPassword([FromBody] RecoverPasswordRequestModel data) + { + RecoverPasswordResponseModel response = await _apiHttpClient.PostAsync("auth/recover-password", data); + return Json(new { success = true, data = response }); + } + + /// + /// Changes the password of an account. + /// + /// User credentials used for password change. + [ValidateAntiForgeryToken] + [HttpPost("change-password")] + public async Task ChangePassword([FromBody] ChangePasswordRequestModel data) + { + data = data with { Username = User?.Identity?.Name }; // assign the currently logged in user as the user for which to change the password + ChangePasswordResponseModel response = await _apiHttpClient.PostAsync("auth/change-password", data); + return Json(new { success = true, data = response }); + } +} diff --git a/src/Lumina.Presentation.Web/Dockerfile b/src/Lumina.Presentation.Web/Dockerfile new file mode 100644 index 00000000..a634add1 --- /dev/null +++ b/src/Lumina.Presentation.Web/Dockerfile @@ -0,0 +1,48 @@ +# This stage is used when running from VS in fast mode (Default for Debug configuration) +FROM mcr.microsoft.com/dotnet/aspnet:8.0 AS base +RUN mkdir /logs && chown -R app:app /logs +USER app +WORKDIR /app +EXPOSE 5012 + + +# ==== Stage 1: Build stage +FROM mcr.microsoft.com/dotnet/sdk:8.0 AS build + +ARG BUILD_CONFIGURATION=Release + +WORKDIR /src + +# restore NuGet packages (keeping this section separate from the rest of the project files allows Docker to cache the restored packages) +COPY ["AssemblyInfo_Shared.cs", "."] +COPY ["Lumina.Presentation.Web/Lumina.Presentation.Web.csproj", "Lumina.Presentation.Web/"] + +RUN dotnet restore "./Lumina.Presentation.Web/Lumina.Presentation.Web.csproj" /p:BaseOutputPath=/app/publish/ + +# build the project +COPY ["Lumina.Presentation.Web/", "Lumina.Presentation.Web/"] +COPY . . +WORKDIR /src/Lumina.Presentation.Web + +RUN dotnet build "./Lumina.Presentation.Web.csproj" -c $BUILD_CONFIGURATION -o /app/build /p:BaseOutputPath=/app/publish/ + +# ==== Stage 2: Publish stage +FROM build AS publish + +ARG BUILD_CONFIGURATION=Release + +RUN dotnet publish "./Lumina.Presentation.Web.csproj" -c $BUILD_CONFIGURATION -o /app/publish /p:UseAppHost=false /p:BaseOutputPath=/app/publish/ + +# ==== Stage 3: Run stage +#FROM mcr.microsoft.com/dotnet/aspnet:8.0 AS runtime +FROM base AS final + +WORKDIR /app + +COPY --from=publish /app/publish . +ENV ASPNETCORE_HTTP_PORTS=5012 +EXPOSE 5012 +ENTRYPOINT ["dotnet", "Lumina.Presentation.Web.dll"] + +# to build this Docker image, run the following command from the root of the project (location of the .sln file): +# docker build --no-cache -t lumina-web -f Lumina.Presentation.Web/Dockerfile . diff --git a/src/Lumina.Presentation.Web/Lumina.Presentation.Web.csproj b/src/Lumina.Presentation.Web/Lumina.Presentation.Web.csproj index d5ab7050..86518506 100644 --- a/src/Lumina.Presentation.Web/Lumina.Presentation.Web.csproj +++ b/src/Lumina.Presentation.Web/Lumina.Presentation.Web.csproj @@ -3,9 +3,15 @@ net9.0 enable disable - $(SolutionDir)..\bin\client\ + $(SolutionDir)..\bin\web\ false true + $(WarningsNotAsErrors);NU1901;NU1902;NU1903;NU1904 + 10a94da9-18ed-4c70-a9da-b461e08958c4 + Linux + lumina-web + lumina-web + ..\docker-compose.dcproj @@ -15,10 +21,16 @@ - - - - + + + + + + + + + + diff --git a/src/Lumina.Presentation.Web/Program.cs b/src/Lumina.Presentation.Web/Program.cs index 8507bb91..109a3e6e 100644 --- a/src/Lumina.Presentation.Web/Program.cs +++ b/src/Lumina.Presentation.Web/Program.cs @@ -1,8 +1,14 @@ #region ========================================================================= USING ===================================================================================== using Lumina.Presentation.Web.Common.DependencyInjection; using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; +using Microsoft.Extensions.Primitives; +using Serilog; +using System; +using System.Diagnostics.CodeAnalysis; +using System.IO; using System.Threading.Tasks; #endregion @@ -11,6 +17,7 @@ namespace Lumina.Presentation.Web; /// /// Application entry point, contains the composition root module, wires up all dependencies of the application. /// +[ExcludeFromCodeCoverage] public class Program { /// @@ -24,10 +31,37 @@ public class Program builder.Services.BindConfiguration(builder.Configuration); builder.Services.AddPresentationWebLayerServices(); + // determine log path based on environment + string logPath; + if (Environment.GetEnvironmentVariable("DOTNET_RUNNING_IN_CONTAINER") == "true") + { + logPath = Environment.GetEnvironmentVariable("LOG_PATH") ?? "/logs"; // use docker volume path + builder.WebHost.ConfigureKestrel(options => + { + options.ListenAnyIP(5012); // HTTP only + }); + } + else + logPath = Path.Combine(AppContext.BaseDirectory, "logs"); // use local binary path + Directory.CreateDirectory(logPath); + if (!logPath.EndsWith(Path.DirectorySeparatorChar.ToString())) + logPath = logPath += Path.DirectorySeparatorChar; + // set environment variable for Serilog configuration + Environment.SetEnvironmentVariable("LOG_PATH", logPath); + + builder.Host.UseSerilog((context, services, configuration) => + { + configuration.ReadFrom.Configuration(context.Configuration) + .ReadFrom.Services(services) + .Enrich.FromLogContext(); + }); + WebApplication app = builder.Build(); + app.UseSerilogRequestLogging(); + // configure the HTTP request pipeline. - if (!app.Environment.IsDevelopment()) + if (!app.Environment.IsDevelopment() && Environment.GetEnvironmentVariable("DOTNET_RUNNING_IN_CONTAINER") != "true") { app.UseExceptionHandler("/Home/Error"); // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts. @@ -36,14 +70,22 @@ public class Program //app.UseHttpsRedirection(); app.UseStaticFiles(); - app.UseRouting(); - + app.UseSession(); + app.UseAuthentication(); app.UseAuthorization(); + app.UseForwardedHeaders(); - app.MapControllerRoute( - name: "default", - pattern: "{controller=Home}/{action=Index}/{id?}"); + // handle path base from reverse proxies + app.Use((context, next) => + { + if (context.Request.Headers.TryGetValue("X-Forwarded-Prefix", out StringValues pathBase)) + context.Request.PathBase = pathBase.ToString(); + return next(); + }); + + + app.MapControllerRoute(name: "default", pattern: "{controller=Home}/{action=Index}/{id?}"); await app.RunAsync(); } diff --git a/src/Lumina.Presentation.Web/Properties/launchSettings.json b/src/Lumina.Presentation.Web/Properties/launchSettings.json index 8a77d161..9cf83bc0 100644 --- a/src/Lumina.Presentation.Web/Properties/launchSettings.json +++ b/src/Lumina.Presentation.Web/Properties/launchSettings.json @@ -1,23 +1,21 @@ { - "$schema": "http://json.schemastore.org/launchsettings.json", "profiles": { "http": { "commandName": "Project", - "dotnetRunMessages": true, - //"launchBrowser": true, - "applicationUrl": "http://localhost:5012", "environmentVariables": { "ASPNETCORE_ENVIRONMENT": "Development" - } + }, + "dotnetRunMessages": true, + "applicationUrl": "http://localhost:5012" }, "https": { "commandName": "Project", - "dotnetRunMessages": true, - //"launchBrowser": true, - "applicationUrl": "http://localhost:5012;https://localhost:7112", "environmentVariables": { "ASPNETCORE_ENVIRONMENT": "Development" - } + }, + "dotnetRunMessages": true, + "applicationUrl": "http://localhost:5012;https://localhost:7112" } - } + }, + "$schema": "http://json.schemastore.org/launchsettings.json" } diff --git a/src/Lumina.Presentation.Web/Renderers/Library/WrittenContentLibrary/BookLibrary/Books/BooksTemplateRenderer.cs b/src/Lumina.Presentation.Web/Renderers/Library/WrittenContentLibrary/BookLibrary/Books/BooksTemplateRenderer.cs new file mode 100644 index 00000000..02466425 --- /dev/null +++ b/src/Lumina.Presentation.Web/Renderers/Library/WrittenContentLibrary/BookLibrary/Books/BooksTemplateRenderer.cs @@ -0,0 +1,5 @@ +namespace Lumina.Presentation.Web.Renderers.Library.WrittenContentLibrary.BookLibrary.Books; + +public class BooksTemplateRenderer +{ +} diff --git a/src/Lumina.Presentation.Web/ViewComponents/FileSystemBrowserViewComponent.cs b/src/Lumina.Presentation.Web/ViewComponents/FileSystemBrowserViewComponent.cs index 271c6d12..f74eec74 100644 --- a/src/Lumina.Presentation.Web/ViewComponents/FileSystemBrowserViewComponent.cs +++ b/src/Lumina.Presentation.Web/ViewComponents/FileSystemBrowserViewComponent.cs @@ -35,7 +35,7 @@ public class FileSystemBrowserViewComponent : ViewComponent { return View(new { - Path = RuntimeInformation.IsOSPlatform(OSPlatform.Linux) ? @"/" : @"C:\", + Path = RuntimeInformation.IsOSPlatform(OSPlatform.Linux) || RuntimeInformation.IsOSPlatform(OSPlatform.OSX) ? @"/" : @"C:\Users\", ServerBasePath = $"{_serverConfigurationModel.BaseAddress}:{_serverConfigurationModel.Port}/api/v{_serverConfigurationModel.ApiVersion}/", ClientBasePath = "http://localhost:5012/", // TODO: take from appsettings or environment ViewMode = FileSystemViewMode.List, diff --git a/src/Lumina.Presentation.Web/Views/Auth/ChangePassword.cshtml b/src/Lumina.Presentation.Web/Views/Auth/ChangePassword.cshtml new file mode 100644 index 00000000..a927e388 --- /dev/null +++ b/src/Lumina.Presentation.Web/Views/Auth/ChangePassword.cshtml @@ -0,0 +1,91 @@ +@* +/auth/change-password/ +*@ + +@using Lumina.Presentation.Web.Common.Models.UsersManagement +@using Lumina.Presentation.Web.Common.Services + +@inject IUrlService _urlService + +@model ChangePasswordRequestModel + +
+
+
+ @Html.AntiForgeryToken() + +
+ +
+
+ + *: +
+
+ +
+ DescriptionCurrentPassword +
+ +
+
+ + *: +
+
+ +
+ DescriptionNewPassword +
+ +
+
+ + *: +
+
+ +
+ DescriptionNewPasswordConfirm +
+
+ +
+
+
+ +
+ +
+
+@section Scripts { + +} diff --git a/src/Lumina.Presentation.Web/Views/Auth/Login.cshtml b/src/Lumina.Presentation.Web/Views/Auth/Login.cshtml new file mode 100644 index 00000000..ebfe6d3f --- /dev/null +++ b/src/Lumina.Presentation.Web/Views/Auth/Login.cshtml @@ -0,0 +1,89 @@ +@* +/auth/login/ +*@ + +@using Lumina.Presentation.Web.Common.Models.UsersManagement +@using Lumina.Presentation.Web.Common.Services + +@inject IUrlService _urlService + +@model LoginRequestModel + +
+
+
+ @Html.AntiForgeryToken() + +
+ +
+
+ : +
+
+ +
+
+ +
+
+ : +
+
+ +
+
+
+ + +
+ + +
+ +
+
+
+
+@section Scripts { + +} diff --git a/src/Lumina.Presentation.Web/Views/Auth/RecoverPassword.cshtml b/src/Lumina.Presentation.Web/Views/Auth/RecoverPassword.cshtml new file mode 100644 index 00000000..4b7f2ab3 --- /dev/null +++ b/src/Lumina.Presentation.Web/Views/Auth/RecoverPassword.cshtml @@ -0,0 +1,84 @@ +@* +/auth/recover-password/ +*@ + +@using Lumina.Presentation.Web.Common.Models.UsersManagement +@using Lumina.Presentation.Web.Common.Services + +@inject IUrlService _urlService + +@model RecoverPasswordRequestModel + +
+
+
+ @Html.AntiForgeryToken() +
+ +
+
+ + *: +
+
+ +
+
+ +
+
+ + *: +
+
+ +
+
+
+ + +
+
+
+ +
+ + +
+
+@section Scripts { + +} diff --git a/src/Lumina.Presentation.Web/Views/Auth/Register.cshtml b/src/Lumina.Presentation.Web/Views/Auth/Register.cshtml new file mode 100644 index 00000000..946594d2 --- /dev/null +++ b/src/Lumina.Presentation.Web/Views/Auth/Register.cshtml @@ -0,0 +1,137 @@ +@* +/auth/register/ +*@ + +@using Lumina.Presentation.Web.Common.Models.UsersManagement +@using Lumina.Presentation.Web.Common.Services + +@{ + string? registrationType = ViewData["RegistrationType"] as string; +} + +@inject IUrlService _urlService + +@model RegisterRequestModel + +
+
+
+ @Html.AntiForgeryToken() + + +
+ @if (registrationType == "Admin") + { +
+

Admin account registration

+
+ } + +
+
+ + *: +
+
+ +
+ DescriptionUsername +
+ +
+
+ + *: +
+
+ +
+ DescriptionPassword +
+ +
+
+ + *: +
+
+ +
+ DescriptionPasswordConfirm +
+ + +
+
+ +
+ Description2Fa +
+
+ +
+
+ +
+
+
+ +
+ + + + +
+
+@section Scripts { + +} diff --git a/src/Lumina.Presentation.Web/Views/Library/Management/Item.cshtml b/src/Lumina.Presentation.Web/Views/Library/Management/Item.cshtml new file mode 100644 index 00000000..62cf43ce --- /dev/null +++ b/src/Lumina.Presentation.Web/Views/Library/Management/Item.cshtml @@ -0,0 +1,130 @@ +@* +/library/manage/item/{id:guid} +*@ + +@using Lumina.Presentation.Web.Common.Models.Libraries + +@{ + var id = Context.Request.RouteValues["id"] as string; +} + +@model LibraryModel + +@await Component.InvokeAsync("FileSystemBrowser") + +
+
+
+ @Html.AntiForgeryToken() + +
+

@(id is not null ? "Edit" : "Add New") Library

+
+
+

General Information

+ +
+
+ + *: +
+
+ +
+ DescriptionTitle +
+ +
+
+ + *: +
+
+
+
+ + +
+
+ +
Book
+
Book
+ +
+
+
+ DescriptionLibraryType +
+ +
+
+ + *: + Add directory +
+
+
+
+ @for (int i = 0; i < Model.Paths.Count; i++) + { +
+ @Model.Paths[i] + Remove +
+ } +
+ DescriptionDirectories +
+
+ +
+
+
+
+@section Scripts { + +} diff --git a/src/Lumina.Presentation.Web/Views/Library/WrittenContentLibrary/BookLibrary/Books/Index.cshtml b/src/Lumina.Presentation.Web/Views/Library/WrittenContentLibrary/BookLibrary/Books/Index.cshtml new file mode 100644 index 00000000..82e19b96 --- /dev/null +++ b/src/Lumina.Presentation.Web/Views/Library/WrittenContentLibrary/BookLibrary/Books/Index.cshtml @@ -0,0 +1,2 @@ + +

All books

one diff --git a/src/Lumina.Presentation.Web/Views/Library/WrittenContentLibrary/BookLibrary/Books/Item.cshtml b/src/Lumina.Presentation.Web/Views/Library/WrittenContentLibrary/BookLibrary/Books/Item.cshtml new file mode 100644 index 00000000..a25adbc1 --- /dev/null +++ b/src/Lumina.Presentation.Web/Views/Library/WrittenContentLibrary/BookLibrary/Books/Item.cshtml @@ -0,0 +1 @@ +

A book

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..2d519483 100644 --- a/src/Lumina.Presentation.Web/Views/Shared/Components/FileSystemBrowser/Default.cshtml +++ b/src/Lumina.Presentation.Web/Views/Shared/Components/FileSystemBrowser/Default.cshtml @@ -3,16 +3,11 @@ @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.UI -@using Lumina.Presentation.Web.Common.Services +@using Lumina.Presentation.Web.Common.Models.FileSystemManagement @using Microsoft.AspNetCore.Components @using System.Text.Json @using System.Text -@inject IApiHttpClient _apiHttpClient -@inject INotificationService _notificationService -
@@ -309,9 +304,9 @@
diff --git a/src/Lumina.Presentation.Web/Views/Shared/_Layout.cshtml b/src/Lumina.Presentation.Web/Views/Shared/_Layout.cshtml index d954e569..6cf12cbf 100644 --- a/src/Lumina.Presentation.Web/Views/Shared/_Layout.cshtml +++ b/src/Lumina.Presentation.Web/Views/Shared/_Layout.cshtml @@ -1,36 +1,51 @@ - - - - @ViewData["Title"] - Lumina - - - - - - - - - - - - -
-
- @await Html.PartialAsync("_NavMenu") -
-
-
- @RenderBody() -
-
-
- - + + + + @ViewData["Title"] - Lumina + + + + + + + + + + + + +
+
+ @await Html.PartialAsync("_NavMenu") +
+
+
+ @RenderBody() +
+
+
+ @if (User?.Identity?.IsAuthenticated == true) - - - @await RenderSectionAsync("Scripts", required: false) - + { + + + } +
+ + + + + + @await RenderSectionAsync("Scripts", required: false) + diff --git a/src/Lumina.Presentation.Web/Views/Shared/_Layout.cshtml.css b/src/Lumina.Presentation.Web/Views/Shared/_Layout.cshtml.css deleted file mode 100644 index c187c02e..00000000 --- a/src/Lumina.Presentation.Web/Views/Shared/_Layout.cshtml.css +++ /dev/null @@ -1,48 +0,0 @@ -/* Please see documentation at https://learn.microsoft.com/aspnet/core/client-side/bundling-and-minification -for details on configuring this project to bundle and minify static web assets. */ - -a.navbar-brand { - white-space: normal; - text-align: center; - word-break: break-all; -} - -a { - color: #0077cc; -} - -.btn-primary { - color: #fff; - background-color: #1b6ec2; - border-color: #1861ac; -} - -.nav-pills .nav-link.active, .nav-pills .show > .nav-link { - color: #fff; - background-color: #1b6ec2; - border-color: #1861ac; -} - -.border-top { - border-top: 1px solid #e5e5e5; -} -.border-bottom { - border-bottom: 1px solid #e5e5e5; -} - -.box-shadow { - box-shadow: 0 .25rem .75rem rgba(0, 0, 0, .05); -} - -button.accept-policy { - font-size: 1rem; - line-height: inherit; -} - -.footer { - position: absolute; - bottom: 0; - width: 100%; - white-space: nowrap; - line-height: 60px; -} diff --git a/src/Lumina.Presentation.Web/Views/Shared/_NavMenu.cshtml b/src/Lumina.Presentation.Web/Views/Shared/_NavMenu.cshtml index 362d39a6..09d5b8e8 100644 --- a/src/Lumina.Presentation.Web/Views/Shared/_NavMenu.cshtml +++ b/src/Lumina.Presentation.Web/Views/Shared/_NavMenu.cshtml @@ -1,3 +1,7 @@ +@using Lumina.Presentation.Web.Common.Services + +@inject IUrlService _urlService +
-
- Tools -
- -
- Library -
- -
- Written Content -
- -
- Audio -
- -
- Video -
- + @if (User?.Identity?.IsAuthenticated == true) + { +
+ Tools +
+ +
+ Library +
+ +
+ Written Content +
+ +
+ Audio +
+ +
+ Video +
+ + }
Help
@@ -64,48 +82,62 @@ - -
  • - - - -
  • -
  • - - -
  • + @if (User?.Identity?.IsAuthenticated == true) + { +
  • + + + +
  • +
  • + + + +
  • + }
  • diff --git a/src/Lumina.Presentation.Web/appsettings.json b/src/Lumina.Presentation.Web/appsettings.json index a5da5368..fa4a93cd 100644 --- a/src/Lumina.Presentation.Web/appsettings.json +++ b/src/Lumina.Presentation.Web/appsettings.json @@ -1,8 +1,51 @@ { - "Logging": { - "LogLevel": { + "EncryptionSettings": { + "SecretKey": "" // base64 string + }, + "Serilog": { + "Using": [ "Serilog.Sinks.Console", "Serilog.Sinks.File" ], + "MinimumLevel": { "Default": "Information", - "Microsoft.AspNetCore": "Warning" + "Override": { + "Microsoft": "Warning", + "System": "Warning", + "Microsoft.AspNetCore": "Warning", + "Microsoft.Hosting.Lifetime": "Information", + "Microsoft.AspNetCore.Mvc.Razor": "Error", + "Microsoft.AspNetCore.Mvc.RazorPages": "Error" + } + }, + "WriteTo": [ + { + "Name": "Console", + "Args": { + "theme": "Serilog.Sinks.SystemConsole.Themes.AnsiConsoleTheme::Literate, Serilog.Sinks.Console", + "outputTemplate": "[{Timestamp:HH:mm:ss} {Level:u3}] {Message:lj}{NewLine}{Exception}" + } + }, + { + "Name": "File", + "Args": { + "path": "%LOG_PATH%lumina_web_.log", + "rollingInterval": "Day", + "outputTemplate": "{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz} [{Level:u3}] {Message:lj}{NewLine}{Exception}", + "retainedFileCountLimit": 7, + "fileSizeLimitBytes": 10485760, + "rollOnFileSizeLimit": true, + "shared": true, + "flushToDiskInterval": "00:00:01" + } + } + ], + "Enrich": [ + "FromLogContext", + "WithMachineName", + "WithThreadId", + "WithEnvironmentName", + "WithRequestId" + ], + "Properties": { + "Application": "LuminaWeb" } }, "AllowedHosts": "*", diff --git a/src/Lumina.Presentation.Web/wwwroot/css/checkbox.css b/src/Lumina.Presentation.Web/wwwroot/css/checkbox.css index f0eb9f70..fe31c67a 100644 --- a/src/Lumina.Presentation.Web/wwwroot/css/checkbox.css +++ b/src/Lumina.Presentation.Web/wwwroot/css/checkbox.css @@ -1,6 +1,36 @@ -namespace Lumina.Presentation.Web.wwwroot.css -{ - public class checkbox - { - } +/* Basic styles for the label and the hidden checkbox */ +.enlightenment-checkbox-label { + display: flex; + align-items: center; + cursor: pointer; + font-size: 14px; + color: #6DCBFE; + user-select: none; +} + +.enlightenment-checkbox-hidden { + display: none; +} + +/* Custom checkbox appearance */ +.enlightenment-checkbox { + width: 14px; + height: 14px; + border-top: #000000 1px solid; + border-bottom: #333333 1px solid; + border-left: #000000 1px solid; + border-right: #333333 1px solid; + border-radius: 0; + margin-right: 10px; + position: relative; + background: linear-gradient(to bottom, #111, #222 50%, #333); +} + +/* Update the custom checkbox appearance when checked */ +.enlightenment-checkbox-hidden:checked + .enlightenment-checkbox { + background-image: linear-gradient(180deg, #5E5D5D, #505050, #424343); + border-top: #888888 1px solid; + border-bottom: #333333 1px solid; + border-left: #666666 1px solid; + border-right: #444444 1px solid; } diff --git a/src/Lumina.Presentation.Web/wwwroot/css/combobox.css b/src/Lumina.Presentation.Web/wwwroot/css/combobox.css index a0b534ab..4ba1e5e1 100644 --- a/src/Lumina.Presentation.Web/wwwroot/css/combobox.css +++ b/src/Lumina.Presentation.Web/wwwroot/css/combobox.css @@ -10,6 +10,16 @@ display: none; } + .enlightenment-toggle-checkbox:checked + .enlightenment-toggle + .enlightenment-dropdown { + display: block; + } + + .enlightenment-toggle-checkbox:checked + .enlightenment-toggle .enlightenment-arrow { + background-size: 9px 11px; + background-position: 3px -2px; + transform: rotate(90deg); + } + .enlightenment-toggle { display: flex; align-items: center; @@ -44,6 +54,21 @@ background-size: 12px 6px, 3px auto, 100%; } +.enlightenment-arrow { + display: inline-block; + width: 12px; + height: 9px; + background-image: url('data:image/svg+xml;charset=US-ASCII,%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20viewBox%3D%22545%20-32.5%2027.5%2065%22%3E%3Cpath%20fill%3D%22%23FFF%22%20d%3D%22M568.254,-7.43524%20568.159,-7.34277%20567.977,-7.52246%20546.559,-28.9417%20525.484,-28.9417%20549.787,-4.63446%20557.439,3.01532%20557.619,3.19629%20550.067,10.7549%20525.758,35.0583%20546.834,35.0583%20568.254,13.6429%20578.792,3.10254%20568.254,-7.43524z%22%2F%3E%3C%2Fsvg%3E'); + background-size: 10px 9px; + background-repeat: no-repeat; + background-position: 3px -0px; + transition: transform 0.3s ease; +} + +.enlightenment-toggle-checkbox:checked + .enlightenment-toggle .enlightenment-arrow { + transform: rotate(90deg); +} + .enlightenment-selected-text { flex: 1; text-align: right; @@ -66,15 +91,9 @@ border-right: #202020 1px solid; padding: 3px; z-index: 999; - max-height: none; - overflow-y: auto; } - .enlightenment-dropdown > .shine-effect:first-child { - top: -4px; - } - -.enlightenment-item { +.enlightenment-option { display: block; border-left: 1px solid #232323; border-right: 1px solid #777777; @@ -88,32 +107,30 @@ cursor: pointer; } - .enlightenment-item.first-item { + .enlightenment-option.first-option { border-top: 1px solid #232323; margin-top: -1px; } - .enlightenment-item.last-item { + .enlightenment-option.last-option { border-bottom: 1px solid #777777; } - .enlightenment-item.disabled { - color: #AAAAAA; + .enlightenment-option.disabled { + color: #AAAAAA; /* Gray color */ } - .enlightenment-item:hover { + .enlightenment-option:hover { background-image: none; background: linear-gradient(to bottom, #505050, #464646, #404040, #363636); color: #1D8AF9; - box-shadow: inset 1px 0 0 0 #777777, inset -1px 0 0 0 #232323, inset 0 1px 0 0 #989898, inset 0 -1px 0 0 #151515; + box-shadow: inset 1px 0 0 0 #777777, /* left */ + inset -1px 0 0 0 #232323, /* right */ + inset 0 1px 0 0 #989898, /* top */ + inset 0 -1px 0 0 #151515; /* bottom */ } -.enlightenment-combobox.open .enlightenment-dropdown { - display: block; -} - .enlightenment-combobox > .shine-effect:first-child { - top: 1px; opacity: 0; transition: opacity 0.5s; } diff --git a/src/Lumina.Presentation.Web/wwwroot/css/file-system-browser.css b/src/Lumina.Presentation.Web/wwwroot/css/file-system-browser.css index 11516f9f..b48cd133 100644 --- a/src/Lumina.Presentation.Web/wwwroot/css/file-system-browser.css +++ b/src/Lumina.Presentation.Web/wwwroot/css/file-system-browser.css @@ -1,6 +1,6 @@ #file-system-browser-dialog { display: none; - position: absolute; + position: fixed; top: 12.5%; bottom: 12.5%; left: 8%; @@ -893,10 +893,6 @@ div[id^="file-system-browser-file-system-explorer"]:not([id*="container"]) { overflow-y: auto; } - .navigator-dropdown.opened { - display: block; - } - .navigator-option { display: block; border-left: 1px solid #232323; @@ -923,7 +919,7 @@ div[id^="file-system-browser-file-system-explorer"]:not([id*="container"]) { } .navigator-option.disabled { - color: #AAAAAA; /* Gray color */ + color: #AAAAAA; } .navigator-option:hover { @@ -1013,8 +1009,8 @@ div[id^="file-system-browser-file-system-explorer"]:not([id*="container"]) { @media screen and (max-width: 768px) { #file-system-browser-dialog { - top: 0; - bottom: 0; + top: 65px; + bottom: 50px; left: 0; right: 0; } diff --git a/src/Lumina.Presentation.Web/wwwroot/css/navigation-menu.css b/src/Lumina.Presentation.Web/wwwroot/css/navigation-menu.css index bb66b6d8..e43cc73e 100644 --- a/src/Lumina.Presentation.Web/wwwroot/css/navigation-menu.css +++ b/src/Lumina.Presentation.Web/wwwroot/css/navigation-menu.css @@ -29,7 +29,7 @@ width: 46px; height: 46px; display: none; - z-index: 2; + z-index: 999; padding: 5px 0; margin: 0px; font-family: 'Cabin', Sans-serif; @@ -185,6 +185,7 @@ position: fixed; top: 0px; left: 0px; + max-height: 22px; width: 100%; z-index: 900; } diff --git a/src/Lumina.Presentation.Web/wwwroot/css/notification.css b/src/Lumina.Presentation.Web/wwwroot/css/notification.css index f2095ab6..327155d2 100644 --- a/src/Lumina.Presentation.Web/wwwroot/css/notification.css +++ b/src/Lumina.Presentation.Web/wwwroot/css/notification.css @@ -21,7 +21,7 @@ border-right: 1px solid #000 !important; border-bottom: 1px solid #000 !important; box-shadow: 5px 5px 5px var(--shadow-color); - animation: fadeIn 0.3s, fadeOut 0.3s 4.7s; + animation: fadeIn 0.3s, fadeOut 0.3s 9.7s; /* animation for notifications fade out effect */ flex-direction: column; flex-wrap: nowrap; align-items: stretch; @@ -60,7 +60,7 @@ flex-shrink: 0; /* prevent button from shrinking */ } -.shine-effect { +.notification-shine-effect { background: linear-gradient(to right, transparent, #fff, transparent); width: 100%; top: -1px; diff --git a/src/Lumina.Presentation.Web/wwwroot/css/site.css b/src/Lumina.Presentation.Web/wwwroot/css/site.css index 12899d10..bfe39c19 100644 --- a/src/Lumina.Presentation.Web/wwwroot/css/site.css +++ b/src/Lumina.Presentation.Web/wwwroot/css/site.css @@ -7,7 +7,10 @@ --border-color-dark: #000000; --border-color-dialog: #1E90FF; --shadow-color: #000000; + --highlight-color: #383838AA; --text-foreground: #6DCBFE; + --light-row-background: #28292B; + --dark-row-background: #191E21; } html, @@ -45,13 +48,58 @@ body { background-color: #222; min-width: 100%; min-height: 100%; + height: 100%; + position: relative; + display: flex; + flex-direction: column; } main { - padding-top: 20px; + position: fixed; + top: 20px; + bottom: 50px; + width: 100%; + overflow-y: auto; + transition: bottom 1s ease, height 1s ease; } -#modal-background { + main.audio-player-not-shown { + bottom: 0; + } + + main.audio-player-full-height { + bottom: calc(100% - 22px); /* full height minus menu height */ + } + +.audio-player-container { + position: fixed; + bottom: 0; + width: 100%; + height: 50px; + transition: height 1s ease; +} + + .audio-player-container.not-shown { + height: 0px; + } + + .audio-player-container.full-height { + height: calc(100% - 22px); /* full height minus menu height */ + } + +#modal-background-menu { + display: none; + z-index: 998; + position: absolute; + top: 0px; + left: 0px; + min-width: 100%; + min-height: 22px; + background-color: #000000; + opacity: 0.6; +} + +#modal-background-article { display: none; z-index: 998; position: absolute; @@ -101,6 +149,10 @@ main { padding: 10px; } +#audio-player-full-height-toggle, #audio-player-close { + cursor: pointer; +} + .text-light-one { color: #6DCBFE; } @@ -134,6 +186,135 @@ main { .no-underline { text-decoration: none; } + +.form-container { + display: flex; + flex-direction: column; + gap: 0.2rem; +} + +.form-row { + display: flex; + flex-wrap: wrap; + justify-content: flex-end; + align-items: center; + gap: 0.5rem; +} + +.form-row-align-start { + display: flex; + flex-wrap: wrap; + justify-content: flex-start; + align-items: center; + gap: 0.5rem; +} + +.form-label { + flex: 2 0 27%; + min-width: 200px; + display: flex; + align-items: center; +} + +.form-field { + flex: 0 0 70%; + min-width: 0; +} + + .form-field input[type="text"], + .form-field input[type="number"], + .form-field input[type="date"], + .form-field input[type="datetime"], + .form-field input[type="datetime-local"], + .form-field textarea, + .form-field input[type="password"] { + width: 100%; + } + +.form-table { + max-height: 150px; + overflow-y: auto; +} + + .form-table > div:nth-child(even) { + background-color: var(--dark-row-background); + } + + .form-table > div:nth-child(odd) { + background-color: var(--light-row-background); + } + +.form-description { + margin-left: 25px; +} +/* +.text-center { + display: flex; + justify-content: center; + width: 100%; +} +*/ +.invalid-feedback { + flex: 0 0 100%; +} + +.mandatory-field { + color: red; +} + +.engraved-title { + margin: 0px; + font-size: 3rem; + background-color: var(--shadow-color); + background-clip: text; + -webkit-background-clip: text; + color: transparent; + text-shadow: var(--highlight-color) 2px 2px 2px; +} + +.engraved-panel { + background-color: #00000033; + border-radius: 5px; + min-height: 70px; + padding: 10px; + -webkit-box-shadow: 0 0 7px 0px var(--shadow-color) inset; + -moz-box-shadow: 0 0 7px 0px var(--shadow-color) inset; + box-shadow: 0 0 7px 0px var(--shadow-color) inset; + flex: 0 0 70%; +} + +.form-table-row { + padding: 3px 8px; + gap: 8px; + width: 100%; + display: flex; + align-items: center; + /*justify-content: space-between;*/ + border-top: 1px solid var(--border-color-light); + border-left: 1px solid var(--border-color-light); + border-bottom: 1px solid var(--border-color-dark); + border-right: 1px solid var(--border-color-dark); +} + + .form-table-row span { + white-space: nowrap; + overflow: hidden; + text-overflow: ellipsis; + flex: 1; + min-width: 0; + } + +.remove-form-table-row-icon { + width: 15px; + flex-shrink: 0; + cursor: pointer; +} + +.add-form-table-row-icon { + width: 15px; + cursor: pointer; +} + /* Margins */ .mt-0 { margin-top: 0px; @@ -1244,5 +1425,4 @@ main { /* For desktop: */ @media only screen and (min-width: 768px) { - } diff --git a/src/Lumina.Presentation.Web/wwwroot/css/textbox.css b/src/Lumina.Presentation.Web/wwwroot/css/textbox.css index 941d7f34..670e88a0 100644 --- a/src/Lumina.Presentation.Web/wwwroot/css/textbox.css +++ b/src/Lumina.Presentation.Web/wwwroot/css/textbox.css @@ -52,5 +52,5 @@ } textarea { - resize: none; + resize: vertical; } diff --git a/src/Lumina.Presentation.Web/wwwroot/images/ui/add-directory.svg b/src/Lumina.Presentation.Web/wwwroot/images/ui/add-directory.svg new file mode 100644 index 00000000..2408e1fc --- /dev/null +++ b/src/Lumina.Presentation.Web/wwwroot/images/ui/add-directory.svg @@ -0,0 +1,4 @@ + + + + diff --git a/src/Lumina.Presentation.Web/wwwroot/images/ui/delete.svg b/src/Lumina.Presentation.Web/wwwroot/images/ui/delete.svg new file mode 100644 index 00000000..7f51a9dd --- /dev/null +++ b/src/Lumina.Presentation.Web/wwwroot/images/ui/delete.svg @@ -0,0 +1,2 @@ + + diff --git a/src/Lumina.Presentation.Web/wwwroot/js/file-system-browser-dialog.js b/src/Lumina.Presentation.Web/wwwroot/js/file-system-browser-dialog.js index 1d48f684..ce9ba6ea 100644 --- a/src/Lumina.Presentation.Web/wwwroot/js/file-system-browser-dialog.js +++ b/src/Lumina.Presentation.Web/wwwroot/js/file-system-browser-dialog.js @@ -2,10 +2,13 @@ //| DOM Elements | //+======================================================================================+ -const modalBackground = document.getElementById('modal-background'); +const modalBackgroundMenu = document.getElementById('modal-background-menu'); +const modalBackgroundArticle = document.getElementById('modal-background-article'); const fileSystemBrowserDialog = document.getElementById('file-system-browser-dialog'); const fileSystemBrowserTreeview = document.getElementById('file-system-browser-treeview'); const pathSegmentsContainer = document.getElementById('navigator-path-segments'); +const article = document.querySelector('article'); +const menubar = document.getElementsByClassName('menubar')[0]; const fileSystemTreeViewContainer = document.getElementById('file-system-browser-file-system-treeview-container'); const fileSystemExplorerContainer = document.getElementById('file-system-browser-file-system-explorer-container'); @@ -46,6 +49,7 @@ const btnExtraLargeIconsView = document.getElementById('navigator-extra-large-ic const btnFileSystemBrowserEditPath = document.getElementById('navigator-edit-path-button'); const btnFileSystemBrowserSubmitPath = document.getElementById('navigator-navigate-button'); const btnFileSystemBrowserConfirm = document.getElementById('file-system-browser-confirm-button'); +const btnFileSystemBrowserCancel = document.getElementById('file-system-browser-cancel-button'); const selectedFileSystemElementsInput = document.getElementById('file-system-browser-selected-element'); @@ -177,18 +181,17 @@ async function initFileSystemBrowser(serverBasePathValue, clientBasePathValue, i addHorizontalScrolling(addressBar); //switchViewMode('list', null, true); switchViewMode(viewModeValue, viewModeValue === 'list' ? null : iconSizeValue, true); - - // TODO: to be removed: - showFileSystemBrowserDialogAsync(initialPath, true); } /** * Shows the file system browser dialog. */ -async function showFileSystemBrowserDialogAsync(path, showHiddenElementsValue) { +async function showFileSystemBrowserDialogAsync(path, showHiddenElementsValue, includeFilesValue, onConfirmCallback) { if (path !== undefined && path !== null) { showHiddenElements = showHiddenElementsValue; - modalBackground.style.display = 'block'; + includeFiles = includeFilesValue; + modalBackgroundMenu.style.display = 'block'; + modalBackgroundArticle.style.display = 'block'; fileSystemBrowserDialog.style.display = 'block'; if (!path.endsWith(pathSeparator)) path += pathSeparator; @@ -197,6 +200,15 @@ async function showFileSystemBrowserDialogAsync(path, showHiddenElementsValue) { await toggleFileSystemTreeViewAsync(false); await toggleShowFileSystemElementsThumbnailsAsync(false); await navigateToPathAsync(path, false, false); + // add click handler for confirm button + btnFileSystemBrowserConfirm.onclick = function () { + const selectedPaths = selectedFileSystemElementsInput.value; + if (onConfirmCallback && typeof onConfirmCallback === 'function') + onConfirmCallback(selectedPaths); + // hide dialog + hideFileSystemBrowserDialog(); + }; + btnFileSystemBrowserCancel.onclick = hideFileSystemBrowserDialog; } else notificationService.Show("Path cannot be null!", NotificationType.ERROR); // TODO: should ask error message from server when translation is implemented } @@ -205,8 +217,9 @@ async function showFileSystemBrowserDialogAsync(path, showHiddenElementsValue) { * Hides the file system browser dialog. */ function hideFileSystemBrowserDialog() { - modalBackground.style.display = 'block'; - fileSystemBrowserDialog.style.display = 'block'; + modalBackgroundMenu.style.display = 'none'; + modalBackgroundArticle.style.display = 'none'; + fileSystemBrowserDialog.style.display = 'none'; } /** @@ -436,7 +449,7 @@ async function handlePathSegmentComboboxChangeAsync(e) { // fetch directory data for the path try { - await streamFileSystemDirectoriesAsync(pathValue, (parsedItem) => { + await fetchFileSystemDirectoriesAsync(pathValue, (parsedItem) => { addDirectoryOption(dropdown, pathValue, parsedItem.name, async () => { const newPath = pathValue + (!pathValue.endsWith(pathSeparator) ? pathSeparator : '') + parsedItem.name + pathSeparator; addressBarInput.value = newPath; @@ -678,8 +691,8 @@ async function loadFileSystemTreeViewChildNodesAsync(parentNode, path) { childNodes.innerHTML = ''; try { showBusyIndicator(); - // stream directory information and create nodes for each - await streamFileSystemDirectoriesAsync(path, (dir) => { + // fetch directory information and create nodes for each + await fetchFileSystemDirectoriesAsync(path, (dir) => { dir.itemType = 'Directory'; const dirNode = createFileSystemTreeViewTreeNode(dir); childNodes.appendChild(dirNode); @@ -693,85 +706,41 @@ async function loadFileSystemTreeViewChildNodesAsync(parentNode, path) { } /** - * Streams directory information from the server for a given path. + * Fetches directory information from the server for a given path. * @param {string} path - The path to get directories from. * @param {Function} callback - Function to call for each directory received. */ -async function streamFileSystemDirectoriesAsync(path, callback) { - await streamJsonDataAsync(`${clientBasePath}directories/get-directories?path=${encodeURIComponent(path)}&includeHiddenElements=${showHiddenElements}`, callback, 'Directory'); +async function fetchFileSystemDirectoriesAsync(path, callback) { + await fetchJsonDataAsync(`${clientBasePath}directories/get-directories?path=${encodeURIComponent(path)}&includeHiddenElements=${showHiddenElements}`, callback, 'Directory'); } /** - * Streams file information from the server for a given path. + * Fetches file information from the server for a given path. * @param {string} path - The path to get files from. * @param {Function} callback - Function to call for each file received. */ -async function streamFileSystemFilesAsync(path, callback) { - await streamJsonDataAsync(`${clientBasePath}files/get-tree-files?path=${encodeURIComponent(path)}&includeHiddenElements=${showHiddenElements}`, callback, 'File'); +async function fetchFileSystemFilesAsync(path, callback) { + await fetchJsonDataAsync(`${clientBasePath}files/get-tree-files?path=${encodeURIComponent(path)}&includeHiddenElements=${showHiddenElements}`, callback, 'File'); } /** - * Streams JSON data from a given URL and processes it item by item. - * This function handles potentially large datasets by processing the data as it arrives, - * rather than waiting for the entire response to load. + * Fetches and processes JSON data from a given URL. + * This function handles the data by processing all items in the response.data array + * and passing them through the callback function. * * @param {string} url - The URL to fetch JSON data from. * @param {Function} callback - Function to call for each processed item. * @param {string} itemType - Type of item being processed ('File' or 'Directory'). */ -async function streamJsonDataAsync(url, callback, itemType) { - // initiate the fetch request from the API - const response = await fetch(url); - // get a reader for the response body stream - const reader = response.body.getReader(); - // create a decoder to convert the incoming byte stream to text - const decoder = new TextDecoder(); - let buffer = ''; // buffer to hold incoming data that hasn't been fully processed yet - // function to process the buffer and extract complete JSON objects - function processBuffer() { - let startIndex = 0; - let endIndex; - // look for complete JSON objects (ending with '},') - while ((endIndex = buffer.indexOf('},', startIndex)) !== -1) { - // extract a single JSON object - let itemJson = buffer.substring(startIndex, endIndex + 1); - // remove leading comma if present (from array structure) - if (itemJson.startsWith(',')) itemJson = itemJson.substring(1); - // remove surrounding square brackets (array indicators) - itemJson = itemJson.replace(/^\[|\]$/g, ''); - // parse the JSON string into an object - var item = JSON.parse(itemJson); - // manually specify he type of to the parsed object +async function fetchJsonDataAsync(url, callback, itemType) { + const response = await callApiGetAsync(url); + if (response !== undefined) { + // process each item in the response.data array + for (let item of response) { + // manually specify the type to the parsed object item.itemType = itemType; // call the provided callback function with the processed item callback(item); - // move the start index to the beginning of the next item - startIndex = endIndex + 2; - } - // keep any incomplete JSON data in the buffer for the next processing cycle - buffer = buffer.slice(startIndex); - } - // main loop to read the stream - while (true) { - // read a chunk from the stream - const { done, value } = await reader.read(); - // if the stream is finished, break the loop - if (done) - break; - // decode the chunk and add it to the buffer - buffer += decoder.decode(value, { stream: true }); - // process the updated buffer - processBuffer(); - } - // process any remaining data in the buffer after the stream is complete - if (buffer.trim()) { - let finalJson = buffer.trim(); - if (finalJson.startsWith(',')) finalJson = finalJson.substring(1); - finalJson = finalJson.replace(/^\[|\]$/g, ''); - if (finalJson !== '') { - var item = JSON.parse(finalJson); - item.itemType = itemType; - callback(item); } } } @@ -844,8 +813,8 @@ async function getFileSystemItemsAsync(path) { try { showBusyIndicator(); - // stream file system items and create explorer items for each - await streamFileSystemItemsAsync(path, (item) => { + // fetch file system items and create explorer items for each + await fetchFileSystemItemsAsync(path, (item) => { const newItem = createFileSystemExplorerItem(item); fileSystemExplorer.appendChild(newItem); }); @@ -858,13 +827,14 @@ async function getFileSystemItemsAsync(path) { } /** - * Streams both directories and files from a specified path. - * @param {string} path - The file system path to stream items from. + * Fetches both directories and files from a specified path. + * @param {string} path - The file system path to fetch items from. * @param {Function} callback - Function to call for each item (directory or file) received. */ -async function streamFileSystemItemsAsync(path, callback) { - await streamFileSystemDirectoriesAsync(path, callback); - await streamFileSystemFilesAsync(path, callback); +async function fetchFileSystemItemsAsync(path, callback) { + await fetchFileSystemDirectoriesAsync(path, callback); + if (includeFiles) + await fetchFileSystemFilesAsync(path, callback); } /** @@ -1112,16 +1082,16 @@ function startSelection(e) { document.body.style.overflowY = 'hidden'; // needed in order to not put a vertical scrollbar on the document, while in vertical layout selection document.documentElement.style.overflowY = 'hidden'; selectionStartPosition.x = e.pageX + fileSystemExplorer.scrollLeft; - selectionStartPosition.y = e.pageY + fileSystemExplorerContainer.scrollTop; // not a mistake - in vertical mode, this is the overflow container! + selectionStartPosition.y = (e.pageY - parseInt(window.getComputedStyle(menubar).height)) + fileSystemExplorerContainer.scrollTop; // not a mistake - in vertical mode, this is the overflow container! // place the selection rectangle at the clicked location (relative to the whole page, and taking into account scroll offset), with 0 size visibleSelectionRectangle.style.left = e.pageX + 'px'; - visibleSelectionRectangle.style.top = e.pageY + 'px'; + visibleSelectionRectangle.style.top = (e.pageY - parseInt(window.getComputedStyle(menubar).height)) + 'px'; visibleSelectionRectangle.style.width = '0px'; visibleSelectionRectangle.style.height = '0px'; visibleSelectionRectangle.style.visibility = 'visible'; selectionRectangle.style.left = e.pageX + 'px'; - selectionRectangle.style.top = e.pageY + 'px'; + selectionRectangle.style.top = (e.pageY - parseInt(window.getComputedStyle(menubar).height)) + 'px'; selectionRectangle.style.width = '0px'; selectionRectangle.style.height = '0px'; } @@ -1134,7 +1104,7 @@ function updateSelection(e) { if (!isSelecting) return; currentMousePosition.x = e.pageX; - currentMousePosition.y = e.pageY; + currentMousePosition.y = e.pageY - parseInt(window.getComputedStyle(menubar).height); handleSelection(); } @@ -1225,10 +1195,10 @@ function handleSelection() { if (right > containerRect.right) visibleSelectionRectangle.style.width = (containerRect.right - left) + 'px'; - if (top < containerRect.top) { - const difference = containerRect.top - top; + if (top < containerRect.top - parseInt(window.getComputedStyle(menubar).height)) { + const difference = containerRect.top - top - parseInt(window.getComputedStyle(menubar).height); visibleSelectionRectangle.style.height = (parseFloat(visibleSelectionRectangle.style.height) - difference) + 'px'; - visibleSelectionRectangle.style.top = containerRect.top + 'px'; + visibleSelectionRectangle.style.top = (containerRect.top - parseInt(window.getComputedStyle(menubar).height)) + 'px'; } if (bottom > containerRect.bottom) visibleSelectionRectangle.style.height = (containerRect.bottom - top) + 'px'; @@ -1509,18 +1479,6 @@ async function toggleShowFileSystemElementsThumbnailsAsync(isManualSet) { } } -/** - * Closes all comboboxes except for the one passed as an argument. - * @param {HTMLElement} exceptionCheckbox - The checkbox of the combobox that should remain open. - */ -function closeAllComboboxesExcept(exceptionCheckbox) { - const checkedCheckboxes = document.querySelectorAll('.enlightenment-toggle-checkbox:checked, .navigator-toggle-checkbox:checked'); - checkedCheckboxes.forEach(function (checkbox) { - if (!exceptionCheckbox || checkbox.id !== exceptionCheckbox.id) - checkbox.checked = false; - }); -} - /** * Gets the icon of the node, based on it type. * @param {any} node The node for which to get the icon. @@ -1618,79 +1576,6 @@ addressBar.addEventListener('click', function (e) { } }); -/** - * Detects changes on any combobox checkbox. If a combobox is opened, this will ensure all other comboboxes are closed. - */ -document.addEventListener('change', function (e) { - if (e.target.matches('.enlightenment-toggle-checkbox, .navigator-toggle-checkbox')) - if (e.target.checked) - closeAllComboboxesExcept(e.target); -}); - -/** - * Event handler for when an option in the combobox is clicked. - * This updates the displayed value of the combobox to the clicked option and closes the dropdown. - */ -document.addEventListener('click', function (e) { - if (e.target.matches('.enlightenment-option')) { - var text = e.target.textContent; - var combobox = e.target.closest('.enlightenment-combobox'); - - var selectedText = combobox.querySelector('.enlightenment-selected-text'); - if (selectedText) - selectedText.textContent = text; - - var toggleCheckbox = combobox.querySelector('.enlightenment-toggle-checkbox'); - if (toggleCheckbox) - toggleCheckbox.checked = false; - } -}); - -/** - * Global click event for the entire document. Closes all combobox dropdowns if the clicked target is outside any combobox. - */ -document.addEventListener('click', function (e) { - // enlightenment combobox logic - if (!e.target.closest('.enlightenment-combobox')) { - const checkbox = document.querySelector('.enlightenment-toggle-checkbox:checked'); - if (checkbox) - checkbox.checked = false; - } - // navigator combobox logic - if (!e.target.closest('.navigator-combobox') && addressBar) { - const checkbox = document.querySelector('.navigator-toggle-checkbox:checked'); - if (checkbox) - checkbox.checked = false; - // when drop down closes, hide address bar overflow - addressBar.style.overflowX = 'auto'; - addressBar.style.overflowY = 'hidden'; - reattachDropdown(); - } -}); - -/** - * Event handler for navigation combobox drop down item clicks. - */ -document.addEventListener("click", function (e) { - if (e.target.matches('.navigator-option')) { - // the address bar drop downs may be destroyed when an option is clicked - they are regenerated each time anyway - addressBar.removeEventListener('scroll', adjustDropdownPosition); - - var parentElement = e.target.parentElement; - if (parentElement) - parentElement.remove(); - } -}); - -/** - * Prevents the global document click event from propagating when clicking on a combobox. - * This ensures the dropdown doesn't close unintentionally. - */ -document.addEventListener('click', function (e) { - if (e.target.closest('.enlightenment-combobox, .navigator-combobox')) - e.stopPropagation(); -}); - /** * Handles the window resize event. */ diff --git a/src/Lumina.Presentation.Web/wwwroot/js/notifications.js b/src/Lumina.Presentation.Web/wwwroot/js/notifications.js index 656ea76b..94072232 100644 --- a/src/Lumina.Presentation.Web/wwwroot/js/notifications.js +++ b/src/Lumina.Presentation.Web/wwwroot/js/notifications.js @@ -62,8 +62,8 @@ class NotificationService { else console.log(message); - // set a timeout to remove the notification after 5 seconds - setTimeout(() => this.removeNotification(notification.id), 5000); + // set a timeout to remove the notification after 10 seconds (fading out effect is handled in notification.css) + setTimeout(() => this.removeNotification(notification.id), 10000); } /** @@ -75,9 +75,8 @@ class NotificationService { if (index !== -1) { this.notifications.splice(index, 1); const element = document.getElementById(`notification-${id}`); - if (element) { + if (element) element.remove(); - } } } @@ -93,7 +92,7 @@ class NotificationService { notificationElement.id = `notification-${notification.id}`; notificationElement.className = `notification ${notification.type}`; notificationElement.innerHTML = ` -
    +
    ${notification.message} diff --git a/src/Lumina.Presentation.Web/wwwroot/js/site.js b/src/Lumina.Presentation.Web/wwwroot/js/site.js index 7ff86336..780b08d1 100644 --- a/src/Lumina.Presentation.Web/wwwroot/js/site.js +++ b/src/Lumina.Presentation.Web/wwwroot/js/site.js @@ -4,8 +4,8 @@ const progressIndicator = document.getElementById('progress-indicator'); const progressIndicatorValue = document.getElementById('progress-indicator-value'); const progressIndicatorValueShadow = document.getElementById('progress-indicator-value-shadow'); const progressIndicatorValueText = document.getElementById('progress-indicator-value-text'); - - +const audioPlayerFullHeightToggle = document.getElementById('audio-player-full-height-toggle'); +const audioPlayerClose = document.getElementById('audio-player-close'); let enableConsoleDebugMessages = false; // whether to display debug messages at the developer console, or not @@ -25,6 +25,8 @@ async function callApiGetAsync(url) { try { // create the URL for the API endpoint const response = await fetch(url); // call the API + if (response.redirected) // if a redirect is requested, perform it + window.location.href = response.url; if (!response.ok) throw new Error('Network response was not ok'); const jsonResponse = await response.json(); @@ -38,6 +40,157 @@ async function callApiGetAsync(url) { } } +/** + * Performs a POST request to the specified API endpoint. + * @param {string} url - The API endpoint URL. + * @param {Object} data - The data to send in the request body. + * @param {Object} [options] - Additional options for the request. + * @param {boolean} [options.useAntiForgery=true] - Whether to include anti-forgery token. + * @param {Object} [options.headers] - Additional headers to include. + * @returns {Promise} The response data if successful, undefined otherwise. + */ +async function callApiPostAsync(url, data, options = {}) { + const defaultOptions = { + useAntiForgery: true, + headers: {} + }; + const finalOptions = { ...defaultOptions, ...options }; + try { + // prepare headers + const headers = { + 'Content-Type': 'application/json', + ...finalOptions.headers + }; + // add anti-forgery token if enabled + if (finalOptions.useAntiForgery) { + const token = document.querySelector('input[name="__RequestVerificationToken"]')?.value; + if (token) + headers['RequestVerificationToken'] = token; + } + // make the request + const response = await fetch(url, { + method: 'POST', + headers: headers, + body: JSON.stringify(data) + }); + if (response.redirected) // if a redirect is requested, perform it + window.location.href = response.url; + if (!response.ok) + throw new Error(`HTTP error! status: ${response.status}`); + const jsonResponse = await response.json(); + if (jsonResponse.success) { + if (jsonResponse.message) + notificationService.show(jsonResponse.message, NotificationType.SUCCESS); + return jsonResponse.data; + } + else + notificationService.show(jsonResponse.errorMessage, NotificationType.ERROR); + } catch (error) { + console.error('Error:', error); + notificationService.show(error, NotificationType.ERROR); + } +} + +//+======================================================================================+ +//| Website navigation | +//+======================================================================================+ + +/** + * Initializes navigation by setting the initial history state, intercepting link clicks, + * and managing back/forward browser actions. + */ +function initializeNavigation() { + // store initial state + const initialState = { + url: window.location.href, + content: document.querySelector('main').innerHTML, + title: document.title + }; + history.replaceState(initialState, document.title, window.location.href); + // initial nav-link binding + bindNavigationLinks(); + + // handle browser back/forward + window.addEventListener('popstate', handlePopState); +} + + +/** + * Binds AJAX navigation behavior to links marked with .nav-link class. + */ +function bindNavigationLinks() { + document.querySelectorAll('.nav-link').forEach(link => { + // only bind if not already bound + if (!link.dataset.boundNavigation) { + link.addEventListener('click', handleNavigation); + link.dataset.boundNavigation = 'true'; + } + }); +} + +/** + * Handles link clicks to navigate dynamically without reloading the page. + * @param {Event} e - The click event for a navigation link. + */ +async function handleNavigation(e) { + e.preventDefault(); + const url = e.target.href; + await updateContent(url, true); +} + +/** + * Restores page content and title when navigating with browser back/forward buttons. + * @param {PopStateEvent} e - The popstate event with previous state data. + */ +async function handlePopState(e) { + if (e.state) { + // if we have cached content in state, use it immediately + if (e.state.content) { + document.querySelector('main').innerHTML = e.state.content; + document.title = e.state.title; + } + // still fetch fresh content to ensure it's up to date + await updateContent(e.state.url, false); + } +} + +/** + * Loads new page content and updates the URL and history if required. + * @param {string} url - URL to fetch new content from. + * @param {boolean} addToHistory - Whether to add the new state to history. + */ +async function updateContent(url, addToHistory) { + try { + const response = await fetch(url); + const html = await response.text(); + + // parse the new content + const parser = new DOMParser(); + const doc = parser.parseFromString(html, 'text/html'); + const content = doc.querySelector('main').innerHTML; + const title = doc.querySelector('title')?.textContent || document.title; + + // update the page + document.querySelector('main').innerHTML = content; + document.title = title; + + // bind navigation links in the new content + bindNavigationLinks(); + + // save to history if needed + if (addToHistory) { + const state = { + url: url, + content: content, + title: title + }; + history.pushState(state, title, url); + } + } catch (error) { + console.error('Navigation failed:', error); + } +} + //+======================================================================================+ //| Common Helper Functions | //+======================================================================================+ @@ -47,7 +200,7 @@ async function callApiGetAsync(url) { */ function showBusyIndicator() { //if (ajaxCallCounter === 0) - //progressIndicator.classList.remove('hidden'); + //progressIndicator.classList.remove('hidden'); ajaxCallCounter++; } @@ -57,7 +210,7 @@ function showBusyIndicator() { function hideBusyIndicator() { ajaxCallCounter--; //if (ajaxCallCounter === 0) - //progressIndicator.classList.add('hidden'); + //progressIndicator.classList.add('hidden'); } /** @@ -192,11 +345,11 @@ const scrollHandler = function (event) { */ function addHorizontalScrolling(idOrElement) { let element = idOrElement; - if (typeof idOrElement === 'string') + if (typeof idOrElement === 'string') element = document.getElementById(idOrElement); - if (element instanceof HTMLElement) + if (element instanceof HTMLElement) element.addEventListener('wheel', scrollHandler, { passive: false }); - else + else console.error('Invalid input: Expected an element ID or HTMLElement'); } @@ -206,11 +359,11 @@ function addHorizontalScrolling(idOrElement) { */ function removeHorizontalScrolling(idOrElement) { let element = idOrElement; - if (typeof idOrElement === 'string') + if (typeof idOrElement === 'string') element = document.getElementById(idOrElement); - if (element instanceof HTMLElement) + if (element instanceof HTMLElement) element.removeEventListener('wheel', scrollHandler, { passive: false }); - else + else console.error('Invalid input: Expected an element ID or HTMLElement'); } @@ -237,3 +390,122 @@ function getElementOffset(id) { height: 0 }; } + +document.querySelectorAll('.remove-form-table-row-icon').forEach(icon => { + icon.addEventListener('click', function () { + this.parentElement.remove(); + }); +}); + +/** + * Toggles the visibility of the audio player. + */ +function toggleAudioPlayerVisibility() { + const playerContainer = document.querySelector('.audio-player-container'); + const contentContainer = document.querySelector('main'); + playerContainer.classList.toggle('not-shown'); + contentContainer.classList.toggle('audio-player-not-shown'); +} + +/** + * Toggles the display of the audio player as collapsed player, or full height player. + */ +function toggleAudioPlayerFullHeight() { + const playerContainer = document.querySelector('.audio-player-container'); + const contentContainer = document.querySelector('main'); + playerContainer.classList.toggle('full-height'); + contentContainer.classList.toggle('audio-player-full-height'); +} + +if (audioPlayerFullHeightToggle) + audioPlayerFullHeightToggle.addEventListener('click', toggleAudioPlayerFullHeight); +if (audioPlayerClose) + audioPlayerClose.addEventListener('click', toggleAudioPlayerVisibility); + + +/** + * Closes all comboboxes except for the one passed as an argument. + * @param {HTMLElement} exceptionCheckbox - The checkbox of the combobox that should remain open. + */ +function closeAllComboboxesExcept(exceptionCheckbox) { + const checkedCheckboxes = document.querySelectorAll('.enlightenment-toggle-checkbox:checked, .navigator-toggle-checkbox:checked'); + checkedCheckboxes.forEach(function (checkbox) { + if (!exceptionCheckbox || checkbox.id !== exceptionCheckbox.id) + checkbox.checked = false; + }); +} + +/** + * Detects changes on any combobox checkbox. If a combobox is opened, this will ensure all other comboboxes are closed. + */ +document.addEventListener('change', function (e) { + if (e.target.matches('.enlightenment-toggle-checkbox, .navigator-toggle-checkbox')) + if (e.target.checked) + closeAllComboboxesExcept(e.target); +}); + +/** + * Event handler for when an option in the combobox is clicked. + * This updates the displayed value of the combobox to the clicked option and closes the dropdown. + */ +document.addEventListener('click', function (e) { + if (e.target.matches('.enlightenment-option')) { + var text = e.target.textContent; + var combobox = e.target.closest('.enlightenment-combobox'); + + var selectedText = combobox.querySelector('.enlightenment-selected-text'); + if (selectedText) + selectedText.textContent = text; + + var toggleCheckbox = combobox.querySelector('.enlightenment-toggle-checkbox'); + if (toggleCheckbox) + toggleCheckbox.checked = false; + } +}); + +/** + * Global click event for the entire document. Closes all combobox dropdowns if the clicked target is outside any combobox. + */ +document.addEventListener('click', function (e) { + // enlightenment combobox logic + if (!e.target.closest('.enlightenment-combobox')) { + const checkbox = document.querySelector('.enlightenment-toggle-checkbox:checked'); + if (checkbox) + checkbox.checked = false; + } + // navigator combobox logic + if (!e.target.closest('.navigator-combobox') && typeof addressBar !== 'undefined' && addressBar !== null) { + const checkbox = document.querySelector('.navigator-toggle-checkbox:checked'); + if (checkbox) + checkbox.checked = false; + // when drop down closes, hide address bar overflow + addressBar.style.overflowX = 'auto'; + addressBar.style.overflowY = 'hidden'; + reattachDropdown(); + } +}); + +/** + * Event handler for navigation combobox drop down item clicks. + */ +document.addEventListener("click", function (e) { + if (e.target.matches('.navigator-option')) { + // the address bar drop downs may be destroyed when an option is clicked - they are regenerated each time anyway + addressBar.removeEventListener('scroll', adjustDropdownPosition); + + var parentElement = e.target.parentElement; + if (parentElement) + parentElement.remove(); + } +}); + +/** + * Prevents the global document click event from propagating when clicking on a combobox. + * This ensures the dropdown doesn't close unintentionally. + */ +document.addEventListener('click', function (e) { + if (e.target.closest('.enlightenment-combobox, .navigator-combobox')) + e.stopPropagation(); +}); + +document.addEventListener('DOMContentLoaded', initializeNavigation); diff --git a/src/Lumina.sln b/src/Lumina.sln index fc1f2199..1f0a285c 100644 --- a/src/Lumina.sln +++ b/src/Lumina.sln @@ -32,6 +32,7 @@ EndProject Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "docs", "docs", "{ACD16983-F1BD-4A92-B282-95BA8C456F6A}" ProjectSection(SolutionItems) = preProject ..\docs\CONTRIBUTING.md = ..\docs\CONTRIBUTING.md + INSTALL.md = INSTALL.md ..\LICENSE.md = ..\LICENSE.md ..\README.md = ..\README.md ..\docs\SOURCES.md = ..\docs\SOURCES.md @@ -47,10 +48,11 @@ 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.FileSystemManagement.md = ..\docs\technical\domain\Aggregates.FileSystemManagement.md ..\docs\technical\domain\Aggregates.VideoLibrary.md = ..\docs\technical\domain\Aggregates.VideoLibrary.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\Domain.md = ..\docs\technical\domain\Domain.md ..\docs\technical\domain\UbiquitousLanguage.md = ..\docs\technical\domain\UbiquitousLanguage.md EndProjectSection EndProject @@ -84,6 +86,10 @@ Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "templates", "templates", "{ EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Lumina.Presentation.Web", "Lumina.Presentation.Web\Lumina.Presentation.Web.csproj", "{613C74E8-720C-4205-8BA7-85B23D2E7881}" EndProject +Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "SecurityTests", "SecurityTests", "{8B06B1D2-80B9-490C-9A36-C7748F58B705}" +EndProject +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Lumina.Presentation.Api.SecurityTests", "..\tests\SecurityTests\Lumina.Presentation.Api.SecurityTests\Lumina.Presentation.Api.SecurityTests.csproj", "{F72DCA2D-0349-42F9-9614-92A38D4B1EA4}" +EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU @@ -150,6 +156,10 @@ Global {613C74E8-720C-4205-8BA7-85B23D2E7881}.Debug|Any CPU.Build.0 = Debug|Any CPU {613C74E8-720C-4205-8BA7-85B23D2E7881}.Release|Any CPU.ActiveCfg = Release|Any CPU {613C74E8-720C-4205-8BA7-85B23D2E7881}.Release|Any CPU.Build.0 = Release|Any CPU + {F72DCA2D-0349-42F9-9614-92A38D4B1EA4}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {F72DCA2D-0349-42F9-9614-92A38D4B1EA4}.Debug|Any CPU.Build.0 = Debug|Any CPU + {F72DCA2D-0349-42F9-9614-92A38D4B1EA4}.Release|Any CPU.ActiveCfg = Release|Any CPU + {F72DCA2D-0349-42F9-9614-92A38D4B1EA4}.Release|Any CPU.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE @@ -177,6 +187,8 @@ Global {6BD85BA8-B3C4-4D79-8858-F6D7676FF2CC} = {3C316ABB-08D5-4450-9A4E-91059DB54254} {A0D07244-9CB2-4E30-85A5-97D520E4B9CC} = {0C0E5A56-AD29-4D0B-AB87-E865F8B933E2} {613C74E8-720C-4205-8BA7-85B23D2E7881} = {3C316ABB-08D5-4450-9A4E-91059DB54254} + {8B06B1D2-80B9-490C-9A36-C7748F58B705} = {16E590D3-DD9F-4B45-BF19-C6E317A57D11} + {F72DCA2D-0349-42F9-9614-92A38D4B1EA4} = {8B06B1D2-80B9-490C-9A36-C7748F58B705} EndGlobalSection GlobalSection(ExtensibilityGlobals) = postSolution SolutionGuid = {4A55A28E-C657-4A0B-95EA-2931AE66004E} diff --git a/src/docker-compose.override.yml b/src/docker-compose.override.yml index e8be593c..e3a748b9 100644 --- a/src/docker-compose.override.yml +++ b/src/docker-compose.override.yml @@ -1,15 +1,33 @@ services: - lumina-server: - container_name: lumina-server + lumina-api: + container_name: lumina-api build: context: . dockerfile: Lumina.Presentation.Api/Dockerfile environment: - ASPNETCORE_ENVIRONMENT=Development - ASPNETCORE_HTTP_PORTS=5214 + - ASPNETCORE_HTTPS_PORTS=7057 ports: - "5214:5214" + - "7057:7057" volumes: - ${APPDATA}/Microsoft/UserSecrets:/home/app/.microsoft/usersecrets:ro - ${APPDATA}/ASP.NET/Https:/home/app/.aspnet/https:ro - command: "dotnet /app/Lumina.Presentation.Api.dll" \ No newline at end of file + command: "dotnet /app/Lumina.Presentation.Api.dll" + lumina-web: + container_name: lumina-web + build: + context: . + dockerfile: Lumina.Presentation.Web/Dockerfile + environment: + - ASPNETCORE_ENVIRONMENT=Development + - ASPNETCORE_HTTP_PORTS=5012 + - ASPNETCORE_HTTPS_PORTS=7112 + ports: + - "5012:5012" + - "7112:7112" + volumes: + - ${APPDATA}/Microsoft/UserSecrets:/home/app/.microsoft/usersecrets:ro + - ${APPDATA}/ASP.NET/Https:/home/app/.aspnet/https:ro + command: "dotnet /app/Lumina.Presentation.Web.dll" diff --git a/src/docker-compose.vs.debug.yml b/src/docker-compose.vs.debug.yml index 341df4e3..45261a83 100644 --- a/src/docker-compose.vs.debug.yml +++ b/src/docker-compose.vs.debug.yml @@ -1,9 +1,15 @@ # this file is required because the default base output path for the projects has been changed, and we need to tell docker compose where to take the files from, in debug mode # this file is the last in the chain of files when docker-compose commands are called, so it always takes precedence services: - lumina-server: + lumina-api: labels: com.microsoft.visualstudio.debuggee.program: "/app/Lumina.Presentation.Api.dll" com.microsoft.visualstudio.debuggee.workingdirectory: "/app" volumes: - - ../bin/server/Debug/net8.0:/app \ No newline at end of file + - ../bin/api/Debug/net8.0:/app + lumina-web: + labels: + com.microsoft.visualstudio.debuggee.program: "/app/Lumina.Presentation.Web.dll" + com.microsoft.visualstudio.debuggee.workingdirectory: "/app" + volumes: + - ../bin/web/Debug/net8.0:/app diff --git a/src/docker-compose.yml b/src/docker-compose.yml index 12f8eaab..10d6ab87 100644 --- a/src/docker-compose.yml +++ b/src/docker-compose.yml @@ -1,7 +1,18 @@ services: - lumina-server: - container_name: lumina-server - image: ${DOCKER_REGISTRY-}lumina-server + lumina-api: + container_name: lumina-api + image: ${DOCKER_REGISTRY-}lumina-api build: context: . dockerfile: Lumina.Presentation.Api/Dockerfile + environment: + - LOG_PATH=/logs + + lumina-web: + container_name: lumina-web + image: ${DOCKER_REGISTRY-}lumina-web + build: + context: . + dockerfile: Lumina.Presentation.Web/Dockerfile + environment: + - LOG_PATH=/logs diff --git a/src/launchSettings.json b/src/launchSettings.json index 9de105e4..5ecb0e98 100644 --- a/src/launchSettings.json +++ b/src/launchSettings.json @@ -4,8 +4,9 @@ "commandName": "DockerCompose", "commandVersion": "1.0", "serviceActions": { - "lumina-server": "StartDebugging" + "lumina-api": "StartDebugging", + "lumina-web": "StartDebugging" } } } -} \ No newline at end of file +} diff --git a/tests/IntegrationTests/Lumina.DataAccess.IntegrationTests/Lumina.DataAccess.IntegrationTests.csproj b/tests/IntegrationTests/Lumina.DataAccess.IntegrationTests/Lumina.DataAccess.IntegrationTests.csproj index 30c4571a..aefdb74d 100644 --- a/tests/IntegrationTests/Lumina.DataAccess.IntegrationTests/Lumina.DataAccess.IntegrationTests.csproj +++ b/tests/IntegrationTests/Lumina.DataAccess.IntegrationTests/Lumina.DataAccess.IntegrationTests.csproj @@ -1,4 +1,4 @@ - + net9.0 @@ -9,6 +9,13 @@ true + + + <_Parameter1>DisableTestParallelization = true + <_Parameter1_IsLiteral>true + + + @@ -16,12 +23,12 @@ 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..e38f0184 100644 --- a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Common/Converters/BookJsonConverter.cs +++ b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Common/Converters/BookJsonConverter.cs @@ -1,11 +1,11 @@ #region ========================================================================= USING ===================================================================================== -using Lumina.Contracts.Enums.BookLibrary; +using Lumina.Domain.Common.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 Lumina.Domain.Core.BoundedContexts.MediaContributorBoundedContext.MediaContributorAggregate.ValueObjects; +using Lumina.Domain.Core.BoundedContexts.WrittenContentLibraryBoundedContext.BookLibraryAggregate; +using Lumina.Domain.Core.BoundedContexts.WrittenContentLibraryBoundedContext.BookLibraryAggregate.Entities; +using Lumina.Domain.Core.BoundedContexts.WrittenContentLibraryBoundedContext.BookLibraryAggregate.ValueObjects; using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; @@ -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/Fixtures/JwtFixture.cs b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Common/Fixtures/JwtFixture.cs new file mode 100644 index 00000000..84a5c625 --- /dev/null +++ b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Common/Fixtures/JwtFixture.cs @@ -0,0 +1,49 @@ +#region ========================================================================= USING ===================================================================================== +using Microsoft.IdentityModel.Tokens; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.IdentityModel.Tokens.Jwt; +using System.Linq; +using System.Security.Claims; +using System.Text; +#endregion + +namespace Lumina.Presentation.Api.IntegrationTests.Common.Fixtures; + +/// +/// Provides JWT token generation functionality for testing purposes. +/// +[ExcludeFromCodeCoverage] +public class JwtFixture +{ + private static readonly string s_secretKey = "test-key-thats-at-least-32-chars-long-for-jwt"; + + /// + /// Generates a JWT token for testing with the specified username and optional roles. + /// + /// The username to include in the token claims. + /// Optional array of roles to include in the token claims. + /// A JWT token string that can be used for authentication in tests. + public static string GenerateJwtToken(string username, string[]? roles = null) + { + byte[] key = Encoding.ASCII.GetBytes(s_secretKey); + List claims = + [ + new(ClaimTypes.Name, username), + new(ClaimTypes.NameIdentifier, username) + ]; + + if (roles?.Length > 0) + claims.AddRange(roles.Select(role => new Claim(ClaimTypes.Role, role))); + + JwtSecurityToken token = new( + issuer: "test-issuer", + audience: "test-audience", + claims: claims, + expires: DateTime.UtcNow.AddHours(1), + signingCredentials: new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature) + ); + return new JwtSecurityTokenHandler().WriteToken(token); + } +} 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..e0890627 100644 --- a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Common/Setup/LuminaApiFactory.cs +++ b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Common/Setup/LuminaApiFactory.cs @@ -1,15 +1,18 @@ #region ========================================================================= USING ===================================================================================== using Lumina.DataAccess.Core.UoW; +using Microsoft.AspNetCore.Authentication.JwtBearer; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Mvc.Testing; using Microsoft.Data.Sqlite; using Microsoft.EntityFrameworkCore; +using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; +using Microsoft.IdentityModel.Tokens; using System; +using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Linq; -using System.Text.Json; -using System.Text.Json.Serialization; +using System.Text; #endregion namespace Lumina.Presentation.Api.IntegrationTests.Common.Setup; @@ -21,6 +24,7 @@ namespace Lumina.Presentation.Api.IntegrationTests.Common.Setup; public class LuminaApiFactory : WebApplicationFactory, IDisposable { private readonly SqliteConnection _connection; + private const string TEST_ENCRYPTION_KEY = "MTIzNDU2Nzg5MDEyMzQ1Njc4OTAxMjM0NTY3ODkwMTI="; /// /// Initializes a new instance of the class. @@ -37,6 +41,22 @@ public class LuminaApiFactory : WebApplicationFactory, IDisposable /// The web host builder to configure. protected override void ConfigureWebHost(IWebHostBuilder builder) { + builder.ConfigureAppConfiguration((context, config) => + { + // clear all existing configuration sources + config.Sources.Clear(); + + config.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true); + config.AddJsonFile($"appsettings.test.json", optional: true, reloadOnChange: true); + config.AddJsonFile("appsettings.shared.json", optional: true, reloadOnChange: true); + config.AddJsonFile($"appsettings.shared.test.json", optional: true, reloadOnChange: true); + // First add the test values directly + config.AddInMemoryCollection(initialData: new Dictionary + { + ["JwtSettings:SecretKey"] = "test-key-thats-at-least-32-chars-long-for-jwt", + ["EncryptionSettings:SecretKey"] = TEST_ENCRYPTION_KEY // base64 encoded test key + }); + }); builder.ConfigureServices(services => { // remove existing DbContext configuration @@ -45,16 +65,30 @@ public class LuminaApiFactory : WebApplicationFactory, IDisposable services.Remove(descriptor); // add SQLite DbContext configuration services.AddDbContext(options => options.UseSqlite(_connection)); + // configure JWT authentication for testing + services.PostConfigure(JwtBearerDefaults.AuthenticationScheme, options => + { + options.TokenValidationParameters = new TokenValidationParameters + { + ValidateIssuer = true, + ValidateAudience = true, + ValidateLifetime = true, + ValidateIssuerSigningKey = true, + ValidIssuer = "test-issuer", + ValidAudience = "test-audience", + IssuerSigningKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes("test-key-thats-at-least-32-chars-long-for-jwt")) + }; + }); // build service provider and ensure database is created ServiceProvider servicePreovider = services.BuildServiceProvider(); using (IServiceScope scope = servicePreovider.CreateScope()) { IServiceProvider scopedServices = scope.ServiceProvider; LuminaDbContext dbContext = scopedServices.GetRequiredService(); - dbContext.Database.EnsureCreated(); + dbContext.Database.Migrate(); } }); - } + } /// /// Disposes the connection to the database. 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/DrivesControllerTests.cs b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Controllers/FileManagement/DrivesControllerTests.cs deleted file mode 100644 index 0506b51e..00000000 --- a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Controllers/FileManagement/DrivesControllerTests.cs +++ /dev/null @@ -1,79 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using FluentAssertions; -using Lumina.Contracts.Enums.FileSystem; -using Lumina.Contracts.Responses.FileManagement; -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; - -/// -/// Contains integration tests for the class. -/// -[ExcludeFromCodeCoverage] -public class DrivesControllerTests : 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 DrivesControllerTests(LuminaApiFactory apiFactory) - { - _client = apiFactory.CreateClient(); - } - - - [Fact] - public async Task GetDrives_WhenCalled_ShouldReturnDrives() - { - // Act - HttpResponseMessage response = await _client.GetAsync($"/api/v1/drives/get-drives"); - - // Assert - response.EnsureSuccessStatusCode(); - response.StatusCode.Should().Be(HttpStatusCode.OK); - - List drives = []; - - 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(); - 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); - } -} 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..3bc59acd --- /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_isUnix = RuntimeInformation.IsOSPlatform(OSPlatform.Linux) || RuntimeInformation.IsOSPlatform(OSPlatform.OSX); + + /// + /// 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_isUnix ? "." : string.Empty) + "NestedDirectory_2"); + firstDirectory.Path.Should().Be(System.IO.Path.Combine(testPath, (s_isUnix ? "." : 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..cd0c8f84 --- /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.Domain.Common.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_isUnix = RuntimeInformation.IsOSPlatform(OSPlatform.Linux) || RuntimeInformation.IsOSPlatform(OSPlatform.OSX); + + /// + /// 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_isUnix) // 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!.Where(node => testPath.StartsWith(node.Name)).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_isUnix) // 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_isUnix ? "." : string.Empty) + "TestFile_1.txt", "TestFile_2.txt"); + } + } + } + } + FileSystemTreeNodeResponse rootNode = treeNodes!.Where(node => testPath.StartsWith(node.Name)).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_isUnix) // 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!.Where(node => testPath.StartsWith(node.Name)).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_isUnix) // 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!.Where(node => testPath.StartsWith(node.Name)).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..eb32d295 --- /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.Domain.Common.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_isUnix = RuntimeInformation.IsOSPlatform(OSPlatform.Linux) || RuntimeInformation.IsOSPlatform(OSPlatform.OSX); + + /// + /// 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_isUnix ? "." : string.Empty) + "NestedDirectory_2"); + firstNode.Path.Should().Be(System.IO.Path.Combine(testPath, (s_isUnix ? "." : 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/Endpoints/FileSystemManagement/Drives/GetDrivesEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/FileSystemManagement/Drives/GetDrivesEndpointTests.cs new file mode 100644 index 00000000..4cc349f2 --- /dev/null +++ b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/FileSystemManagement/Drives/GetDrivesEndpointTests.cs @@ -0,0 +1,65 @@ +#region ========================================================================= USING ===================================================================================== +using FluentAssertions; +using Lumina.Domain.Common.Enums.FileSystem; +using Lumina.Contracts.Responses.FileSystemManagement.Common; +using Lumina.Presentation.Api.IntegrationTests.Common.Setup; +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.Tasks; +#endregion + +namespace Lumina.Presentation.Api.IntegrationTests.Core.Endpoints.FileSystemManagement.Drives; + +/// +/// Contains integration tests for the class. +/// +[ExcludeFromCodeCoverage] +public class GetDrivesEndpointTests : 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_isUnix = RuntimeInformation.IsOSPlatform(OSPlatform.Linux) || RuntimeInformation.IsOSPlatform(OSPlatform.OSX); + + /// + /// Initializes a new instance of the class. + /// + /// Injected in-memory API factory. + public GetDrivesEndpointTests(LuminaApiFactory apiFactory) + { + _client = apiFactory.CreateClient(); + } + + [Fact] + public async Task ExecuteAsync_WhenCalled_ShouldReturnDrives() + { + // Act + HttpResponseMessage response = await _client.GetAsync($"/api/v1/drives/get-drives"); + + // Assert + response.EnsureSuccessStatusCode(); + response.StatusCode.Should().Be(HttpStatusCode.OK); + + string content = await response.Content.ReadAsStringAsync(); + List? drives = JsonSerializer.Deserialize>(content, _jsonOptions); + + drives.Should().NotBeNull(); + drives.Should().NotBeEmpty(); + + FileSystemTreeNodeResponse firstDrive = drives!.First(); + firstDrive.Name.Should().Be(s_isUnix ? "/" : "C:\\"); + firstDrive.Path.Should().Be(s_isUnix ? "/" : "C:\\"); + firstDrive.ItemType.Should().Be(FileSystemItemType.Root); + 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 70% 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..e6941eea 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.Domain.Common.Enums.FileSystem; +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..189d8b77 --- /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_isUnix = RuntimeInformation.IsOSPlatform(OSPlatform.Linux) || RuntimeInformation.IsOSPlatform(OSPlatform.OSX); + + /// + /// 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_isUnix ? "." : string.Empty) + "TestFile_1.txt"); + firstDirectory.Path.Should().Be(System.IO.Path.Combine(testPath, (s_isUnix ? "." : 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..4c2c2f7b --- /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_isUnix = RuntimeInformation.IsOSPlatform(OSPlatform.Linux) || RuntimeInformation.IsOSPlatform(OSPlatform.OSX); + + /// + /// 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_isUnix ? "." : string.Empty) + "TestFile_1.txt"); + firstDirectory.Path.Should().Be(System.IO.Path.Combine(testPath, (s_isUnix ? "." : 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 92% 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..8f4bfc94 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.Domain.Common.Enums.FileSystem; +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..3f1cfec4 --- /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_isUnix = RuntimeInformation.IsOSPlatform(OSPlatform.Linux) || RuntimeInformation.IsOSPlatform(OSPlatform.OSX); + + /// + /// 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_isUnix && 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/Endpoints/Maintenance/ApplicationSetup/CheckInitializationEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Maintenance/ApplicationSetup/CheckInitializationEndpointTests.cs new file mode 100644 index 00000000..f2220547 --- /dev/null +++ b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Maintenance/ApplicationSetup/CheckInitializationEndpointTests.cs @@ -0,0 +1,132 @@ +#region ========================================================================= USING ===================================================================================== +using FluentAssertions; +using Lumina.Application.Common.DataAccess.Entities.UsersManagement; +using Lumina.Contracts.Responses.UsersManagement; +using Lumina.DataAccess.Core.UoW; +using Lumina.Infrastructure.Core.Security; +using Lumina.Presentation.Api.IntegrationTests.Common.Setup; +using Microsoft.Extensions.DependencyInjection; +using System; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +using System.Net; +using System.Net.Http; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Api.IntegrationTests.Core.Endpoints.Maintenance.ApplicationSetup; + +/// +/// Contains integration tests for the class. +/// +[ExcludeFromCodeCoverage] +public class CheckInitializationEndpointTests : IClassFixture, IDisposable +{ + private readonly LuminaApiFactory _apiFactory; + private readonly HttpClient _client; + private readonly JsonSerializerOptions _jsonOptions = new() + { + PropertyNameCaseInsensitive = true, + Converters = { new JsonStringEnumConverter(JsonNamingPolicy.CamelCase) } + }; + private readonly string _testUsername; + + /// + /// Initializes a new instance of the class. + /// + /// Injected in-memory API factory. + public CheckInitializationEndpointTests(LuminaApiFactory apiFactory) + { + _apiFactory = apiFactory; + _client = apiFactory.CreateClient(); + _testUsername = $"testuser_{Guid.NewGuid()}"; + } + + [Fact] + public async Task ExecuteAsync_WhenNoUsersExist_ShouldReturnNotInitialized() + { + // Act + HttpResponseMessage response = await _client.GetAsync("/api/v1/initialization"); + + // Assert + response.EnsureSuccessStatusCode(); + response.StatusCode.Should().Be(HttpStatusCode.OK); + + string content = await response.Content.ReadAsStringAsync(); + InitializationResponse? result = JsonSerializer.Deserialize(content, _jsonOptions); + + result.Should().NotBeNull(); + result!.IsInitialized.Should().BeFalse(); + } + + [Fact] + public async Task ExecuteAsync_WhenUsersExist_ShouldReturnInitialized() + { + // Arrange + await CreateTestUser(); + + // Act + HttpResponseMessage response = await _client.GetAsync("/api/v1/initialization"); + + // Assert + response.EnsureSuccessStatusCode(); + response.StatusCode.Should().Be(HttpStatusCode.OK); + + string content = await response.Content.ReadAsStringAsync(); + InitializationResponse? result = JsonSerializer.Deserialize(content, _jsonOptions); + + result.Should().NotBeNull(); + result!.IsInitialized.Should().BeTrue(); + } + + [Fact] + public async Task ExecuteAsync_WhenCancellationRequested_ShouldThrowTaskCanceledException() + { + // Arrange + using CancellationTokenSource cts = new(); + + // Act + Func act = async () => + { + cts.Cancel(); + await _client.GetAsync("/api/v1/initialization", cts.Token); + }; + + // Assert + await act.Should().ThrowAsync(); + } + + private async Task CreateTestUser() + { + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + + UserEntity user = new() + { + Username = _testUsername, + Password = new HashService().HashString("TestPass123!"), + Libraries = [], + Created = DateTime.UtcNow + }; + + dbContext.Users.Add(user); + await dbContext.SaveChangesAsync(); + return user; + } + + public void Dispose() + { + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + + UserEntity? user = dbContext.Users.FirstOrDefault(u => u.Username == _testUsername); + if (user is not null) + { + dbContext.Users.Remove(user); + dbContext.SaveChanges(); + } + } +} diff --git a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Maintenance/ApplicationSetup/SetupApplicationEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Maintenance/ApplicationSetup/SetupApplicationEndpointTests.cs new file mode 100644 index 00000000..180e5594 --- /dev/null +++ b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Maintenance/ApplicationSetup/SetupApplicationEndpointTests.cs @@ -0,0 +1,187 @@ +#region ========================================================================= USING ===================================================================================== +using FluentAssertions; +using Lumina.Application.Common.DataAccess.Entities.UsersManagement; +using Lumina.Contracts.Requests.Authentication; +using Lumina.Contracts.Responses.Authentication; +using Lumina.DataAccess.Core.UoW; +using Lumina.Infrastructure.Core.Security; +using Lumina.Presentation.Api.IntegrationTests.Common.Setup; +using Microsoft.AspNetCore.Http; +using Microsoft.Extensions.DependencyInjection; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +using System.Net; +using System.Net.Http; +using System.Net.Http.Json; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Api.IntegrationTests.Core.Endpoints.Maintenance.ApplicationSetup; + +/// +/// Contains integration tests for the class. +/// +[ExcludeFromCodeCoverage] +public class SetupApplicationEndpointTests : IClassFixture, IDisposable +{ + private readonly LuminaApiFactory _apiFactory; + private readonly HttpClient _client; + private readonly JsonSerializerOptions _jsonOptions = new() + { + PropertyNameCaseInsensitive = true, + Converters = { new JsonStringEnumConverter(JsonNamingPolicy.CamelCase) } + }; + private readonly string _testUsername; + + /// + /// Initializes a new instance of the class. + /// + /// Injected in-memory API factory. + public SetupApplicationEndpointTests(LuminaApiFactory apiFactory) + { + _apiFactory = apiFactory; + _client = apiFactory.CreateClient(); + _testUsername = $"testuser_{Guid.NewGuid()}"; + } + + [Fact] + public async Task ExecuteAsync_WhenCalledWithValidRequestAnd2FA_ShouldSetupApplicationSuccessfully() + { + // Arrange + RegistrationRequest request = new( + Username: _testUsername, + Password: "TestPass123!", + PasswordConfirm: "TestPass123!", + Use2fa: true + ); + + // Act + HttpResponseMessage response = await _client.PostAsJsonAsync("/api/v1/initialization", request); + + // Assert + response.StatusCode.Should().Be(HttpStatusCode.Created); + string content = await response.Content.ReadAsStringAsync(); + RegistrationResponse? result = JsonSerializer.Deserialize(content, _jsonOptions); + + result.Should().NotBeNull(); + result!.Username.Should().Be(_testUsername); + result.Id.Should().NotBe(Guid.Empty); + result.TotpSecret.Should().NotBeNullOrEmpty(); + result.TotpSecret.Should().StartWith("data:image/png;base64,"); + + response.Headers.Location.Should().NotBeNull(); + response.Headers.Location!.ToString().Should().Be($"http://localhost/api/v1/users/{result.Id}"); + } + + [Fact] + public async Task ExecuteAsync_WhenCalledWithValidRequestWithout2FA_ShouldSetupApplicationSuccessfully() + { + // Arrange + RegistrationRequest request = new( + Username: _testUsername, + Password: "TestPass123!", + PasswordConfirm: "TestPass123!", + Use2fa: false + ); + + // Act + HttpResponseMessage response = await _client.PostAsJsonAsync("/api/v1/initialization", request); + + // Assert + response.StatusCode.Should().Be(HttpStatusCode.Created); + string content = await response.Content.ReadAsStringAsync(); + RegistrationResponse? result = JsonSerializer.Deserialize(content, _jsonOptions); + + result.Should().NotBeNull(); + result!.Username.Should().Be(_testUsername); + result.Id.Should().NotBe(Guid.Empty); + result.TotpSecret.Should().BeNull(); + + response.Headers.Location.Should().NotBeNull(); + response.Headers.Location!.ToString().Should().Be($"http://localhost/api/v1/users/{result.Id}"); + } + + [Fact] + public async Task ExecuteAsync_WhenAdminAccountAlreadyExists_ShouldReturnConflict() + { + // Arrange + await CreateTestUser(); + RegistrationRequest request = new( + Username: "another_admin", + Password: "TestPass123!", + PasswordConfirm: "TestPass123!", + Use2fa: false + ); + + // Act + HttpResponseMessage response = await _client.PostAsJsonAsync("/api/v1/initialization", request); + + // 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["type"].GetString().Should().Be("https://tools.ietf.org/html/rfc9110#section-15.5.4"); + problemDetails["title"].GetString().Should().Be("General.Unauthorized"); + problemDetails["detail"].GetString().Should().Be("AdminAccountAlreadyCreated"); + problemDetails["instance"].GetString().Should().Be("/api/v1/initialization"); + problemDetails["traceId"].GetString().Should().NotBeNullOrWhiteSpace(); + } + + [Fact] + public async Task ExecuteAsync_WhenRequestIsNull_ShouldReturnValidationError() + { + // Arrange + RegistrationRequest? request = null; + + // Act + HttpResponseMessage response = await _client.PostAsJsonAsync("/api/v1/initialization", request); + + // Assert + response.StatusCode.Should().Be(HttpStatusCode.UnprocessableContent); + string content = await response.Content.ReadAsStringAsync(); + + Dictionary? problemDetails = JsonSerializer.Deserialize>(content, _jsonOptions); + problemDetails.Should().NotBeNull(); + Dictionary? errors = problemDetails!["errors"].Deserialize>(_jsonOptions); + errors.Should().ContainKey("General.Validation") + .WhoseValue.Should().Contain(["UsernameCannotBeEmpty", "PasswordCannotBeEmpty", "PasswordConfirmCannotBeEmpty"]); + } + + private async Task CreateTestUser() + { + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + + UserEntity user = new() + { + Username = _testUsername, + Password = new HashService().HashString("TestPass123!"), + Libraries = [], + Created = DateTime.UtcNow + }; + + dbContext.Users.Add(user); + await dbContext.SaveChangesAsync(); + return user; + } + + public void Dispose() + { + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + + UserEntity? user = dbContext.Users.FirstOrDefault(u => u.Username == _testUsername); + if (user is not null) + { + dbContext.Users.Remove(user); + dbContext.SaveChanges(); + } + } +} diff --git a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/UsersManagement/Authentication/ChangePasswordEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/UsersManagement/Authentication/ChangePasswordEndpointTests.cs new file mode 100644 index 00000000..e6cb419c --- /dev/null +++ b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/UsersManagement/Authentication/ChangePasswordEndpointTests.cs @@ -0,0 +1,255 @@ +#region ========================================================================= USING ===================================================================================== +using FluentAssertions; +using Lumina.Application.Common.DataAccess.Entities.UsersManagement; +using Lumina.Contracts.Requests.Authentication; +using Lumina.Contracts.Responses.Authentication; +using Lumina.DataAccess.Core.UoW; +using Lumina.Infrastructure.Core.Security; +using Lumina.Presentation.Api.IntegrationTests.Common.Fixtures; +using Lumina.Presentation.Api.IntegrationTests.Common.Setup; +using Microsoft.AspNetCore.Http; +using Microsoft.Extensions.DependencyInjection; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +using System.Net; +using System.Net.Http; +using System.Net.Http.Headers; +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.UsersManagement.Authentication; + +/// +/// Contains integration tests for the class. +/// +[ExcludeFromCodeCoverage] +public class ChangePasswordEndpointTests : IClassFixture, IDisposable +{ + private readonly HashService _hashService; + private readonly LuminaApiFactory _apiFactory; + private readonly HttpClient _client; + private readonly JsonSerializerOptions _jsonOptions = new() + { + PropertyNameCaseInsensitive = true, + Converters = { new JsonStringEnumConverter(JsonNamingPolicy.CamelCase) } + }; + private readonly string _testUsername; + + /// + /// Initializes a new instance of the class. + /// + /// Injected in-memory API factory. + public ChangePasswordEndpointTests(LuminaApiFactory apiFactory) + { + _apiFactory = apiFactory; + _client = apiFactory.CreateClient(); + _hashService = new HashService(); + _testUsername = $"testuser_{Guid.NewGuid()}"; + + // Set authorization header with unique username + string token = JwtFixture.GenerateJwtToken(_testUsername, ["User"]); + _client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token); + } + + [Fact] + public async Task ExecuteAsync_WhenCalledWithValidRequest_ShouldChangePasswordSuccessfully() + { + // Arrange + UserEntity user = await CreateTestUser(); + ChangePasswordRequest request = new( + Username: user.Username, + CurrentPassword: "OldPass123!", + NewPassword: "NewPass123!", + NewPasswordConfirm: "NewPass123!" + ); + + // Act + HttpResponseMessage response = await _client.PostAsJsonAsync("/api/v1/auth/change-password", request); + + // Assert + response.EnsureSuccessStatusCode(); + response.StatusCode.Should().Be(HttpStatusCode.OK); + + string content = await response.Content.ReadAsStringAsync(); + ChangePasswordResponse? result = JsonSerializer.Deserialize(content, _jsonOptions); + + result.Should().NotBeNull(); + result!.IsPasswordChanged.Should().BeTrue(); + } + + [Fact] + public async Task ExecuteAsync_WhenPasswordsDoNotMatch_ShouldReturnValidationError() + { + // Arrange + UserEntity user = await CreateTestUser(); + ChangePasswordRequest request = new( + Username: user.Username, + CurrentPassword: "OldPass123!", + NewPassword: "NewPass123!", + NewPasswordConfirm: "DifferentPass123!" + ); + + // Act + HttpResponseMessage response = await _client.PostAsJsonAsync("/api/v1/auth/change-password", request); + + // Assert + response.StatusCode.Should().Be(HttpStatusCode.UnprocessableContent); + string content = await response.Content.ReadAsStringAsync(); + + Dictionary? problemDetails = JsonSerializer.Deserialize>(content, _jsonOptions); + problemDetails.Should().NotBeNull(); + problemDetails!["status"].GetInt32().Should().Be(StatusCodes.Status422UnprocessableEntity); + problemDetails["type"].GetString().Should().Be("https://tools.ietf.org/html/rfc4918#section-11.2"); + problemDetails["title"].GetString().Should().Be("Validation Error"); + problemDetails["detail"].GetString().Should().Be("One or more validation errors occurred."); + problemDetails["instance"].GetString().Should().Be("/api/v1/auth/change-password"); + problemDetails["traceId"].GetString().Should().NotBeNullOrWhiteSpace(); + + Dictionary? errors = problemDetails["errors"].Deserialize>(_jsonOptions); + errors.Should().ContainKey("General.Validation").WhoseValue.Should().Contain("PasswordsNotMatch"); + } + + [Fact] + public async Task ExecuteAsync_WhenUserDoesNotExist_ShouldReturnNotFound() + { + // Arrange + ChangePasswordRequest request = new( + Username: "nonexistentuser", + CurrentPassword: "OldPass123!", + NewPassword: "NewPass123!", + NewPasswordConfirm: "NewPass123!" + ); + + // Act + HttpResponseMessage response = await _client.PostAsJsonAsync("/api/v1/auth/change-password", request); + + // Assert + response.StatusCode.Should().Be(HttpStatusCode.NotFound); + string content = await response.Content.ReadAsStringAsync(); + + Dictionary? problemDetails = JsonSerializer.Deserialize>(content, _jsonOptions); + problemDetails.Should().NotBeNull(); + problemDetails!["status"].GetInt32().Should().Be(StatusCodes.Status404NotFound); + problemDetails["type"].GetString().Should().Be("https://tools.ietf.org/html/rfc9110#section-15.5.5"); + problemDetails["title"].GetString().Should().Be("General.NotFound"); + problemDetails["detail"].GetString().Should().Be("UsernameDoesNotExist"); + problemDetails["instance"].GetString().Should().Be("/api/v1/auth/change-password"); + problemDetails["traceId"].GetString().Should().NotBeNullOrWhiteSpace(); + } + + [Fact] + public async Task ExecuteAsync_WhenCurrentPasswordIsIncorrect_ShouldReturnForbidden() + { + // Arrange + UserEntity user = await CreateTestUser(); + ChangePasswordRequest request = new( + Username: user.Username, + CurrentPassword: "WrongPass123!", + NewPassword: "NewPass123!", + NewPasswordConfirm: "NewPass123!" + ); + + // Act + HttpResponseMessage response = await _client.PostAsJsonAsync("/api/v1/auth/change-password", request); + + // 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["type"].GetString().Should().Be("https://tools.ietf.org/html/rfc9110#section-15.5.4"); + problemDetails["title"].GetString().Should().Be("General.Failure"); + problemDetails["detail"].GetString().Should().Be("InvalidCurrentPassword"); + problemDetails["instance"].GetString().Should().Be("/api/v1/auth/change-password"); + problemDetails["traceId"].GetString().Should().NotBeNullOrWhiteSpace(); + } + + [Fact] + public async Task ExecuteAsync_WhenRequestIsNull_ShouldReturnValidationError() + { + // Arrange + ChangePasswordRequest? request = null; + + // Act + HttpResponseMessage response = await _client.PostAsJsonAsync("/api/v1/auth/change-password", request); + + // Assert + response.StatusCode.Should().Be(HttpStatusCode.UnprocessableContent); + string content = await response.Content.ReadAsStringAsync(); + + Dictionary? problemDetails = JsonSerializer.Deserialize>(content, _jsonOptions); + problemDetails.Should().NotBeNull(); + problemDetails!["status"].GetInt32().Should().Be(StatusCodes.Status422UnprocessableEntity); + problemDetails["type"].GetString().Should().Be("https://tools.ietf.org/html/rfc4918#section-11.2"); + problemDetails["title"].GetString().Should().Be("Validation Error"); + problemDetails["detail"].GetString().Should().Be("One or more validation errors occurred."); + problemDetails["instance"].GetString().Should().Be("/api/v1/auth/change-password"); + problemDetails["traceId"].GetString().Should().NotBeNullOrWhiteSpace(); + + Dictionary? errors = problemDetails["errors"].Deserialize>(_jsonOptions); + errors.Should().ContainKey("General.Validation").WhoseValue.Should().Contain(["UsernameCannotBeEmpty", "CurrentPasswordCannotBeEmpty", "NewPasswordCannotBeEmpty", "NewPasswordConfirmCannotBeEmpty"]); + } + + [Fact] + public async Task ExecuteAsync_WhenCancellationRequested_ShouldThrowTaskCanceledException() + { + // Arrange + UserEntity user = await CreateTestUser(); + ChangePasswordRequest request = new( + Username: user.Username, + CurrentPassword: "OldPass123!", + NewPassword: "NewPass123!", + NewPasswordConfirm: "NewPass123!" + ); + using CancellationTokenSource cts = new(); + + // Act + Func act = async () => + { + cts.Cancel(); + await _client.PostAsJsonAsync("/api/v1/auth/change-password", request, cts.Token); + }; + + // Assert + await act.Should().ThrowAsync(); + } + + private async Task CreateTestUser() + { + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + + UserEntity user = new() + { + Username = _testUsername, + Password = _hashService.HashString("OldPass123!"), + Libraries = [], + Created = DateTime.UtcNow + }; + + dbContext.Users.Add(user); + await dbContext.SaveChangesAsync(); + return user; + } + + public void Dispose() + { + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + + UserEntity? user = dbContext.Users.FirstOrDefault(u => u.Username == _testUsername); + if (user is not null) + { + dbContext.Users.Remove(user); + dbContext.SaveChanges(); + } + } +} diff --git a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/UsersManagement/Authentication/LoginEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/UsersManagement/Authentication/LoginEndpointTests.cs new file mode 100644 index 00000000..7f468272 --- /dev/null +++ b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/UsersManagement/Authentication/LoginEndpointTests.cs @@ -0,0 +1,319 @@ +#region ========================================================================= USING ===================================================================================== +using FluentAssertions; +using Lumina.Application.Common.DataAccess.Entities.UsersManagement; +using Lumina.Application.Common.Infrastructure.Security; +using Lumina.Contracts.Requests.Authentication; +using Lumina.Contracts.Responses.Authentication; +using Lumina.DataAccess.Core.UoW; +using Lumina.Infrastructure.Core.Authentication; +using Lumina.Infrastructure.Core.Security; +using Lumina.Presentation.Api.IntegrationTests.Common.Setup; +using Microsoft.AspNetCore.Http; +using Microsoft.Extensions.DependencyInjection; +using OtpNet; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +using System.Net; +using System.Net.Http; +using System.Net.Http.Json; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Api.IntegrationTests.Core.Endpoints.UsersManagement.Authentication; + +/// +/// Contains integration tests for the class. +/// +[ExcludeFromCodeCoverage] +public class LoginEndpointTests : IClassFixture, IDisposable +{ + private readonly HashService _hashService; + private readonly ICryptographyService _cryptographyService; + private readonly TotpTokenGenerator _totpTokenGenerator; + private readonly LuminaApiFactory _apiFactory; + private readonly HttpClient _client; + private readonly JsonSerializerOptions _jsonOptions = new() + { + PropertyNameCaseInsensitive = true, + Converters = { new JsonStringEnumConverter(JsonNamingPolicy.CamelCase) } + }; + private readonly string _testUsername; + + /// + /// Initializes a new instance of the class. + /// + /// Injected in-memory API factory. + public LoginEndpointTests(LuminaApiFactory apiFactory) + { + _apiFactory = apiFactory; + _client = apiFactory.CreateClient(); + _hashService = new HashService(); + _totpTokenGenerator = new TotpTokenGenerator(); + _testUsername = $"testuser_{Guid.NewGuid()}"; + + using IServiceScope scope = apiFactory.Services.CreateScope(); + _cryptographyService = scope.ServiceProvider.GetRequiredService(); + } + + [Fact] + public async Task ExecuteAsync_WhenCalledWithValidCredentials_ShouldLoginSuccessfully() + { + // Arrange + UserEntity user = await CreateTestUser(); + LoginRequest request = new( + Username: user.Username, + Password: "TestPass123!" + ); + + // Act + HttpResponseMessage response = await _client.PostAsJsonAsync("/api/v1/auth/login", request); + + // Assert + response.EnsureSuccessStatusCode(); + response.StatusCode.Should().Be(HttpStatusCode.OK); + + string content = await response.Content.ReadAsStringAsync(); + LoginResponse? result = JsonSerializer.Deserialize(content, _jsonOptions); + + result.Should().NotBeNull(); + result!.Username.Should().Be(user.Username); + result.UsesTotp.Should().BeFalse(); + result.Token.Should().NotBeNullOrEmpty(); + } + + [Fact] + public async Task ExecuteAsync_WhenCalledWithValidCredentialsAndTotp_ShouldLoginSuccessfully() + { + // Arrange + UserEntity user = await CreateTestUserWithTotp(); + byte[] totpSecret = Convert.FromBase64String(_cryptographyService.Decrypt(user.TotpSecret!)); + Totp totp = new(totpSecret); + string validTotpCode = totp.ComputeTotp(DateTime.UtcNow); + + LoginRequest request = new( + Username: user.Username, + Password: "TestPass123!", + TotpCode: validTotpCode + ); + + // Act + HttpResponseMessage response = await _client.PostAsJsonAsync("/api/v1/auth/login", request); + + // Assert + response.EnsureSuccessStatusCode(); + response.StatusCode.Should().Be(HttpStatusCode.OK); + + string content = await response.Content.ReadAsStringAsync(); + LoginResponse? result = JsonSerializer.Deserialize(content, _jsonOptions); + + result.Should().NotBeNull(); + result!.Username.Should().Be(user.Username); + result.UsesTotp.Should().BeTrue(); + result.Token.Should().NotBeNullOrEmpty(); + } + + [Fact] + public async Task ExecuteAsync_WhenCalledWithTempPassword_ShouldLoginSuccessfully() + { + // Arrange + UserEntity user = await CreateTestUserWithTempPassword(); + LoginRequest request = new( + Username: user.Username, + Password: "TempPass123!" + ); + + // Act + HttpResponseMessage response = await _client.PostAsJsonAsync("/api/v1/auth/login", request); + + // Assert + response.EnsureSuccessStatusCode(); + response.StatusCode.Should().Be(HttpStatusCode.OK); + + string content = await response.Content.ReadAsStringAsync(); + LoginResponse? result = JsonSerializer.Deserialize(content, _jsonOptions); + + result.Should().NotBeNull(); + result!.Username.Should().Be(user.Username); + result.Token.Should().NotBeNullOrEmpty(); + } + + [Fact] + public async Task ExecuteAsync_WhenCalledWithExpiredTempPassword_ShouldReturnUnauthorized() + { + // Arrange + UserEntity user = await CreateTestUserWithExpiredTempPassword(); + LoginRequest request = new( + Username: user.Username, + Password: "TempPass123!" + ); + + // Act + HttpResponseMessage response = await _client.PostAsJsonAsync("/api/v1/auth/login", request); + + // 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["type"].GetString().Should().Be("https://tools.ietf.org/html/rfc9110#section-15.5.4"); + problemDetails["title"].GetString().Should().Be("General.Failure"); + problemDetails["detail"].GetString().Should().Be("TempPasswordExpired"); + problemDetails["instance"].GetString().Should().Be("/api/v1/auth/login"); + problemDetails["traceId"].GetString().Should().NotBeNullOrWhiteSpace(); + } + + [Fact] + public async Task ExecuteAsync_WhenCalledWithInvalidCredentials_ShouldReturnUnauthorized() + { + // Arrange + UserEntity user = await CreateTestUser(); + LoginRequest request = new( + Username: user.Username, + Password: "WrongPass123!" + ); + + // Act + HttpResponseMessage response = await _client.PostAsJsonAsync("/api/v1/auth/login", request); + + // 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["type"].GetString().Should().Be("https://tools.ietf.org/html/rfc9110#section-15.5.4"); + problemDetails["title"].GetString().Should().Be("General.Failure"); + problemDetails["detail"].GetString().Should().Be("InvalidUsernameOrPassword"); + problemDetails["instance"].GetString().Should().Be("/api/v1/auth/login"); + problemDetails["traceId"].GetString().Should().NotBeNullOrWhiteSpace(); + } + + [Fact] + public async Task ExecuteAsync_WhenCalledWithInvalidTotpCode_ShouldReturnUnauthorized() + { + // Arrange + UserEntity user = await CreateTestUserWithTotp(); + LoginRequest request = new( + Username: user.Username, + Password: "TestPass123!", + TotpCode: "000000" + ); + + // Act + HttpResponseMessage response = await _client.PostAsJsonAsync("/api/v1/auth/login", request); + + // Assert + response.StatusCode.Should().Be(HttpStatusCode.UnprocessableEntity); + string content = await response.Content.ReadAsStringAsync(); + + Dictionary? problemDetails = JsonSerializer.Deserialize>(content, _jsonOptions); + problemDetails.Should().NotBeNull(); + problemDetails!["status"].GetInt32().Should().Be(StatusCodes.Status422UnprocessableEntity); + problemDetails["type"].GetString().Should().Be("https://tools.ietf.org/html/rfc4918#section-11.2"); + problemDetails["title"].GetString().Should().Be("Validation Error"); + problemDetails["detail"].GetString().Should().Be("One or more validation errors occurred."); + problemDetails["instance"].GetString().Should().Be("/api/v1/auth/login"); + problemDetails["traceId"].GetString().Should().NotBeNullOrWhiteSpace(); + + Dictionary? errors = problemDetails["errors"].Deserialize>(_jsonOptions); + errors.Should().ContainKey("General.Validation").WhoseValue.Should().Contain(["InvalidTotpCode"]); + } + + private async Task CreateTestUser() + { + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + + UserEntity user = new() + { + Username = _testUsername, + Password = _hashService.HashString("TestPass123!"), + Libraries = [], + Created = DateTime.UtcNow + }; + + dbContext.Users.Add(user); + await dbContext.SaveChangesAsync(); + return user; + } + + private async Task CreateTestUserWithTotp() + { + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + + byte[] totpSecret = _totpTokenGenerator.GenerateSecret(); + UserEntity user = new() + { + Username = _testUsername, + Password = _hashService.HashString("TestPass123!"), + TotpSecret = _cryptographyService.Encrypt(Convert.ToBase64String(totpSecret)), + Libraries = [], + Created = DateTime.UtcNow + }; + + dbContext.Users.Add(user); + await dbContext.SaveChangesAsync(); + return user; + } + + private async Task CreateTestUserWithTempPassword() + { + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + + UserEntity user = new() + { + Username = _testUsername, + Password = _hashService.HashString("TestPass123!"), + TempPassword = Uri.EscapeDataString(_hashService.HashString("TempPass123!")), + TempPasswordCreated = DateTime.UtcNow, + Libraries = [], + Created = DateTime.UtcNow + }; + + dbContext.Users.Add(user); + await dbContext.SaveChangesAsync(); + return user; + } + + private async Task CreateTestUserWithExpiredTempPassword() + { + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + + UserEntity user = new() + { + Username = _testUsername, + Password = _hashService.HashString("TestPass123!"), + TempPassword = Uri.EscapeDataString(_hashService.HashString("TempPass123!")), + TempPasswordCreated = DateTime.UtcNow.AddMinutes(-16), // expired (> 15 minutes old) + Libraries = [], + Created = DateTime.UtcNow + }; + + dbContext.Users.Add(user); + await dbContext.SaveChangesAsync(); + return user; + } + + public void Dispose() + { + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + + UserEntity? user = dbContext.Users.FirstOrDefault(u => u.Username == _testUsername); + if (user is not null) + { + dbContext.Users.Remove(user); + dbContext.SaveChanges(); + } + } +} diff --git a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/UsersManagement/Authentication/RecoverPasswordEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/UsersManagement/Authentication/RecoverPasswordEndpointTests.cs new file mode 100644 index 00000000..1b8cc3b7 --- /dev/null +++ b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/UsersManagement/Authentication/RecoverPasswordEndpointTests.cs @@ -0,0 +1,339 @@ +#region ========================================================================= USING ===================================================================================== +using FluentAssertions; +using Lumina.Application.Common.DataAccess.Entities.UsersManagement; +using Lumina.Application.Common.Infrastructure.Security; +using Lumina.Contracts.Requests.Authentication; +using Lumina.Contracts.Responses.Authentication; +using Lumina.DataAccess.Core.UoW; +using Lumina.Infrastructure.Core.Authentication; +using Lumina.Infrastructure.Core.Security; +using Lumina.Presentation.Api.IntegrationTests.Common.Setup; +using Microsoft.AspNetCore.Http; +using Microsoft.EntityFrameworkCore; +using Microsoft.Extensions.DependencyInjection; +using OtpNet; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +using System.Net; +using System.Net.Http; +using System.Net.Http.Json; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Api.IntegrationTests.Core.Endpoints.UsersManagement.Authentication; + +/// +/// Contains integration tests for the class. +/// +[ExcludeFromCodeCoverage] +public class RecoverPasswordEndpointTests : IClassFixture, IDisposable +{ + private readonly HashService _hashService; + private readonly ICryptographyService _cryptographyService; + private readonly TotpTokenGenerator _totpTokenGenerator; + private readonly LuminaApiFactory _apiFactory; + private readonly HttpClient _client; + private readonly JsonSerializerOptions _jsonOptions = new() + { + PropertyNameCaseInsensitive = true, + Converters = { new JsonStringEnumConverter(JsonNamingPolicy.CamelCase) } + }; + private readonly string _testUsername; + + /// + /// Initializes a new instance of the class. + /// + /// Injected in-memory API factory. + public RecoverPasswordEndpointTests(LuminaApiFactory apiFactory) + { + _apiFactory = apiFactory; + _client = apiFactory.CreateClient(); + _hashService = new HashService(); + _totpTokenGenerator = new TotpTokenGenerator(); + _testUsername = $"testuser_{Guid.NewGuid()}"; + + // get the encryption service with the test key from factory + using IServiceScope scope = apiFactory.Services.CreateScope(); + _cryptographyService = scope.ServiceProvider.GetRequiredService(); + } + + [Fact] + public async Task ExecuteAsync_WhenCalledWithValidRequest_ShouldResetPassword() + { + // Arrange + UserEntity user = await CreateUserWithTotp(); + + // decrypt the TOTP secret and generate a valid code + byte[] totpSecret = Convert.FromBase64String(_cryptographyService.Decrypt(user.TotpSecret!)); + Totp totp = new(totpSecret); + string validTotpCode = totp.ComputeTotp(DateTime.UtcNow); + + RecoverPasswordRequest request = new( + Username: user.Username, + TotpCode: validTotpCode + ); + + // Act + HttpResponseMessage response = await _client.PostAsJsonAsync("/api/v1/auth/recover-password", request); + + // Assert + response.EnsureSuccessStatusCode(); + response.StatusCode.Should().Be(HttpStatusCode.OK); + + string content = await response.Content.ReadAsStringAsync(); + RecoverPasswordResponse? result = JsonSerializer.Deserialize(content, _jsonOptions); + + result.Should().NotBeNull(); + result!.IsPasswordReset.Should().BeTrue(); + + // Create a new context to get fresh data + using IServiceScope verificationScope = _apiFactory.Services.CreateScope(); + LuminaDbContext verificationContext = verificationScope.ServiceProvider.GetRequiredService(); + + // Ensure we get fresh data from the database + verificationContext.ChangeTracker.QueryTrackingBehavior = QueryTrackingBehavior.NoTracking; + UserEntity? updatedUser = await verificationContext.Users + .AsNoTracking() + .FirstOrDefaultAsync(u => u.Username == user.Username); + + updatedUser.Should().NotBeNull(); + updatedUser!.TempPassword.Should().NotBeNull(); + updatedUser.TempPasswordCreated.Should().BeCloseTo(DateTime.UtcNow, TimeSpan.FromSeconds(5)); + } + + [Fact] + public async Task ExecuteAsync_WhenUserDoesNotExist_ShouldReturnNotFound() + { + // Arrange + RecoverPasswordRequest request = new( + Username: "nonexistentuser", + TotpCode: "123456" + ); + + // Act + HttpResponseMessage response = await _client.PostAsJsonAsync("/api/v1/auth/recover-password", request); + + // Assert + response.StatusCode.Should().Be(HttpStatusCode.NotFound); + string content = await response.Content.ReadAsStringAsync(); + + Dictionary? problemDetails = JsonSerializer.Deserialize>(content, _jsonOptions); + problemDetails.Should().NotBeNull(); + problemDetails!["status"].GetInt32().Should().Be(StatusCodes.Status404NotFound); + problemDetails["type"].GetString().Should().Be("https://tools.ietf.org/html/rfc9110#section-15.5.5"); + problemDetails["title"].GetString().Should().Be("General.NotFound"); + problemDetails["detail"].GetString().Should().Be("UsernameDoesNotExist"); + problemDetails["instance"].GetString().Should().Be("/api/v1/auth/recover-password"); + problemDetails["traceId"].GetString().Should().NotBeNullOrWhiteSpace(); + } + + [Fact] + public async Task ExecuteAsync_WhenInvalidTotpCode_ShouldReturnForbidden() + { + // Arrange + UserEntity user = await CreateUserWithTotp(); + RecoverPasswordRequest request = new( + Username: user.Username, + TotpCode: "000000" + ); + + // Act + HttpResponseMessage response = await _client.PostAsJsonAsync("/api/v1/auth/recover-password", request); + + // Assert + response.StatusCode.Should().Be(HttpStatusCode.UnprocessableEntity); + string content = await response.Content.ReadAsStringAsync(); + + Dictionary? problemDetails = JsonSerializer.Deserialize>(content, _jsonOptions); + problemDetails.Should().NotBeNull(); + problemDetails!["status"].GetInt32().Should().Be(StatusCodes.Status422UnprocessableEntity); + problemDetails["type"].GetString().Should().Be("https://tools.ietf.org/html/rfc4918#section-11.2"); + problemDetails["title"].GetString().Should().Be("Validation Error"); + problemDetails["detail"].GetString().Should().Be("One or more validation errors occurred."); + problemDetails["instance"].GetString().Should().Be("/api/v1/auth/recover-password"); + problemDetails["traceId"].GetString().Should().NotBeNullOrWhiteSpace(); + + Dictionary? errors = problemDetails["errors"].Deserialize>(_jsonOptions); + errors.Should().ContainKey("General.Validation").WhoseValue.Should().Contain(["InvalidTotpCode"]); + } + + [Fact] + public async Task ExecuteAsync_WhenRequestIsNull_ShouldReturnValidationError() + { + // Arrange + RecoverPasswordRequest? request = null; + + // Act + HttpResponseMessage response = await _client.PostAsJsonAsync("/api/v1/auth/recover-password", request); + + // Assert + response.StatusCode.Should().Be(HttpStatusCode.UnprocessableContent); + string content = await response.Content.ReadAsStringAsync(); + + Dictionary? problemDetails = JsonSerializer.Deserialize>(content, _jsonOptions); + problemDetails.Should().NotBeNull(); + problemDetails!["status"].GetInt32().Should().Be(StatusCodes.Status422UnprocessableEntity); + problemDetails["type"].GetString().Should().Be("https://tools.ietf.org/html/rfc4918#section-11.2"); + problemDetails["title"].GetString().Should().Be("Validation Error"); + problemDetails["detail"].GetString().Should().Be("One or more validation errors occurred."); + problemDetails["instance"].GetString().Should().Be("/api/v1/auth/recover-password"); + problemDetails["traceId"].GetString().Should().NotBeNullOrWhiteSpace(); + + Dictionary? errors = problemDetails["errors"].Deserialize>(_jsonOptions); + errors.Should().ContainKey("General.Validation").WhoseValue.Should().Contain(["UsernameCannotBeEmpty", "TotpCannotBeEmpty"]); + } + + [Fact] + public async Task ExecuteAsync_WhenUserDoesNotUseTotpAndTriesToRecover_ShouldReturnForbidden() + { + // Arrange + UserEntity user = await CreateUserWithoutTotp(); + + RecoverPasswordRequest request = new( + Username: user.Username, + TotpCode: "123456" + ); + + // Act + HttpResponseMessage response = await _client.PostAsJsonAsync("/api/v1/auth/recover-password", request); + + // Assert + response.StatusCode.Should().Be(HttpStatusCode.UnprocessableContent); + string content = await response.Content.ReadAsStringAsync(); + + Dictionary? problemDetails = JsonSerializer.Deserialize>(content, _jsonOptions); + problemDetails.Should().NotBeNull(); + problemDetails!["status"].GetInt32().Should().Be(StatusCodes.Status422UnprocessableEntity); + problemDetails["type"].GetString().Should().Be("https://tools.ietf.org/html/rfc4918#section-11.2"); + problemDetails["title"].GetString().Should().Be("Validation Error"); + problemDetails["detail"].GetString().Should().Be("One or more validation errors occurred."); + problemDetails["instance"].GetString().Should().Be("/api/v1/auth/recover-password"); + problemDetails["traceId"].GetString().Should().NotBeNullOrWhiteSpace(); + + Dictionary? errors = problemDetails["errors"].Deserialize>(_jsonOptions); + errors.Should().ContainKey("General.Validation").WhoseValue.Should().Contain(["InvalidTotpCode"]); + } + + [Fact] + public async Task ExecuteAsync_WhenUserDoesNotUseTotpAndTriesToRecoverWithoutCode_ShouldReturnForbidden() + { + // Arrange + // Setup user without TOTP + using (IServiceScope scope = _apiFactory.Services.CreateScope()) + { + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + UserEntity userWithoutTotp = new() + { + Username = "userwithoutotp2", + Password = _hashService.HashString("OldPass123!"), + TotpSecret = null, // No TOTP configured + Libraries = [], + Created = DateTime.UtcNow + }; + dbContext.Users.Add(userWithoutTotp); + await dbContext.SaveChangesAsync(); + } + + RecoverPasswordRequest request = new( + Username: "userwithoutotp2", + TotpCode: null + ); + + // Act + HttpResponseMessage response = await _client.PostAsJsonAsync("/api/v1/auth/recover-password", request); + + // Assert + response.StatusCode.Should().Be(HttpStatusCode.UnprocessableEntity); + string content = await response.Content.ReadAsStringAsync(); + + Dictionary? problemDetails = JsonSerializer.Deserialize>(content, _jsonOptions); + problemDetails.Should().NotBeNull(); + problemDetails!["status"].GetInt32().Should().Be(StatusCodes.Status422UnprocessableEntity); + problemDetails["type"].GetString().Should().Be("https://tools.ietf.org/html/rfc4918#section-11.2"); + problemDetails["title"].GetString().Should().Be("Validation Error"); + problemDetails["detail"].GetString().Should().Be("One or more validation errors occurred."); + problemDetails["instance"].GetString().Should().Be("/api/v1/auth/recover-password"); + problemDetails["traceId"].GetString().Should().NotBeNullOrWhiteSpace(); + + Dictionary? errors = problemDetails["errors"].Deserialize>(_jsonOptions); + errors.Should().ContainKey("General.Validation").WhoseValue.Should().Contain(["TotpCannotBeEmpty"]); + } + + [Fact] + public async Task ExecuteAsync_WhenCancellationRequested_ShouldThrowTaskCanceledException() + { + // Arrange + RecoverPasswordRequest request = new( + Username: "testuser", + TotpCode: "123456" + ); + using CancellationTokenSource cts = new(); + + // Act + Func act = async () => + { + cts.Cancel(); + await _client.PostAsJsonAsync("/api/v1/auth/recover-password", request, cts.Token); + }; + + // Assert + await act.Should().ThrowAsync(); + } + + private async Task CreateUserWithTotp() + { + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + + byte[] totpSecret = _totpTokenGenerator.GenerateSecret(); + UserEntity user = new() + { + Username = _testUsername, + Password = _hashService.HashString("OldPass123!"), + TotpSecret = _cryptographyService.Encrypt(Convert.ToBase64String(totpSecret)), + Libraries = [], + Created = DateTime.UtcNow + }; + + dbContext.Users.Add(user); + await dbContext.SaveChangesAsync(); + return user; + } + + private async Task CreateUserWithoutTotp() + { + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + + UserEntity user = new() + { + Username = _testUsername, + Password = _hashService.HashString("OldPass123!"), + TotpSecret = null, + Libraries = [], + Created = DateTime.UtcNow + }; + + dbContext.Users.Add(user); + await dbContext.SaveChangesAsync(); + return user; + } + + public void Dispose() + { + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + + UserEntity? user = dbContext.Users.FirstOrDefault(u => u.Username == _testUsername); + if (user is not null) + { + dbContext.Users.Remove(user); + dbContext.SaveChanges(); + } + } +} diff --git a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/UsersManagement/Authentication/RegisterEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/UsersManagement/Authentication/RegisterEndpointTests.cs new file mode 100644 index 00000000..83eeb4b2 --- /dev/null +++ b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/UsersManagement/Authentication/RegisterEndpointTests.cs @@ -0,0 +1,205 @@ +#region ========================================================================= USING ===================================================================================== +using FluentAssertions; +using Lumina.Application.Common.DataAccess.Entities.UsersManagement; +using Lumina.Contracts.Requests.Authentication; +using Lumina.Contracts.Responses.Authentication; +using Lumina.DataAccess.Core.UoW; +using Lumina.Infrastructure.Core.Security; +using Lumina.Presentation.Api.IntegrationTests.Common.Setup; +using Microsoft.AspNetCore.Http; +using Microsoft.Extensions.DependencyInjection; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +using System.Net; +using System.Net.Http; +using System.Net.Http.Json; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Api.IntegrationTests.Core.Endpoints.UsersManagement.Authentication; + +/// +/// Contains integration tests for the class. +/// +[ExcludeFromCodeCoverage] +public class RegisterEndpointTests : IClassFixture, IDisposable +{ + private readonly LuminaApiFactory _apiFactory; + private readonly HttpClient _client; + private readonly JsonSerializerOptions _jsonOptions = new() + { + PropertyNameCaseInsensitive = true, + Converters = { new JsonStringEnumConverter(JsonNamingPolicy.CamelCase) } + }; + private readonly string _testUsername; + + /// + /// Initializes a new instance of the class. + /// + /// Injected in-memory API factory. + public RegisterEndpointTests(LuminaApiFactory apiFactory) + { + _apiFactory = apiFactory; + _client = apiFactory.CreateClient(); + _testUsername = $"testuser_{Guid.NewGuid()}"; + } + + [Fact] + public async Task ExecuteAsync_WhenCalledWithValidRequest_ShouldRegisterUserSuccessfully() + { + // Arrange + RegistrationRequest request = new( + Username: _testUsername, + Password: "TestPass123!", + PasswordConfirm: "TestPass123!", + Use2fa: false + ); + + // Act + HttpResponseMessage response = await _client.PostAsJsonAsync("/api/v1/auth/register", request); + + // Assert + response.StatusCode.Should().Be(HttpStatusCode.Created); + string content = await response.Content.ReadAsStringAsync(); + RegistrationResponse? result = JsonSerializer.Deserialize(content, _jsonOptions); + + result.Should().NotBeNull(); + result!.Username.Should().Be(_testUsername); + result.Id.Should().NotBe(Guid.Empty); + result.TotpSecret.Should().BeNull(); + + response.Headers.Location.Should().NotBeNull(); + response.Headers.Location!.ToString().Should().Be($"http://localhost/api/v1/users/{result.Id}"); + } + + [Fact] + public async Task ExecuteAsync_WhenCalledWithValidRequestAnd2FA_ShouldRegisterUserWithTotp() + { + // Arrange + RegistrationRequest request = new( + Username: _testUsername, + Password: "TestPass123!", + PasswordConfirm: "TestPass123!", + Use2fa: true + ); + + // Act + HttpResponseMessage response = await _client.PostAsJsonAsync("/api/v1/auth/register", request); + + // Assert + response.StatusCode.Should().Be(HttpStatusCode.Created); + string content = await response.Content.ReadAsStringAsync(); + RegistrationResponse? result = JsonSerializer.Deserialize(content, _jsonOptions); + + result.Should().NotBeNull(); + result!.Username.Should().Be(_testUsername); + result.Id.Should().NotBe(Guid.Empty); + result.TotpSecret.Should().NotBeNullOrEmpty(); + result.TotpSecret.Should().StartWith("data:image/png;base64,"); + } + + [Fact] + public async Task ExecuteAsync_WhenUsernameAlreadyExists_ShouldReturnConflict() + { + // Arrange + await CreateTestUser(); + RegistrationRequest request = new( + Username: _testUsername, + Password: "TestPass123!", + PasswordConfirm: "TestPass123!", + Use2fa: false + ); + + // Act + HttpResponseMessage response = await _client.PostAsJsonAsync("/api/v1/auth/register", request); + + // Assert + response.StatusCode.Should().Be(HttpStatusCode.Conflict); + string content = await response.Content.ReadAsStringAsync(); + + Dictionary? problemDetails = JsonSerializer.Deserialize>(content, _jsonOptions); + problemDetails.Should().NotBeNull(); + problemDetails!["status"].GetInt32().Should().Be(StatusCodes.Status409Conflict); + problemDetails["title"].GetString().Should().Be("General.Conflict"); + problemDetails["detail"].GetString().Should().Be("UsernameAlreadyExists"); + } + + [Fact] + public async Task ExecuteAsync_WhenPasswordsDoNotMatch_ShouldReturnValidationError() + { + // Arrange + RegistrationRequest request = new( + Username: _testUsername, + Password: "TestPass123!", + PasswordConfirm: "DifferentPass123!", + Use2fa: false + ); + + // Act + HttpResponseMessage response = await _client.PostAsJsonAsync("/api/v1/auth/register", request); + + // Assert + response.StatusCode.Should().Be(HttpStatusCode.UnprocessableContent); + string content = await response.Content.ReadAsStringAsync(); + + Dictionary? problemDetails = JsonSerializer.Deserialize>(content, _jsonOptions); + problemDetails.Should().NotBeNull(); + Dictionary? errors = problemDetails!["errors"].Deserialize>(_jsonOptions); + errors.Should().ContainKey("General.Validation").WhoseValue.Should().Contain("PasswordsNotMatch"); + } + + [Fact] + public async Task ExecuteAsync_WhenRequestIsNull_ShouldReturnValidationError() + { + // Arrange + RegistrationRequest? request = null; + + // Act + HttpResponseMessage response = await _client.PostAsJsonAsync("/api/v1/auth/register", request); + + // Assert + response.StatusCode.Should().Be(HttpStatusCode.UnprocessableContent); + string content = await response.Content.ReadAsStringAsync(); + + Dictionary? problemDetails = JsonSerializer.Deserialize>(content, _jsonOptions); + problemDetails.Should().NotBeNull(); + Dictionary? errors = problemDetails!["errors"].Deserialize>(_jsonOptions); + errors.Should().ContainKey("General.Validation") + .WhoseValue.Should().Contain(["UsernameCannotBeEmpty", "PasswordCannotBeEmpty", "PasswordConfirmCannotBeEmpty"]); + } + + private async Task CreateTestUser() + { + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + + UserEntity user = new() + { + Username = _testUsername, + Password = new HashService().HashString("TestPass123!"), + Libraries = [], + Created = DateTime.UtcNow + }; + + dbContext.Users.Add(user); + await dbContext.SaveChangesAsync(); + return user; + } + + public void Dispose() + { + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + + UserEntity? user = dbContext.Users.FirstOrDefault(u => u.Username == _testUsername); + if (user is not null) + { + dbContext.Users.Remove(user); + dbContext.SaveChanges(); + } + } +} 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..1f53e632 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.Domain.Core.BoundedContexts.WrittenContentLibraryBoundedContext.BookLibraryAggregate; 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.Domain.Common.Enums.BookLibrary; +using Lumina.Presentation.Api.IntegrationTests.Common.Converters; +using Lumina.Contracts.Requests.MediaLibrary.WrittenContentLibrary.BookLibrary.Books; #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 69% 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..c39103ae 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,20 +1,19 @@ #region ========================================================================= USING ===================================================================================== using AutoFixture; using Bogus; -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.DTO.Common; +using Lumina.Contracts.DTO.MediaContributors; +using Lumina.Contracts.DTO.MediaLibrary.WrittenContentLibrary; +using Lumina.Contracts.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary; +using Lumina.Contracts.Requests.MediaLibrary.WrittenContentLibrary.BookLibrary.Books; +using Lumina.Domain.Common.Enums.BookLibrary; using Lumina.Presentation.Api.IntegrationTests.Common.Setup; using System; -using System.Collections.Generic; 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 +45,8 @@ public class AddBookRequestFixture int releaseYear = _random.Next(2000, 2010); int reReleaseYear = _random.Next(2010, 2020); - ReleaseInfoModel releaseInfo = new Faker() - .CustomInstantiator(f => new ReleaseInfoModel( + ReleaseInfoDto releaseInfo = new Faker() + .CustomInstantiator(f => new ReleaseInfoDto( default, default, default, @@ -63,44 +62,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 GenreDto( 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 TagDto( 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 MediaContributorRoleDto( 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 MediaContributorNameDto( 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 MediaContributorDto( 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 BookRatingDto( default, default, default, @@ -111,8 +110,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 LanguageInfoDto( default!, default!, default @@ -121,8 +120,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 LanguageInfoDto( default!, default!, default @@ -131,8 +130,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 WrittenContentMetadataDto( default!, default, default, @@ -155,8 +154,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 IsbnDto( default!, default )) @@ -272,72 +271,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 86% 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..75ab030e 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 @@ -1,19 +1,19 @@ #region ========================================================================= USING ===================================================================================== using AutoFixture; -using Lumina.Contracts.Enums.BookLibrary; +using Lumina.Domain.Common.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 Lumina.Domain.Core.BoundedContexts.MediaContributorBoundedContext.MediaContributorAggregate.ValueObjects; +using Lumina.Domain.Core.BoundedContexts.WrittenContentLibraryBoundedContext.BookLibraryAggregate; +using Lumina.Domain.Core.BoundedContexts.WrittenContentLibraryBoundedContext.BookLibraryAggregate.Entities; +using Lumina.Domain.Core.BoundedContexts.WrittenContentLibraryBoundedContext.BookLibraryAggregate.ValueObjects; using Lumina.Presentation.Api.IntegrationTests.Common.Setup; using System; 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..35039b04 --- /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.BoundedContexts.WrittenContentLibraryBoundedContext.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 2e0b8403..6fbd0762 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 @@ -1,4 +1,4 @@ - + net9.0 @@ -9,21 +9,28 @@ true + + + <_Parameter1>DisableTestParallelization = true + <_Parameter1_IsLiteral>true + + + - + all runtime; build; native; contentfiles; analyzers; buildtransitive - - - + + + - + - + all runtime; build; native; contentfiles; analyzers; buildtransitive diff --git a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Common/Setup/LuminaApiFactory.cs b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Common/Setup/LuminaApiFactory.cs new file mode 100644 index 00000000..59b90215 --- /dev/null +++ b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Common/Setup/LuminaApiFactory.cs @@ -0,0 +1,99 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.DataAccess.Core.UoW; +using Microsoft.AspNetCore.Authentication.JwtBearer; +using Microsoft.AspNetCore.Hosting; +using Microsoft.AspNetCore.Mvc.Testing; +using Microsoft.Data.Sqlite; +using Microsoft.EntityFrameworkCore; +using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.IdentityModel.Tokens; +using System.Diagnostics.CodeAnalysis; +using System.Text; +#endregion + +namespace Lumina.Presentation.Api.SecurityTests.Common.Setup; + +/// +/// Factory for creating a web application for security tests. +/// +[ExcludeFromCodeCoverage] +public class LuminaApiFactory : WebApplicationFactory, IDisposable +{ + private readonly SqliteConnection _connection; + private const string TEST_ENCRYPTION_KEY = "MTIzNDU2Nzg5MDEyMzQ1Njc4OTAxMjM0NTY3ODkwMTI="; + + /// + /// Initializes a new instance of the class. + /// + public LuminaApiFactory() + { + _connection = new SqliteConnection("DataSource=:memory:"); + _connection.Open(); + } + + /// + /// Configures the web host for the security tests. + /// + /// The web host builder to configure. + protected override void ConfigureWebHost(IWebHostBuilder builder) + { + builder.ConfigureAppConfiguration((context, config) => + { + // clear all existing configuration sources + config.Sources.Clear(); + + config.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true); + config.AddJsonFile($"appsettings.test.json", optional: true, reloadOnChange: true); + config.AddJsonFile("appsettings.shared.json", optional: true, reloadOnChange: true); + config.AddJsonFile($"appsettings.shared.test.json", optional: true, reloadOnChange: true); + // First add the test values directly + config.AddInMemoryCollection(initialData: new Dictionary + { + ["JwtSettings:SecretKey"] = "test-key-thats-at-least-32-chars-long-for-jwt", + ["JwtSettings:ExpiryMinutes"] = "15", // control the expiry time during tests + ["EncryptionSettings:SecretKey"] = TEST_ENCRYPTION_KEY // base64 encoded test key + }); + }); + builder.ConfigureServices(services => + { + // remove existing DbContext configuration + ServiceDescriptor? descriptor = services.SingleOrDefault(serviceDescriptor => serviceDescriptor.ServiceType == typeof(DbContextOptions)); + if (descriptor is not null) + services.Remove(descriptor); + // add SQLite DbContext configuration + services.AddDbContext(options => options.UseSqlite(_connection)); + // configure JWT authentication for testing + services.PostConfigure(JwtBearerDefaults.AuthenticationScheme, options => + { + options.TokenValidationParameters = new TokenValidationParameters + { + ValidateIssuer = true, + ValidateAudience = true, + ValidateLifetime = true, + ValidateIssuerSigningKey = true, + ValidIssuer = "test-issuer", + ValidAudience = "test-audience", + IssuerSigningKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes("test-key-thats-at-least-32-chars-long-for-jwt")) + }; + }); + // build service provider and ensure database is created + ServiceProvider servicePreovider = services.BuildServiceProvider(); + using (IServiceScope scope = servicePreovider.CreateScope()) + { + IServiceProvider scopedServices = scope.ServiceProvider; + LuminaDbContext dbContext = scopedServices.GetRequiredService(); + dbContext.Database.Migrate(); + } + }); + } + + /// + /// Disposes the connection to the database. + /// + public new void Dispose() + { + _connection.Close(); + base.Dispose(); + } +} diff --git a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/UsersManagement/Authentication/AuthChangePasswordTests.cs b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/UsersManagement/Authentication/AuthChangePasswordTests.cs new file mode 100644 index 00000000..489480f5 --- /dev/null +++ b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/UsersManagement/Authentication/AuthChangePasswordTests.cs @@ -0,0 +1,157 @@ +#region ========================================================================= USING ===================================================================================== +using FluentAssertions; +using Lumina.Application.Common.DataAccess.Entities.UsersManagement; +using Lumina.Application.Common.Infrastructure.Security; +using Lumina.Contracts.Requests.Authentication; +using Lumina.Contracts.Responses.Authentication; +using Lumina.DataAccess.Core.UoW; +using Lumina.Infrastructure.Core.Authentication; +using Lumina.Infrastructure.Core.Security; +using Lumina.Presentation.Api.SecurityTests.Common.Setup; +using Microsoft.AspNetCore.Http; +using Microsoft.Extensions.DependencyInjection; +using System.Diagnostics; +using System.Diagnostics.CodeAnalysis; +using System.IdentityModel.Tokens.Jwt; +using System.Net; +using System.Net.Http.Headers; +using System.Net.Http.Json; +using System.Text.Json; +using System.Text.Json.Serialization; +#endregion + +namespace Lumina.Presentation.Api.SecurityTests.Core.Endpoints.UsersManagement.Authentication; + +/// +/// Contains security tests for the /auth/change-password route. +/// +[ExcludeFromCodeCoverage] +public class AuthChangePasswordTests : IClassFixture, IDisposable +{ + private readonly LuminaApiFactory _apiFactory; + private readonly HttpClient _client; + private readonly HashService _hashService; + private readonly string _testUsername; + private readonly JsonSerializerOptions _jsonOptions = new() + { + PropertyNameCaseInsensitive = true + }; + + /// + /// Initializes a new instance of the class. + /// + /// Injected in-memory API factory. + public AuthChangePasswordTests(LuminaApiFactory apiFactory) + { + _apiFactory = apiFactory; + _client = apiFactory.CreateClient(); + _client.DefaultRequestHeaders.Clear(); + _client.DefaultRequestHeaders.Add("X-Forwarded-For", $"192.168.1.12"); + _hashService = new HashService(); + _testUsername = $"testuser_{Guid.NewGuid()}"; + } + + [Fact] + public async Task ChangePassword_WithoutAuthentication_ShouldReturn401() + { + // Arrange + ChangePasswordRequest request = new( + Username: _testUsername, + CurrentPassword: "OldPass123!", + NewPassword: "NewPass123!", + NewPasswordConfirm: "NewPass123!" + ); + + // Act + HttpResponseMessage response = await _client.PostAsJsonAsync("/api/v1/auth/change-password", request); + + // Assert + response.StatusCode.Should().Be(HttpStatusCode.Unauthorized); + } + + [Fact] + public async Task ChangePassword_WithValidRequest_ShouldNotLeakTimingInformation() + { + // Arrange + UserEntity user = await CreateAndAuthenticateUser(); + Stopwatch stopwatch = new(); + List timings = []; + + // Act + for (int i = 0; i < 10; i++) + { + await Task.Delay(100); + stopwatch.Restart(); + await _client.PostAsJsonAsync("/api/v1/auth/change-password", new ChangePasswordRequest( + Username: user.Username, + CurrentPassword: "WrongPass123!", + NewPassword: "NewPass123!", + NewPasswordConfirm: "NewPass123!" + )); + stopwatch.Stop(); + timings.Add(stopwatch.ElapsedMilliseconds); + } + + timings.Sort(); + timings = timings.Skip(1).SkipLast(1).ToList(); // remove outliers + + // Assert + double stdDev = CalculateStandardDeviation(timings); + stdDev.Should().BeLessThan(200); + } + + private double CalculateStandardDeviation(List values) + { + double average = values.Average(); + double sumOfSquaresOfDifferences = values.Select(value => (value - average) * (value - average)).Sum(); + return Math.Sqrt(sumOfSquaresOfDifferences / values.Count); + } + + private async Task CreateAndAuthenticateUser() + { + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + + // create test user + UserEntity user = new() + { + Username = _testUsername, + Password = _hashService.HashString("TestPass123!"), + Libraries = [], + Created = DateTime.UtcNow + }; + + dbContext.Users.Add(user); + await dbContext.SaveChangesAsync(); + + // authenticate user + LoginRequest loginRequest = new( + Username: user.Username, + Password: "TestPass123!" + ); + + HttpResponseMessage loginResponse = await _client.PostAsJsonAsync("/api/v1/auth/login", loginRequest); + string content = await loginResponse.Content.ReadAsStringAsync(); + LoginResponse? result = JsonSerializer.Deserialize(content, _jsonOptions); + + // set auth header for subsequent requests + _client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", result!.Token); + + return user; + } + + public void Dispose() + { + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + + UserEntity? user = dbContext.Users.FirstOrDefault(u => u.Username == _testUsername); + if (user is not null) + { + dbContext.Users.Remove(user); + dbContext.SaveChanges(); + } + + _client.DefaultRequestHeaders.Authorization = null; + } +} diff --git a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/UsersManagement/Authentication/AuthLoginTests.cs b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/UsersManagement/Authentication/AuthLoginTests.cs new file mode 100644 index 00000000..d8c74341 --- /dev/null +++ b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/UsersManagement/Authentication/AuthLoginTests.cs @@ -0,0 +1,350 @@ +#region ========================================================================= USING ===================================================================================== +using FluentAssertions; +using Lumina.Application.Common.DataAccess.Entities.UsersManagement; +using Lumina.Application.Common.Infrastructure.Security; +using Lumina.Contracts.Requests.Authentication; +using Lumina.Contracts.Responses.Authentication; +using Lumina.DataAccess.Core.UoW; +using Lumina.Infrastructure.Core.Authentication; +using Lumina.Infrastructure.Core.Security; +using Lumina.Presentation.Api.SecurityTests.Common.Setup; +using Microsoft.AspNetCore.Http; +using Microsoft.Extensions.DependencyInjection; +using System.Diagnostics; +using System.Diagnostics.CodeAnalysis; +using System.IdentityModel.Tokens.Jwt; +using System.Net; +using System.Net.Http.Json; +using System.Text.Json; +using System.Text.Json.Serialization; +#endregion + +namespace Lumina.Presentation.Api.SecurityTests.Core.Endpoints.UsersManagement.Authentication; + +/// +/// Contains security tests for the /auth/login route. +/// +[ExcludeFromCodeCoverage] +public class AuthLoginTests : IClassFixture, IDisposable +{ + private readonly HashService _hashService; + private readonly ICryptographyService _cryptographyService; + private readonly TotpTokenGenerator _totpTokenGenerator; + private readonly LuminaApiFactory _apiFactory; + private readonly HttpClient _client; + private readonly JsonSerializerOptions _jsonOptions = new() + { + PropertyNameCaseInsensitive = true, + Converters = { new JsonStringEnumConverter(JsonNamingPolicy.CamelCase) } + }; + private readonly string _testUsername; + + /// + /// Initializes a new instance of the class. + /// + /// Injected in-memory API factory. + public AuthLoginTests(LuminaApiFactory apiFactory) + { + _apiFactory = apiFactory; + _client = apiFactory.CreateClient(); + // set a fake IP for this test instance + _client.DefaultRequestHeaders.Clear(); + _client.DefaultRequestHeaders.Add("X-Forwarded-For", $"192.168.1.1"); + _hashService = new HashService(); + _totpTokenGenerator = new TotpTokenGenerator(); + _testUsername = $"testuser_{Guid.NewGuid()}"; + + using IServiceScope scope = apiFactory.Services.CreateScope(); + _cryptographyService = scope.ServiceProvider.GetRequiredService(); + } + + [Fact] + public async Task Login_WithValidCredentials_ShouldAuthenticateSuccessfully() + { + // Arrange + UserEntity user = await CreateTestUser(); + LoginRequest request = new( + Username: user.Username, + Password: "TestPass123!" + ); + DateTimeOffset beforeRequest = DateTimeOffset.UtcNow; + _client.DefaultRequestHeaders.Clear(); + _client.DefaultRequestHeaders.Add("X-Forwarded-For", $"192.168.1.10"); + + // Act + HttpResponseMessage response = await _client.PostAsJsonAsync("/api/v1/auth/login", request); + string content = await response.Content.ReadAsStringAsync(); + LoginResponse? result = JsonSerializer.Deserialize(content, _jsonOptions); + + // Assert + JwtSecurityTokenHandler handler = new(); + JwtSecurityToken token = handler.ReadJwtToken(result!.Token); + + string expValue = token.Claims.First(c => c.Type == "exp").Value; // get token claims + DateTimeOffset tokenExpiration = DateTimeOffset.FromUnixTimeSeconds(long.Parse(expValue)); + DateTimeOffset expectedExpiration = beforeRequest.AddMinutes(15); + + // verify token duration (should be 15 minutes from request time - expiration value is set in tests setup class) + TimeSpan allowedVariance = TimeSpan.FromSeconds(30); // allow for processing time + TimeSpan actualDifference = tokenExpiration - beforeRequest; + TimeSpan expectedDifference = TimeSpan.FromMinutes(15); + + actualDifference.Should().BeCloseTo(expectedDifference, precision: allowedVariance); + + token.Header.Alg.Should().Be("HS256"); + token.Claims.Should().Contain(c => c.Type == "sub" && c.Value == user.Id.ToString()); + token.Claims.Should().Contain(c => c.Type == "unique_name" && c.Value == user.Username); + token.Claims.Should().Contain(c => c.Type == "jti"); + token.Claims.Should().Contain(c => c.Type == "iss" && c.Value == "Lumina"); + token.Claims.Should().Contain(c => c.Type == "aud" && c.Value == "Lumina"); + + content.Should().NotContain("password"); + content.Should().NotContain("hash"); + content.Should().NotContain("salt"); + + // TODO: implement more strict security checks: + // // check security headers + // response.Headers.Should().ContainKey("X-Content-Type-Options") + // .WhoseValue.Should().Contain("nosniff"); + // response.Headers.Should().ContainKey("X-Frame-Options") + // .WhoseValue.Should().Contain("DENY"); + // response.Headers.Should().ContainKey("X-XSS-Protection") + // .WhoseValue.Should().Contain("1; mode=block"); + } + + [Fact] + public async Task Login_WithValidCredentials_ShouldNotLeakTimingInformation() + { + // Arrange + UserEntity user = await CreateTestUser(); + Stopwatch stopwatch = new(); + List timings = []; + // since this test is rigged to trigger the rate limiting, assign a different IP to it + _client.DefaultRequestHeaders.Clear(); + _client.DefaultRequestHeaders.Add("X-Forwarded-For", $"192.168.1.2"); + + // Act + for (int i = 0; i < 10; i++) + { + await Task.Delay(100); // add small delay between requests + stopwatch.Restart(); + await _client.PostAsJsonAsync("/api/v1/auth/login", new LoginRequest( + Username: user.Username, + Password: "TestPass123!" + )); + stopwatch.Stop(); + timings.Add(stopwatch.ElapsedMilliseconds); + } + // remove the highest and lowest values to account for outliers + timings.Sort(); + timings = timings.Skip(1).SkipLast(1).ToList(); + + // Assert + // check for timing consistency to prevent timing attacks + double stdDev = CalculateStandardDeviation(timings); + stdDev.Should().BeLessThan(200); + } + + [Fact] + public async Task ExecuteAsync_WhenRateLimitExceeded_ShouldReturnTooManyRequests() + { + // Arrange + // set a fake IP for this test instance + _client.DefaultRequestHeaders.Clear(); + _client.DefaultRequestHeaders.Add("X-Forwarded-For", $"192.168.1.3"); + LoginRequest request = new( + Username: "testuser", + Password: "TestPass123!" + ); + + // Act + List responses = []; + for (int i = 0; i < 11; i++) // exceed the 10 request limit + responses.Add(await _client.PostAsJsonAsync("/api/v1/auth/login", request)); + + // Assert + HttpResponseMessage lastResponse = responses.Last(); + lastResponse.StatusCode.Should().Be(HttpStatusCode.TooManyRequests); + string content = await lastResponse.Content.ReadAsStringAsync(); + + Dictionary? problemDetails = JsonSerializer.Deserialize>(content, _jsonOptions); + problemDetails.Should().NotBeNull(); + problemDetails!["status"].GetInt32().Should().Be(StatusCodes.Status429TooManyRequests); + problemDetails["type"].GetString().Should().Be("https://tools.ietf.org/html/rfc7231#section-6.5.29"); + problemDetails["title"].GetString().Should().Be("TooManyRequests"); + problemDetails["detail"].GetString().Should().Be("Too many attempts. Please try again later."); + problemDetails["retryAfter"].GetString().Should().Be("15"); + + lastResponse.Headers.Should().ContainKey("X-RateLimit-Limit"); + lastResponse.Headers.Should().ContainKey("X-RateLimit-Reset"); + lastResponse.Headers.Should().ContainKey("X-RateLimit-Remaining"); + } + + [Theory] + [InlineData("' OR '1'='1")] // basic SQL injection + [InlineData("admin'--")] // comment injection + [InlineData("' UNION SELECT * FROM Users--")] // union injection + [InlineData("'; DROP TABLE Users--")] // destructive injection + [InlineData("' WAITFOR DELAY '0:0:10'--")] // time-based injection + public async Task Login_WithSQLInjectionAttempt_ShouldRemainSecure(string maliciousUsername) + { + // Arrange + UserEntity legitimateUser = await CreateTestUser(); + LoginRequest request = new( + Username: maliciousUsername, + Password: "Abcd123$" + ); + + // Act + HttpResponseMessage response = await _client.PostAsJsonAsync("/api/v1/auth/login", request); + string content = await response.Content.ReadAsStringAsync(); + + // Assert + response.StatusCode.Should().Be(HttpStatusCode.Forbidden); + content.Should().NotContain("SQL"); + content.Should().NotContain("Exception"); + content.Should().NotContain(legitimateUser.Username); // shouldn't expose other usernames + content.Should().NotContain(legitimateUser.Password); // shouldn't expose password hashes + } + + [Fact] + public async Task Login_WithSQLInjectionInValidUser_ShouldRemainSecure() + { + // Arrange + UserEntity user = await CreateTestUser(); + LoginRequest request = new( + Username: user.Username, + Password: "' OR '1'='1" + ); + _client.DefaultRequestHeaders.Clear(); + _client.DefaultRequestHeaders.Add("X-Forwarded-For", $"192.168.1.11"); + + // Act + HttpResponseMessage response = await _client.PostAsJsonAsync("/api/v1/auth/login", request); + string content = await response.Content.ReadAsStringAsync(); + + // Assert + response.StatusCode.Should().Be(HttpStatusCode.Forbidden); + content.Should().NotContain("SQL"); + content.Should().NotContain("Exception"); + } + + [Fact] + public async Task Login_WithInjectionInTotpCode_ShouldRemainSecure() + { + // Arrange + UserEntity user = await CreateTestUserWithTotp(); + LoginRequest request = new( + Username: user.Username, + Password: "TestPass123!", + TotpCode: "' OR '1'='1" + ); + + // Act + HttpResponseMessage response = await _client.PostAsJsonAsync("/api/v1/auth/login", request); + string content = await response.Content.ReadAsStringAsync(); + + // Assert + response.StatusCode.Should().Be(HttpStatusCode.UnprocessableContent); + content.Should().NotContain("SQL"); + content.Should().NotContain("Exception"); + } + + private double CalculateStandardDeviation(List values) + { + double average = values.Average(); + double sumOfSquaresOfDifferences = values.Select(value => (value - average) * (value - average)).Sum(); + return Math.Sqrt(sumOfSquaresOfDifferences / values.Count); + } + + private async Task CreateTestUser() + { + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + + UserEntity user = new() + { + Username = _testUsername, + Password = _hashService.HashString("TestPass123!"), + Libraries = [], + Created = DateTime.UtcNow + }; + + dbContext.Users.Add(user); + await dbContext.SaveChangesAsync(); + return user; + } + + private async Task CreateTestUserWithTotp() + { + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + + byte[] totpSecret = _totpTokenGenerator.GenerateSecret(); + UserEntity user = new() + { + Username = _testUsername, + Password = _hashService.HashString("TestPass123!"), + TotpSecret = _cryptographyService.Encrypt(Convert.ToBase64String(totpSecret)), + Libraries = [], + Created = DateTime.UtcNow + }; + + dbContext.Users.Add(user); + await dbContext.SaveChangesAsync(); + return user; + } + + private async Task CreateTestUserWithTempPassword() + { + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + + UserEntity user = new() + { + Username = _testUsername, + Password = _hashService.HashString("TestPass123!"), + TempPassword = Uri.EscapeDataString(_hashService.HashString("TempPass123!")), + TempPasswordCreated = DateTime.UtcNow, + Libraries = [], + Created = DateTime.UtcNow + }; + + dbContext.Users.Add(user); + await dbContext.SaveChangesAsync(); + return user; + } + + private async Task CreateTestUserWithExpiredTempPassword() + { + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + + UserEntity user = new() + { + Username = _testUsername, + Password = _hashService.HashString("TestPass123!"), + TempPassword = Uri.EscapeDataString(_hashService.HashString("TempPass123!")), + TempPasswordCreated = DateTime.UtcNow.AddMinutes(-16), // expired (> 15 minutes old) + Libraries = [], + Created = DateTime.UtcNow + }; + + dbContext.Users.Add(user); + await dbContext.SaveChangesAsync(); + return user; + } + + public void Dispose() + { + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + + UserEntity? user = dbContext.Users.FirstOrDefault(u => u.Username == _testUsername); + if (user is not null) + { + dbContext.Users.Remove(user); + dbContext.SaveChanges(); + } + } +} diff --git a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/UsersManagement/Authentication/AuthRecoverPasswordTests.cs b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/UsersManagement/Authentication/AuthRecoverPasswordTests.cs new file mode 100644 index 00000000..b2268000 --- /dev/null +++ b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/UsersManagement/Authentication/AuthRecoverPasswordTests.cs @@ -0,0 +1,91 @@ +#region ========================================================================= USING ===================================================================================== +using FluentAssertions; +using Lumina.Application.Common.DataAccess.Entities.UsersManagement; +using Lumina.Contracts.Requests.Authentication; +using Lumina.DataAccess.Core.UoW; +using Lumina.Presentation.Api.SecurityTests.Common.Setup; +using Microsoft.AspNetCore.Http; +using Microsoft.Extensions.DependencyInjection; +using System.Diagnostics.CodeAnalysis; +using System.Net; +using System.Net.Http.Json; +using System.Text.Json; +using System.Text.Json.Serialization; +#endregion + +namespace Lumina.Presentation.Api.SecurityTests.Core.Endpoints.UsersManagement.Authentication; + +/// +/// Contains security tests for the /auth/recover-password route. +/// +[ExcludeFromCodeCoverage] +public class AuthRecoverPasswordTests : IClassFixture, IDisposable +{ + private readonly LuminaApiFactory _apiFactory; + private readonly HttpClient _client; + private readonly JsonSerializerOptions _jsonOptions = new() + { + PropertyNameCaseInsensitive = true, + Converters = { new JsonStringEnumConverter(JsonNamingPolicy.CamelCase) } + }; + private readonly string _testUsername; + + /// + /// Initializes a new instance of the class. + /// + /// Injected in-memory API factory. + public AuthRecoverPasswordTests(LuminaApiFactory apiFactory) + { + _apiFactory = apiFactory; + _client = apiFactory.CreateClient(); + // set a fake IP for this test instance + _client.DefaultRequestHeaders.Clear(); + _client.DefaultRequestHeaders.Add("X-Forwarded-For", $"192.168.1.4"); + _testUsername = $"testuser_{Guid.NewGuid()}"; + } + + [Fact] + public async Task ExecuteAsync_WhenRateLimitExceeded_ShouldReturnTooManyRequests() + { + // Arrange + RecoverPasswordRequest request = new( + Username: "testuser", + TotpCode: "123456" + ); + + // Act + List responses = []; + for (int i = 0; i < 11; i++) // exceed the 10 request limit + responses.Add(await _client.PostAsJsonAsync("/api/v1/auth/recover-password", request)); + + // Assert + HttpResponseMessage lastResponse = responses.Last(); + lastResponse.StatusCode.Should().Be(HttpStatusCode.TooManyRequests); + string content = await lastResponse.Content.ReadAsStringAsync(); + + Dictionary? problemDetails = JsonSerializer.Deserialize>(content, _jsonOptions); + problemDetails.Should().NotBeNull(); + problemDetails!["status"].GetInt32().Should().Be(StatusCodes.Status429TooManyRequests); + problemDetails["type"].GetString().Should().Be("https://tools.ietf.org/html/rfc7231#section-6.5.29"); + problemDetails["title"].GetString().Should().Be("TooManyRequests"); + problemDetails["detail"].GetString().Should().Be("Too many attempts. Please try again later."); + problemDetails["retryAfter"].GetString().Should().Be("15"); + + lastResponse.Headers.Should().ContainKey("X-RateLimit-Limit"); + lastResponse.Headers.Should().ContainKey("X-RateLimit-Reset"); + lastResponse.Headers.Should().ContainKey("X-RateLimit-Remaining"); + } + + public void Dispose() + { + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + + UserEntity? user = dbContext.Users.FirstOrDefault(u => u.Username == _testUsername); + if (user is not null) + { + dbContext.Users.Remove(user); + dbContext.SaveChanges(); + } + } +} diff --git a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/UsersManagement/Authentication/AuthRegisterTests.cs b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/UsersManagement/Authentication/AuthRegisterTests.cs new file mode 100644 index 00000000..306cfce7 --- /dev/null +++ b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/UsersManagement/Authentication/AuthRegisterTests.cs @@ -0,0 +1,246 @@ +#region ========================================================================= USING ===================================================================================== +using FluentAssertions; +using Lumina.Application.Common.DataAccess.Entities.UsersManagement; +using Lumina.Contracts.Requests.Authentication; +using Lumina.DataAccess.Core.UoW; +using Lumina.Infrastructure.Core.Security; +using Lumina.Presentation.Api.SecurityTests.Common.Setup; +using Microsoft.AspNetCore.Http; +using Microsoft.Extensions.DependencyInjection; +using System.Diagnostics; +using System.Diagnostics.CodeAnalysis; +using System.Net; +using System.Net.Http.Json; +using System.Text.Json; +using System.Text.Json.Serialization; +#endregion + +namespace Lumina.Presentation.Api.SecurityTests.Core.Endpoints.UsersManagement.Authentication; + +/// +/// Contains security tests for the /auth/register route. +/// +[ExcludeFromCodeCoverage] +public class AuthRegisterTests : IClassFixture, IDisposable +{ + private readonly HashService _hashService; + private readonly LuminaApiFactory _apiFactory; + private readonly HttpClient _client; + private readonly JsonSerializerOptions _jsonOptions = new() + { + PropertyNameCaseInsensitive = true, + Converters = { new JsonStringEnumConverter(JsonNamingPolicy.CamelCase) } + }; + private readonly string _testUsername; + + public AuthRegisterTests(LuminaApiFactory apiFactory) + { + _apiFactory = apiFactory; + _client = apiFactory.CreateClient(); + _client.DefaultRequestHeaders.Clear(); + _client.DefaultRequestHeaders.Add("X-Forwarded-For", $"192.168.1.5"); + _hashService = new HashService(); + _testUsername = $"testuser_{Guid.NewGuid()}"; + } + + [Fact] + public async Task Register_WithValidData_ShouldNotLeakTimingInformation() + { + // Arrange + Stopwatch stopwatch = new(); + List timings = []; + _client.DefaultRequestHeaders.Clear(); + _client.DefaultRequestHeaders.Add("X-Forwarded-For", $"192.168.1.6"); + RegistrationRequest request = new( + Username: _testUsername, + Password: "TestPass123!", + PasswordConfirm: "TestPass123!" + ); + + // Act + for (int i = 0; i < 10; i++) + { + await Task.Delay(100); + stopwatch.Restart(); + await _client.PostAsJsonAsync("/api/v1/auth/register", request); + stopwatch.Stop(); + timings.Add(stopwatch.ElapsedMilliseconds); + } + timings.Sort(); + timings = timings.Skip(1).SkipLast(1).ToList(); + + // Assert + double stdDev = CalculateStandardDeviation(timings); + stdDev.Should().BeLessThan(200); + } + + [Fact] + public async Task Register_WhenRateLimitExceeded_ShouldReturnTooManyRequests() + { + // Arrange + _client.DefaultRequestHeaders.Clear(); + _client.DefaultRequestHeaders.Add("X-Forwarded-For", $"192.168.1.7"); + RegistrationRequest request = new( + Username: _testUsername, + Password: "TestPass123!", + PasswordConfirm: "TestPass123!" + ); + + // Act + List responses = []; + for (int i = 0; i < 11; i++) + responses.Add(await _client.PostAsJsonAsync("/api/v1/auth/register", request)); + + // Assert + HttpResponseMessage lastResponse = responses.Last(); + lastResponse.StatusCode.Should().Be(HttpStatusCode.TooManyRequests); + string content = await lastResponse.Content.ReadAsStringAsync(); + + Dictionary? problemDetails = JsonSerializer.Deserialize>(content, _jsonOptions); + problemDetails.Should().NotBeNull(); + problemDetails!["status"].GetInt32().Should().Be(StatusCodes.Status429TooManyRequests); + problemDetails["type"].GetString().Should().Be("https://tools.ietf.org/html/rfc7231#section-6.5.29"); + problemDetails["title"].GetString().Should().Be("TooManyRequests"); + problemDetails["detail"].GetString().Should().Be("Too many attempts. Please try again later."); + problemDetails["retryAfter"].GetString().Should().Be("15"); + + lastResponse.Headers.Should().ContainKey("X-RateLimit-Limit"); + lastResponse.Headers.Should().ContainKey("X-RateLimit-Reset"); + lastResponse.Headers.Should().ContainKey("X-RateLimit-Remaining"); + } + + [Theory] + [InlineData("' OR '1'='1")] // basic SQL injection + [InlineData("admin'--")] // comment injection + [InlineData("' UNION SELECT * FROM Users--")] // union injection + [InlineData("'; DROP TABLE Users--")] // destructive injection + [InlineData("' WAITFOR DELAY '0:0:10'--")] // time-based injection + public async Task Register_WithSQLInjectionAttempt_ShouldRemainSecure(string maliciousUsername) + { + // Arrange + RegistrationRequest request = new( + Username: maliciousUsername, + Password: "TestPass123!", + PasswordConfirm: "TestPass123!" + ); + + // Act + HttpResponseMessage response = await _client.PostAsJsonAsync("/api/v1/auth/register", request); + string content = await response.Content.ReadAsStringAsync(); + + // Assert + response.StatusCode.Should().Be(HttpStatusCode.UnprocessableContent); + content.Should().NotContain("SQL"); + content.Should().NotContain("Exception"); + content.Should().NotContain("password"); + content.Should().NotContain("hash"); + content.Should().NotContain("salt"); + } + + [Theory] + [InlineData("password123")] // common password + [InlineData("123456789")] // numeric only + [InlineData("abcdefgh")] // lowercase only + [InlineData("short")] // too short + public async Task Register_WithWeakPassword_ShouldBeDenied(string weakPassword) + { + // Arrange + RegistrationRequest request = new( + Username: _testUsername, + Password: weakPassword, + PasswordConfirm: weakPassword + ); + _client.DefaultRequestHeaders.Clear(); + _client.DefaultRequestHeaders.Add("X-Forwarded-For", $"192.168.1.8"); + + // Act + HttpResponseMessage response = await _client.PostAsJsonAsync("/api/v1/auth/register", request); + string content = await response.Content.ReadAsStringAsync(); + + // Assert + response.StatusCode.Should().Be(HttpStatusCode.UnprocessableContent); + content.Should().NotContain(weakPassword); // shouldn't leak the actual password + } + + [Theory] + [InlineData("TestPass123!")] // valid password + [InlineData("Ab1!defghijklmnopqrstuvwxyz")] // long password + public async Task Register_WithValidPassword_ShouldAcceptPassword(string password) + { + // Arrange + RegistrationRequest request = new( + Username: _testUsername, + Password: password, + PasswordConfirm: password + ); + + // Act + HttpResponseMessage response = await _client.PostAsJsonAsync("/api/v1/auth/register", request); + + // Assert + response.StatusCode.Should().Be(HttpStatusCode.Created); + } + + [Fact] + public async Task Register_WithExistingUsername_ShouldNotLeakUserExistence() + { + // Arrange + await CreateTestUser(); + RegistrationRequest request = new( + Username: _testUsername, + Password: "TestPass123!", + PasswordConfirm: "TestPass123!" + ); + _client.DefaultRequestHeaders.Clear(); + _client.DefaultRequestHeaders.Add("X-Forwarded-For", $"192.168.1.9"); + + // Act + HttpResponseMessage response = await _client.PostAsJsonAsync("/api/v1/auth/register", request); + string content = await response.Content.ReadAsStringAsync(); + + // Assert + response.StatusCode.Should().Be(HttpStatusCode.Conflict); + content.Should().NotContain(_testUsername); + content.Should().NotContain("password"); + content.Should().NotContain("hash"); + content.Should().NotContain("salt"); + } + + private double CalculateStandardDeviation(List values) + { + double average = values.Average(); + double sumOfSquaresOfDifferences = values.Select(value => (value - average) * (value - average)).Sum(); + return Math.Sqrt(sumOfSquaresOfDifferences / values.Count); + } + + private async Task CreateTestUser() + { + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + + UserEntity user = new() + { + Username = _testUsername, + Password = _hashService.HashString("TestPass123!"), + Libraries = [], + Created = DateTime.UtcNow + }; + + dbContext.Users.Add(user); + await dbContext.SaveChangesAsync(); + return user; + } + + public void Dispose() + { + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + + UserEntity? user = dbContext.Users.FirstOrDefault(u => u.Username == _testUsername); + if (user is not null) + { + dbContext.Users.Remove(user); + dbContext.SaveChanges(); + } + } +} diff --git a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Lumina.Presentation.Api.SecurityTests.csproj b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Lumina.Presentation.Api.SecurityTests.csproj new file mode 100644 index 00000000..5a20671e --- /dev/null +++ b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Lumina.Presentation.Api.SecurityTests.csproj @@ -0,0 +1,46 @@ + + + + net9.0 + enable + enable + + false + true + + + + + <_Parameter1>DisableTestParallelization = true + <_Parameter1_IsLiteral>true + + + + + + + + + all + runtime; build; native; contentfiles; analyzers; buildtransitive + + + + + + + + + all + runtime; build; native; contentfiles; analyzers; buildtransitive + + + + + + + + + + + diff --git a/tests/UnitTests/Lumina.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/Authentication/ChangePasswordRequestMappingTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Authentication/ChangePasswordRequestMappingTests.cs new file mode 100644 index 00000000..baa0a82c --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Authentication/ChangePasswordRequestMappingTests.cs @@ -0,0 +1,85 @@ +#region ========================================================================= USING ===================================================================================== +using FluentAssertions; +using Lumina.Application.Core.UsersManagement.Authentication.Commands.ChangePassword; +using Lumina.Application.UnitTests.Core.UsersManagement.Authentication.Commands.ChangePassword.Fixtures; +using Lumina.Contracts.Requests.Authentication; +using System.Diagnostics.CodeAnalysis; +using Lumina.Application.Common.Mapping.Authentication; +#endregion + +namespace Lumina.Application.UnitTests.Common.Mapping.Authentication; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class ChangePasswordRequestMappingTests +{ + private readonly ChangePasswordRequestFixture _fixture; + + /// + /// Initializes a new instance of the class. + /// + public ChangePasswordRequestMappingTests() + { + _fixture = new(); + } + + [Fact] + public void ToCommand_WhenMappingRequest_ShouldMapCorrectly() + { + // Arrange + ChangePasswordRequest request = _fixture.CreateChangePasswordRequest(); + + // Act + ChangePasswordCommand result = request.ToCommand(); + + // Assert + result.Should().NotBeNull(); + result.Username.Should().Be(request.Username); + result.CurrentPassword.Should().Be(request.CurrentPassword); + result.NewPassword.Should().Be(request.NewPassword); + result.NewPasswordConfirm.Should().Be(request.NewPasswordConfirm); + } + + [Fact] + public void ToCommand_WhenMappingRequestWithNullValues_ShouldMapCorrectly() + { + // Arrange + ChangePasswordRequest request = new(null, null, null, null); + + // Act + ChangePasswordCommand result = request.ToCommand(); + + // Assert + result.Should().NotBeNull(); + result.Username.Should().BeNull(); + result.CurrentPassword.Should().BeNull(); + result.NewPassword.Should().BeNull(); + result.NewPasswordConfirm.Should().BeNull(); + } + + [Theory] + [InlineData("user1", "oldPass", "newPass", "newPass")] + [InlineData("", "", "", "")] + [InlineData("testUser", null, "pass123", "pass123")] + public void ToCommand_WhenMappingRequestWithSpecificValues_ShouldMapCorrectly( + string? username, + string? currentPassword, + string? newPassword, + string? newPasswordConfirm) + { + // Arrange + ChangePasswordRequest request = new(username, currentPassword, newPassword, newPasswordConfirm); + + // Act + ChangePasswordCommand result = request.ToCommand(); + + // Assert + result.Should().NotBeNull(); + result.Username.Should().Be(username); + result.CurrentPassword.Should().Be(currentPassword); + result.NewPassword.Should().Be(newPassword); + result.NewPasswordConfirm.Should().Be(newPasswordConfirm); + } +} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Authentication/LoginRequestMappingTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Authentication/LoginRequestMappingTests.cs new file mode 100644 index 00000000..bfe307f4 --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Authentication/LoginRequestMappingTests.cs @@ -0,0 +1,82 @@ +#region ========================================================================= USING ===================================================================================== +using FluentAssertions; +using Lumina.Application.Common.Mapping.Authentication; +using Lumina.Application.Core.UsersManagement.Authentication.Queries.LoginUser; +using Lumina.Application.UnitTests.Core.UsersManagement.Authentication.Queries.LoginUser.Fixtures; +using Lumina.Contracts.Requests.Authentication; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Application.UnitTests.Common.Mapping.Authentication; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class LoginRequestMappingTests +{ + private readonly LoginRequestFixture _fixture; + + /// + /// Initializes a new instance of the class. + /// + public LoginRequestMappingTests() + { + _fixture = new(); + } + + [Fact] + public void ToQuery_WhenMappingRequest_ShouldMapCorrectly() + { + // Arrange + LoginRequest request = _fixture.CreateLoginRequest(); + + // Act + LoginUserQuery result = request.ToQuery(); + + // Assert + result.Should().NotBeNull(); + result.Username.Should().Be(request.Username); + result.Password.Should().Be(request.Password); + result.TotpCode.Should().Be(request.TotpCode); + } + + [Fact] + public void ToQuery_WhenMappingRequestWithNullValues_ShouldMapCorrectly() + { + // Arrange + LoginRequest request = new(null, null); + + // Act + LoginUserQuery result = request.ToQuery(); + + // Assert + result.Should().NotBeNull(); + result.Username.Should().BeNull(); + result.Password.Should().BeNull(); + result.TotpCode.Should().BeNull(); + } + + [Theory] + [InlineData("user1", "pass123", "123456")] + [InlineData("", "", "")] + [InlineData("testUser", null, null)] + [InlineData("admin", "admin123", null)] + public void ToQuery_WhenMappingRequestWithSpecificValues_ShouldMapCorrectly( + string? username, + string? password, + string? totpCode) + { + // Arrange + LoginRequest request = new(username, password, totpCode); + + // Act + LoginUserQuery result = request.ToQuery(); + + // Assert + result.Should().NotBeNull(); + result.Username.Should().Be(username); + result.Password.Should().Be(password); + result.TotpCode.Should().Be(totpCode); + } +} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Authentication/RecoverPasswordRequestMappingTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Authentication/RecoverPasswordRequestMappingTests.cs new file mode 100644 index 00000000..23b09457 --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Authentication/RecoverPasswordRequestMappingTests.cs @@ -0,0 +1,78 @@ +#region ========================================================================= USING ===================================================================================== +using FluentAssertions; +using Lumina.Application.Common.Mapping.Authentication; +using Lumina.Application.Core.UsersManagement.Authentication.Commands.RecoverPassword; +using Lumina.Application.UnitTests.Core.UsersManagement.Authentication.Commands.RecoverPassword.Fixtures; +using Lumina.Contracts.Requests.Authentication; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Application.UnitTests.Common.Mapping.Authentication; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class RecoverPasswordRequestMappingTests +{ + private readonly RecoverPasswordRequestFixture _fixture; + + /// + /// Initializes a new instance of the class. + /// + public RecoverPasswordRequestMappingTests() + { + _fixture = new(); + } + + [Fact] + public void ToCommand_WhenMappingRequest_ShouldMapCorrectly() + { + // Arrange + RecoverPasswordRequest request = _fixture.CreateRecoverPasswordRequest(); + + // Act + RecoverPasswordCommand result = request.ToCommand(); + + // Assert + result.Should().NotBeNull(); + result.Username.Should().Be(request.Username); + result.TotpCode.Should().Be(request.TotpCode); + } + + [Fact] + public void ToCommand_WhenMappingRequestWithNullValues_ShouldMapCorrectly() + { + // Arrange + RecoverPasswordRequest request = new(null, null); + + // Act + RecoverPasswordCommand result = request.ToCommand(); + + // Assert + result.Should().NotBeNull(); + result.Username.Should().BeNull(); + result.TotpCode.Should().BeNull(); + } + + [Theory] + [InlineData("user1", "123456")] + [InlineData("", "")] + [InlineData("testUser", null)] + [InlineData(null, "654321")] + public void ToCommand_WhenMappingRequestWithSpecificValues_ShouldMapCorrectly( + string? username, + string? totpCode) + { + // Arrange + RecoverPasswordRequest request = new(username, totpCode); + + // Act + RecoverPasswordCommand result = request.ToCommand(); + + // Assert + result.Should().NotBeNull(); + result.Username.Should().Be(username); + result.TotpCode.Should().Be(totpCode); + } +} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Authentication/RegistrationRequestMappingTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Authentication/RegistrationRequestMappingTests.cs new file mode 100644 index 00000000..155d6df4 --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Authentication/RegistrationRequestMappingTests.cs @@ -0,0 +1,146 @@ +#region ========================================================================= USING ===================================================================================== +using FluentAssertions; +using Lumina.Application.Common.Mapping.Authentication; +using Lumina.Application.Core.Maintenance.ApplicationSetup.Commands.SetupApplication; +using Lumina.Application.Core.UsersManagement.Authentication.Commands.RegisterUser; +using Lumina.Application.UnitTests.Core.UsersManagement.Authentication.Commands.RegisterUser.Fixture; +using Lumina.Contracts.Requests.Authentication; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Application.UnitTests.Common.Mapping.Authentication; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class RegistrationRequestMappingTests +{ + private readonly RegistrationRequestFixture _fixture; + + /// + /// Initializes a new instance of the class. + /// + public RegistrationRequestMappingTests() + { + _fixture = new(); + } + + [Fact] + public void ToSetupCommand_WhenMappingRequest_ShouldMapCorrectly() + { + // Arrange + RegistrationRequest request = _fixture.CreateRegistrationRequest(); + + // Act + SetupApplicationCommand result = request.ToSetupCommand(); + + // Assert + result.Should().NotBeNull(); + result.Username.Should().Be(request.Username); + result.Password.Should().Be(request.Password); + result.PasswordConfirm.Should().Be(request.PasswordConfirm); + result.Use2fa.Should().Be(request.Use2fa); + } + + [Fact] + public void ToCommand_WhenMappingRequest_ShouldMapCorrectly() + { + // Arrange + RegistrationRequest request = _fixture.CreateRegistrationRequest(); + + // Act + RegisterUserCommand result = request.ToCommand(); + + // Assert + result.Should().NotBeNull(); + result.Username.Should().Be(request.Username); + result.Password.Should().Be(request.Password); + result.PasswordConfirm.Should().Be(request.PasswordConfirm); + result.Use2fa.Should().Be(request.Use2fa); + } + + [Fact] + public void ToSetupCommand_WhenMappingRequestWithNullValues_ShouldMapCorrectly() + { + // Arrange + RegistrationRequest request = new(); + + // Act + SetupApplicationCommand result = request.ToSetupCommand(); + + // Assert + result.Should().NotBeNull(); + result.Username.Should().BeNull(); + result.Password.Should().BeNull(); + result.PasswordConfirm.Should().BeNull(); + result.Use2fa.Should().BeTrue(); + } + + [Fact] + public void ToCommand_WhenMappingRequestWithNullValues_ShouldMapCorrectly() + { + // Arrange + RegistrationRequest request = new(); + + // Act + RegisterUserCommand result = request.ToCommand(); + + // Assert + result.Should().NotBeNull(); + result.Username.Should().BeNull(); + result.Password.Should().BeNull(); + result.PasswordConfirm.Should().BeNull(); + result.Use2fa.Should().BeTrue(); + } + + [Theory] + [InlineData("user1", "pass123", "pass123", true)] + [InlineData("", "", "", false)] + [InlineData("testUser", null, null, true)] + [InlineData(null, "pass123", "pass123", false)] + public void ToSetupCommand_WhenMappingRequestWithSpecificValues_ShouldMapCorrectly( + string? username, + string? password, + string? passwordConfirm, + bool use2fa) + { + // Arrange + RegistrationRequest request = new(username, password, passwordConfirm, use2fa); + + // Act + SetupApplicationCommand result = request.ToSetupCommand(); + + // Assert + result.Should().NotBeNull(); + result.Username.Should().Be(username); + result.Password.Should().Be(password); + result.PasswordConfirm.Should().Be(passwordConfirm); + result.Use2fa.Should().Be(use2fa); + } + + [Theory] + [InlineData("user1", "pass123", "pass123", true)] + [InlineData("", "", "", false)] + [InlineData("testUser", null, null, true)] + [InlineData(null, "pass123", "pass123", false)] + public void ToCommand_WhenMappingRequestWithSpecificValues_ShouldMapCorrectly( + string? username, + string? password, + string? passwordConfirm, + bool use2fa) + { + // Arrange + RegistrationRequest request = new(username, password, passwordConfirm, use2fa); + + // Act + RegisterUserCommand result = request.ToCommand(); + + // Assert + result.Should().NotBeNull(); + result.Username.Should().Be(username); + result.Password.Should().Be(password); + result.PasswordConfirm.Should().Be(passwordConfirm); + result.Use2fa.Should().Be(use2fa); + } +} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Common/Metadata/GenreDtoMappingTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Common/Metadata/GenreDtoMappingTests.cs new file mode 100644 index 00000000..b0cb20f7 --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Common/Metadata/GenreDtoMappingTests.cs @@ -0,0 +1,127 @@ +#region ========================================================================= USING ===================================================================================== +using ErrorOr; +using FluentAssertions; +using Lumina.Application.Common.Mapping.Common.Metadata; +using Lumina.Contracts.DTO.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 GenreDtoMappingTests +{ + [Fact] + public void ToDomainEntity_WhenMappingValidGenreDto_ShouldMapCorrectly() + { + // Arrange + GenreDto genreDto = new("Rock"); + + // Act + ErrorOr result = genreDto.ToDomainEntity(); + + // Assert + result.IsError.Should().BeFalse(); + result.Value.Should().NotBeNull(); + result.Value.Name.Should().Be(genreDto.Name); + } + + [Theory] + [InlineData("Rock")] + [InlineData("Jazz")] + [InlineData("Classical")] + [InlineData("Pop")] + public void ToDomainEntity_WhenMappingDifferentValidGenreDtos_ShouldMapCorrectly(string name) + { + // Arrange + GenreDto genreDto = new(name); + + // Act + ErrorOr result = genreDto.ToDomainEntity(); + + // Assert + result.IsError.Should().BeFalse(); + result.Value.Should().NotBeNull(); + result.Value.Name.Should().Be(genreDto.Name); + } + + [Theory] + [InlineData("")] + [InlineData(" ")] + [InlineData(null)] + public void ToDomainEntity_WhenMappingInvalidGenreDto_ShouldReturnError(string? invalidName) + { + // Arrange + GenreDto genreDto = new(invalidName); + + // Act + ErrorOr result = genreDto.ToDomainEntity(); + + // Assert + result.IsError.Should().BeTrue(); + } + + [Fact] + public void ToDomainModels_WhenMappingMultipleValidGenreDtos_ShouldMapAllCorrectly() + { + // Arrange + List genreDtos = + [ + new GenreDto("Rock"), + new GenreDto("Jazz"), + new GenreDto("Classical"), + new GenreDto("Pop") + ]; + + // Act + IEnumerable> results = genreDtos.ToDomainEntities(); + + // Assert + results.Should().NotBeNull(); + results.Should().HaveCount(genreDtos.Count); + + List> resultList = results.ToList(); + for (int i = 0; i < genreDtos.Count; i++) + { + resultList[i].IsError.Should().BeFalse(); + resultList[i].Value.Name.Should().Be(genreDtos[i].Name); + } + } + + [Fact] + public void ToDomainModels_WhenMappingMixedValidAndInvalidGenreDtos_ShouldReturnMixedResults() + { + // Arrange + List genreDtos = + [ + new GenreDto("Rock"), + new GenreDto(""), + new GenreDto("Jazz"), + new GenreDto(" ") + ]; + + // Act + IEnumerable> results = genreDtos.ToDomainEntities(); + + // Assert + results.Should().NotBeNull(); + results.Should().HaveCount(genreDtos.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/GenreEntityMappingTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Common/Metadata/GenreEntityMappingTests.cs new file mode 100644 index 00000000..8251d2af --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Common/Metadata/GenreEntityMappingTests.cs @@ -0,0 +1,154 @@ +#region ========================================================================= USING ===================================================================================== +using ErrorOr; +using FluentAssertions; +using Lumina.Application.Common.DataAccess.Entities.Common; +using Lumina.Application.Common.Mapping.Common.Metadata; +using Lumina.Contracts.DTO.Common; +using Lumina.Domain.Common.ValueObjects.Metadata; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +using Lumina.Domain.Common.Errors; +#endregion + +namespace Lumina.Application.UnitTests.Common.Mapping.Common.Metadata; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class GenreEntityMappingTests +{ + [Fact] + public void ToResponse_WhenMappingValidGenreEntity_ShouldMapCorrectly() + { + // Arrange + GenreEntity entity = new("Fiction"); + + // Act + GenreDto result = entity.ToResponse(); + + // Assert + result.Should().NotBeNull(); + result.Name.Should().Be(entity.Name); + } + + [Theory] + [InlineData("Fiction")] + [InlineData("Science Fiction")] + [InlineData("Mystery")] + [InlineData("Romance")] + public void ToResponse_WhenMappingDifferentValidGenreEntities_ShouldMapCorrectly(string name) + { + // Arrange + GenreEntity entity = new(name); + + // Act + GenreDto result = entity.ToResponse(); + + // Assert + result.Should().NotBeNull(); + result.Name.Should().Be(entity.Name); + } + + [Theory] + [InlineData("")] + [InlineData(" ")] + [InlineData(null)] + public void ToResponse_WhenMappingInvalidGenreEntity_ShouldMapToDefault(string? invalidName) + { + // Arrange + GenreEntity entity = new(invalidName); + + // Act + GenreDto result = entity.ToResponse(); + + // Assert + result.Name.Should().Be(invalidName); + } + + [Fact] + public void ToDomainEntity_WhenMappingValidGenreEntity_ShouldMapCorrectly() + { + // Arrange + GenreEntity entity = new("Fiction"); + + // Act + ErrorOr result = entity.ToDomainEntity(); + + // Assert + result.IsError.Should().BeFalse(); + result.Value.Should().NotBeNull(); + result.Value.Name.Should().Be(entity.Name); + } + + [Theory] + [InlineData("")] + [InlineData(" ")] + [InlineData(null)] + public void ToDomainEntity_WhenMappingInvalidGenreEntity_ShouldMapToDefault(string? invalidName) + { + // Arrange + GenreEntity entity = new(invalidName); + + // Act + ErrorOr result = entity.ToDomainEntity(); + + // Assert + result.IsError.Should().BeTrue(); + result.FirstError.Should().Be(Errors.Metadata.GenreNameCannotBeEmpty); + } + + [Fact] + public void ToDomainEntities_WhenMappingMultipleValidGenreEntities_ShouldMapAllCorrectly() + { + // Arrange + List entities = + [ + new GenreEntity("Fiction"), + new GenreEntity("Mystery"), + new GenreEntity("Romance"), + new GenreEntity("Thriller") + ]; + + // Act + IEnumerable> results = entities.ToDomainEntities(); + + // Assert + results.Should().NotBeNull(); + results.Should().HaveCount(entities.Count); + + List> resultList = results.ToList(); + for (int i = 0; i < entities.Count; i++) + { + resultList[i].IsError.Should().BeFalse(); + resultList[i].Value.Name.Should().Be(entities[i].Name); + } + } + + [Fact] + public void ToResponses_WhenMappingMultipleValidGenreEntities_ShouldMapAllCorrectly() + { + // Arrange + List entities = + [ + new GenreEntity("Fiction"), + new GenreEntity("Mystery"), + new GenreEntity("Romance"), + new GenreEntity("Thriller") + ]; + + // Act + IEnumerable results = entities.ToResponses(); + + // Assert + results.Should().NotBeNull(); + results.Should().HaveCount(entities.Count); + + List resultList = results.ToList(); + for (int i = 0; i < entities.Count; i++) + { + resultList[i].Name.Should().Be(entities[i].Name); + } + } +} 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..10a7fa05 --- /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.DataAccess.Entities.Common; +using Lumina.Application.Common.Mapping.Common.Metadata; +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/TagDtoMappingTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Common/Metadata/TagDtoMappingTests.cs new file mode 100644 index 00000000..c6d870ba --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Common/Metadata/TagDtoMappingTests.cs @@ -0,0 +1,128 @@ +#region ========================================================================= USING ===================================================================================== +using ErrorOr; +using FluentAssertions; +using Lumina.Application.Common.Mapping.Common.Metadata; +using Lumina.Contracts.DTO.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 TagDtoMappingTests +{ + [Fact] + public void ToDomainEntity_WhenMappingValidTagDto_ShouldMapCorrectly() + { + // Arrange + TagDto tagDto = new("indie"); + + // Act + ErrorOr result = tagDto.ToDomainEntity(); + + // Assert + result.IsError.Should().BeFalse(); + result.Value.Should().NotBeNull(); + result.Value.Name.Should().Be(tagDto.Name); + } + + [Theory] + [InlineData("indie")] + [InlineData("electronic")] + [InlineData("instrumental")] + [InlineData("live")] + [InlineData("acoustic")] + public void ToDomainEntity_WhenMappingDifferentValidTagDtos_ShouldMapCorrectly(string name) + { + // Arrange + TagDto tagDto = new(name); + + // Act + ErrorOr result = tagDto.ToDomainEntity(); + + // Assert + result.IsError.Should().BeFalse(); + result.Value.Should().NotBeNull(); + result.Value.Name.Should().Be(tagDto.Name); + } + + [Theory] + [InlineData("")] + [InlineData(" ")] + [InlineData(null)] + public void ToDomainEntity_WhenMappingInvalidTagDto_ShouldReturnError(string? invalidName) + { + // Arrange + TagDto tagDto = new(invalidName); + + // Act + ErrorOr result = tagDto.ToDomainEntity(); + + // Assert + result.IsError.Should().BeTrue(); + } + + [Fact] + public void ToDomainModels_WhenMappingMultipleValidTagDtos_ShouldMapAllCorrectly() + { + // Arrange + List tagDtos = + [ + new TagDto("indie"), + new TagDto("electronic"), + new TagDto("instrumental"), + new TagDto("live") + ]; + + // Act + IEnumerable> results = tagDtos.ToDomainEntities(); + + // Assert + results.Should().NotBeNull(); + results.Should().HaveCount(tagDtos.Count); + + List> resultList = results.ToList(); + for (int i = 0; i < tagDtos.Count; i++) + { + resultList[i].IsError.Should().BeFalse(); + resultList[i].Value.Name.Should().Be(tagDtos[i].Name); + } + } + + [Fact] + public void ToDomainModels_WhenMappingMixedValidAndInvalidTagDtos_ShouldReturnMixedResults() + { + // Arrange + List tagDtos = + [ + new TagDto("indie"), + new TagDto(""), + new TagDto("electronic"), + new TagDto(" ") + ]; + + // Act + IEnumerable> results = tagDtos.ToDomainEntities(); + + // Assert + results.Should().NotBeNull(); + results.Should().HaveCount(tagDtos.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/Common/Metadata/TagEntityMappingTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Common/Metadata/TagEntityMappingTests.cs new file mode 100644 index 00000000..51ff7b6d --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Common/Metadata/TagEntityMappingTests.cs @@ -0,0 +1,154 @@ +#region ========================================================================= USING ===================================================================================== +using ErrorOr; +using FluentAssertions; +using Lumina.Application.Common.DataAccess.Entities.Common; +using Lumina.Application.Common.Mapping.Common.Metadata; +using Lumina.Contracts.DTO.Common; +using Lumina.Domain.Common.ValueObjects.Metadata; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +using Lumina.Domain.Common.Errors; +#endregion + +namespace Lumina.Application.UnitTests.Common.Mapping.Common.Metadata; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class TagEntityMappingTests +{ + [Fact] + public void ToResponse_WhenMappingValidTagEntity_ShouldMapCorrectly() + { + // Arrange + TagEntity entity = new("Fantasy"); + + // Act + TagDto result = entity.ToResponse(); + + // Assert + result.Should().NotBeNull(); + result.Name.Should().Be(entity.Name); + } + + [Theory] + [InlineData("Fantasy")] + [InlineData("Young Adult")] + [InlineData("Historical")] + [InlineData("Coming of Age")] + public void ToResponse_WhenMappingDifferentValidTagEntities_ShouldMapCorrectly(string name) + { + // Arrange + TagEntity entity = new(name); + + // Act + TagDto result = entity.ToResponse(); + + // Assert + result.Should().NotBeNull(); + result.Name.Should().Be(entity.Name); + } + + [Theory] + [InlineData("")] + [InlineData(" ")] + [InlineData(null)] + public void ToResponse_WhenMappingInvalidTagEntity_ShouldMapToDefault(string? invalidName) + { + // Arrange + TagEntity entity = new(invalidName); + + // Act + TagDto result = entity.ToResponse(); + + // Assert + result.Name.Should().Be(invalidName); + } + + [Fact] + public void ToDomainEntity_WhenMappingValidTagEntity_ShouldMapCorrectly() + { + // Arrange + TagEntity entity = new("Fantasy"); + + // Act + ErrorOr result = entity.ToDomainEntity(); + + // Assert + result.IsError.Should().BeFalse(); + result.Value.Should().NotBeNull(); + result.Value.Name.Should().Be(entity.Name); + } + + [Theory] + [InlineData("")] + [InlineData(" ")] + [InlineData(null)] + public void ToDomainEntity_WhenMappingInvalidTagEntity_ShouldMapToDefault(string? invalidName) + { + // Arrange + TagEntity entity = new(invalidName); + + // Act + ErrorOr result = entity.ToDomainEntity(); + + // Assert + result.IsError.Should().BeTrue(); + result.FirstError.Should().Be(Errors.Metadata.TagNameCannotBeEmpty); + } + + [Fact] + public void ToDomainEntities_WhenMappingMultipleValidTagEntities_ShouldMapAllCorrectly() + { + // Arrange + List entities = + [ + new TagEntity("Fantasy"), + new TagEntity("Young Adult"), + new TagEntity("Historical"), + new TagEntity("Coming of Age") + ]; + + // Act + IEnumerable> results = entities.ToDomainEntities(); + + // Assert + results.Should().NotBeNull(); + results.Should().HaveCount(entities.Count); + + List> resultList = results.ToList(); + for (int i = 0; i < entities.Count; i++) + { + resultList[i].IsError.Should().BeFalse(); + resultList[i].Value.Name.Should().Be(entities[i].Name); + } + } + + [Fact] + public void ToResponses_WhenMappingMultipleValidTagEntities_ShouldMapAllCorrectly() + { + // Arrange + List entities = + [ + new TagEntity("Fantasy"), + new TagEntity("Young Adult"), + new TagEntity("Historical"), + new TagEntity("Coming of Age") + ]; + + // Act + IEnumerable results = entities.ToResponses(); + + // Assert + results.Should().NotBeNull(); + results.Should().HaveCount(entities.Count); + + List resultList = results.ToList(); + for (int i = 0; i < entities.Count; i++) + { + resultList[i].Name.Should().Be(entities[i].Name); + } + } +} 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..4a00a61d --- /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.DataAccess.Entities.Common; +using Lumina.Application.Common.Mapping.Common.Metadata; +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/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..19c85af5 --- /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.Domain.Common.Enums.FileSystem; +using Lumina.Contracts.Responses.FileSystemManagement.Common; +using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.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..f1adcfc6 --- /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.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate; +using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.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..ce4edb46 --- /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.Responses.FileSystemManagement.Common; +using Lumina.Domain.Common.Enums.FileSystem; +using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate; +using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Entities; +using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.ValueObjects; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +using Lumina.Contracts.DTO.FileSystemManagement; +#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 + FileSystemItemDto result = domainModel.ToFileSystemItemDto(); + + // 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 + FileSystemItemDto result = domainModel.ToFileSystemItemDto(); + + // 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..14234647 --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/FileSystemManagement/FileSystem/Fixtures/FileSystemItemFixture.cs @@ -0,0 +1,26 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Domain.Common.Enums.FileSystem; +using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate; +using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.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..1d9a03d0 --- /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.Domain.Common.Enums.FileSystem; +using Lumina.Contracts.Responses.FileSystemManagement.Common; +using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate; +using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.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..d874a86a --- /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.Domain.Common.Enums.FileSystem; +using Lumina.Contracts.Responses.FileSystemManagement.Common; +using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.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..baf979f7 --- /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.BoundedContexts.FileSystemManagementBoundedContext.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/CheckPathExistsRequestMappingTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/FileSystemManagement/Paths/CheckPathExistsRequestMappingTests.cs new file mode 100644 index 00000000..3410b47d --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/FileSystemManagement/Paths/CheckPathExistsRequestMappingTests.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 CheckPathExistsRequestMappingTests +{ + private readonly IFixture _fixture; + + /// + /// Initializes a new instance of the class. + /// + public CheckPathExistsRequestMappingTests() + { + _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..28967086 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.BoundedContexts.FileSystemManagementBoundedContext.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..e6aaafbf --- /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.Domain.Common.Enums.PhotoLibrary; +using Lumina.Contracts.Responses.FileSystemManagement.Thumbnails; +using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.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/MediaLibrary/Management/AddMediaLibraryRequestMappingTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/Management/AddMediaLibraryRequestMappingTests.cs new file mode 100644 index 00000000..fa265725 --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/Management/AddMediaLibraryRequestMappingTests.cs @@ -0,0 +1,93 @@ +#region ========================================================================= USING ===================================================================================== +using FluentAssertions; +using Lumina.Application.Common.Mapping.MediaLibrary.Management; +using Lumina.Application.Core.MediaLibrary.Management.Commands.AddLibrary; +using Lumina.Contracts.Requests.MediaLibrary.Management; +using Lumina.Domain.Common.Enums.MediaLibrary; +using System; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Application.UnitTests.Common.Mapping.MediaLibrary.Management; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class AddMediaLibraryRequestMappingTests +{ + [Fact] + public void ToCommand_WhenMappingValidRequest_ShouldMapCorrectly() + { + // Arrange + AddLibraryRequest request = new( + Guid.NewGuid(), + "My Library", + LibraryType.Book, + ["C:/Books", "D:/Media/Books"] + ); + + // Act + AddLibraryCommand result = request.ToCommand(); + + // Assert + result.Should().NotBeNull(); + result.UserId.Should().Be(request.UserId); + result.Title.Should().Be(request.Title); + result.LibraryType.Should().Be(request.LibraryType); + result.ContentLocations.Should().BeEquivalentTo(request.ContentLocations); + } + + [Theory] + [InlineData(LibraryType.Book)] + [InlineData(LibraryType.Movie)] + [InlineData(LibraryType.TvShow)] + [InlineData(LibraryType.Music)] + public void ToCommand_WhenMappingDifferentLibraryTypes_ShouldMapCorrectly(LibraryType libraryType) + { + // Arrange + AddLibraryRequest request = new( + Guid.NewGuid(), + "My Library", + libraryType, + ["C:/Media"] + ); + + // Act + AddLibraryCommand result = request.ToCommand(); + + // Assert + result.Should().NotBeNull(); + result.UserId.Should().Be(request.UserId); + result.Title.Should().Be(request.Title); + result.LibraryType.Should().Be(libraryType); + result.ContentLocations.Should().BeEquivalentTo(request.ContentLocations); + } + + [Fact] + public void ToCommand_WhenMappingMultipleContentLocations_ShouldMapAllCorrectly() + { + // Arrange + string[] contentLocations = + [ + "C:/Media/Books", + "D:/Books", + "E:/Digital Library/Books", + "F:/Reading Material" + ]; + + AddLibraryRequest request = new( + Guid.NewGuid(), + "My Library", + LibraryType.Book, + contentLocations + ); + + // Act + AddLibraryCommand result = request.ToCommand(); + + // Assert + result.Should().NotBeNull(); + result.ContentLocations.Should().BeEquivalentTo(contentLocations); + } +} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/Management/LibraryEntityMappingTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/Management/LibraryEntityMappingTests.cs new file mode 100644 index 00000000..850fb472 --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/Management/LibraryEntityMappingTests.cs @@ -0,0 +1,132 @@ +#region ========================================================================= USING ===================================================================================== +using FluentAssertions; +using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management; +using Lumina.Application.Common.Mapping.MediaLibrary.Management; +using Lumina.Contracts.Responses.MediaLibrary.Management; +using Lumina.Domain.Common.Enums.MediaLibrary; +using System; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Application.UnitTests.Common.Mapping.MediaLibrary.Management; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class LibraryEntityMappingTests +{ + [Fact] + public void ToResponse_WhenMappingValidLibraryEntity_ShouldMapCorrectly() + { + // Arrange + LibraryEntity entity = new() + { + Id = Guid.NewGuid(), + UserId = Guid.NewGuid(), + Title = "My Library", + LibraryType = LibraryType.Book, + ContentLocations = + [ + new() { Path = "C:/Books" }, + new() { Path = "D:/Media/Books" } + ], + Created = DateTime.UtcNow, + Updated = null + }; + + // Act + LibraryResponse result = entity.ToResponse(); + + // Assert + result.Should().NotBeNull(); + result.Id.Should().Be(entity.Id); + result.UserId.Should().Be(entity.UserId); + result.Title.Should().Be(entity.Title); + result.LibraryType.Should().Be(entity.LibraryType); + result.ContentLocations.Should().BeEquivalentTo(entity.ContentLocations.Select(l => l.Path)); + result.Created.Should().Be(entity.Created); + result.Updated.Should().Be(entity.Updated); + } + + [Theory] + [InlineData(LibraryType.Book)] + [InlineData(LibraryType.Movie)] + [InlineData(LibraryType.TvShow)] + [InlineData(LibraryType.Music)] + public void ToResponse_WhenMappingDifferentLibraryTypes_ShouldMapCorrectly(LibraryType libraryType) + { + // Arrange + LibraryEntity entity = new() + { + Id = Guid.NewGuid(), + UserId = Guid.NewGuid(), + Title = "My Library", + LibraryType = libraryType, + ContentLocations = [new() { Path = "C:/Media" }], + Created = DateTime.UtcNow, + Updated = null + }; + + // Act + LibraryResponse result = entity.ToResponse(); + + // Assert + result.Should().NotBeNull(); + result.LibraryType.Should().Be(libraryType); + } + + [Fact] + public void ToResponse_WhenMappingMultipleContentLocations_ShouldMapAllCorrectly() + { + // Arrange + LibraryEntity entity = new() + { + Id = Guid.NewGuid(), + UserId = Guid.NewGuid(), + Title = "My Library", + LibraryType = LibraryType.Book, + ContentLocations = + [ + new() { Path = "C:/Media/Books" }, + new() { Path = "D:/Books" }, + new() { Path = "E:/Digital Library/Books" }, + new() { Path = "F:/Reading Material" } + ], + Created = DateTime.UtcNow, + Updated = null + }; + + // Act + LibraryResponse result = entity.ToResponse(); + + // Assert + result.Should().NotBeNull(); + result.ContentLocations.Should().BeEquivalentTo(entity.ContentLocations.Select(l => l.Path)); + } + + [Fact] + public void ToResponse_WhenMappingWithUpdatedDateTime_ShouldMapCorrectly() + { + // Arrange + DateTime updated = DateTime.UtcNow.AddDays(-1); + LibraryEntity entity = new() + { + Id = Guid.NewGuid(), + UserId = Guid.NewGuid(), + Title = "My Library", + LibraryType = LibraryType.Book, + ContentLocations = [new() { Path = "C:/Books" }], + Created = DateTime.UtcNow, + Updated = updated + }; + + // Act + LibraryResponse result = entity.ToResponse(); + + // Assert + result.Should().NotBeNull(); + result.Updated.Should().Be(updated); + } +} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/Management/LibraryMappingTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/Management/LibraryMappingTests.cs new file mode 100644 index 00000000..ed6fca91 --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/Management/LibraryMappingTests.cs @@ -0,0 +1,123 @@ +#region ========================================================================= USING ===================================================================================== +using ErrorOr; +using FluentAssertions; +using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management; +using Lumina.Application.Common.Mapping.Common.Metadata; +using Lumina.Application.Common.Mapping.MediaLibrary.Management; +using Lumina.Application.Common.Mapping.MediaLibrary.WrittenContentLibrary.BookLibrary.Common; +using Lumina.Domain.Common.Enums.MediaLibrary; +using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Application.UnitTests.Common.Mapping.MediaLibrary.Management; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class LibraryMappingTests +{ + [Fact] + public void ToRepositoryEntity_WhenMappingValidLibrary_ShouldMapCorrectly() + { + // Arrange + ErrorOr libraryResult = Library.Create( + Guid.NewGuid(), + "Test Library", + LibraryType.Book, + ["C:/Books", "D:/Media/Books"] + ); + Library library = libraryResult.Value; + + // Act + LibraryEntity result = library.ToRepositoryEntity(); + + // Assert + result.Should().NotBeNull(); + result.Id.Should().Be(library.Id.Value); + result.UserId.Should().Be(library.UserId.Value); + result.Title.Should().Be(library.Title); + result.LibraryType.Should().Be(library.LibraryType); + result.ContentLocations.Select(l => l.Path) + .Should().BeEquivalentTo(library.ContentLocations.Select(l => l.Path)); + result.Created.Should().Be(library.Created); + result.Updated.Should().Be(library.Updated.HasValue ? library.Updated : null); + } + + [Fact] + public void ToRepositoryEntity_WhenMappingLibraryWithEmptyContentLocations_ShouldMapCorrectly() + { + // Arrange + ErrorOr libraryResult = Library.Create( + Guid.NewGuid(), + "Empty Library", + LibraryType.Book, + [] + ); + Library library = libraryResult.Value; + + // Act + LibraryEntity result = library.ToRepositoryEntity(); + + // Assert + result.Should().NotBeNull(); + result.ContentLocations.Should().BeEmpty(); + } + + [Theory] + [InlineData(LibraryType.Book)] + [InlineData(LibraryType.Movie)] + [InlineData(LibraryType.TvShow)] + [InlineData(LibraryType.Music)] + public void ToRepositoryEntity_WhenMappingDifferentLibraryTypes_ShouldMapCorrectly(LibraryType libraryType) + { + // Arrange + ErrorOr libraryResult = Library.Create( + Guid.NewGuid(), + "Test Library", + libraryType, + ["C:/Media"] + ); + Library library = libraryResult.Value; + + // Act + LibraryEntity result = library.ToRepositoryEntity(); + + // Assert + result.Should().NotBeNull(); + result.LibraryType.Should().Be(libraryType); + } + + [Fact] + public void ToRepositoryEntity_WhenMappingMultipleContentLocations_ShouldMapAllCorrectly() + { + // Arrange + List contentLocations = + [ + "C:/Media/Books", + "D:/Books", + "E:/Digital Library/Books", + "F:/Reading Material" + ]; + + ErrorOr libraryResult = Library.Create( + Guid.NewGuid(), + "Test Library", + LibraryType.Book, + contentLocations + ); + Library library = libraryResult.Value; + + // Act + LibraryEntity result = library.ToRepositoryEntity(); + + // Assert + result.Should().NotBeNull(); + result.ContentLocations.Select(l => l.Path) + .Should().BeEquivalentTo(library.ContentLocations.Select(l => l.Path)); + } +} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/AddBookRequestMappingTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/AddBookRequestMappingTests.cs new file mode 100644 index 00000000..02ae92b3 --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/AddBookRequestMappingTests.cs @@ -0,0 +1,166 @@ +#region ========================================================================= USING ===================================================================================== +using FluentAssertions; +using Lumina.Application.Common.Mapping.MediaLibrary.WrittenContentLibrary.BookLibrary.Books; +using Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BooksLibrary.Books.Commands.AddBook; +using Lumina.Application.UnitTests.Core.MediaLibrary.WrittenContentLibrary.BooksLibrary.Books.Commands.AddBook.Fixtures; +using Lumina.Contracts.DTO.MediaContributors; +using Lumina.Contracts.DTO.MediaLibrary.WrittenContentLibrary; +using Lumina.Contracts.Requests.MediaLibrary.WrittenContentLibrary.BookLibrary.Books; +using Lumina.Domain.Common.Enums.BookLibrary; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Application.UnitTests.Common.Mapping.MediaLibrary.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 WrittenContentMetadataDto( + Title: "Test Book", + OriginalTitle: null, + Description: null, + ReleaseInfo: null, + Genres: null, + Tags: null, + Language: null, + OriginalLanguage: null, + Publisher: null, + PageCount: null), + Format: null, + Edition: null, + VolumeNumber: null, + Series: null, + ASIN: null, + GoodreadsId: null, + LCCN: null, + OCLCNumber: null, + OpenLibraryId: null, + LibraryThingId: null, + GoogleBooksId: null, + BarnesAndNobleId: null, + AppleBooksId: null, + ISBNs: null, + Contributors: null, + Ratings: null); + + // 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 WrittenContentMetadataDto( + Title: "Test Book", + OriginalTitle: null, + Description: null, + ReleaseInfo: null, + Genres: null, + Tags: null, + Language: null, + OriginalLanguage: null, + Publisher: null, + PageCount: null), + Format: null, + Edition: null, + VolumeNumber: null, + Series: null, + ASIN: null, + GoodreadsId: null, + LCCN: null, + OCLCNumber: null, + OpenLibraryId: null, + LibraryThingId: null, + GoogleBooksId: null, + BarnesAndNobleId: null, + AppleBooksId: null, + ISBNs: [new("978-0-123456-78-9", IsbnFormat.Isbn13)], + Contributors: + [ + new( + new MediaContributorNameDto("John Doe", "John Smith Doe"), + new MediaContributorRoleDto("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/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/BookMappingTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/BookMappingTests.cs new file mode 100644 index 00000000..7c5c6d93 --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/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.MediaLibrary.WrittenContentLibrary.BookLibrary.Books; +using Lumina.Application.Common.Mapping.MediaLibrary.WrittenContentLibrary.BookLibrary.Common; +using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary; +using Lumina.Domain.Core.BoundedContexts.WrittenContentLibraryBoundedContext.BookLibraryAggregate; +using System.Diagnostics.CodeAnalysis; +using Lumina.Application.UnitTests.Core.MediaLibrary.WrittenContentLibrary.BooksLibrary.Books.Commands.AddBook.Fixtures; +#endregion + +namespace Lumina.Application.UnitTests.Common.Mapping.MediaLibrary.WrittenContentLibrary.BookLibrary.Books; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class BookMappingTests +{ + private readonly BookFixture _bookFixture; + + /// + /// Initializes a new instance of the class. + /// + public BookMappingTests() + { + _bookFixture = new BookFixture(); + } + + [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.HasValue ? book.Format.Value : null); + 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/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/BookModelMappingTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/BookModelMappingTests.cs new file mode 100644 index 00000000..9f55af6c --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/BookModelMappingTests.cs @@ -0,0 +1,347 @@ +#region ========================================================================= USING ===================================================================================== +using ErrorOr; +using FluentAssertions; +using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary; +using Lumina.Application.Common.Mapping.Common.Metadata; +using Lumina.Application.Common.Mapping.MediaLibrary.WrittenContentLibrary.BookLibrary.Books; +using Lumina.Application.UnitTests.Core.MediaLibrary.WrittenContentLibrary.BooksLibrary.Books.Commands.AddBook.Fixtures; +using Lumina.Contracts.Responses.MediaLibrary.WrittenContentLibrary.BookLibrary.Books; +using Lumina.Domain.Core.BoundedContexts.WrittenContentLibraryBoundedContext.BookLibraryAggregate; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Application.UnitTests.Common.Mapping.MediaLibrary.WrittenContentLibrary.BookLibrary.Books; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class BookEntityMappingTests +{ + private readonly BookEntityFixture _bookEntityFixture; + + /// + /// Initializes a new instance of the class. + /// + public BookEntityMappingTests() + { + _bookEntityFixture = new BookEntityFixture(); + } + + [Fact] + public void ToDomainEntity_WhenMappingValidBookEntity_ShouldMapCorrectly() + { + // Arrange + BookEntity bookEntity = _bookEntityFixture.CreateBook(); + + // Act + ErrorOr result = bookEntity.ToDomainEntity(); + + // 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(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(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.ToDomainEntities(); + + // 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/MediaLibrary/WrittenContentLibrary/BookLibrary/Common/BookRatingDtoMappingTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Common/BookRatingDtoMappingTests.cs new file mode 100644 index 00000000..aa53b573 --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Common/BookRatingDtoMappingTests.cs @@ -0,0 +1,152 @@ +#region ========================================================================= USING ===================================================================================== +using ErrorOr; +using FluentAssertions; +using Lumina.Application.Common.Mapping.Common.Metadata; +using Lumina.Application.Common.Mapping.MediaLibrary.WrittenContentLibrary.BookLibrary.Common; +using Lumina.Application.UnitTests.Core.MediaLibrary.WrittenContentLibrary.BooksLibrary.Common.Fixtures; +using Lumina.Contracts.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary; +using Lumina.Domain.Core.BoundedContexts.WrittenContentLibraryBoundedContext.BookLibraryAggregate.ValueObjects; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Application.UnitTests.Common.Mapping.MediaLibrary.WrittenContentLibrary.BookLibrary.Common; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class BookRatingDtoMappingTests +{ + private readonly BookRatingDtoFixture _bookRatingDtoFixture; + + /// + /// Initializes a new instance of the class. + /// + public BookRatingDtoMappingTests() + { + _bookRatingDtoFixture = new BookRatingDtoFixture(); + } + + [Fact] + public void ToDomainEntity_WhenMappingCompleteBookRatinDto_ShouldMapAllPropertiesCorrectly() + { + // Arrange + BookRatingDto dto = _bookRatingDtoFixture.CreateComplete(); + + // Act + ErrorOr result = dto.ToDomainEntity(); + + // Assert + result.IsError.Should().BeFalse(); + result.Value.Should().NotBeNull(); + result.Value.Value.Should().Be(dto.Value!.Value); + result.Value.MaxValue.Should().Be(dto.MaxValue!.Value); + + if (dto.Source.HasValue) + { + result.Value.Source.HasValue.Should().BeTrue(); + result.Value.Source.Value.Should().Be(dto.Source.Value); + } + else + result.Value.Source.HasValue.Should().BeFalse(); + + if (dto.VoteCount.HasValue) + { + result.Value.VoteCount.HasValue.Should().BeTrue(); + result.Value.VoteCount.Value.Should().Be(dto.VoteCount.Value); + } + else + result.Value.VoteCount.HasValue.Should().BeFalse(); + } + + [Fact] + public void ToDomainEntity_WhenMappingMinimalBookRatingDto_ShouldMapRequiredPropertiesCorrectly() + { + // Arrange + BookRatingDto dto = _bookRatingDtoFixture.CreateMinimal(); + + // Act + ErrorOr result = dto.ToDomainEntity(); + + // Assert + result.IsError.Should().BeFalse(); + result.Value.Should().NotBeNull(); + result.Value.Value.Should().Be(dto.Value!.Value); + result.Value.MaxValue.Should().Be(dto.MaxValue!.Value); + result.Value.Source.HasValue.Should().BeFalse(); + result.Value.VoteCount.HasValue.Should().BeFalse(); + } + + [Fact] + public void ToDomainEntity_WhenMappingInvalidBookRatingDto_ShouldReturnError() + { + // Arrange + BookRatingDto dto = _bookRatingDtoFixture.CreateInvalid(); + + // Act + ErrorOr result = dto.ToDomainEntity(); + + // Assert + result.IsError.Should().BeTrue(); + } + + [Fact] + public void ToDomainModels_WhenMappingMultipleValidBookRatingDtos_ShouldMapAllCorrectly() + { + // Arrange + List dtos = + [ + _bookRatingDtoFixture.CreateComplete(), + _bookRatingDtoFixture.CreateMinimal() + ]; + + // Act + IEnumerable> results = dtos.ToDomainEntities(); + + // Assert + results.Should().NotBeNull(); + results.Should().HaveCount(dtos.Count); + + List> resultList = results.ToList(); + resultList.Should().AllSatisfy(result => result.IsError.Should().BeFalse()); + + // Complete rating + resultList[0].Value.Value.Should().Be(dtos[0].Value!.Value); + resultList[0].Value.MaxValue.Should().Be(dtos[0].MaxValue!.Value); + resultList[0].Value.Source.Value.Should().Be(dtos[0].Source!.Value); + resultList[0].Value.VoteCount.Value.Should().Be(dtos[0].VoteCount!.Value); + + // Minimal rating + resultList[1].Value.Value.Should().Be(dtos[1].Value!.Value); + resultList[1].Value.MaxValue.Should().Be(dtos[1].MaxValue!.Value); + resultList[1].Value.Source.HasValue.Should().BeFalse(); + resultList[1].Value.VoteCount.HasValue.Should().BeFalse(); + } + + [Fact] + public void ToDomainModels_WhenMappingMixedValidAndInvalidBookRatingDtos_ShouldReturnMixedResults() + { + // Arrange + List dtos = + [ + _bookRatingDtoFixture.CreateComplete(), + _bookRatingDtoFixture.CreateInvalid(), + _bookRatingDtoFixture.CreateMinimal() + ]; + + // Act + IEnumerable> results = dtos.ToDomainEntities(); + + // Assert + results.Should().NotBeNull(); + results.Should().HaveCount(dtos.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/MediaLibrary/WrittenContentLibrary/BookLibrary/Common/BookRatingEntityMappingTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Common/BookRatingEntityMappingTests.cs new file mode 100644 index 00000000..30793cf5 --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Common/BookRatingEntityMappingTests.cs @@ -0,0 +1,153 @@ +#region ========================================================================= USING ===================================================================================== +using ErrorOr; +using FluentAssertions; +using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary; +using Lumina.Application.Common.Mapping.Common.Metadata; +using Lumina.Application.Common.Mapping.MediaLibrary.WrittenContentLibrary.BookLibrary.Common; +using Lumina.Application.UnitTests.Core.MediaLibrary.WrittenContentLibrary.BooksLibrary.Common.Fixtures; +using Lumina.Contracts.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary; +using Lumina.Domain.Core.BoundedContexts.WrittenContentLibraryBoundedContext.BookLibraryAggregate.ValueObjects; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Application.UnitTests.Common.Mapping.MediaLibrary.WrittenContentLibrary.BookLibrary.Common; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class BookRatingEntityMappingTests +{ + private readonly BookRatingEntityFixture _fixture; + + /// + /// Initializes a new instance of the class. + /// + public BookRatingEntityMappingTests() + { + _fixture = new BookRatingEntityFixture(); + } + + [Fact] + public void ToResponse_WhenMappingValidBookRatingEntity_ShouldMapCorrectly() + { + // Arrange + BookRatingEntity entity = _fixture.CreateBookRating(); + + // Act + BookRatingDto result = entity.ToResponse(); + + // Assert + result.Should().NotBeNull(); + result.Value.Should().Be(entity.Value!.Value); + result.MaxValue.Should().Be(entity.MaxValue!.Value); + result.Source.Should().Be(entity.Source); + result.VoteCount.Should().Be(entity.VoteCount); + } + + [Fact] + public void ToResponse_WhenMappingInvalidBookRatingEntity_ShouldMapToDefaults() + { + // Arrange + BookRatingEntity entity = _fixture.CreateInvalidBookRating(); + + // Act + BookRatingDto result = entity.ToResponse(); + + // Assert + result.Should().NotBeNull(); + result.Value.Should().Be(default); + result.MaxValue.Should().Be(default); + result.Source.Should().Be(entity.Source); + result.VoteCount.Should().Be(entity.VoteCount); + } + + [Fact] + public void ToResponses_WhenMappingMultipleBookRatingEntities_ShouldMapAllCorrectly() + { + // Arrange + List entities = + [ + _fixture.CreateBookRating(), + _fixture.CreateBookRating() + ]; + + // Act + IEnumerable results = entities.ToResponses(); + + // Assert + results.Should().NotBeNull(); + results.Should().HaveCount(entities.Count); + results.Should().AllSatisfy(result => + { + result.Should().NotBeNull(); + result.Value.Should().BeInRange(1, 5); + result.MaxValue.Should().Be(5); + result.VoteCount.Should().BeInRange(1, 1000); + }); + } + + [Fact] + public void ToDomainEntity_WhenMappingValidBookRatingEntity_ShouldMapCorrectly() + { + // Arrange + BookRatingEntity entity = _fixture.CreateBookRating(); + + // Act + ErrorOr result = entity.ToDomainEntity(); + + // Assert + result.IsError.Should().BeFalse(); + result.Value.Should().NotBeNull(); + result.Value.Value.Should().Be(entity.Value); + result.Value.MaxValue.Should().Be(entity.MaxValue); + result.Value.Source.Value.Should().Be(entity.Source); + result.Value.VoteCount.Value.Should().Be(entity.VoteCount); + } + + [Fact] + public void ToDomainEntity_WhenMappingInvalidBookRatingEntity_ShouldMapToDefaults() + { + // Arrange + BookRatingEntity entity = _fixture.CreateInvalidBookRating(); + + // Act + ErrorOr result = entity.ToDomainEntity(); + + // Assert + result.IsError.Should().BeFalse(); + result.Value.Should().NotBeNull(); + result.Value.Value.Should().Be(default); + result.Value.MaxValue.Should().Be(default); + result.Value.Source.HasValue.Should().BeFalse(); + result.Value.VoteCount.HasValue.Should().BeFalse(); + } + + [Fact] + public void ToDomainEntities_WhenMappingMultipleBookRatingEntities_ShouldMapAllCorrectly() + { + // Arrange + List entities = + [ + _fixture.CreateBookRating(), + _fixture.CreateBookRating() + ]; + + // Act + IEnumerable> results = entities.ToDomainEntities(); + + // Assert + results.Should().NotBeNull(); + results.Should().HaveCount(entities.Count); + results.Should().AllSatisfy(result => + { + result.IsError.Should().BeFalse(); + result.Value.Should().NotBeNull(); + result.Value.Value.Should().BeInRange(1, 5); + result.Value.MaxValue.Should().Be(5); + result.Value.Source.HasValue.Should().BeTrue(); + result.Value.VoteCount.Value.Should().BeInRange(1, 1000); + }); + } +} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Common/BookRatingMappingTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Common/BookRatingMappingTests.cs new file mode 100644 index 00000000..60960ed0 --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Common/BookRatingMappingTests.cs @@ -0,0 +1,120 @@ +#region ========================================================================= USING ===================================================================================== +using FluentAssertions; +using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary; +using Lumina.Application.Common.Mapping.Common.Metadata; +using Lumina.Application.Common.Mapping.MediaLibrary.WrittenContentLibrary.BookLibrary.Common; +using Lumina.Application.UnitTests.Core.MediaLibrary.WrittenContentLibrary.BooksLibrary.Common.Fixtures; +using Lumina.Domain.Core.BoundedContexts.WrittenContentLibraryBoundedContext.BookLibraryAggregate.ValueObjects; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Application.UnitTests.Common.Mapping.MediaLibrary.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/MediaLibrary/WrittenContentLibrary/BookLibrary/Common/IsbnDtoMappingTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Common/IsbnDtoMappingTests.cs new file mode 100644 index 00000000..cbd3dad9 --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Common/IsbnDtoMappingTests.cs @@ -0,0 +1,153 @@ +#region ========================================================================= USING ===================================================================================== +using ErrorOr; +using FluentAssertions; +using Lumina.Application.Common.Mapping.Common.Metadata; +using Lumina.Application.Common.Mapping.MediaLibrary.WrittenContentLibrary.BookLibrary.Common; +using Lumina.Application.UnitTests.Core.MediaLibrary.WrittenContentLibrary.BooksLibrary.Common.Fixtures; +using Lumina.Contracts.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary; +using Lumina.Domain.Common.Enums.BookLibrary; +using Lumina.Domain.Core.BoundedContexts.WrittenContentLibraryBoundedContext.BookLibraryAggregate.ValueObjects; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Application.UnitTests.Common.Mapping.MediaLibrary.WrittenContentLibrary.BookLibrary.Common; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class IsbnDtoMappingTests +{ + private readonly IsbnDtoFixture _isbnDtoFixture; + + /// + /// Initializes a new instance of the class. + /// + public IsbnDtoMappingTests() + { + _isbnDtoFixture = new IsbnDtoFixture(); + } + + [Fact] + public void ToDomainEntity_WhenMappingValidIsbn10Dto_ShouldMapCorrectly() + { + // Arrange + IsbnDto dto = _isbnDtoFixture.CreateIsbn10(); + + // Act + ErrorOr result = dto.ToDomainEntity(); + + // Assert + result.IsError.Should().BeFalse(); + result.Value.Should().NotBeNull(); + result.Value.Value.Should().Be(dto.Value); + result.Value.Format.Should().Be(dto.Format!.Value); + } + + [Fact] + public void ToDomainEntity_WhenMappingValidIsbn13Dto_ShouldMapCorrectly() + { + // Arrange + IsbnDto dto = _isbnDtoFixture.CreateIsbn13(); + + // Act + ErrorOr result = dto.ToDomainEntity(); + + // Assert + result.IsError.Should().BeFalse(); + result.Value.Should().NotBeNull(); + result.Value.Value.Should().Be(dto.Value); + result.Value.Format.Should().Be(dto.Format!.Value); + } + + [Fact] + public void ToDomainEntity_WhenMappingDtoWithoutFormat_ShouldUseDefaultFormat() + { + // Arrange + IsbnDto dto = _isbnDtoFixture.CreateWithoutFormat(); + + // Act + ErrorOr result = dto.ToDomainEntity(); + + // Assert + result.IsError.Should().BeFalse(); + result.Value.Should().NotBeNull(); + result.Value.Value.Should().Be(dto.Value); + result.Value.Format.Should().Be(IsbnFormat.Isbn13); // Default format + } + + [Fact] + public void ToDomainEntity_WhenMappingInvalidIsbnDto_ShouldReturnError() + { + // Arrange + IsbnDto dto = _isbnDtoFixture.CreateInvalid(); + + // Act + ErrorOr result = dto.ToDomainEntity(); + + // Assert + result.IsError.Should().BeTrue(); + } + + [Fact] + public void ToDomainModels_WhenMappingMultipleValidIsbnDtos_ShouldMapAllCorrectly() + { + // Arrange + List dtos = + [ + _isbnDtoFixture.CreateIsbn10(), + _isbnDtoFixture.CreateIsbn13(), + _isbnDtoFixture.CreateWithoutFormat() + ]; + + // Act + IEnumerable> results = dtos.ToDomainEntities(); + + // Assert + results.Should().NotBeNull(); + results.Should().HaveCount(dtos.Count); + + List> resultList = results.ToList(); + resultList.Should().AllSatisfy(result => result.IsError.Should().BeFalse()); + + resultList[0].Value.Value.Should().Be(dtos[0].Value); + resultList[0].Value.Format.Should().Be(dtos[0].Format!.Value); + + resultList[1].Value.Value.Should().Be(dtos[1].Value); + resultList[1].Value.Format.Should().Be(dtos[1].Format!.Value); + + resultList[2].Value.Value.Should().Be(dtos[2].Value); + resultList[2].Value.Format.Should().Be(IsbnFormat.Isbn13); // Default format + } + + [Fact] + public void ToDomainModels_WhenMappingMixedValidAndInvalidIsbnDtos_ShouldReturnMixedResults() + { + // Arrange + List dtos = + [ + _isbnDtoFixture.CreateIsbn10(), + _isbnDtoFixture.CreateInvalid(), + _isbnDtoFixture.CreateIsbn13() + ]; + + // Act + IEnumerable> results = dtos.ToDomainEntities(); + + // Assert + results.Should().NotBeNull(); + results.Should().HaveCount(dtos.Count); + + List> resultList = results.ToList(); + + resultList[0].IsError.Should().BeFalse(); + resultList[0].Value.Value.Should().Be(dtos[0].Value); + + resultList[1].IsError.Should().BeTrue(); + + resultList[2].IsError.Should().BeFalse(); + resultList[2].Value.Value.Should().Be(dtos[2].Value); + } +} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Common/IsbnEntityMappingTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Common/IsbnEntityMappingTests.cs new file mode 100644 index 00000000..17970e83 --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Common/IsbnEntityMappingTests.cs @@ -0,0 +1,154 @@ +#region ========================================================================= USING ===================================================================================== +using ErrorOr; +using FluentAssertions; +using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary; +using Lumina.Application.Common.Mapping.Common.Metadata; +using Lumina.Application.Common.Mapping.MediaLibrary.WrittenContentLibrary.BookLibrary.Common; +using Lumina.Contracts.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary; +using Lumina.Domain.Common.Enums.BookLibrary; +using Lumina.Domain.Core.BoundedContexts.WrittenContentLibraryBoundedContext.BookLibraryAggregate.ValueObjects; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Application.UnitTests.Common.Mapping.MediaLibrary.WrittenContentLibrary.BookLibrary.Common; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class IsbnEntityMappingTests +{ + [Fact] + public void ToResponse_WhenMappingValidIsbnEntity_ShouldMapCorrectly() + { + // Arrange + IsbnEntity entity = new("0-7475-3269-9", IsbnFormat.Isbn10); + + // Act + IsbnDto result = entity.ToResponse(); + + // Assert + result.Should().NotBeNull(); + result.Value.Should().Be(entity.Value); + result.Format.Should().Be(entity.Format); + } + + [Theory] + [InlineData("0-7475-3269-9", IsbnFormat.Isbn10)] + [InlineData("978-0-7475-3269-9", IsbnFormat.Isbn13)] + public void ToResponse_WhenMappingDifferentValidIsbnEntities_ShouldMapCorrectly(string value, IsbnFormat format) + { + // Arrange + IsbnEntity entity = new(value, format); + + // Act + IsbnDto result = entity.ToResponse(); + + // Assert + result.Should().NotBeNull(); + result.Value.Should().Be(value); + result.Format.Should().Be(format); + } + + [Theory] + [InlineData("", null)] + [InlineData(" ", null)] + [InlineData(null, null)] + public void ToResponse_WhenMappingInvalidIsbnEntity_ShouldPreserveValues(string? value, IsbnFormat? format) + { + // Arrange + IsbnEntity entity = new(value, format); + + // Act + IsbnDto result = entity.ToResponse(); + + // Assert + result.Value.Should().Be(value); + result.Format.Should().Be(format); + } + + [Fact] + public void ToDomainEntity_WhenMappingValidIsbnEntity_ShouldMapCorrectly() + { + // Arrange + IsbnEntity entity = new("0-7475-3269-9", IsbnFormat.Isbn10); + + // Act + ErrorOr result = entity.ToDomainEntity(); + + // Assert + result.IsError.Should().BeFalse(); + result.Value.Should().NotBeNull(); + result.Value.Value.Should().Be(entity.Value); + result.Value.Format.Should().Be(entity.Format); + } + + [Theory] + [InlineData("")] + [InlineData(" ")] + [InlineData(null)] + public void ToDomainEntity_WhenMappingInvalidIsbnEntity_ShouldReturnError(string? invalidValue) + { + // Arrange + IsbnEntity entity = new(invalidValue, null); + + // Act + ErrorOr result = entity.ToDomainEntity(); + + // Assert + result.IsError.Should().BeTrue(); + } + + [Fact] + public void ToDomainEntities_WhenMappingMultipleValidIsbnEntities_ShouldMapAllCorrectly() + { + // Arrange + List entities = + [ + new IsbnEntity("0-7475-3269-9", IsbnFormat.Isbn10), + new IsbnEntity("978-0-7475-3269-9", IsbnFormat.Isbn13) + ]; + + // Act + IEnumerable> results = entities.ToDomainEntities(); + + // Assert + results.Should().NotBeNull(); + results.Should().HaveCount(entities.Count); + + List> resultList = results.ToList(); + for (int i = 0; i < entities.Count; i++) + { + resultList[i].IsError.Should().BeFalse(); + resultList[i].Value.Value.Should().Be(entities[i].Value); + resultList[i].Value.Format.Should().Be(entities[i].Format); + } + } + + [Fact] + public void ToResponses_WhenMappingMultipleValidIsbnEntities_ShouldMapAllCorrectly() + { + // Arrange + List entities = + [ + new IsbnEntity("0-7475-3269-9", IsbnFormat.Isbn10), + new IsbnEntity("978-0-7475-3269-9", IsbnFormat.Isbn13) + ]; + + // Act + IEnumerable results = entities.ToResponses(); + + // Assert + results.Should().NotBeNull(); + results.Should().HaveCount(entities.Count); + + List resultList = results.ToList(); + for (int i = 0; i < entities.Count; i++) + { + resultList[i].Value.Should().Be(entities[i].Value); + resultList[i].Format.Should().Be(entities[i].Format); + } + } +} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Common/IsbnMappingTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Common/IsbnMappingTests.cs new file mode 100644 index 00000000..1b10355d --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Common/IsbnMappingTests.cs @@ -0,0 +1,101 @@ +#region ========================================================================= USING ===================================================================================== +using FluentAssertions; +using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary; +using Lumina.Application.Common.Mapping.Common.Metadata; +using Lumina.Application.Common.Mapping.MediaLibrary.WrittenContentLibrary.BookLibrary.Common; +using Lumina.Application.UnitTests.Core.MediaLibrary.WrittenContentLibrary.BooksLibrary.Common.Fixtures; +using Lumina.Domain.Common.Enums.BookLibrary; +using Lumina.Domain.Core.BoundedContexts.WrittenContentLibraryBoundedContext.BookLibraryAggregate.ValueObjects; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Application.UnitTests.Common.Mapping.MediaLibrary.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/UserManagement/Users/Fixtures/UserEntityFixture.cs b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/UserManagement/Users/Fixtures/UserEntityFixture.cs new file mode 100644 index 00000000..7b999cf2 --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/UserManagement/Users/Fixtures/UserEntityFixture.cs @@ -0,0 +1,69 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management; +using Lumina.Application.Common.DataAccess.Entities.UsersManagement; +using Lumina.Domain.Common.Enums.MediaLibrary; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Application.UnitTests.Common.Mapping.UserManagement.Users.Fixtures; + +/// +/// Fixture class for the class. +/// +[ExcludeFromCodeCoverage] +public class UserEntityFixture +{ + /// + /// Creates a random valid user entity. + /// + /// Number of libraries to generate. Default is 0. + /// The created user entity. + public static UserEntity CreateUserEntity(int libraryCount = 0) + { + Guid userId = Guid.NewGuid(); + List libraries = [.. new Faker() + .CustomInstantiator(f => new LibraryEntity + { + Id = Guid.NewGuid(), + UserId = userId, + Title = f.Commerce.ProductName(), + LibraryType = f.PickRandom(), + ContentLocations = [], + Created = f.Date.Past(), + Updated = null + }) + .Generate(libraryCount)]; + + return new Faker() + .CustomInstantiator(f => new UserEntity + { + Id = userId, + Username = default!, + Password = default!, + Created = default, + TotpSecret = default, + Libraries = libraries + }) + .RuleFor(x => x.Username, f => f.Internet.UserName()) + .RuleFor(x => x.Password, f => Uri.EscapeDataString(f.Internet.Password())) + .RuleFor(x => x.Created, f => f.Date.Past()) + .RuleFor(x => x.TotpSecret, f => f.Random.Bool() ? f.Random.String2(32) : null) + .Generate(); + } + + /// + /// Creates a list of user entities. + /// + /// The number of entities to create. + /// The created list. + public static List CreateMany(int count = 3) + { + return Enumerable.Range(0, count) + .Select(_ => CreateUserEntity()) + .ToList(); + } +} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/UserManagement/Users/UserEntityMappingTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/UserManagement/Users/UserEntityMappingTests.cs new file mode 100644 index 00000000..c9a5e2c2 --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/UserManagement/Users/UserEntityMappingTests.cs @@ -0,0 +1,99 @@ +#region ========================================================================= USING ===================================================================================== +using FluentAssertions; +using Lumina.Application.Common.DataAccess.Entities.UsersManagement; +using Lumina.Application.Common.Mapping.Common.Metadata; +using Lumina.Application.Common.Mapping.MediaLibrary.WrittenContentLibrary.BookLibrary.Common; +using Lumina.Application.Common.Mapping.UsersManagement.Users; +using Lumina.Application.UnitTests.Common.Mapping.UserManagement.Users.Fixtures; +using Lumina.Contracts.Responses.UsersManagement.Users; +using Lumina.Domain.Common.Enums.MediaLibrary; +using System; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Application.UnitTests.Common.Mapping.UserManagement.Users; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class UserEntityMappingTests +{ + private readonly UserEntityFixture _fixture; + + /// + /// Initializes a new instance of the class. + /// + public UserEntityMappingTests() + { + _fixture = new UserEntityFixture(); + } + + [Fact] + public void ToResponse_WhenMappingValidUserEntity_ShouldMapCorrectly() + { + // Arrange + UserEntity entity = UserEntityFixture.CreateUserEntity(); + + // Act + UserResponse result = entity.ToResponse(); + + // Assert + result.Should().NotBeNull(); + result.Id.Should().Be(entity.Id); + result.Username.Should().Be(entity.Username); + result.Created.Should().Be(entity.Created); + result.Updated.Should().Be(entity.Updated); + } + + [Theory] + [InlineData("user1")] + [InlineData("test.user")] + [InlineData("john_doe")] + [InlineData("jane.doe@example.com")] + public void ToResponse_WhenMappingDifferentUsernames_ShouldMapCorrectly(string username) + { + // Arrange + UserEntity entity = UserEntityFixture.CreateUserEntity(); + entity.Username = username; + + // Act + UserResponse result = entity.ToResponse(); + + // Assert + result.Should().NotBeNull(); + result.Username.Should().Be(username); + } + + [Fact] + public void ToResponse_WhenMappingWithUpdatedDateTime_ShouldMapCorrectly() + { + // Arrange + UserEntity entity = UserEntityFixture.CreateUserEntity(); + entity.Updated = DateTime.UtcNow.AddDays(-1); + + // Act + UserResponse result = entity.ToResponse(); + + // Assert + result.Should().NotBeNull(); + result.Updated.Should().Be(entity.Updated); + } + + [Fact] + public void ToResponse_WhenMappingWithLibraries_ShouldNotAffectMapping() + { + // Arrange + UserEntity entity = UserEntityFixture.CreateUserEntity(2); + + // Act + UserResponse result = entity.ToResponse(); + + // Assert + result.Should().NotBeNull(); + result.Id.Should().Be(entity.Id); + result.Username.Should().Be(entity.Username); + result.Created.Should().Be(entity.Created); + result.Updated.Should().Be(entity.Updated); + } +} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/UserManagement/Users/UserMappingTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/UserManagement/Users/UserMappingTests.cs new file mode 100644 index 00000000..dfabb39a --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/UserManagement/Users/UserMappingTests.cs @@ -0,0 +1,147 @@ +#region ========================================================================= USING ===================================================================================== +using FluentAssertions; +using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management; +using Lumina.Application.Common.DataAccess.Entities.UsersManagement; +using Lumina.Application.Common.Mapping.Common.Metadata; +using Lumina.Application.Common.Mapping.MediaLibrary.WrittenContentLibrary.BookLibrary.Common; +using Lumina.Application.Common.Mapping.UsersManagement.Users; +using Lumina.Domain.Common.Enums.MediaLibrary; +using Lumina.Domain.Core.BoundedContexts.UserManagementBoundedContext.UserAggregate; +using Lumina.Domain.Core.BoundedContexts.UserManagementBoundedContext.UserAggregate.ValueObjects; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Application.UnitTests.Common.Mapping.UserManagement.Users; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class UserMappingTests +{ + [Fact] + public void ToRepositoryEntity_WhenMappingValidUser_ShouldOnlyUpdateUsername() + { + // Arrange + User domainEntity = User.Create( + UserId.Create(Guid.NewGuid()), + "newusername" + ).Value; + + UserEntity repositoryEntity = new() + { + Id = Guid.NewGuid(), + Username = "oldusername", + Password = "hashedpassword", + TotpSecret = "totpsecret", + VerificationToken = "verificationtoken", + VerificationTokenCreated = DateTime.UtcNow, + Libraries = [], + Created = DateTime.UtcNow, + Updated = null + }; + + // Act + UserEntity result = domainEntity.ToRepositoryEntity(repositoryEntity); + + // Assert + result.Should().NotBeNull(); + result.Should().BeSameAs(repositoryEntity); // Should modify the same instance + result.Username.Should().Be(domainEntity.Username); // Only username should be updated + + // Verify other properties remain unchanged + result.Id.Should().Be(repositoryEntity.Id); + result.Password.Should().Be(repositoryEntity.Password); + result.TotpSecret.Should().Be(repositoryEntity.TotpSecret); + result.VerificationToken.Should().Be(repositoryEntity.VerificationToken); + result.VerificationTokenCreated.Should().Be(repositoryEntity.VerificationTokenCreated); + result.Libraries.Should().BeSameAs(repositoryEntity.Libraries); + result.Created.Should().Be(repositoryEntity.Created); + result.Updated.Should().Be(repositoryEntity.Updated); + } + + [Theory] + [InlineData("user1")] + [InlineData("test.user")] + [InlineData("john_doe")] + [InlineData("jane.doe@example.com")] + public void ToRepositoryEntity_WhenMappingDifferentUsernames_ShouldUpdateCorrectly(string newUsername) + { + // Arrange + User domainEntity = User.Create( + UserId.Create(Guid.NewGuid()), + newUsername + ).Value; + + UserEntity repositoryEntity = new() + { + Id = Guid.NewGuid(), + Username = "oldusername", + Password = "hashedpassword", + Libraries = [], + Created = DateTime.UtcNow, + Updated = null + }; + + // Act + UserEntity result = domainEntity.ToRepositoryEntity(repositoryEntity); + + // Assert + result.Should().NotBeNull(); + result.Username.Should().Be(newUsername); + } + + [Fact] + public void ToRepositoryEntity_WhenRepositoryEntityHasLibraries_ShouldPreserveLibraries() + { + // Arrange + User domainEntity = User.Create( + UserId.Create(Guid.NewGuid()), + "newusername" + ).Value; + + List libraries = + [ + new() + { + Id = Guid.NewGuid(), + UserId = Guid.NewGuid(), + Title = "Library 1", + LibraryType = LibraryType.Book, + ContentLocations = [], + Created = DateTime.UtcNow, + Updated = null + }, + new() + { + Id = Guid.NewGuid(), + UserId = Guid.NewGuid(), + Title = "Library 2", + LibraryType = LibraryType.Movie, + ContentLocations = [], + Created = DateTime.UtcNow, + Updated = null + } + ]; + + UserEntity repositoryEntity = new() + { + Id = Guid.NewGuid(), + Username = "oldusername", + Password = "hashedpassword", + Libraries = libraries, + Created = DateTime.UtcNow, + Updated = null + }; + + // Act + UserEntity result = domainEntity.ToRepositoryEntity(repositoryEntity); + + // Assert + result.Should().NotBeNull(); + result.Libraries.Should().BeSameAs(libraries); + result.Libraries.Should().HaveCount(2); + } +} 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 84% 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..87453ea4 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 @@ -1,17 +1,17 @@ #region ========================================================================= USING ===================================================================================== using Bogus; using ErrorOr; -using Lumina.Contracts.Enums.FileSystem; +using Lumina.Domain.Common.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.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate; +using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.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. @@ -98,12 +98,18 @@ public class DirectoryFixture private Directory CreateNestedDirectory(int currentDepth, int maxDepth, int maxChildrenPerDirectory) { List childItems = []; - + // ensure we create at least one child if we haven't reached max depth if (currentDepth < maxDepth) { - int childCount = _faker.Random.Int(0, maxChildrenPerDirectory); + // force at least 1 child, up to maxChildrenPerDirectory + int childCount = _faker.Random.Int(1, maxChildrenPerDirectory); for (int i = 0; i < childCount; i++) - childItems.Add(CreateNestedDirectory(currentDepth + 1, maxDepth, maxChildrenPerDirectory)); + { + Directory childDirectory = CreateNestedDirectory(currentDepth + 1, maxDepth, maxChildrenPerDirectory); + ErrorOr addResult = childDirectory.SetParent(childDirectory); + if (!addResult.IsError) + childItems.Add(childDirectory); + } } return CreateDirectory(childItems: childItems); } 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..67fed2ac 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.DTO.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 FileSystemItemDto Create() { - return new FileSystemItemModel( + return new FileSystemItemDto( _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 92% 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..6ec10643 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.Domain.Common.Enums.FileSystem; +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..3590122a 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.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Services; +using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Entities; 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..e3cf4fc5 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.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate; +using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Entities; +using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Services; +using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.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..82010e94 --- /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.Domain.Common.Enums.FileSystem; +using Lumina.Contracts.Responses.FileSystemManagement.Common; +using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate; +using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Services; +using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Entities; +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 92% 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..4bed3c8d 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.Domain.Common.Enums.FileSystem; +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..13b69994 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.Domain.Common.Enums.FileSystem; +using Lumina.Contracts.Responses.FileSystemManagement.Common; +using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate; +using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Entities; +using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.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 62% 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..d9c9c5dd 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 @@ -1,13 +1,13 @@ #region ========================================================================= USING ===================================================================================== using Bogus; using ErrorOr; -using Lumina.Contracts.Enums.FileSystem; -using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.Entities; +using Lumina.Domain.Common.Enums.FileSystem; +using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.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..f16d6856 --- /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.Domain.Common.Enums.FileSystem; +using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.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 90% 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..474cb4ab 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.Contracts.Enums.FileSystem; -using Lumina.Contracts.Responses.FileManagement; -using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.Strategies.Platform; +using Lumina.Application.Core.FileSystemManagement.FileSystem.Queries.GetFileSystem; +using Lumina.Domain.Common.Enums.FileSystem; +using Lumina.Contracts.Responses.FileSystemManagement.FileSystem; +using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.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 91% 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..49439742 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 @@ -1,16 +1,16 @@ #region ========================================================================= USING ===================================================================================== using Bogus; using ErrorOr; -using Lumina.Contracts.Enums.FileSystem; +using Lumina.Domain.Common.Enums.FileSystem; using Lumina.Domain.Common.Primitives; -using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.Entities; +using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.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..c3db6f95 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.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Entities; +using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Services; using NSubstitute; using System; using System.Collections.Generic; @@ -19,8 +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; /// /// Contains unit tests for the class. @@ -29,11 +27,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 +38,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 +49,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 +83,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 +116,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 +125,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 +134,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 58% 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..a35acf54 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.Domain.Common.Enums.FileSystem; +using Lumina.Contracts.Responses.FileSystemManagement.Common; +using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Entities; +using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.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..3e85e421 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.BoundedContexts.FileSystemManagementBoundedContext.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 79% 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..e131676e 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.BoundedContexts.FileSystemManagementBoundedContext.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..04aeaa83 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.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Services; +using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.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 89% 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..9104707a 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.BoundedContexts.FileSystemManagementBoundedContext.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..5940d286 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.BoundedContexts.FileSystemManagementBoundedContext.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..4b35ccd4 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.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Services; +using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.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..8a73e859 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.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Services; +using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.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 89% 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..03fbeb64 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.BoundedContexts.FileSystemManagementBoundedContext.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 78% 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..d61f6b92 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.BoundedContexts.FileSystemManagementBoundedContext.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 82% 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..d64ff04c 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.Domain.Common.Enums.PhotoLibrary; +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..a3af9ea0 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.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Services; +using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.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/Maintenance/ApplicationSetup/Commands/SetupApplication/Fixtures/SetupApplicationCommandFixture.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/Maintenance/ApplicationSetup/Commands/SetupApplication/Fixtures/SetupApplicationCommandFixture.cs new file mode 100644 index 00000000..c4449632 --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/Maintenance/ApplicationSetup/Commands/SetupApplication/Fixtures/SetupApplicationCommandFixture.cs @@ -0,0 +1,35 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Application.Core.Maintenance.ApplicationSetup.Commands.SetupApplication; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Application.UnitTests.Core.Maintenance.ApplicationSetup.Commands.SetupApplication.Fixtures; + +/// +/// Fixture class for the class. +/// +[ExcludeFromCodeCoverage] +public class SetupApplicationCommandFixture +{ + /// + /// Creates a random valid command for the application setup. + /// + /// The created command. + public SetupApplicationCommand CreateSetupApplicationCommand() + { + string password = "Abcd123$"; + return new Faker() + .CustomInstantiator(f => new SetupApplicationCommand( + default!, + default!, + default!, + true + )) + .RuleFor(x => x.Username, f => f.Internet.UserName()) + .RuleFor(x => x.Password, password) + .RuleFor(x => x.PasswordConfirm, password) + .RuleFor(x => x.Use2fa, f => f.Random.Bool()) + .Generate(); + } +} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/Maintenance/ApplicationSetup/Commands/SetupApplication/SetupApplicationCommandHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/Maintenance/ApplicationSetup/Commands/SetupApplication/SetupApplicationCommandHandlerTests.cs new file mode 100644 index 00000000..276d67b1 --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/Maintenance/ApplicationSetup/Commands/SetupApplication/SetupApplicationCommandHandlerTests.cs @@ -0,0 +1,194 @@ +#region ========================================================================= USING ===================================================================================== +using ErrorOr; +using FluentAssertions; +using Lumina.Application.Common.DataAccess.Entities.UsersManagement; +using Lumina.Application.Common.DataAccess.Repositories.Users; +using Lumina.Application.Common.DataAccess.UoW; +using Lumina.Application.Common.Errors; +using Lumina.Application.Common.Infrastructure.Authentication; +using Lumina.Application.Common.Infrastructure.Security; +using Lumina.Application.Core.Maintenance.ApplicationSetup.Commands.SetupApplication; +using Lumina.Application.UnitTests.Common.Mapping.UserManagement.Users.Fixtures; +using Lumina.Application.UnitTests.Core.Maintenance.ApplicationSetup.Commands.SetupApplication.Fixtures; +using Lumina.Contracts.Responses.Authentication; +using NSubstitute; +using System; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Application.UnitTests.Core.Maintenance.ApplicationSetup.Commands.SetupApplication; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class SetupApplicationCommandHandlerTests +{ + private readonly IUnitOfWork _mockUnitOfWork; + private readonly IHashService _mockHashService; + private readonly ICryptographyService _mockCryptographyService; + private readonly ITotpTokenGenerator _mockTotpTokenGenerator; + private readonly IQRCodeGenerator _mockQRCodeGenerator; + private readonly IUserRepository _mockUserRepository; + private readonly SetupApplicationCommandHandler _sut; + private readonly SetupApplicationCommandFixture _setupApplicationCommandFixture; + + /// + /// Initializes a new instance of the class. + /// + public SetupApplicationCommandHandlerTests() + { + _mockUnitOfWork = Substitute.For(); + _mockHashService = Substitute.For(); + _mockCryptographyService = Substitute.For(); + _mockTotpTokenGenerator = Substitute.For(); + _mockQRCodeGenerator = Substitute.For(); + _mockUserRepository = Substitute.For(); + _setupApplicationCommandFixture = new SetupApplicationCommandFixture(); + + _mockUnitOfWork.GetRepository().Returns(_mockUserRepository); + + _sut = new SetupApplicationCommandHandler( + _mockUnitOfWork, + _mockHashService, + _mockCryptographyService, + _mockTotpTokenGenerator, + _mockQRCodeGenerator); + } + + [Fact] + public async Task Handle_WhenNoExistingUsers_ShouldCreateAdminUserWithout2FA() + { + // Arrange + SetupApplicationCommand command = _setupApplicationCommandFixture.CreateSetupApplicationCommand() with { Use2fa = false }; + string hashedPassword = Uri.EscapeDataString("hashedPassword"); + + _mockUserRepository.GetAllAsync(Arg.Any()) + .Returns(ErrorOrFactory.From(Enumerable.Empty())); + _mockHashService.HashString(command.Password!) + .Returns(hashedPassword); + _mockUserRepository.InsertAsync(Arg.Any(), Arg.Any()) + .Returns(Result.Created); + + // Act + ErrorOr result = await _sut.Handle(command, CancellationToken.None); + + // Assert + result.IsError.Should().BeFalse(); + result.Value.Should().NotBeNull(); + result.Value.Username.Should().Be(command.Username); + result.Value.TotpSecret.Should().BeNull(); + + await _mockUserRepository.Received(1).GetAllAsync(Arg.Any()); + await _mockUserRepository.Received(1).InsertAsync(Arg.Any(), Arg.Any()); + await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task Handle_WhenNoExistingUsersAndWith2FA_ShouldCreateAdminUserWithTOTP() + { + // Arrange + SetupApplicationCommand command = _setupApplicationCommandFixture.CreateSetupApplicationCommand() with { Use2fa = true }; + string hashedPassword = Uri.EscapeDataString("hashedPassword"); + byte[] totpSecret = [1, 2, 3]; + string qrCodeUri = "data:image/png;base64,test"; + string encryptedSecret = "encryptedSecret"; + + _mockUserRepository.GetAllAsync(Arg.Any()) + .Returns(ErrorOrFactory.From(Enumerable.Empty())); + _mockHashService.HashString(command.Password!) + .Returns(hashedPassword); + _mockTotpTokenGenerator.GenerateSecret() + .Returns(totpSecret); + _mockQRCodeGenerator.GenerateQrCodeDataUri(command.Username!, totpSecret) + .Returns(qrCodeUri); + _mockCryptographyService.Encrypt(Arg.Any()) + .Returns(encryptedSecret); + _mockUserRepository.InsertAsync(Arg.Any(), Arg.Any()) + .Returns(Result.Created); + + // Act + ErrorOr result = await _sut.Handle(command, CancellationToken.None); + + // Assert + result.IsError.Should().BeFalse(); + result.Value.Should().NotBeNull(); + result.Value.Username.Should().Be(command.Username); + result.Value.TotpSecret.Should().Be(qrCodeUri); + + await _mockUserRepository.Received(1).GetAllAsync(Arg.Any()); + await _mockUserRepository.Received(1).InsertAsync(Arg.Any(), Arg.Any()); + await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task Handle_WhenUserAlreadyExists_ShouldReturnError() + { + // Arrange + SetupApplicationCommand command = _setupApplicationCommandFixture.CreateSetupApplicationCommand(); + UserEntity existingUser = UserEntityFixture.CreateUserEntity(); + + _mockUserRepository.GetAllAsync(Arg.Any()) + .Returns(new[] { existingUser }); + + // Act + ErrorOr result = await _sut.Handle(command, CancellationToken.None); + + // Assert + result.IsError.Should().BeTrue(); + result.FirstError.Should().Be(Errors.Authorization.AdminAccountAlreadyCreated); + + await _mockUserRepository.Received(1).GetAllAsync(Arg.Any()); + await _mockUserRepository.DidNotReceive().InsertAsync(Arg.Any(), Arg.Any()); + await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task Handle_WhenGetAllUsersReturnsError_ShouldReturnError() + { + // Arrange + SetupApplicationCommand command = _setupApplicationCommandFixture.CreateSetupApplicationCommand(); + Error error = Error.Failure("Database.Error", "Failed to retrieve users"); + + _mockUserRepository.GetAllAsync(Arg.Any()) + .Returns(error); + + // Act + ErrorOr result = await _sut.Handle(command, CancellationToken.None); + + // Assert + result.IsError.Should().BeTrue(); + result.FirstError.Should().Be(error); + + await _mockUserRepository.Received(1).GetAllAsync(Arg.Any()); + await _mockUserRepository.DidNotReceive().InsertAsync(Arg.Any(), Arg.Any()); + await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task Handle_WhenInsertUserReturnsError_ShouldReturnError() + { + // Arrange + SetupApplicationCommand command = _setupApplicationCommandFixture.CreateSetupApplicationCommand(); + Error error = Error.Failure("Database.Error", "Failed to insert user"); + + _mockUserRepository.GetAllAsync(Arg.Any()) + .Returns(ErrorOrFactory.From(Enumerable.Empty())); + _mockUserRepository.InsertAsync(Arg.Any(), Arg.Any()) + .Returns(error); + + // Act + ErrorOr result = await _sut.Handle(command, CancellationToken.None); + + // Assert + result.IsError.Should().BeTrue(); + result.FirstError.Should().Be(error); + + await _mockUserRepository.Received(1).GetAllAsync(Arg.Any()); + await _mockUserRepository.Received(1).InsertAsync(Arg.Any(), Arg.Any()); + await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); + } +} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/Maintenance/ApplicationSetup/Commands/SetupApplication/SetupApplicationCommandValidatorTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/Maintenance/ApplicationSetup/Commands/SetupApplication/SetupApplicationCommandValidatorTests.cs new file mode 100644 index 00000000..d0752370 --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/Maintenance/ApplicationSetup/Commands/SetupApplication/SetupApplicationCommandValidatorTests.cs @@ -0,0 +1,233 @@ +#region ========================================================================= USING ===================================================================================== +using FluentValidation.TestHelper; +using Lumina.Application.Common.Errors; +using Lumina.Application.Core.Maintenance.ApplicationSetup.Commands.SetupApplication; +using Lumina.Application.UnitTests.Core.Maintenance.ApplicationSetup.Commands.SetupApplication.Fixtures; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Application.UnitTests.Core.Maintenance.ApplicationSetup.Commands.SetupApplication; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class SetupApplicationCommandValidatorTests +{ + private readonly SetupApplicationCommandValidator _validator; + private readonly SetupApplicationCommandFixture _commandFixture; + + /// + /// Initializes a new instance of the class. + /// + public SetupApplicationCommandValidatorTests() + { + _validator = new SetupApplicationCommandValidator(); + _commandFixture = new SetupApplicationCommandFixture(); + } + + [Fact] + public void Validate_WhenUsernameIsNull_ShouldHaveValidationError() + { + // Arrange + SetupApplicationCommand command = _commandFixture.CreateSetupApplicationCommand(); + command = command with { Username = null }; + + // Act + TestValidationResult result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationErrorFor(x => x.Username) + .WithErrorMessage(Errors.Authentication.UsernameCannotBeEmpty.Description); + } + + [Fact] + public void Validate_WhenUsernameIsEmpty_ShouldHaveValidationError() + { + // Arrange + SetupApplicationCommand command = _commandFixture.CreateSetupApplicationCommand(); + command = command with { Username = string.Empty }; + + // Act + TestValidationResult result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationErrorFor(x => x.Username) + .WithErrorMessage(Errors.Authentication.UsernameCannotBeEmpty.Description); + } + + [Fact] + public void Validate_WhenUsernameIsWhiteSpace_ShouldHaveValidationError() + { + // Arrange + SetupApplicationCommand command = _commandFixture.CreateSetupApplicationCommand(); + command = command with { Username = " " }; + + // Act + TestValidationResult result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationErrorFor(x => x.Username) + .WithErrorMessage(Errors.Authentication.UsernameCannotBeEmpty.Description); + } + + [Fact] + public void Validate_WhenPasswordIsNull_ShouldHaveValidationError() + { + // Arrange + SetupApplicationCommand command = _commandFixture.CreateSetupApplicationCommand(); + command = command with { Password = null! }; + + // Act + TestValidationResult result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationErrorFor(x => x.Password) + .WithErrorMessage(Errors.Authentication.PasswordCannotBeEmpty.Description); + } + + [Fact] + public void Validate_WhenPasswordIsEmpty_ShouldHaveValidationError() + { + // Arrange + SetupApplicationCommand command = _commandFixture.CreateSetupApplicationCommand(); + command = command with { Password = string.Empty }; + + // Act + TestValidationResult result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationErrorFor(x => x.Password) + .WithErrorMessage(Errors.Authentication.PasswordCannotBeEmpty.Description); + } + + [Fact] + public void Validate_WhenPasswordIsWhiteSpace_ShouldHaveValidationError() + { + // Arrange + SetupApplicationCommand command = _commandFixture.CreateSetupApplicationCommand(); + command = command with { Password = " " }; + + // Act + TestValidationResult result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationErrorFor(x => x.Password) + .WithErrorMessage(Errors.Authentication.PasswordCannotBeEmpty.Description); + } + + [Fact] + public void Validate_WhenPasswordConfirmIsNull_ShouldHaveValidationError() + { + // Arrange + SetupApplicationCommand command = _commandFixture.CreateSetupApplicationCommand(); + command = command with { PasswordConfirm = null! }; + + // Act + TestValidationResult result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationErrorFor(x => x.PasswordConfirm) + .WithErrorMessage(Errors.Authentication.PasswordConfirmCannotBeEmpty.Description); + } + + [Fact] + public void Validate_WhenPasswordConfirmIsEmpty_ShouldHaveValidationError() + { + // Arrange + SetupApplicationCommand command = _commandFixture.CreateSetupApplicationCommand(); + command = command with { PasswordConfirm = string.Empty }; + + // Act + TestValidationResult result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationErrorFor(x => x.PasswordConfirm) + .WithErrorMessage(Errors.Authentication.PasswordConfirmCannotBeEmpty.Description); + } + + [Fact] + public void Validate_WhenPasswordConfirmIsWhiteSpace_ShouldHaveValidationError() + { + // Arrange + SetupApplicationCommand command = _commandFixture.CreateSetupApplicationCommand(); + command = command with { PasswordConfirm = " " }; + + // Act + TestValidationResult result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationErrorFor(x => x.PasswordConfirm) + .WithErrorMessage(Errors.Authentication.PasswordConfirmCannotBeEmpty.Description); + } + + [Fact] + public void Validate_WhenPasswordAndPasswordConfirmDontMatch_ShouldHaveValidationError() + { + // Arrange + SetupApplicationCommand command = _commandFixture.CreateSetupApplicationCommand(); + command = command with { PasswordConfirm = "$321Bcda" }; + + // Act + TestValidationResult result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationErrorFor(x => x.Password) + .WithErrorMessage(Errors.Authentication.PasswordsNotMatch.Description); + } + + [Theory] + [InlineData("password123")] // Missing uppercase and special character + [InlineData("PASSWORD123")] // Missing special character + [InlineData("Password123")] // Missing special character + [InlineData("Password!@#")] // Missing number + [InlineData("Pass1!")] // Too short + [InlineData("password")] // Missing uppercase, number, and special character + public void Validate_WhenPasswordDoesNotMatchPattern_ShouldHaveValidationError(string password) + { + // Arrange + SetupApplicationCommand command = _commandFixture.CreateSetupApplicationCommand(); + command = command with { Password = password, PasswordConfirm = password }; + + // Act + TestValidationResult result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationErrorFor(x => x.Password) + .WithErrorMessage(Errors.Authentication.InvalidPassword.Description); + } + + [Theory] + [InlineData("Password1!")] // Valid password + [InlineData("Complex1@Password")] // Valid password + [InlineData("MyP@ssw0rd")] // Valid password + [InlineData("Abcd123!@#")] // Valid password + public void Validate_WhenPasswordMatchesPattern_ShouldNotHaveValidationError(string password) + { + // Arrange + SetupApplicationCommand command = _commandFixture.CreateSetupApplicationCommand(); + command = command with { Password = password, PasswordConfirm = password }; + + // Act + TestValidationResult result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationErrorFor(x => x.Password); + } + + [Fact] + public void Validate_WhenCommandIsValid_ShouldNotHaveValidationError() + { + // Arrange + SetupApplicationCommand command = _commandFixture.CreateSetupApplicationCommand(); + command = command with { Password = "$321Bcda", PasswordConfirm = "$321Bcda" }; + + // Act + TestValidationResult result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationErrorFor(x => x.Username); + result.ShouldNotHaveValidationErrorFor(x => x.Password); + result.ShouldNotHaveValidationErrorFor(x => x.PasswordConfirm); + } +} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/Maintenance/ApplicationSetup/Queries/CheckInitiliazation/CheckInitializationQueryHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/Maintenance/ApplicationSetup/Queries/CheckInitiliazation/CheckInitializationQueryHandlerTests.cs new file mode 100644 index 00000000..06801841 --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/Maintenance/ApplicationSetup/Queries/CheckInitiliazation/CheckInitializationQueryHandlerTests.cs @@ -0,0 +1,91 @@ +#region ========================================================================= USING ===================================================================================== +using AutoFixture; +using AutoFixture.AutoNSubstitute; +using ErrorOr; +using FluentAssertions; +using Lumina.Application.Common.DataAccess.Entities.UsersManagement; +using Lumina.Application.Common.DataAccess.Repositories.Users; +using Lumina.Application.Common.DataAccess.UoW; +using Lumina.Application.Core.Maintenance.ApplicationSetup.Queries.CheckInitialization; +using Lumina.Application.UnitTests.Common.Mapping.UserManagement.Users.Fixtures; +using Lumina.Contracts.Responses.UsersManagement; +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.Maintenance.ApplicationSetup.Queries.CheckInitiliazation; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class CheckInitializationQueryHandlerTests +{ + private readonly IUnitOfWork _mockUnitOfWork; + private readonly IUserRepository _mockUserRepository; + private readonly CheckInitializationQueryHandler _sut; + + /// + /// Initializes a new instance of the class. + /// + public CheckInitializationQueryHandlerTests() + { + _mockUnitOfWork = Substitute.For(); + _mockUserRepository = Substitute.For(); + + _mockUnitOfWork.GetRepository().Returns(_mockUserRepository); + + _sut = new CheckInitializationQueryHandler(_mockUnitOfWork); + } + + [Fact] + public async Task Handle_WhenUsersExist_ShouldReturnInitialized() + { + // Arrange + List users = UserEntityFixture.CreateMany(); + _mockUserRepository.GetAllAsync(Arg.Any()) + .Returns(ErrorOrFactory.From(users.AsEnumerable())); + + // Act + InitializationResponse result = await _sut.Handle(new CheckInitializationQuery(), CancellationToken.None); + + // Assert + result.IsInitialized.Should().BeTrue(); + await _mockUserRepository.Received(1).GetAllAsync(Arg.Any()); + } + + [Fact] + public async Task Handle_WhenNoUsersExist_ShouldReturnNotInitialized() + { + // Arrange + _mockUserRepository.GetAllAsync(Arg.Any()) + .Returns(ErrorOrFactory.From(Enumerable.Empty())); + + // Act + InitializationResponse result = await _sut.Handle(new CheckInitializationQuery(), CancellationToken.None); + + // Assert + result.IsInitialized.Should().BeFalse(); + await _mockUserRepository.Received(1).GetAllAsync(Arg.Any()); + } + + [Fact] + public async Task Handle_WhenRepositoryReturnsError_ShouldReturnNotInitialized() + { + // Arrange + Error error = Error.Failure("Database.Error", "Failed to retrieve users"); + _mockUserRepository.GetAllAsync(Arg.Any()) + .Returns(error); + + // Act + InitializationResponse result = await _sut.Handle(new CheckInitializationQuery(), CancellationToken.None); + + // Assert + result.IsInitialized.Should().BeFalse(); + await _mockUserRepository.Received(1).GetAllAsync(Arg.Any()); + } +} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/Management/Fixtures/DomainLibraryFixture.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/Management/Fixtures/DomainLibraryFixture.cs new file mode 100644 index 00000000..eb981649 --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/Management/Fixtures/DomainLibraryFixture.cs @@ -0,0 +1,81 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using ErrorOr; +using Lumina.Contracts.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary; +using Lumina.Domain.Common.Enums.MediaLibrary; +using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate; +using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Application.UnitTests.Core.MediaLibrary.Management.Fixtures; + +/// +/// Fixture class for the . +/// +[ExcludeFromCodeCoverage] +public class DomainLibraryFixture +{ + private readonly Faker _faker; + private readonly Random _random = new(); + + /// + /// Initializes a new instance of the class. + /// + public DomainLibraryFixture() + { + _faker = new Faker(); + } + + /// + /// Creates a media library domain entity. + /// + /// The created media library entity. + public Library CreateLibrary() + { + List validPaths = + [ + "C:/Media", + "D:/Books", + "E:/Digital Library", + "F:/Content" + ]; + + ErrorOr library = Library.Create( + Guid.NewGuid(), + _faker.Random.String2(_faker.Random.Number(1, 50)), + _faker.PickRandom(), + validPaths.Take(_random.Next(1, validPaths.Count)) + ); + + return library.Value; + } + + public Library CreateLibraryWithSpecificValues( + Guid? id = null, + Guid? userId = null, + string? title = null, + LibraryType? libraryType = null, + IEnumerable? contentLocations = null) + { + ErrorOr library = id is null ? + Library.Create( + userId ?? Guid.NewGuid(), + title ?? _faker.Random.String2(_faker.Random.Number(1, 50)), + libraryType ?? LibraryType.Book, + contentLocations ?? ["C:/Media"] + ) : + Library.Create( + LibraryId.Create(id.Value), + userId ?? Guid.NewGuid(), + title ?? _faker.Random.String2(_faker.Random.Number(1, 50)), + libraryType ?? LibraryType.Book, + contentLocations ?? ["C:/Media"] + ); + + return library.Value; + } +} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/WrittenContentLibrary/BooksLibrary/Books/Commands/AddBook/AddBookCommandHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/WrittenContentLibrary/BooksLibrary/Books/Commands/AddBook/AddBookCommandHandlerTests.cs similarity index 62% rename from tests/UnitTests/Lumina.Application.UnitTests/Core/WrittenContentLibrary/BooksLibrary/Books/Commands/AddBook/AddBookCommandHandlerTests.cs rename to tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/WrittenContentLibrary/BooksLibrary/Books/Commands/AddBook/AddBookCommandHandlerTests.cs index 1b31b0e5..9876cb4f 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/WrittenContentLibrary/BooksLibrary/Books/Commands/AddBook/AddBookCommandHandlerTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/WrittenContentLibrary/BooksLibrary/Books/Commands/AddBook/AddBookCommandHandlerTests.cs @@ -1,19 +1,19 @@ -#region ========================================================================= USING ===================================================================================== +#region ========================================================================= USING ===================================================================================== using AutoFixture; using AutoFixture.AutoNSubstitute; using ErrorOr; using FluentAssertions; +using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary; using Lumina.Application.Common.DataAccess.Repositories.Books; using Lumina.Application.Common.DataAccess.UoW; -using Lumina.Application.Core.WrittenContentLibrary.BooksLibrary.Books.Commands.AddBook; +using Lumina.Application.Core.MediaLibrary.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.Enums.BookLibrary; -using Lumina.Contracts.Models.Common; -using Lumina.Contracts.Models.WrittenContentLibrary.BookLibrary; +using Lumina.Application.UnitTests.Core.MediaLibrary.WrittenContentLibrary.BooksLibrary.Books.Commands.AddBook.Fixtures; +using Lumina.Contracts.DTO.Common; +using Lumina.Contracts.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary; +using Lumina.Contracts.Responses.MediaLibrary.WrittenContentLibrary.BookLibrary.Books; +using Lumina.Domain.Common.Enums.BookLibrary; using Lumina.Domain.Common.Errors; -using Lumina.Domain.Core.Aggregates.WrittenContentLibrary.BookLibraryAggregate; -using MapsterMapper; using NSubstitute; using System; using System.Diagnostics.CodeAnalysis; @@ -21,7 +21,7 @@ using System.Threading; using System.Threading.Tasks; #endregion -namespace Lumina.Application.UnitTests.Core.WrittenContentLibrary.BooksLibrary.Books.Commands.AddBook; +namespace Lumina.Application.UnitTests.Core.MediaLibrary.WrittenContentLibrary.BooksLibrary.Books.Commands.AddBook; /// /// Contains unit tests for the class. @@ -31,7 +31,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 +45,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 +58,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 +77,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 +94,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 +113,15 @@ public class AddBookCommandHandlerTests { // Arrange AddBookCommand bookCommand = _commandBookFixture.CreateCommandBook(); - bookCommand = bookCommand with { ISBNs = [new IsbnModel("invalid", IsbnFormat.Isbn13)] }; + bookCommand = bookCommand with { ISBNs = [new IsbnDto("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 +130,15 @@ public class AddBookCommandHandlerTests { // Arrange AddBookCommand bookCommand = _commandBookFixture.CreateCommandBook(); - bookCommand = bookCommand with { Ratings = [new BookRatingModel(-1, 5, null, null)] }; + bookCommand = bookCommand with { Ratings = [new BookRatingDto(-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 +149,19 @@ public class AddBookCommandHandlerTests AddBookCommand bookCommand = _commandBookFixture.CreateCommandBook(); bookCommand = bookCommand with { - Metadata = bookCommand.Metadata with + Metadata = bookCommand.Metadata! with { - Genres = [new GenreModel("")] + Genres = [new GenreDto("")] } }; // 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 +172,19 @@ public class AddBookCommandHandlerTests AddBookCommand bookCommand = _commandBookFixture.CreateCommandBook(); bookCommand = bookCommand with { - Metadata = bookCommand.Metadata with + Metadata = bookCommand.Metadata! with { - Tags = [new TagModel("")] + Tags = [new TagDto("")] } }; // 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 +195,9 @@ public class AddBookCommandHandlerTests AddBookCommand bookCommand = _commandBookFixture.CreateCommandBook(); bookCommand = bookCommand with { - Metadata = bookCommand.Metadata with + Metadata = bookCommand.Metadata! with { - ReleaseInfo = new ReleaseInfoModel( + ReleaseInfo = new ReleaseInfoDto( OriginalReleaseDate: new DateOnly(2025, 1, 1), ReReleaseDate: new DateOnly(2024, 1, 1), OriginalReleaseYear: null, @@ -215,12 +209,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 +225,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 LanguageInfoDto("", "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 +248,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 LanguageInfoDto("", "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/MediaLibrary/WrittenContentLibrary/BooksLibrary/Books/Commands/AddBook/AddBookCommandValidatorTests.cs similarity index 87% rename from tests/UnitTests/Lumina.Application.UnitTests/Core/WrittenContentLibrary/BooksLibrary/Books/Commands/AddBook/AddBookCommandValidatorTests.cs rename to tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/WrittenContentLibrary/BooksLibrary/Books/Commands/AddBook/AddBookCommandValidatorTests.cs index f7636d20..90d6c117 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/WrittenContentLibrary/BooksLibrary/Books/Commands/AddBook/AddBookCommandValidatorTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/WrittenContentLibrary/BooksLibrary/Books/Commands/AddBook/AddBookCommandValidatorTests.cs @@ -1,16 +1,16 @@ #region ========================================================================= USING ===================================================================================== using Bogus; using FluentValidation.TestHelper; -using Lumina.Application.Core.WrittenContentLibrary.BooksLibrary.Books.Commands.AddBook; -using Lumina.Application.UnitTests.Core.WrittenContentLibrary.BooksLibrary.Books.Commands.AddBook.Fixtures; -using Lumina.Contracts.Enums.BookLibrary; +using Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BooksLibrary.Books.Commands.AddBook; +using Lumina.Application.UnitTests.Core.MediaLibrary.WrittenContentLibrary.BooksLibrary.Books.Commands.AddBook.Fixtures; +using Lumina.Domain.Common.Enums.BookLibrary; using Lumina.Domain.Common.Errors; using System; using System.Diagnostics.CodeAnalysis; using System.Linq; #endregion -namespace Lumina.Application.UnitTests.Core.WrittenContentLibrary.BooksLibrary.Books.Commands.AddBook; +namespace Lumina.Application.UnitTests.Core.MediaLibrary.WrittenContentLibrary.BooksLibrary.Books.Commands.AddBook; /// /// Contains unit tests for the class. @@ -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/MediaLibrary/WrittenContentLibrary/BooksLibrary/Books/Commands/AddBook/Fixtures/AddBookCommandFixture.cs similarity index 80% rename from tests/UnitTests/Lumina.Application.UnitTests/Core/WrittenContentLibrary/BooksLibrary/Books/Commands/AddBook/Fixtures/AddBookCommandFixture.cs rename to tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/WrittenContentLibrary/BooksLibrary/Books/Commands/AddBook/Fixtures/AddBookCommandFixture.cs index 31b46d05..64e98c87 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/WrittenContentLibrary/BooksLibrary/Books/Commands/AddBook/Fixtures/AddBookCommandFixture.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/WrittenContentLibrary/BooksLibrary/Books/Commands/AddBook/Fixtures/AddBookCommandFixture.cs @@ -1,20 +1,20 @@ #region ========================================================================= USING ===================================================================================== using AutoFixture; using Bogus; -using Lumina.Application.Core.WrittenContentLibrary.BooksLibrary.Books.Commands.AddBook; +using Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BooksLibrary.Books.Commands.AddBook; using Lumina.Application.UnitTests.Common.Setup; -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.DTO.Common; +using Lumina.Contracts.DTO.MediaContributors; +using Lumina.Contracts.DTO.MediaLibrary.WrittenContentLibrary; +using Lumina.Contracts.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary; +using Lumina.Domain.Common.Enums.BookLibrary; 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; +namespace Lumina.Application.UnitTests.Core.MediaLibrary.WrittenContentLibrary.BooksLibrary.Books.Commands.AddBook.Fixtures; /// /// Fixture class for the class. @@ -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( + ReleaseInfoDto releaseInfo = new Faker() + .CustomInstantiator(f => new ReleaseInfoDto( 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 GenreDto( 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 TagDto( 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 MediaContributorRoleDto( 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 MediaContributorNameDto( 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 MediaContributorDto( 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 BookRatingDto( 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 LanguageInfoDto( 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 LanguageInfoDto( 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 WrittenContentMetadataDto( 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 IsbnDto( default!, default )) @@ -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 ReleaseInfoDto( _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 GenreDto( _fixture.Create() )); - _fixture.Register(() => new TagModel( + _fixture.Register(() => new TagDto( _fixture.Create() )); - _fixture.Register(() => new LanguageInfoModel( + _fixture.Register(() => new LanguageInfoDto( _fixture.Create(), _fixture.Create(), _fixture.Create() )); - _fixture.Register(() => new IsbnModel( + _fixture.Register(() => new IsbnDto( _fixture.Create(), _fixture.Create() )); - _fixture.Register(() => new BookRatingModel( + _fixture.Register(() => new BookRatingDto( _fixture.Create(), _fixture.Create(), _fixture.Create(), _fixture.Create() )); - _fixture.Register(() => new WrittenContentMetadataModel( + _fixture.Register(() => new WrittenContentMetadataDto( _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 BookSeriesDto( _fixture.Create() )); - _fixture.Register(() => new MediaContributorRoleModel( + _fixture.Register(() => new MediaContributorRoleDto( _fixture.Create(), _fixture.Create() )); - _fixture.Register(() => new MediaContributorNameModel( + _fixture.Register(() => new MediaContributorNameDto( _fixture.Create(), _fixture.Create() )); - _fixture.Register(() => new MediaContributorModel( - _fixture.Create(), - _fixture.Create() + _fixture.Register(() => new MediaContributorDto( + _fixture.Create(), + _fixture.Create() )); } diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/WrittenContentLibrary/BooksLibrary/Books/Commands/AddBook/Fixtures/AddBookRequestFixture.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/WrittenContentLibrary/BooksLibrary/Books/Commands/AddBook/Fixtures/AddBookRequestFixture.cs new file mode 100644 index 00000000..5eb89f32 --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/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.Domain.Common.Enums.BookLibrary; +using Lumina.Contracts.Requests.MediaLibrary.WrittenContentLibrary.BookLibrary.Books; +using System; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +using Lumina.Contracts.DTO.Common; +using Lumina.Contracts.DTO.MediaContributors; +using Lumina.Contracts.DTO.MediaLibrary.WrittenContentLibrary; +using Lumina.Contracts.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary; +#endregion + +namespace Lumina.Application.UnitTests.Core.MediaLibrary.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); + + ReleaseInfoDto releaseInfo = new Faker() + .CustomInstantiator(f => new ReleaseInfoDto( + 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 GenreDto( + default! + )) + .RuleFor(e => e.Name, f => f.Random.String2(f.Random.Number(1, 50))); + + Faker tag = new Faker() + .CustomInstantiator(f => new TagDto( + default! + )) + .RuleFor(e => e.Name, f => f.Random.String2(f.Random.Number(1, 50))); + + Faker mediaContributorRole = new Faker() + .CustomInstantiator(f => new MediaContributorRoleDto( + 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 MediaContributorNameDto( + 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 MediaContributorDto( + default!, + default! + )) + .RuleFor(e => e.Name, mediaContributorName) + .RuleFor(e => e.Role, mediaContributorRole); + + Faker rating = new Faker() + .CustomInstantiator(f => new BookRatingDto( + 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 LanguageInfoDto( + 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 LanguageInfoDto( + 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 WrittenContentMetadataDto( + 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 IsbnDto( + 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/MediaLibrary/WrittenContentLibrary/BooksLibrary/Books/Commands/AddBook/Fixtures/BookEntityFixture.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/WrittenContentLibrary/BooksLibrary/Books/Commands/AddBook/Fixtures/BookEntityFixture.cs new file mode 100644 index 00000000..899473fc --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/WrittenContentLibrary/BooksLibrary/Books/Commands/AddBook/Fixtures/BookEntityFixture.cs @@ -0,0 +1,145 @@ +#region ========================================================================= USING ===================================================================================== +using AutoFixture; +using Bogus; +using Lumina.Application.Common.DataAccess.Entities.Common; +using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary; +using Lumina.Application.UnitTests.Common.Setup; +using Lumina.Domain.Common.Enums.BookLibrary; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Application.UnitTests.Core.MediaLibrary.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(), + 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/MediaLibrary/WrittenContentLibrary/BooksLibrary/Books/Commands/AddBook/Fixtures/BookFixture.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/WrittenContentLibrary/BooksLibrary/Books/Commands/AddBook/Fixtures/BookFixture.cs new file mode 100644 index 00000000..c36a31be --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/WrittenContentLibrary/BooksLibrary/Books/Commands/AddBook/Fixtures/BookFixture.cs @@ -0,0 +1,118 @@ +#region ========================================================================= USING ===================================================================================== +using AutoFixture; +using Lumina.Application.UnitTests.Common.Setup; +using Lumina.Domain.Common.Enums.BookLibrary; +using Lumina.Domain.Common.Primitives; +using Lumina.Domain.Common.ValueObjects.Metadata; +using Lumina.Domain.Core.BoundedContexts.MediaContributorBoundedContext.MediaContributorAggregate.ValueObjects; +using Lumina.Domain.Core.BoundedContexts.WrittenContentLibraryBoundedContext.BookLibraryAggregate; +using Lumina.Domain.Core.BoundedContexts.WrittenContentLibraryBoundedContext.BookLibraryAggregate.Entities; +using Lumina.Domain.Core.BoundedContexts.WrittenContentLibraryBoundedContext.BookLibraryAggregate.ValueObjects; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Application.UnitTests.Core.MediaLibrary.WrittenContentLibrary.BooksLibrary.Books.Commands.AddBook.Fixtures; + +/// +/// Fixture class for the domain entity. +/// +[ExcludeFromCodeCoverage] +public class BookFixture +{ + private readonly Fixture _fixture; + + /// + /// Initializes a new instance of the class. + /// + public BookFixture() + { + _fixture = new Fixture(); + _fixture.Customizations.Add(new DateOnlySpecimenBuilder()); + _fixture.Customizations.Add(new NullableDateOnlySpecimenBuilder()); + ConfigureCustomDomainTypes(); + } + + /// + /// Creates a random valid book domain entity. + /// + /// The created book domain entity. + 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(() => + { + 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; + }); + + _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/MediaLibrary/WrittenContentLibrary/BooksLibrary/Common/Fixtures/BookRatingDtoFixture.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/WrittenContentLibrary/BooksLibrary/Common/Fixtures/BookRatingDtoFixture.cs new file mode 100644 index 00000000..52db71a6 --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/WrittenContentLibrary/BooksLibrary/Common/Fixtures/BookRatingDtoFixture.cs @@ -0,0 +1,69 @@ +#region ========================================================================= USING ===================================================================================== +using AutoFixture; +using Lumina.Contracts.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary; +using Lumina.Domain.Common.Enums.BookLibrary; +using System; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Application.UnitTests.Core.MediaLibrary.WrittenContentLibrary.BooksLibrary.Common.Fixtures; + +/// +/// Fixture class for the . +/// +[ExcludeFromCodeCoverage] +public class BookRatingDtoFixture +{ + private readonly Fixture _fixture; + private readonly Random _random = new(); + + /// + /// Initializes a new instance of the class. + /// + public BookRatingDtoFixture() + { + _fixture = new Fixture(); + } + + /// + /// Creates a complete book rating DTO with all properties. + /// + /// The created book rating DTO. + public BookRatingDto CreateComplete() + { + return new BookRatingDto( + _random.Next(1, 5), + 5, + _fixture.Create(), + _random.Next(1, 1000) + ); + } + + /// + /// Creates a minimal book rating DTO with only required properties. + /// + /// The created book rating DTO. + public BookRatingDto CreateMinimal() + { + return new BookRatingDto( + _random.Next(1, 5), + 5, + null, + null + ); + } + + /// + /// Creates an invalid book rating DTO. + /// + /// The created invalid book rating DTO. + public BookRatingDto CreateInvalid() + { + return new BookRatingDto( + 10, // invalid: value > maxValue + 5, + _fixture.Create(), + _random.Next(1, 1000) + ); + } +} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/WrittenContentLibrary/BooksLibrary/Common/Fixtures/BookRatingEntityFixture.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/WrittenContentLibrary/BooksLibrary/Common/Fixtures/BookRatingEntityFixture.cs new file mode 100644 index 00000000..9c527f39 --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/WrittenContentLibrary/BooksLibrary/Common/Fixtures/BookRatingEntityFixture.cs @@ -0,0 +1,55 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary; +using Lumina.Domain.Common.Enums.BookLibrary; +using System; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Application.UnitTests.Core.MediaLibrary.WrittenContentLibrary.BooksLibrary.Common.Fixtures; + +/// +/// Fixture class for the . +/// +[ExcludeFromCodeCoverage] +public class BookRatingEntityFixture +{ + private readonly Random _random = new(); + private readonly Faker _faker; + + /// + /// Initializes a new instance of the class. + /// + public BookRatingEntityFixture() + { + _faker = new Faker(); + } + + /// + /// Creates a book rating entity. + /// + /// The created book rating entity. + public BookRatingEntity CreateBookRating() + { + return new BookRatingEntity( + _random.Next(1, 5), + 5, + _faker.PickRandom(), + _random.Next(1, 1000) + ); + } + + /// + /// Creates an invalid book rating entity. + /// + /// The created invalid book rating entity. + public BookRatingEntity CreateInvalidBookRating() + { + return new BookRatingEntity( + null, + null, + null, + null + ); + } +} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/WrittenContentLibrary/BooksLibrary/Common/Fixtures/BookRatingFixture.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/WrittenContentLibrary/BooksLibrary/Common/Fixtures/BookRatingFixture.cs new file mode 100644 index 00000000..f79f507b --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/WrittenContentLibrary/BooksLibrary/Common/Fixtures/BookRatingFixture.cs @@ -0,0 +1,85 @@ +#region ========================================================================= USING ===================================================================================== +using AutoFixture; +using Lumina.Domain.Common.Enums.BookLibrary; +using Lumina.Domain.Common.Primitives; +using Lumina.Domain.Core.BoundedContexts.WrittenContentLibraryBoundedContext.BookLibraryAggregate.ValueObjects; +using System; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Application.UnitTests.Core.MediaLibrary.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/MediaLibrary/WrittenContentLibrary/BooksLibrary/Common/Fixtures/IsbnDtoFixture.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/WrittenContentLibrary/BooksLibrary/Common/Fixtures/IsbnDtoFixture.cs new file mode 100644 index 00000000..b521d391 --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/WrittenContentLibrary/BooksLibrary/Common/Fixtures/IsbnDtoFixture.cs @@ -0,0 +1,98 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Contracts.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary; +using Lumina.Domain.Common.Enums.BookLibrary; +using System; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Application.UnitTests.Core.MediaLibrary.WrittenContentLibrary.BooksLibrary.Common.Fixtures; + +/// +/// Fixture class for the . +/// +[ExcludeFromCodeCoverage] +public class IsbnDtoFixture +{ + private readonly Random _random = new(); + + /// + /// Creates a valid ISBN-10 DTO. + /// + /// The created ISBN DTO. + public IsbnDto CreateIsbn10() + { + return new IsbnDto( + GenerateValidIsbn10(), + IsbnFormat.Isbn10 + ); + } + + /// + /// Creates a valid ISBN-13 DTO. + /// + /// The created ISBN DTO. + public IsbnDto CreateIsbn13() + { + return new IsbnDto( + GenerateValidIsbn13(), + IsbnFormat.Isbn13 + ); + } + + /// + /// Creates an invalid ISBN DTO. + /// + /// The created invalid ISBN DTO. + public IsbnDto CreateInvalid() + { + return new IsbnDto( + "invalid-isbn", + IsbnFormat.Isbn13 + ); + } + + /// + /// Creates an ISBN entity without format. + /// + /// The created ISBN entity. + public IsbnDto CreateWithoutFormat() + { + return new IsbnDto( + 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/MediaLibrary/WrittenContentLibrary/BooksLibrary/Common/Fixtures/IsbnFixture.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/WrittenContentLibrary/BooksLibrary/Common/Fixtures/IsbnFixture.cs new file mode 100644 index 00000000..8d10d29b --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/WrittenContentLibrary/BooksLibrary/Common/Fixtures/IsbnFixture.cs @@ -0,0 +1,70 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Domain.Common.Enums.BookLibrary; +using Lumina.Domain.Core.BoundedContexts.WrittenContentLibraryBoundedContext.BookLibraryAggregate.ValueObjects; +using System; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Application.UnitTests.Core.MediaLibrary.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/Core/UsersManagement/Authentication/Commands/ChangePassword/ChangePasswordCommandHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Authentication/Commands/ChangePassword/ChangePasswordCommandHandlerTests.cs new file mode 100644 index 00000000..e2e7c9b2 --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Authentication/Commands/ChangePassword/ChangePasswordCommandHandlerTests.cs @@ -0,0 +1,207 @@ +#region ========================================================================= USING ===================================================================================== +using ErrorOr; +using FluentAssertions; +using Lumina.Application.Common.DataAccess.Entities.UsersManagement; +using Lumina.Application.Common.DataAccess.Repositories.Users; +using Lumina.Application.Common.DataAccess.UoW; +using Lumina.Application.Common.Errors; +using Lumina.Application.Common.Infrastructure.Security; +using Lumina.Application.Core.UsersManagement.Authentication.Commands.ChangePassword; +using Lumina.Application.UnitTests.Common.Mapping.UserManagement.Users.Fixtures; +using Lumina.Contracts.Responses.Authentication; +using NSubstitute; +using System; +using System.Diagnostics.CodeAnalysis; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Application.UnitTests.Core.UsersManagement.Authentication.Commands.ChangePassword; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class ChangePasswordCommandHandlerTests +{ + private readonly IUnitOfWork _mockUnitOfWork; + private readonly IHashService _mockHashService; + private readonly IUserRepository _mockUserRepository; + private readonly ChangePasswordCommandHandler _sut; + + /// + /// Initializes a new instance of the class. + /// + public ChangePasswordCommandHandlerTests() + { + _mockUnitOfWork = Substitute.For(); + _mockHashService = Substitute.For(); + _mockUserRepository = Substitute.For(); + + _mockUnitOfWork.GetRepository().Returns(_mockUserRepository); + + _sut = new ChangePasswordCommandHandler( + _mockUnitOfWork, + _mockHashService); + } + + [Fact] + public async Task Handle_WhenPasswordChangeIsSuccessful_ShouldUpdateUserAndReturnSuccess() + { + // Arrange + string currentPassword = "currentPassword"; + string newPassword = "newPassword"; + string hashedNewPassword = "hashedNewPassword"; + string escapedHashedCurrentPassword = Uri.EscapeDataString("hashedCurrentPassword"); + + UserEntity user = UserEntityFixture.CreateUserEntity(); + user.Password = escapedHashedCurrentPassword; + + ChangePasswordCommand command = new( + user.Username, + currentPassword, + newPassword, + newPassword); + + _mockUserRepository.GetByUsernameAsync(user.Username, Arg.Any()) + .Returns(ErrorOrFactory.From(user)); + _mockHashService.CheckStringAgainstHash(currentPassword, "hashedCurrentPassword") + .Returns(true); + _mockHashService.HashString(newPassword) + .Returns(hashedNewPassword); + _mockUserRepository.UpdateAsync(Arg.Any(), Arg.Any()) + .Returns(Result.Updated); + + // Act + ErrorOr result = await _sut.Handle(command, CancellationToken.None); + + // Assert + result.IsError.Should().BeFalse(); + result.Value.IsPasswordChanged.Should().BeTrue(); + + await _mockUserRepository.Received(1).GetByUsernameAsync(user.Username, Arg.Any()); + _mockHashService.Received(1).CheckStringAgainstHash(currentPassword, "hashedCurrentPassword"); + _mockHashService.Received(1).HashString(newPassword); + await _mockUserRepository.Received(1).UpdateAsync(Arg.Any(), Arg.Any()); + await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task Handle_WhenUserDoesNotExist_ShouldReturnError() + { + // Arrange + ChangePasswordCommand command = new("nonexistentUser", "oldPass", "newPass", "newPass"); + + _mockUserRepository.GetByUsernameAsync(command.Username!, Arg.Any()) + .Returns(ErrorOrFactory.From(null)); + + // Act + ErrorOr result = await _sut.Handle(command, CancellationToken.None); + + // Assert + result.IsError.Should().BeTrue(); + result.FirstError.Should().Be(Errors.Authentication.UsernameDoesNotExist); + + await _mockUserRepository.Received(1).GetByUsernameAsync(command.Username!, Arg.Any()); + await _mockUserRepository.DidNotReceive().UpdateAsync(Arg.Any(), Arg.Any()); + await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task Handle_WhenCurrentPasswordIsIncorrect_ShouldReturnError() + { + // Arrange + UserEntity user = UserEntityFixture.CreateUserEntity(); + string incorrectPassword = "wrongPassword"; + + ChangePasswordCommand command = new( + user.Username, + incorrectPassword, + "newPass", + "newPass"); + + _mockUserRepository.GetByUsernameAsync(user.Username, Arg.Any()) + .Returns(ErrorOrFactory.From(user)); + _mockHashService.CheckStringAgainstHash(incorrectPassword, Uri.UnescapeDataString(user.Password)) + .Returns(false); + + // Act + ErrorOr result = await _sut.Handle(command, CancellationToken.None); + + // Assert + result.IsError.Should().BeTrue(); + result.FirstError.Should().Be(Errors.Authentication.InvalidCurrentPassword); + + await _mockUserRepository.Received(1).GetByUsernameAsync(user.Username, Arg.Any()); + _mockHashService.Received(1).CheckStringAgainstHash(incorrectPassword, Uri.UnescapeDataString(user.Password)); + await _mockUserRepository.DidNotReceive().UpdateAsync(Arg.Any(), Arg.Any()); + await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task Handle_WhenUpdateFails_ShouldReturnError() + { + // Arrange + string currentPassword = "currentPassword"; + string newPassword = "newPassword"; + string escapedHashedCurrentPassword = Uri.EscapeDataString("hashedCurrentPassword"); + Error error = Error.Failure("Database.Error", "Failed to update user"); + + UserEntity user = UserEntityFixture.CreateUserEntity(); + user.Password = escapedHashedCurrentPassword; + + ChangePasswordCommand command = new( + user.Username, + currentPassword, + newPassword, + newPassword); + + _mockUserRepository.GetByUsernameAsync(user.Username, Arg.Any()) + .Returns(ErrorOrFactory.From(user)); + _mockHashService.CheckStringAgainstHash(currentPassword, "hashedCurrentPassword") + .Returns(true); + _mockUserRepository.UpdateAsync(Arg.Any(), Arg.Any()) + .Returns(error); + + // Act + ErrorOr result = await _sut.Handle(command, CancellationToken.None); + + // Assert + result.IsError.Should().BeTrue(); + result.FirstError.Should().Be(error); + + await _mockUserRepository.Received(1).GetByUsernameAsync(user.Username, Arg.Any()); + _mockHashService.Received(1).CheckStringAgainstHash(currentPassword, "hashedCurrentPassword"); + await _mockUserRepository.Received(1).UpdateAsync(Arg.Any(), Arg.Any()); + await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task Handle_WhenGetByUsernameReturnsError_ShouldReturnError() + { + // Arrange + string currentPassword = "currentPassword"; + string newPassword = "newPassword"; + UserEntity user = UserEntityFixture.CreateUserEntity(); + ChangePasswordCommand command = new( + user.Username, + currentPassword, + newPassword, + newPassword); + Error error = Error.Failure("Database.Error", "Failed to check username"); + + _mockUserRepository.GetByUsernameAsync(command.Username!, Arg.Any()) + .Returns(error); + + // Act + ErrorOr result = await _sut.Handle(command, CancellationToken.None); + + // Assert + result.IsError.Should().BeTrue(); + result.FirstError.Should().Be(error); + + await _mockUserRepository.Received(1).GetByUsernameAsync(command.Username!, Arg.Any()); + await _mockUserRepository.DidNotReceive().InsertAsync(Arg.Any(), Arg.Any()); + await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); + } +} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Authentication/Commands/ChangePassword/ChangePasswordCommandValidatorTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Authentication/Commands/ChangePassword/ChangePasswordCommandValidatorTests.cs new file mode 100644 index 00000000..2c272751 --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Authentication/Commands/ChangePassword/ChangePasswordCommandValidatorTests.cs @@ -0,0 +1,303 @@ +#region ========================================================================= USING ===================================================================================== +using FluentValidation.TestHelper; +using Lumina.Application.Common.Errors; +using Lumina.Application.Core.UsersManagement.Authentication.Commands.ChangePassword; +using Lumina.Application.UnitTests.Core.UsersManagement.Authentication.Commands.ChangePassword.Fixtures; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Application.UnitTests.Core.UsersManagement.Authentication.Commands.ChangePassword; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class ChangePasswordCommandValidatorTests +{ + private readonly ChangePasswordCommandValidator _validator; + + /// + /// Initializes a new instance of the class. + /// + public ChangePasswordCommandValidatorTests() + { + _validator = new ChangePasswordCommandValidator(); + } + + [Fact] + public void Validate_WhenUsernameIsNull_ShouldHaveValidationError() + { + // Arrange + ChangePasswordCommand command = ChangePasswordCommandFixture.CreateChangePasswordCommand(); + command = command with { Username = null! }; + + // Act + TestValidationResult result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationErrorFor(x => x.Username) + .WithErrorMessage(Errors.Authentication.UsernameCannotBeEmpty.Description); + } + + [Fact] + public void Validate_WhenUsernameIsEmpty_ShouldHaveValidationError() + { + // Arrange + ChangePasswordCommand command = ChangePasswordCommandFixture.CreateChangePasswordCommand(); + command = command with { Username = string.Empty }; + + // Act + TestValidationResult result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationErrorFor(x => x.Username) + .WithErrorMessage(Errors.Authentication.UsernameCannotBeEmpty.Description); + } + + [Fact] + public void Validate_WhenUsernameIsWhiteSpace_ShouldHaveValidationError() + { + // Arrange + ChangePasswordCommand command = ChangePasswordCommandFixture.CreateChangePasswordCommand(); + command = command with { Username = " " }; + + // Act + TestValidationResult result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationErrorFor(x => x.Username) + .WithErrorMessage(Errors.Authentication.UsernameCannotBeEmpty.Description); + } + + [Fact] + public void Validate_WhenCurrentPasswordIsNull_ShouldHaveValidationError() + { + // Arrange + ChangePasswordCommand command = ChangePasswordCommandFixture.CreateChangePasswordCommand(); + command = command with { CurrentPassword = null! }; + + // Act + TestValidationResult result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationErrorFor(x => x.CurrentPassword) + .WithErrorMessage(Errors.Authentication.CurrentPasswordCannotBeEmpty.Description); + } + + [Fact] + public void Validate_WhenCurrentPasswordIsEmpty_ShouldHaveValidationError() + { + // Arrange + ChangePasswordCommand command = ChangePasswordCommandFixture.CreateChangePasswordCommand(); + command = command with { CurrentPassword = string.Empty }; + + // Act + TestValidationResult result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationErrorFor(x => x.CurrentPassword) + .WithErrorMessage(Errors.Authentication.CurrentPasswordCannotBeEmpty.Description); + } + + [Fact] + public void Validate_WhenCurrentPasswordIsWhiteSpace_ShouldHaveValidationError() + { + // Arrange + ChangePasswordCommand command = ChangePasswordCommandFixture.CreateChangePasswordCommand(); + command = command with { CurrentPassword = " " }; + + // Act + TestValidationResult result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationErrorFor(x => x.CurrentPassword) + .WithErrorMessage(Errors.Authentication.CurrentPasswordCannotBeEmpty.Description); + } + + [Fact] + public void Validate_WhenNewPasswordIsNull_ShouldHaveValidationError() + { + // Arrange + ChangePasswordCommand command = ChangePasswordCommandFixture.CreateChangePasswordCommand(); + command = command with { NewPassword = null! }; + + // Act + TestValidationResult result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationErrorFor(x => x.NewPassword) + .WithErrorMessage(Errors.Authentication.NewPasswordCannotBeEmpty.Description); + } + + [Fact] + public void Validate_WhenNewPasswordIsEmpty_ShouldHaveValidationError() + { + // Arrange + ChangePasswordCommand command = ChangePasswordCommandFixture.CreateChangePasswordCommand(); + command = command with { NewPassword = string.Empty }; + + // Act + TestValidationResult result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationErrorFor(x => x.NewPassword) + .WithErrorMessage(Errors.Authentication.NewPasswordCannotBeEmpty.Description); + } + + [Fact] + public void Validate_WhenNewPasswordIsWhiteSpace_ShouldHaveValidationError() + { + // Arrange + ChangePasswordCommand command = ChangePasswordCommandFixture.CreateChangePasswordCommand(); + command = command with { NewPassword = " " }; + + // Act + TestValidationResult result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationErrorFor(x => x.NewPassword) + .WithErrorMessage(Errors.Authentication.NewPasswordCannotBeEmpty.Description); + } + + [Fact] + public void Validate_WhenNewPasswordConfirmIsNull_ShouldHaveValidationError() + { + // Arrange + ChangePasswordCommand command = ChangePasswordCommandFixture.CreateChangePasswordCommand(); + command = command with { NewPasswordConfirm = null! }; + + // Act + TestValidationResult result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationErrorFor(x => x.NewPasswordConfirm) + .WithErrorMessage(Errors.Authentication.NewPasswordConfirmCannotBeEmpty.Description); + } + + [Fact] + public void Validate_WhenNewPasswordConfirmIsEmpty_ShouldHaveValidationError() + { + // Arrange + ChangePasswordCommand command = ChangePasswordCommandFixture.CreateChangePasswordCommand(); + command = command with { NewPasswordConfirm = string.Empty }; + + // Act + TestValidationResult result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationErrorFor(x => x.NewPasswordConfirm) + .WithErrorMessage(Errors.Authentication.NewPasswordConfirmCannotBeEmpty.Description); + } + + [Fact] + public void Validate_WhenNewPasswordConfirmIsWhiteSpace_ShouldHaveValidationError() + { + // Arrange + ChangePasswordCommand command = ChangePasswordCommandFixture.CreateChangePasswordCommand(); + command = command with { NewPasswordConfirm = " " }; + + // Act + TestValidationResult result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationErrorFor(x => x.NewPasswordConfirm) + .WithErrorMessage(Errors.Authentication.NewPasswordConfirmCannotBeEmpty.Description); + } + + [Fact] + public void Validate_WhenNewPasswordAndNewPasswordConfirmDontMatch_ShouldHaveValidationError() + { + // Arrange + ChangePasswordCommand command = ChangePasswordCommandFixture.CreateChangePasswordCommand(); + command = command with { NewPasswordConfirm = "$321Bcda" }; + + // Act + TestValidationResult result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationErrorFor(x => x.NewPassword) + .WithErrorMessage(Errors.Authentication.PasswordsNotMatch.Description); + } + + [Theory] + [InlineData("password123")] // Missing uppercase and special character + [InlineData("PASSWORD123")] // Missing special character + [InlineData("Password123")] // Missing special character + [InlineData("Password!@#")] // Missing number + [InlineData("Pass1!")] // Too short + [InlineData("password")] // Missing uppercase, number, and special character + public void Validate_WhenCurrentPasswordDoesNotMatchPattern_ShouldHaveValidationError(string password) + { + // Arrange + ChangePasswordCommand command = ChangePasswordCommandFixture.CreateChangePasswordCommand(); + command = command with { CurrentPassword = password }; + + // Act + TestValidationResult result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationErrorFor(x => x.CurrentPassword) + .WithErrorMessage(Errors.Authentication.InvalidPassword.Description); + } + + [Theory] + [InlineData("password123")] // Missing uppercase and special character + [InlineData("PASSWORD123")] // Missing special character + [InlineData("Password123")] // Missing special character + [InlineData("Password!@#")] // Missing number + [InlineData("Pass1!")] // Too short + [InlineData("password")] // Missing uppercase, number, and special character + public void Validate_WhenNewPasswordDoesNotMatchPattern_ShouldHaveValidationError(string password) + { + // Arrange + ChangePasswordCommand command = ChangePasswordCommandFixture.CreateChangePasswordCommand(); + command = command with { NewPassword = password, NewPasswordConfirm = password }; + + // Act + TestValidationResult result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationErrorFor(x => x.NewPassword) + .WithErrorMessage(Errors.Authentication.InvalidPassword.Description); + } + + [Theory] + [InlineData("Password1!")] // Valid password + [InlineData("Complex1@Password")] // Valid password + [InlineData("MyP@ssw0rd")] // Valid password + [InlineData("Abcd123!@#")] // Valid password + public void Validate_WhenPasswordsMatchPattern_ShouldNotHaveValidationError(string password) + { + // Arrange + ChangePasswordCommand command = ChangePasswordCommandFixture.CreateChangePasswordCommand(); + command = command with + { + CurrentPassword = password, + NewPassword = password, + NewPasswordConfirm = password + }; + + // Act + TestValidationResult result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationErrorFor(x => x.CurrentPassword); + result.ShouldNotHaveValidationErrorFor(x => x.NewPassword); + } + + [Fact] + public void Validate_WhenCommandIsValid_ShouldNotHaveValidationError() + { + // Arrange + ChangePasswordCommand command = ChangePasswordCommandFixture.CreateChangePasswordCommand(); + + // Act + TestValidationResult result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationErrorFor(x => x.Username); + result.ShouldNotHaveValidationErrorFor(x => x.CurrentPassword); + result.ShouldNotHaveValidationErrorFor(x => x.NewPassword); + result.ShouldNotHaveValidationErrorFor(x => x.NewPasswordConfirm); + } +} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Authentication/Commands/ChangePassword/Fixtures/ChangePasswordCommandFixture.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Authentication/Commands/ChangePassword/Fixtures/ChangePasswordCommandFixture.cs new file mode 100644 index 00000000..49ca6c5b --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Authentication/Commands/ChangePassword/Fixtures/ChangePasswordCommandFixture.cs @@ -0,0 +1,35 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Application.Core.UsersManagement.Authentication.Commands.ChangePassword; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Application.UnitTests.Core.UsersManagement.Authentication.Commands.ChangePassword.Fixtures; + +/// +/// Fixture class for the class. +/// +[ExcludeFromCodeCoverage] +public class ChangePasswordCommandFixture +{ + /// + /// Creates a random valid command for changing a password. + /// + /// The created command. + public static ChangePasswordCommand CreateChangePasswordCommand() + { + string currentPassword = "Abcd123$"; + string newPassword = "Wxyz789#"; + return new Faker() + .CustomInstantiator(f => new ChangePasswordCommand( + default!, + default!, + default!, + default! + )) + .RuleFor(x => x.Username, f => f.Person.UserName) + .RuleFor(x => x.CurrentPassword, currentPassword) + .RuleFor(x => x.NewPassword, newPassword) + .RuleFor(x => x.NewPasswordConfirm, newPassword); + } +} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Authentication/Commands/ChangePassword/Fixtures/ChangePasswordRequestFixture.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Authentication/Commands/ChangePassword/Fixtures/ChangePasswordRequestFixture.cs new file mode 100644 index 00000000..28141e51 --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Authentication/Commands/ChangePassword/Fixtures/ChangePasswordRequestFixture.cs @@ -0,0 +1,56 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Contracts.Requests.Authentication; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Application.UnitTests.Core.UsersManagement.Authentication.Commands.ChangePassword.Fixtures; + +/// +/// Fixture class for the class. +/// +[ExcludeFromCodeCoverage] +public class ChangePasswordRequestFixture +{ + private readonly Faker _faker; + + /// + /// Initializes a new instance of the class. + /// + public ChangePasswordRequestFixture() + { + _faker = new Faker(); + } + + /// + /// Creates a random valid . + /// + /// The created . + public ChangePasswordRequest CreateChangePasswordRequest( + string? username = null, + string? currentPassword = null, + string? newPassword = null, + string? newPasswordConfirm = null) + { + return new ChangePasswordRequest( + username ?? _faker.Internet.UserName(), + currentPassword ?? _faker.Internet.Password(), + newPassword ?? _faker.Internet.Password(), + newPasswordConfirm ?? _faker.Internet.Password() + ); + } + + /// + /// Creates a list of . + /// + /// The number of elements to create. + /// The created list. + public List CreateMany(int count = 3) + { + return Enumerable.Range(0, count) + .Select(_ => CreateChangePasswordRequest()) + .ToList(); + } +} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Authentication/Commands/RecoverPassword/Fixtures/RecoverPasswordCommandFixture.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Authentication/Commands/RecoverPassword/Fixtures/RecoverPasswordCommandFixture.cs new file mode 100644 index 00000000..ec608ab4 --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Authentication/Commands/RecoverPassword/Fixtures/RecoverPasswordCommandFixture.cs @@ -0,0 +1,29 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Application.Core.UsersManagement.Authentication.Commands.RecoverPassword; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Application.UnitTests.Core.UsersManagement.Authentication.Commands.RecoverPassword.Fixtures; + +/// +/// Fixture class for the class. +/// +[ExcludeFromCodeCoverage] +public class RecoverPasswordCommandFixture +{ + /// + /// Creates a random valid command for password recovery. + /// + /// The created command. + public static RecoverPasswordCommand CreateRecoverPasswordCommand() + { + return new Faker() + .CustomInstantiator(f => new RecoverPasswordCommand( + default!, + default! + )) + .RuleFor(x => x.Username, f => f.Person.UserName) + .RuleFor(x => x.TotpCode, f => f.Random.Replace("######")); // generates 6 random digits + } +} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Authentication/Commands/RecoverPassword/Fixtures/RecoverPasswordRequestFixture.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Authentication/Commands/RecoverPassword/Fixtures/RecoverPasswordRequestFixture.cs new file mode 100644 index 00000000..b5d1c413 --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Authentication/Commands/RecoverPassword/Fixtures/RecoverPasswordRequestFixture.cs @@ -0,0 +1,52 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Contracts.Requests.Authentication; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Application.UnitTests.Core.UsersManagement.Authentication.Commands.RecoverPassword.Fixtures; + +/// +/// Fixture class for the class. +/// +[ExcludeFromCodeCoverage] +public class RecoverPasswordRequestFixture +{ + private readonly Faker _faker; + + /// + /// Initializes a new instance of the class. + /// + public RecoverPasswordRequestFixture() + { + _faker = new Faker(); + } + + /// + /// Creates a random valid . + /// + /// The created . + public RecoverPasswordRequest CreateRecoverPasswordRequest( + string? username = null, + string? totpCode = null) + { + return new RecoverPasswordRequest( + username ?? _faker.Internet.UserName(), + totpCode ?? _faker.Random.Number(100000, 999999).ToString() + ); + } + + /// + /// Creates a list of . + /// + /// The number of elements to create. + /// The created list. + public List CreateMany(int count = 3) + { + return Enumerable.Range(0, count) + .Select(_ => CreateRecoverPasswordRequest()) + .ToList(); + } +} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Authentication/Commands/RecoverPassword/RecoverPasswordCommandHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Authentication/Commands/RecoverPassword/RecoverPasswordCommandHandlerTests.cs new file mode 100644 index 00000000..2e54a568 --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Authentication/Commands/RecoverPassword/RecoverPasswordCommandHandlerTests.cs @@ -0,0 +1,288 @@ +#region ========================================================================= USING ===================================================================================== +using ErrorOr; +using FluentAssertions; +using Lumina.Application.Common.DataAccess.Entities.UsersManagement; +using Lumina.Application.Common.DataAccess.Repositories.Users; +using Lumina.Application.Common.DataAccess.UoW; +using Lumina.Application.Common.Errors; +using Lumina.Application.Common.Infrastructure.Authentication; +using Lumina.Application.Common.Infrastructure.Security; +using Lumina.Application.Core.UsersManagement.Authentication.Commands.RecoverPassword; +using Lumina.Application.UnitTests.Common.Mapping.UserManagement.Users.Fixtures; +using Lumina.Contracts.Responses.Authentication; +using NSubstitute; +using System; +using System.Diagnostics.CodeAnalysis; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Application.UnitTests.Core.UsersManagement.Authentication.Commands.RecoverPassword; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class RecoverPasswordCommandHandlerTests +{ + private readonly IUnitOfWork _mockUnitOfWork; + private readonly IHashService _mockHashService; + private readonly ITotpTokenGenerator _mockTotpTokenGenerator; + private readonly ICryptographyService _mockCryptographyService; + private readonly IUserRepository _mockUserRepository; + private readonly RecoverPasswordCommandHandler _sut; + + /// + /// Initializes a new instance of the class. + /// + public RecoverPasswordCommandHandlerTests() + { + _mockUnitOfWork = Substitute.For(); + _mockHashService = Substitute.For(); + _mockTotpTokenGenerator = Substitute.For(); + _mockCryptographyService = Substitute.For(); + _mockUserRepository = Substitute.For(); + + _mockUnitOfWork.GetRepository().Returns(_mockUserRepository); + + _sut = new RecoverPasswordCommandHandler( + _mockUnitOfWork, + _mockHashService, + _mockTotpTokenGenerator, + _mockCryptographyService); + } + + [Fact] + public async Task Handle_WhenUserExistsAndTotpIsValid_ShouldResetPassword() + { + // Arrange + string totpCode = "123456"; + string encryptedTotpSecret = Convert.ToBase64String(new byte[] { 1, 2, 3 }); + string decryptedTotpSecret = Convert.ToBase64String(new byte[] { 4, 5, 6 }); + string hashedTempPassword = "hashedTempPassword"; + + UserEntity user = UserEntityFixture.CreateUserEntity(); + user.TotpSecret = encryptedTotpSecret; + user.TempPassword = null; + + RecoverPasswordCommand command = new(user.Username, totpCode); + + _mockUserRepository.GetByUsernameAsync(user.Username, Arg.Any()) + .Returns(ErrorOrFactory.From(user)); + _mockCryptographyService.Decrypt(encryptedTotpSecret) + .Returns(decryptedTotpSecret); + _mockTotpTokenGenerator.ValidateToken(Arg.Any(), totpCode) + .Returns(true); + _mockHashService.HashString("Abcd123$") + .Returns(hashedTempPassword); + _mockUserRepository.UpdateAsync(Arg.Any(), Arg.Any()) + .Returns(Result.Updated); + + // Act + ErrorOr result = await _sut.Handle(command, CancellationToken.None); + + // Assert + result.IsError.Should().BeFalse(); + result.Value.IsPasswordReset.Should().BeTrue(); + + await _mockUserRepository.Received(1).GetByUsernameAsync(user.Username, Arg.Any()); + _mockTotpTokenGenerator.Received(1).ValidateToken(Arg.Any(), totpCode); + _mockHashService.Received(1).HashString("Abcd123$"); + await _mockUserRepository.Received(1).UpdateAsync(Arg.Any(), Arg.Any()); + await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task Handle_WhenUserDoesNotExist_ShouldReturnError() + { + // Arrange + RecoverPasswordCommand command = new("nonexistentUser", "123456"); + + _mockUserRepository.GetByUsernameAsync(command.Username!, Arg.Any()) + .Returns(ErrorOrFactory.From(null)); + + // Act + ErrorOr result = await _sut.Handle(command, CancellationToken.None); + + // Assert + result.IsError.Should().BeTrue(); + result.FirstError.Should().Be(Errors.Authentication.UsernameDoesNotExist); + + await _mockUserRepository.Received(1).GetByUsernameAsync(command.Username!, Arg.Any()); + await _mockUserRepository.DidNotReceive().UpdateAsync(Arg.Any(), Arg.Any()); + await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task Handle_WhenTempPasswordExists_ShouldReturnError() + { + // Arrange + UserEntity user = UserEntityFixture.CreateUserEntity(); + user.TempPassword = "existingTempPassword"; + user.TempPasswordCreated = DateTime.UtcNow; + + RecoverPasswordCommand command = new(user.Username, "123456"); + + _mockUserRepository.GetByUsernameAsync(user.Username, Arg.Any()) + .Returns(ErrorOrFactory.From(user)); + + // Act + ErrorOr result = await _sut.Handle(command, CancellationToken.None); + + // Assert + result.IsError.Should().BeTrue(); + result.FirstError.Should().Be(Errors.Authentication.PasswordResetAlreadyRequested); + + await _mockUserRepository.Received(1).GetByUsernameAsync(user.Username, Arg.Any()); + await _mockUserRepository.DidNotReceive().UpdateAsync(Arg.Any(), Arg.Any()); + await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task Handle_WhenUserDoesNotUseTOTP_ShouldReturnError() + { + // Arrange + UserEntity user = UserEntityFixture.CreateUserEntity(); + user.TotpSecret = null; + + RecoverPasswordCommand command = new(user.Username, "123456"); + + _mockUserRepository.GetByUsernameAsync(user.Username, Arg.Any()) + .Returns(ErrorOrFactory.From(user)); + + // Act + ErrorOr result = await _sut.Handle(command, CancellationToken.None); + + // Assert + result.IsError.Should().BeTrue(); + result.FirstError.Should().Be(Errors.Authentication.InvalidTotpCode); + + await _mockUserRepository.Received(1).GetByUsernameAsync(user.Username, Arg.Any()); + await _mockUserRepository.DidNotReceive().UpdateAsync(Arg.Any(), Arg.Any()); + await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task Handle_WhenTotpCodeIsInvalid_ShouldReturnError() + { + // Arrange + string totpCode = "123456"; + string encryptedTotpSecret = Convert.ToBase64String(new byte[] { 1, 2, 3 }); + string decryptedTotpSecret = Convert.ToBase64String(new byte[] { 4, 5, 6 }); + + UserEntity user = UserEntityFixture.CreateUserEntity(); + user.TotpSecret = encryptedTotpSecret; + + RecoverPasswordCommand command = new(user.Username, totpCode); + + _mockUserRepository.GetByUsernameAsync(user.Username, Arg.Any()) + .Returns(ErrorOrFactory.From(user)); + _mockCryptographyService.Decrypt(encryptedTotpSecret) + .Returns(decryptedTotpSecret); + _mockTotpTokenGenerator.ValidateToken(Arg.Any(), totpCode) + .Returns(false); + + // Act + ErrorOr result = await _sut.Handle(command, CancellationToken.None); + + // Assert + result.IsError.Should().BeTrue(); + result.FirstError.Should().Be(Errors.Authentication.InvalidTotpCode); + + await _mockUserRepository.Received(1).GetByUsernameAsync(user.Username, Arg.Any()); + _mockTotpTokenGenerator.Received(1).ValidateToken(Arg.Any(), totpCode); + await _mockUserRepository.DidNotReceive().UpdateAsync(Arg.Any(), Arg.Any()); + await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task Handle_WhenUpdateFails_ShouldReturnError() + { + // Arrange + string totpCode = "123456"; + string encryptedTotpSecret = Convert.ToBase64String(new byte[] { 1, 2, 3 }); + string decryptedTotpSecret = Convert.ToBase64String(new byte[] { 4, 5, 6 }); + Error error = Error.Failure("Database.Error", "Failed to update user"); + + UserEntity user = UserEntityFixture.CreateUserEntity(); + user.TotpSecret = encryptedTotpSecret; + + RecoverPasswordCommand command = new(user.Username, totpCode); + + _mockUserRepository.GetByUsernameAsync(user.Username, Arg.Any()) + .Returns(ErrorOrFactory.From(user)); + _mockCryptographyService.Decrypt(encryptedTotpSecret) + .Returns(decryptedTotpSecret); + _mockTotpTokenGenerator.ValidateToken(Arg.Any(), totpCode) + .Returns(true); + _mockUserRepository.UpdateAsync(Arg.Any(), Arg.Any()) + .Returns(error); + + // Act + ErrorOr result = await _sut.Handle(command, CancellationToken.None); + + // Assert + result.IsError.Should().BeTrue(); + result.FirstError.Should().Be(error); + + await _mockUserRepository.Received(1).GetByUsernameAsync(user.Username, Arg.Any()); + _mockTotpTokenGenerator.Received(1).ValidateToken(Arg.Any(), totpCode); + await _mockUserRepository.Received(1).UpdateAsync(Arg.Any(), Arg.Any()); + await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task Handle_WhenGetByUsernameReturnsError_ShouldReturnError() + { + // Arrange + string totpCode = "123456"; + string encryptedTotpSecret = Convert.ToBase64String(new byte[] { 1, 2, 3 }); + + UserEntity user = UserEntityFixture.CreateUserEntity(); + user.TotpSecret = encryptedTotpSecret; + + RecoverPasswordCommand command = new(user.Username, totpCode); + Error error = Error.Failure("Database.Error", "Failed to check username"); + + _mockUserRepository.GetByUsernameAsync(command.Username!, Arg.Any()) + .Returns(error); + + // Act + ErrorOr result = await _sut.Handle(command, CancellationToken.None); + + // Assert + result.IsError.Should().BeTrue(); + result.FirstError.Should().Be(error); + + await _mockUserRepository.Received(1).GetByUsernameAsync(command.Username!, Arg.Any()); + await _mockUserRepository.DidNotReceive().InsertAsync(Arg.Any(), Arg.Any()); + await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task Handle_WhenUserUsesTOTPButNoCodeProvided_ShouldReturnError() + { + // Arrange + string encryptedTotpSecret = Convert.ToBase64String(new byte[] { 1, 2, 3 }); + + UserEntity user = UserEntityFixture.CreateUserEntity(); + user.TotpSecret = encryptedTotpSecret; + + RecoverPasswordCommand command = new(user.Username, null); + + _mockUserRepository.GetByUsernameAsync(user.Username, Arg.Any()) + .Returns(ErrorOrFactory.From(user)); + + // Act + ErrorOr result = await _sut.Handle(command, CancellationToken.None); + + // Assert + result.IsError.Should().BeTrue(); + result.FirstError.Should().Be(Errors.Authentication.InvalidTotpCode); + + await _mockUserRepository.Received(1).GetByUsernameAsync(user.Username, Arg.Any()); + _mockTotpTokenGenerator.DidNotReceive().ValidateToken(Arg.Any(), Arg.Any()); + await _mockUserRepository.DidNotReceive().UpdateAsync(Arg.Any(), Arg.Any()); + await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); + } +} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Authentication/Commands/RecoverPassword/RecoverPasswordCommandValidatorTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Authentication/Commands/RecoverPassword/RecoverPasswordCommandValidatorTests.cs new file mode 100644 index 00000000..1459a1ac --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Authentication/Commands/RecoverPassword/RecoverPasswordCommandValidatorTests.cs @@ -0,0 +1,168 @@ +#region ========================================================================= USING ===================================================================================== +using FluentValidation.TestHelper; +using Lumina.Application.Common.Errors; +using Lumina.Application.Core.UsersManagement.Authentication.Commands.RecoverPassword; +using Lumina.Application.UnitTests.Core.UsersManagement.Authentication.Commands.RecoverPassword.Fixtures; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Application.UnitTests.Core.UsersManagement.Authentication.Commands.RecoverPassword; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class RecoverPasswordCommandValidatorTests +{ + private readonly RecoverPasswordCommandValidator _validator; + + /// + /// Initializes a new instance of the class. + /// + public RecoverPasswordCommandValidatorTests() + { + _validator = new RecoverPasswordCommandValidator(); + } + + [Fact] + public void Validate_WhenUsernameIsNull_ShouldHaveValidationError() + { + // Arrange + RecoverPasswordCommand command = RecoverPasswordCommandFixture.CreateRecoverPasswordCommand(); + command = command with { Username = null! }; + + // Act + TestValidationResult result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationErrorFor(x => x.Username) + .WithErrorMessage(Errors.Authentication.UsernameCannotBeEmpty.Description); + } + + [Fact] + public void Validate_WhenUsernameIsEmpty_ShouldHaveValidationError() + { + // Arrange + RecoverPasswordCommand command = RecoverPasswordCommandFixture.CreateRecoverPasswordCommand(); + command = command with { Username = string.Empty }; + + // Act + TestValidationResult result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationErrorFor(x => x.Username) + .WithErrorMessage(Errors.Authentication.UsernameCannotBeEmpty.Description); + } + + [Fact] + public void Validate_WhenUsernameIsWhiteSpace_ShouldHaveValidationError() + { + // Arrange + RecoverPasswordCommand command = RecoverPasswordCommandFixture.CreateRecoverPasswordCommand(); + command = command with { Username = " " }; + + // Act + TestValidationResult result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationErrorFor(x => x.Username) + .WithErrorMessage(Errors.Authentication.UsernameCannotBeEmpty.Description); + } + + [Fact] + public void Validate_WhenTotpCodeIsNull_ShouldHaveValidationError() + { + // Arrange + RecoverPasswordCommand command = RecoverPasswordCommandFixture.CreateRecoverPasswordCommand(); + command = command with { TotpCode = null! }; + + // Act + TestValidationResult result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationErrorFor(x => x.TotpCode) + .WithErrorMessage(Errors.Authentication.TotpCannotBeEmpty.Description); + } + + [Fact] + public void Validate_WhenTotpCodeIsEmpty_ShouldHaveValidationError() + { + // Arrange + RecoverPasswordCommand command = RecoverPasswordCommandFixture.CreateRecoverPasswordCommand(); + command = command with { TotpCode = string.Empty }; + + // Act + TestValidationResult result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationErrorFor(x => x.TotpCode) + .WithErrorMessage(Errors.Authentication.TotpCannotBeEmpty.Description); + } + + [Fact] + public void Validate_WhenTotpCodeIsWhiteSpace_ShouldHaveValidationError() + { + // Arrange + RecoverPasswordCommand command = RecoverPasswordCommandFixture.CreateRecoverPasswordCommand(); + command = command with { TotpCode = " " }; + + // Act + TestValidationResult result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationErrorFor(x => x.TotpCode) + .WithErrorMessage(Errors.Authentication.TotpCannotBeEmpty.Description); + } + + [Theory] + [InlineData("12345")] // Too short + [InlineData("1234567")] // Too long + [InlineData("abcdef")] // Contains letters + [InlineData("12345a")] // Contains letters + [InlineData("12.345")] // Contains special characters + [InlineData("12 345")] // Contains whitespace + public void Validate_WhenTotpCodeIsInvalid_ShouldHaveValidationError(string totpCode) + { + // Arrange + RecoverPasswordCommand command = RecoverPasswordCommandFixture.CreateRecoverPasswordCommand(); + command = command with { TotpCode = totpCode }; + + // Act + TestValidationResult result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationErrorFor(x => x.TotpCode) + .WithErrorMessage(Errors.Authentication.InvalidTotpCode.Description); + } + + [Theory] + [InlineData("123456")] + [InlineData("000000")] + [InlineData("999999")] + public void Validate_WhenTotpCodeIsValid_ShouldNotHaveValidationError(string totpCode) + { + // Arrange + RecoverPasswordCommand command = RecoverPasswordCommandFixture.CreateRecoverPasswordCommand(); + command = command with { TotpCode = totpCode }; + + // Act + TestValidationResult result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationErrorFor(x => x.TotpCode); + } + + [Fact] + public void Validate_WhenCommandIsValid_ShouldNotHaveValidationError() + { + // Arrange + RecoverPasswordCommand command = RecoverPasswordCommandFixture.CreateRecoverPasswordCommand(); + + // Act + TestValidationResult result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationErrorFor(x => x.Username); + result.ShouldNotHaveValidationErrorFor(x => x.TotpCode); + } +} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Authentication/Commands/RegisterUser/Fixture/RegisterUserCommandFixture.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Authentication/Commands/RegisterUser/Fixture/RegisterUserCommandFixture.cs new file mode 100644 index 00000000..8f8f7aba --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Authentication/Commands/RegisterUser/Fixture/RegisterUserCommandFixture.cs @@ -0,0 +1,33 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Application.Core.UsersManagement.Authentication.Commands.RegisterUser; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Application.UnitTests.Core.UsersManagement.Authentication.Commands.RegisterUser.Fixture; + +/// +/// Fixture class for the class. +/// +[ExcludeFromCodeCoverage] +public class RegisterUserCommandFixture +{ + /// + /// Creates a random valid command for a new account registration. + /// + /// The created command. + public static RegisterUserCommand CreateRegisterCommand() + { + string password = "Abcd123$"; + return new Faker() + .CustomInstantiator(f => new RegisterUserCommand( + default!, + default!, + default!, + true + )) + .RuleFor(x => x.Username, f => f.Person.UserName) + .RuleFor(x => x.Password, password) + .RuleFor(x => x.PasswordConfirm, password); + } +} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Authentication/Commands/RegisterUser/Fixture/RegistrationRequestFixture.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Authentication/Commands/RegisterUser/Fixture/RegistrationRequestFixture.cs new file mode 100644 index 00000000..daa0679f --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Authentication/Commands/RegisterUser/Fixture/RegistrationRequestFixture.cs @@ -0,0 +1,58 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Contracts.Requests.Authentication; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Application.UnitTests.Core.UsersManagement.Authentication.Commands.RegisterUser.Fixture; + +/// +/// Fixture class for the class. +/// +[ExcludeFromCodeCoverage] +public class RegistrationRequestFixture +{ + private readonly Faker _faker; + + /// + /// Initializes a new instance of the class. + /// + public RegistrationRequestFixture() + { + _faker = new Faker(); + } + + /// + /// Creates a random valid . + /// + /// The created . + public RegistrationRequest CreateRegistrationRequest( + string? username = null, + string? password = null, + string? passwordConfirm = null, + bool? use2fa = null) + { + password ??= _faker.Internet.Password(); + + return new RegistrationRequest( + username ?? _faker.Internet.UserName(), + password, + passwordConfirm ?? password, + use2fa ?? _faker.Random.Bool() + ); + } + + /// + /// Creates a list of . + /// + /// The number of elements to create. + /// The created list. + public List CreateMany(int count = 3) + { + return Enumerable.Range(0, count) + .Select(_ => CreateRegistrationRequest()) + .ToList(); + } +} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Authentication/Commands/RegisterUser/RegisterUserCommandHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Authentication/Commands/RegisterUser/RegisterUserCommandHandlerTests.cs new file mode 100644 index 00000000..f3c42fb8 --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Authentication/Commands/RegisterUser/RegisterUserCommandHandlerTests.cs @@ -0,0 +1,197 @@ +#region ========================================================================= USING ===================================================================================== +using ErrorOr; +using FluentAssertions; +using Lumina.Application.Common.DataAccess.Entities.UsersManagement; +using Lumina.Application.Common.DataAccess.Repositories.Users; +using Lumina.Application.Common.DataAccess.UoW; +using Lumina.Application.Common.Errors; +using Lumina.Application.Common.Infrastructure.Authentication; +using Lumina.Application.Common.Infrastructure.Security; +using Lumina.Application.Core.UsersManagement.Authentication.Commands.RegisterUser; +using Lumina.Application.UnitTests.Common.Mapping.UserManagement.Users.Fixtures; +using Lumina.Application.UnitTests.Core.UsersManagement.Authentication.Commands.RegisterUser.Fixture; +using Lumina.Contracts.Responses.Authentication; +using NSubstitute; +using System; +using System.Diagnostics.CodeAnalysis; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Application.UnitTests.Core.UsersManagement.Authentication.Commands.RegisterUser; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class RegisterUserCommandHandlerTests +{ + private readonly IUnitOfWork _mockUnitOfWork; + private readonly IHashService _mockHashService; + private readonly ICryptographyService _mockCryptographyService; + private readonly ITotpTokenGenerator _mockTotpTokenGenerator; + private readonly IQRCodeGenerator _mockQRCodeGenerator; + private readonly IUserRepository _mockUserRepository; + private readonly RegisterUserCommandHandler _sut; + + /// + /// Initializes a new instance of the class. + /// + public RegisterUserCommandHandlerTests() + { + _mockUnitOfWork = Substitute.For(); + _mockHashService = Substitute.For(); + _mockCryptographyService = Substitute.For(); + _mockTotpTokenGenerator = Substitute.For(); + _mockQRCodeGenerator = Substitute.For(); + _mockUserRepository = Substitute.For(); + + _mockUnitOfWork.GetRepository().Returns(_mockUserRepository); + + _sut = new RegisterUserCommandHandler( + _mockUnitOfWork, + _mockHashService, + _mockCryptographyService, + _mockTotpTokenGenerator, + _mockQRCodeGenerator); + } + + [Fact] + public async Task Handle_WhenUserDoesNotExistAndWith2FA_ShouldRegisterUser() + { + // Arrange + RegisterUserCommand command = RegisterUserCommandFixture.CreateRegisterCommand(); + byte[] totpSecret = [1, 2, 3]; + string qrCodeUri = "data:image/png;base64,test"; + string encryptedSecret = "encryptedSecret"; + string hashedPassword = "hashedPassword"; + + _mockUserRepository.GetByUsernameAsync(command.Username!, Arg.Any()) + .Returns(ErrorOrFactory.From(null)); + _mockHashService.HashString(command.Password!) + .Returns(hashedPassword); + _mockTotpTokenGenerator.GenerateSecret() + .Returns(totpSecret); + _mockQRCodeGenerator.GenerateQrCodeDataUri(command.Username!, totpSecret) + .Returns(qrCodeUri); + _mockCryptographyService.Encrypt(Convert.ToBase64String(totpSecret)) + .Returns(encryptedSecret); + _mockUserRepository.InsertAsync(Arg.Any(), Arg.Any()) + .Returns(Result.Created); + + // Act + ErrorOr result = await _sut.Handle(command, CancellationToken.None); + + // Assert + result.IsError.Should().BeFalse(); + result.Value.Username.Should().Be(command.Username); + result.Value.TotpSecret.Should().Be(qrCodeUri); + + await _mockUserRepository.Received(1).GetByUsernameAsync(command.Username!, Arg.Any()); + _mockHashService.Received(1).HashString(command.Password!); + _mockTotpTokenGenerator.Received(1).GenerateSecret(); + _mockQRCodeGenerator.Received(1).GenerateQrCodeDataUri(command.Username!, totpSecret); + _mockCryptographyService.Received(1).Encrypt(Convert.ToBase64String(totpSecret)); + await _mockUserRepository.Received(1).InsertAsync(Arg.Any(), Arg.Any()); + await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task Handle_WhenUserDoesNotExistAndWithout2FA_ShouldRegisterUser() + { + // Arrange + RegisterUserCommand command = RegisterUserCommandFixture.CreateRegisterCommand() with { Use2fa = false }; + string hashedPassword = "hashedPassword"; + + _mockUserRepository.GetByUsernameAsync(command.Username!, Arg.Any()) + .Returns(ErrorOrFactory.From(null)); + _mockHashService.HashString(command.Password!) + .Returns(hashedPassword); + _mockUserRepository.InsertAsync(Arg.Any(), Arg.Any()) + .Returns(Result.Created); + + // Act + ErrorOr result = await _sut.Handle(command, CancellationToken.None); + + // Assert + result.IsError.Should().BeFalse(); + result.Value.Username.Should().Be(command.Username); + result.Value.TotpSecret.Should().BeNull(); + + await _mockUserRepository.Received(1).GetByUsernameAsync(command.Username!, Arg.Any()); + _mockHashService.Received(1).HashString(command.Password!); + _mockTotpTokenGenerator.DidNotReceive().GenerateSecret(); + _mockQRCodeGenerator.DidNotReceive().GenerateQrCodeDataUri(Arg.Any(), Arg.Any()); + _mockCryptographyService.DidNotReceive().Encrypt(Arg.Any()); + await _mockUserRepository.Received(1).InsertAsync(Arg.Any(), Arg.Any()); + await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task Handle_WhenUserAlreadyExists_ShouldReturnError() + { + // Arrange + RegisterUserCommand command = RegisterUserCommandFixture.CreateRegisterCommand(); + UserEntity existingUser = UserEntityFixture.CreateUserEntity(); + + _mockUserRepository.GetByUsernameAsync(command.Username!, Arg.Any()) + .Returns(ErrorOrFactory.From(existingUser)); + + // Act + ErrorOr result = await _sut.Handle(command, CancellationToken.None); + + // Assert + result.IsError.Should().BeTrue(); + result.FirstError.Should().Be(Errors.Authentication.UsernameAlreadyExists); + + await _mockUserRepository.Received(1).GetByUsernameAsync(command.Username!, Arg.Any()); + await _mockUserRepository.DidNotReceive().InsertAsync(Arg.Any(), Arg.Any()); + await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task Handle_WhenInsertFails_ShouldReturnError() + { + // Arrange + RegisterUserCommand command = RegisterUserCommandFixture.CreateRegisterCommand(); + Error error = Error.Failure("Database.Error", "Failed to insert user"); + + _mockUserRepository.GetByUsernameAsync(command.Username!, Arg.Any()) + .Returns(ErrorOrFactory.From(null)); + _mockUserRepository.InsertAsync(Arg.Any(), Arg.Any()) + .Returns(error); + + // Act + ErrorOr result = await _sut.Handle(command, CancellationToken.None); + + // Assert + result.IsError.Should().BeTrue(); + result.FirstError.Should().Be(error); + + await _mockUserRepository.Received(1).GetByUsernameAsync(command.Username!, Arg.Any()); + await _mockUserRepository.Received(1).InsertAsync(Arg.Any(), Arg.Any()); + await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task Handle_WhenGetByUsernameReturnsError_ShouldReturnError() + { + // Arrange + RegisterUserCommand command = RegisterUserCommandFixture.CreateRegisterCommand(); + Error error = Error.Failure("Database.Error", "Failed to check username"); + + _mockUserRepository.GetByUsernameAsync(command.Username!, Arg.Any()) + .Returns(error); + + // Act + ErrorOr result = await _sut.Handle(command, CancellationToken.None); + + // Assert + result.IsError.Should().BeTrue(); + result.FirstError.Should().Be(error); + + await _mockUserRepository.Received(1).GetByUsernameAsync(command.Username!, Arg.Any()); + await _mockUserRepository.DidNotReceive().InsertAsync(Arg.Any(), Arg.Any()); + await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); + } +} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Authentication/Commands/RegisterUser/RegisterUserCommandValidatorTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Authentication/Commands/RegisterUser/RegisterUserCommandValidatorTests.cs new file mode 100644 index 00000000..ac218583 --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Authentication/Commands/RegisterUser/RegisterUserCommandValidatorTests.cs @@ -0,0 +1,299 @@ +#region ========================================================================= USING ===================================================================================== +using FluentValidation.TestHelper; +using Lumina.Application.Common.Errors; +using Lumina.Application.Core.UsersManagement.Authentication.Commands.RegisterUser; +using Lumina.Application.UnitTests.Core.UsersManagement.Authentication.Commands.RegisterUser.Fixture; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Application.UnitTests.Core.UsersManagement.Authentication.Commands.RegisterUser; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class RegisterUserCommandValidatorTests +{ + private readonly RegisterUserCommandValidator _validator; + + /// + /// Initializes a new instance of the class. + /// + public RegisterUserCommandValidatorTests() + { + _validator = new RegisterUserCommandValidator(); + } + + [Fact] + public void Validate_WhenUsernameIsNull_ShouldHaveValidationError() + { + // Arrange + RegisterUserCommand command = RegisterUserCommandFixture.CreateRegisterCommand(); + command = command with { Username = null! }; + + // Act + TestValidationResult result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationErrorFor(x => x.Username) + .WithErrorMessage(Errors.Authentication.UsernameCannotBeEmpty.Description); + } + + [Fact] + public void Validate_WhenUsernameIsEmpty_ShouldHaveValidationError() + { + // Arrange + RegisterUserCommand command = RegisterUserCommandFixture.CreateRegisterCommand(); + command = command with { Username = string.Empty }; + + // Act + TestValidationResult result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationErrorFor(x => x.Username) + .WithErrorMessage(Errors.Authentication.UsernameCannotBeEmpty.Description); + } + + [Fact] + public void Validate_WhenUsernameIsWhiteSpace_ShouldHaveValidationError() + { + // Arrange + RegisterUserCommand command = RegisterUserCommandFixture.CreateRegisterCommand(); + command = command with { Username = " " }; + + // Act + TestValidationResult result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationErrorFor(x => x.Username) + .WithErrorMessage(Errors.Authentication.UsernameCannotBeEmpty.Description); + } + + [Fact] + public void Validate_WhenPasswordIsNull_ShouldHaveValidationError() + { + // Arrange + RegisterUserCommand command = RegisterUserCommandFixture.CreateRegisterCommand(); + command = command with { Password = null! }; + + // Act + TestValidationResult result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationErrorFor(x => x.Password) + .WithErrorMessage(Errors.Authentication.PasswordCannotBeEmpty.Description); + } + + [Fact] + public void Validate_WhenPasswordIsEmpty_ShouldHaveValidationError() + { + // Arrange + RegisterUserCommand command = RegisterUserCommandFixture.CreateRegisterCommand(); + command = command with { Password = string.Empty }; + + // Act + TestValidationResult result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationErrorFor(x => x.Password) + .WithErrorMessage(Errors.Authentication.PasswordCannotBeEmpty.Description); + } + + [Fact] + public void Validate_WhenPasswordIsWhiteSpace_ShouldHaveValidationError() + { + // Arrange + RegisterUserCommand command = RegisterUserCommandFixture.CreateRegisterCommand(); + command = command with { Password = " " }; + + // Act + TestValidationResult result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationErrorFor(x => x.Password) + .WithErrorMessage(Errors.Authentication.PasswordCannotBeEmpty.Description); + } + + [Fact] + public void Validate_WhenPasswordConfirmIsNull_ShouldHaveValidationError() + { + // Arrange + RegisterUserCommand command = RegisterUserCommandFixture.CreateRegisterCommand(); + command = command with { PasswordConfirm = null! }; + + // Act + TestValidationResult result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationErrorFor(x => x.PasswordConfirm) + .WithErrorMessage(Errors.Authentication.PasswordConfirmCannotBeEmpty.Description); + } + + [Fact] + public void Validate_WhenPasswordConfirmIsEmpty_ShouldHaveValidationError() + { + // Arrange + RegisterUserCommand command = RegisterUserCommandFixture.CreateRegisterCommand(); + command = command with { PasswordConfirm = string.Empty }; + + // Act + TestValidationResult result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationErrorFor(x => x.PasswordConfirm) + .WithErrorMessage(Errors.Authentication.PasswordConfirmCannotBeEmpty.Description); + } + + [Fact] + public void Validate_WhenPasswordConfirmIsWhiteSpace_ShouldHaveValidationError() + { + // Arrange + RegisterUserCommand command = RegisterUserCommandFixture.CreateRegisterCommand(); + command = command with { PasswordConfirm = " " }; + + // Act + TestValidationResult result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationErrorFor(x => x.PasswordConfirm) + .WithErrorMessage(Errors.Authentication.PasswordConfirmCannotBeEmpty.Description); + } + + [Fact] + public void Validate_WhenPasswordAndPasswordConfirmDontMatch_ShouldHaveValidationError() + { + // Arrange + RegisterUserCommand command = RegisterUserCommandFixture.CreateRegisterCommand(); + command = command with { PasswordConfirm = "$321Bcda" }; + + // Act + TestValidationResult result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationErrorFor(x => x.Password) + .WithErrorMessage(Errors.Authentication.PasswordsNotMatch.Description); + } + + [Theory] + [InlineData("password123")] // missing uppercase and special character + [InlineData("PASSWORD123")] // missing special character + [InlineData("Password123")] // missing special character + [InlineData("Password!@#")] // missing number + [InlineData("Pass1!")] // too short + [InlineData("password")] // missing uppercase, number, and special character + public void Validate_WhenPasswordDoesNotMatchPattern_ShouldHaveValidationError(string password) + { + // Arrange + RegisterUserCommand command = RegisterUserCommandFixture.CreateRegisterCommand(); + command = command with { Password = password, PasswordConfirm = password }; + + // Act + TestValidationResult result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationErrorFor(x => x.Password) + .WithErrorMessage(Errors.Authentication.InvalidPassword.Description); + } + + [Theory] + [InlineData("Password1!")] // valid password + [InlineData("Complex1@Password")] // valid password + [InlineData("MyP@ssw0rd")] // valid password + [InlineData("Abcd123!@#")] // valid password + public void Validate_WhenPasswordMatchesPattern_ShouldNotHaveValidationError(string password) + { + // Arrange + RegisterUserCommand command = RegisterUserCommandFixture.CreateRegisterCommand(); + command = command with { Password = password, PasswordConfirm = password }; + + // Act + TestValidationResult result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationErrorFor(x => x.Password); + } + + [Fact] + public void Validate_WhenCommandIsValid_ShouldNotHaveValidationError() + { + // Arrange + RegisterUserCommand command = RegisterUserCommandFixture.CreateRegisterCommand(); + command = command with + { + Username = "valid.user123", + Password = "$321Bcda", + PasswordConfirm = "$321Bcda" + }; + + // Act + TestValidationResult result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationErrorFor(x => x.Username); + result.ShouldNotHaveValidationErrorFor(x => x.Password); + result.ShouldNotHaveValidationErrorFor(x => x.PasswordConfirm); + } + + [Theory] + [InlineData("a")] // too short + [InlineData("ab")] // too short + [InlineData("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa")] // too long (256 chars) + public void Validate_WhenUsernameHasInvalidLength_ShouldHaveValidationError(string username) + { + // Arrange + RegisterUserCommand command = RegisterUserCommandFixture.CreateRegisterCommand(); + command = command with { Username = username }; + + // Act + TestValidationResult result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationErrorFor(x => x.Username) + .WithErrorMessage(Errors.Authentication.UsernameMustBeBetween3And255CharactersLong.Description); + } + + [Theory] + [InlineData(".username")] // starts with special character + [InlineData("username.")] // ends with special character + [InlineData("_username")] // starts with special character + [InlineData("username_")] // ends with special character + [InlineData("-username")] // starts with special character + [InlineData("username-")] // ends with special character + [InlineData("user name")] // contains space + [InlineData("user@name")] // contains invalid special char + [InlineData("user#name")] // contains invalid special char + [InlineData("user$name")] // contains invalid special char + public void Validate_WhenUsernameHasInvalidFormat_ShouldHaveValidationError(string username) + { + // Arrange + RegisterUserCommand command = RegisterUserCommandFixture.CreateRegisterCommand(); + command = command with { Username = username }; + + // Act + TestValidationResult result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationErrorFor(x => x.Username); + } + + [Theory] + [InlineData("user123")] // basic alphanumeric + [InlineData("user.name")] // with dot + [InlineData("user_name")] // with underscore + [InlineData("user-name")] // with hyphen + [InlineData("User.Name123")] // mixed case with special chars and numbers + [InlineData("a1b")] // minimum length + [InlineData("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa")] // maximum length (255 chars) + public void Validate_WhenUsernameHasValidFormat_ShouldNotHaveValidationError(string username) + { + // Arrange + RegisterUserCommand command = RegisterUserCommandFixture.CreateRegisterCommand(); + command = command with { Username = username }; + + // Act + TestValidationResult result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationErrorFor(x => x.Username); + } +} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Authentication/Queries/LoginUser/Fixtures/LoginRequestFixture.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Authentication/Queries/LoginUser/Fixtures/LoginRequestFixture.cs new file mode 100644 index 00000000..2d46f9cb --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Authentication/Queries/LoginUser/Fixtures/LoginRequestFixture.cs @@ -0,0 +1,54 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Contracts.Requests.Authentication; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Application.UnitTests.Core.UsersManagement.Authentication.Queries.LoginUser.Fixtures; + +/// +/// Fixture class for the class. +/// +[ExcludeFromCodeCoverage] +public class LoginRequestFixture +{ + private readonly Faker _faker; + + /// + /// Initializes a new instance of the class. + /// + public LoginRequestFixture() + { + _faker = new Faker(); + } + + /// + /// Creates a random valid . + /// + /// The created . + public LoginRequest CreateLoginRequest( + string? username = null, + string? password = null, + string? totpCode = null) + { + return new LoginRequest( + username ?? _faker.Internet.UserName(), + password ?? _faker.Internet.Password(), + totpCode ?? _faker.Random.Number(100000, 999999).ToString() + ); + } + + /// + /// Creates a list of . + /// + /// The number of elements to create. + /// The created list. + public List CreateMany(int count = 3) + { + return Enumerable.Range(0, count) + .Select(_ => CreateLoginRequest()) + .ToList(); + } +} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Authentication/Queries/LoginUser/Fixtures/LoginUserQueryFixture.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Authentication/Queries/LoginUser/Fixtures/LoginUserQueryFixture.cs new file mode 100644 index 00000000..c3773353 --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Authentication/Queries/LoginUser/Fixtures/LoginUserQueryFixture.cs @@ -0,0 +1,36 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Application.Core.UsersManagement.Authentication.Queries.LoginUser; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Application.UnitTests.Core.UsersManagement.Authentication.Queries.LoginUser.Fixtures; + +/// +/// Fixture class for the class. +/// +[ExcludeFromCodeCoverage] +public class LoginUserQueryFixture +{ + /// + /// Creates a random valid query for user login. + /// + /// Whether to include a TOTP code in the query. + /// The created query. + public static LoginUserQuery CreateLoginQuery(bool includeTotpCode = false) + { + string password = "Abcd123$"; + Faker faker = new Faker() + .CustomInstantiator(f => new LoginUserQuery( + default!, + default!, + default + )) + .RuleFor(x => x.Username, f => f.Person.UserName) + .RuleFor(x => x.Password, password); + + if (includeTotpCode) + faker.RuleFor(x => x.TotpCode, f => f.Random.Replace("######")); // generates 6 random digits + return faker; + } +} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Authentication/Queries/LoginUser/LoginUserQueryHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Authentication/Queries/LoginUser/LoginUserQueryHandlerTests.cs new file mode 100644 index 00000000..27df63bb --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Authentication/Queries/LoginUser/LoginUserQueryHandlerTests.cs @@ -0,0 +1,357 @@ +#region ========================================================================= USING ===================================================================================== +using ErrorOr; +using FluentAssertions; +using Lumina.Application.Common.DataAccess.Entities.UsersManagement; +using Lumina.Application.Common.DataAccess.Repositories.Users; +using Lumina.Application.Common.DataAccess.UoW; +using Lumina.Application.Common.Errors; +using Lumina.Application.Common.Infrastructure.Authentication; +using Lumina.Application.Common.Infrastructure.Security; +using Lumina.Application.Core.UsersManagement.Authentication.Queries.LoginUser; +using Lumina.Application.UnitTests.Common.Mapping.UserManagement.Users.Fixtures; +using Lumina.Contracts.Responses.Authentication; +using NSubstitute; +using System; +using System.Diagnostics.CodeAnalysis; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Application.UnitTests.Core.UsersManagement.Authentication.Queries.LoginUser; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class LoginUserQueryHandlerTests +{ + private readonly IUnitOfWork _mockUnitOfWork; + private readonly IHashService _mockHashService; + private readonly IJwtTokenGenerator _mockJwtTokenGenerator; + private readonly ITotpTokenGenerator _mockTotpTokenGenerator; + private readonly ICryptographyService _mockCryptographyService; + private readonly IUserRepository _mockUserRepository; + private readonly LoginUserQueryHandler _sut; + + /// + /// Initializes a new instance of the class. + /// + public LoginUserQueryHandlerTests() + { + _mockUnitOfWork = Substitute.For(); + _mockHashService = Substitute.For(); + _mockJwtTokenGenerator = Substitute.For(); + _mockTotpTokenGenerator = Substitute.For(); + _mockCryptographyService = Substitute.For(); + _mockUserRepository = Substitute.For(); + + _mockUnitOfWork.GetRepository().Returns(_mockUserRepository); + + _sut = new LoginUserQueryHandler( + _mockUnitOfWork, + _mockHashService, + _mockJwtTokenGenerator, + _mockTotpTokenGenerator, + _mockCryptographyService); + } + + [Fact] + public async Task Handle_WhenValidCredentialsWithoutTOTP_ShouldReturnLoginResponse() + { + // Arrange + string password = "password123"; + string hashedPassword = "hashedPassword"; + string jwtToken = "jwtToken"; + + UserEntity user = UserEntityFixture.CreateUserEntity(); + user.Password = Uri.EscapeDataString(hashedPassword); + user.TotpSecret = null; + + LoginUserQuery query = new(user.Username, password); + + _mockUserRepository.GetByUsernameAsync(user.Username, Arg.Any()) + .Returns(ErrorOrFactory.From(user)); + _mockHashService.CheckStringAgainstHash(password, hashedPassword) + .Returns(true); + _mockJwtTokenGenerator.GenerateToken(user.Id.ToString(), user.Username) + .Returns(jwtToken); + + // Act + ErrorOr result = await _sut.Handle(query, CancellationToken.None); + + // Assert + result.IsError.Should().BeFalse(); + result.Value.Id.Should().Be(user.Id); + result.Value.Username.Should().Be(user.Username); + result.Value.Token.Should().Be(jwtToken); + result.Value.UsesTotp.Should().BeFalse(); + } + + [Fact] + public async Task Handle_WhenValidCredentialsWithTOTP_ShouldReturnLoginResponse() + { + // Arrange + string password = "password123"; + string hashedPassword = "hashedPassword"; + string jwtToken = "jwtToken"; + string totpCode = "123456"; + string encryptedTotpSecret = Convert.ToBase64String(new byte[] { 1, 2, 3 }); + string decryptedTotpSecret = Convert.ToBase64String(new byte[] { 4, 5, 6 }); + + UserEntity user = UserEntityFixture.CreateUserEntity(); + user.Password = Uri.EscapeDataString(hashedPassword); + user.TotpSecret = encryptedTotpSecret; + + LoginUserQuery query = new(user.Username, password, totpCode); + + _mockUserRepository.GetByUsernameAsync(user.Username, Arg.Any()) + .Returns(ErrorOrFactory.From(user)); + _mockHashService.CheckStringAgainstHash(password, hashedPassword) + .Returns(true); + _mockJwtTokenGenerator.GenerateToken(user.Id.ToString(), user.Username) + .Returns(jwtToken); + _mockCryptographyService.Decrypt(encryptedTotpSecret) + .Returns(decryptedTotpSecret); + _mockTotpTokenGenerator.ValidateToken(Arg.Any(), totpCode) + .Returns(true); + + // Act + ErrorOr result = await _sut.Handle(query, CancellationToken.None); + + // Assert + result.IsError.Should().BeFalse(); + result.Value.Id.Should().Be(user.Id); + result.Value.Username.Should().Be(user.Username); + result.Value.Token.Should().Be(jwtToken); + result.Value.UsesTotp.Should().BeTrue(); + } + + [Fact] + public async Task Handle_WhenUserDoesNotExist_ShouldReturnError() + { + // Arrange + LoginUserQuery query = new("nonexistentUser", "password"); + + _mockUserRepository.GetByUsernameAsync(query.Username!, Arg.Any()) + .Returns(ErrorOrFactory.From(null)); + + // Act + ErrorOr result = await _sut.Handle(query, CancellationToken.None); + + // Assert + result.IsError.Should().BeTrue(); + result.FirstError.Should().Be(Errors.Authentication.InvalidUsernameOrPassword); + } + + [Fact] + public async Task Handle_WhenPasswordIsIncorrect_ShouldReturnError() + { + // Arrange + string password = "wrongPassword"; + string hashedPassword = "hashedPassword"; + + UserEntity user = UserEntityFixture.CreateUserEntity(); + user.Password = Uri.EscapeDataString(hashedPassword); + user.TempPassword = null; + + LoginUserQuery query = new(user.Username, password); + + _mockUserRepository.GetByUsernameAsync(user.Username, Arg.Any()) + .Returns(ErrorOrFactory.From(user)); + _mockHashService.CheckStringAgainstHash(password, hashedPassword) + .Returns(false); + + // Act + ErrorOr result = await _sut.Handle(query, CancellationToken.None); + + // Assert + result.IsError.Should().BeTrue(); + result.FirstError.Should().Be(Errors.Authentication.InvalidUsernameOrPassword); + } + + [Fact] + public async Task Handle_WhenTempPasswordIsExpired_ShouldReturnError() + { + // Arrange + string password = "tempPassword"; + string hashedPassword = "hashedPassword"; + string hashedTempPassword = "hashedTempPassword"; + + UserEntity user = UserEntityFixture.CreateUserEntity(); + user.Password = Uri.EscapeDataString(hashedPassword); + user.TempPassword = Uri.EscapeDataString(hashedTempPassword); + user.TempPasswordCreated = DateTime.UtcNow.AddMinutes(-16); // Expired (more than 15 minutes old) + + LoginUserQuery query = new(user.Username, password); + + _mockUserRepository.GetByUsernameAsync(user.Username, Arg.Any()) + .Returns(ErrorOrFactory.From(user)); + _mockHashService.CheckStringAgainstHash(password, hashedPassword) + .Returns(false); + _mockHashService.CheckStringAgainstHash(password, hashedTempPassword) + .Returns(true); + + // Act + ErrorOr result = await _sut.Handle(query, CancellationToken.None); + + // Assert + result.IsError.Should().BeTrue(); + result.FirstError.Should().Be(Errors.Authentication.TempPasswordExpired); + + await _mockUserRepository.Received(1).UpdateAsync(Arg.Is(u => + u.TempPassword == null && u.TempPasswordCreated == null), + Arg.Any()); + await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task Handle_WhenValidTempPassword_ShouldReturnLoginResponse() + { + // Arrange + string password = "tempPassword"; + string hashedPassword = "hashedPassword"; + string hashedTempPassword = "hashedTempPassword"; + string jwtToken = "jwtToken"; + + UserEntity user = UserEntityFixture.CreateUserEntity(); + user.Password = Uri.EscapeDataString(hashedPassword); + user.TempPassword = Uri.EscapeDataString(hashedTempPassword); + // Set temp password created time to 10 minutes ago (still valid) + user.TempPasswordCreated = DateTime.UtcNow.AddMinutes(-10); + user.TotpSecret = null; // Ensure no TOTP validation is needed + + LoginUserQuery query = new(user.Username, password); + + _mockUserRepository.GetByUsernameAsync(user.Username, Arg.Any()) + .Returns(ErrorOrFactory.From(user)); + _mockHashService.CheckStringAgainstHash(password, hashedPassword) + .Returns(false); // Regular password check fails + _mockHashService.CheckStringAgainstHash(password, hashedTempPassword) + .Returns(true); // Temp password check succeeds + _mockJwtTokenGenerator.GenerateToken(user.Id.ToString(), user.Username) + .Returns(jwtToken); + + // Act + ErrorOr result = await _sut.Handle(query, CancellationToken.None); + + // Assert + result.IsError.Should().BeFalse(); + result.Value.Id.Should().Be(user.Id); + result.Value.Username.Should().Be(user.Username); + result.Value.Token.Should().Be(jwtToken); + result.Value.UsesTotp.Should().BeFalse(); + } + + [Fact] + public async Task Handle_WhenUserHasTOTPButNoCodeProvided_ShouldReturnError() + { + // Arrange + string password = "password123"; + string hashedPassword = "hashedPassword"; + string encryptedTotpSecret = Convert.ToBase64String(new byte[] { 1, 2, 3 }); + + UserEntity user = UserEntityFixture.CreateUserEntity(); + user.Password = Uri.EscapeDataString(hashedPassword); + user.TotpSecret = encryptedTotpSecret; + + LoginUserQuery query = new(user.Username, password); + + _mockUserRepository.GetByUsernameAsync(user.Username, Arg.Any()) + .Returns(ErrorOrFactory.From(user)); + _mockHashService.CheckStringAgainstHash(password, hashedPassword) + .Returns(true); + + // Act + ErrorOr result = await _sut.Handle(query, CancellationToken.None); + + // Assert + result.IsError.Should().BeTrue(); + result.FirstError.Should().Be(Errors.Authentication.InvalidTotpCode); + } + + [Fact] + public async Task Handle_WhenTOTPCodeIsInvalid_ShouldReturnError() + { + // Arrange + string password = "password123"; + string hashedPassword = "hashedPassword"; + string totpCode = "123456"; + string encryptedTotpSecret = Convert.ToBase64String(new byte[] { 1, 2, 3 }); + string decryptedTotpSecret = Convert.ToBase64String(new byte[] { 4, 5, 6 }); + + UserEntity user = UserEntityFixture.CreateUserEntity(); + user.Password = Uri.EscapeDataString(hashedPassword); + user.TotpSecret = encryptedTotpSecret; + + LoginUserQuery query = new(user.Username, password, totpCode); + + _mockUserRepository.GetByUsernameAsync(user.Username, Arg.Any()) + .Returns(ErrorOrFactory.From(user)); + _mockHashService.CheckStringAgainstHash(password, hashedPassword) + .Returns(true); + _mockCryptographyService.Decrypt(encryptedTotpSecret) + .Returns(decryptedTotpSecret); + _mockTotpTokenGenerator.ValidateToken(Arg.Any(), totpCode) + .Returns(false); + + // Act + ErrorOr result = await _sut.Handle(query, CancellationToken.None); + + // Assert + result.IsError.Should().BeTrue(); + result.FirstError.Should().Be(Errors.Authentication.InvalidTotpCode); + } + + [Fact] + public async Task Handle_WhenGetByUsernameReturnsError_ShouldReturnError() + { + // Arrange + LoginUserQuery query = new("username", "password"); + Error error = Error.Failure("Database.Error", "Failed to retrieve user"); + + _mockUserRepository.GetByUsernameAsync(query.Username!, Arg.Any()) + .Returns(error); + + // Act + ErrorOr result = await _sut.Handle(query, CancellationToken.None); + + // Assert + result.IsError.Should().BeTrue(); + result.FirstError.Should().Be(error); + } + + [Fact] + public async Task Handle_WhenBothRegularAndTempPasswordsAreIncorrect_ShouldReturnError() + { + // Arrange + string password = "wrongPassword"; + string hashedPassword = "hashedPassword"; + string hashedTempPassword = "hashedTempPassword"; + + UserEntity user = UserEntityFixture.CreateUserEntity(); + user.Password = Uri.EscapeDataString(hashedPassword); + user.TempPassword = Uri.EscapeDataString(hashedTempPassword); + user.TempPasswordCreated = DateTime.UtcNow.AddMinutes(-10); // Valid timeframe + + LoginUserQuery query = new(user.Username, password); + + _mockUserRepository.GetByUsernameAsync(user.Username, Arg.Any()) + .Returns(ErrorOrFactory.From(user)); + _mockHashService.CheckStringAgainstHash(password, hashedPassword) + .Returns(false); // Regular password check fails + _mockHashService.CheckStringAgainstHash(password, hashedTempPassword) + .Returns(false); // Temp password check also fails + + // Act + ErrorOr result = await _sut.Handle(query, CancellationToken.None); + + // Assert + result.IsError.Should().BeTrue(); + result.FirstError.Should().Be(Errors.Authentication.InvalidUsernameOrPassword); + + _mockHashService.Received(1).CheckStringAgainstHash(password, hashedPassword); + _mockHashService.Received(1).CheckStringAgainstHash(password, hashedTempPassword); + await _mockUserRepository.DidNotReceive().UpdateAsync(Arg.Any(), Arg.Any()); + await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); + } +} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Authentication/Queries/LoginUser/LoginUserQueryValidatorTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Authentication/Queries/LoginUser/LoginUserQueryValidatorTests.cs new file mode 100644 index 00000000..3bae7a22 --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Authentication/Queries/LoginUser/LoginUserQueryValidatorTests.cs @@ -0,0 +1,222 @@ +#region ========================================================================= USING ===================================================================================== +using FluentValidation.TestHelper; +using Lumina.Application.Common.Errors; +using Lumina.Application.Core.UsersManagement.Authentication.Queries.LoginUser; +using Lumina.Application.UnitTests.Core.UsersManagement.Authentication.Queries.LoginUser.Fixtures; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Application.UnitTests.Core.UsersManagement.Authentication.Queries.LoginUser; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class LoginUserQueryValidatorTests +{ + private readonly LoginUserQueryValidator _validator; + + /// + /// Initializes a new instance of the class. + /// + public LoginUserQueryValidatorTests() + { + _validator = new LoginUserQueryValidator(); + } + + [Fact] + public void Validate_WhenUsernameIsNull_ShouldHaveValidationError() + { + // Arrange + LoginUserQuery query = LoginUserQueryFixture.CreateLoginQuery(); + query = query with { Username = null! }; + + // Act + TestValidationResult result = _validator.TestValidate(query); + + // Assert + result.ShouldHaveValidationErrorFor(x => x.Username) + .WithErrorMessage(Errors.Authentication.UsernameCannotBeEmpty.Description); + } + + [Fact] + public void Validate_WhenUsernameIsEmpty_ShouldHaveValidationError() + { + // Arrange + LoginUserQuery query = LoginUserQueryFixture.CreateLoginQuery(); + query = query with { Username = string.Empty }; + + // Act + TestValidationResult result = _validator.TestValidate(query); + + // Assert + result.ShouldHaveValidationErrorFor(x => x.Username) + .WithErrorMessage(Errors.Authentication.UsernameCannotBeEmpty.Description); + } + + [Fact] + public void Validate_WhenUsernameIsWhiteSpace_ShouldHaveValidationError() + { + // Arrange + LoginUserQuery query = LoginUserQueryFixture.CreateLoginQuery(); + query = query with { Username = " " }; + + // Act + TestValidationResult result = _validator.TestValidate(query); + + // Assert + result.ShouldHaveValidationErrorFor(x => x.Username) + .WithErrorMessage(Errors.Authentication.UsernameCannotBeEmpty.Description); + } + + [Fact] + public void Validate_WhenPasswordIsNull_ShouldHaveValidationError() + { + // Arrange + LoginUserQuery query = LoginUserQueryFixture.CreateLoginQuery(); + query = query with { Password = null! }; + + // Act + TestValidationResult result = _validator.TestValidate(query); + + // Assert + result.ShouldHaveValidationErrorFor(x => x.Password) + .WithErrorMessage(Errors.Authentication.PasswordCannotBeEmpty.Description); + } + + [Fact] + public void Validate_WhenPasswordIsEmpty_ShouldHaveValidationError() + { + // Arrange + LoginUserQuery query = LoginUserQueryFixture.CreateLoginQuery(); + query = query with { Password = string.Empty }; + + // Act + TestValidationResult result = _validator.TestValidate(query); + + // Assert + result.ShouldHaveValidationErrorFor(x => x.Password) + .WithErrorMessage(Errors.Authentication.PasswordCannotBeEmpty.Description); + } + + [Fact] + public void Validate_WhenPasswordIsWhiteSpace_ShouldHaveValidationError() + { + // Arrange + LoginUserQuery query = LoginUserQueryFixture.CreateLoginQuery(); + query = query with { Password = " " }; + + // Act + TestValidationResult result = _validator.TestValidate(query); + + // Assert + result.ShouldHaveValidationErrorFor(x => x.Password) + .WithErrorMessage(Errors.Authentication.PasswordCannotBeEmpty.Description); + } + + [Theory] + [InlineData("password123")] // Missing uppercase and special character + [InlineData("PASSWORD123")] // Missing special character + [InlineData("Password123")] // Missing special character + [InlineData("Password!@#")] // Missing number + [InlineData("Pass1!")] // Too short + [InlineData("password")] // Missing uppercase, number, and special character + public void Validate_WhenPasswordDoesNotMatchPattern_ShouldHaveValidationError(string password) + { + // Arrange + LoginUserQuery query = LoginUserQueryFixture.CreateLoginQuery(); + query = query with { Password = password }; + + // Act + TestValidationResult result = _validator.TestValidate(query); + + // Assert + result.ShouldHaveValidationErrorFor(x => x.Password) + .WithErrorMessage(Errors.Authentication.InvalidPassword.Description); + } + + [Theory] + [InlineData("Password1!")] // Valid password + [InlineData("Complex1@Password")] // Valid password + [InlineData("MyP@ssw0rd")] // Valid password + [InlineData("Abcd123!@#")] // Valid password + public void Validate_WhenPasswordMatchesPattern_ShouldNotHaveValidationError(string password) + { + // Arrange + LoginUserQuery query = LoginUserQueryFixture.CreateLoginQuery(); + query = query with { Password = password }; + + // Act + TestValidationResult result = _validator.TestValidate(query); + + // Assert + result.ShouldNotHaveValidationErrorFor(x => x.Password); + } + + [Theory] + [InlineData("12345")] // Too short + [InlineData("1234567")] // Too long + [InlineData("abcdef")] // Contains letters + [InlineData("12345a")] // Contains letters + [InlineData("12.345")] // Contains special characters + [InlineData("12 345")] // Contains whitespace + public void Validate_WhenTotpCodeIsInvalid_ShouldHaveValidationError(string totpCode) + { + // Arrange + LoginUserQuery query = LoginUserQueryFixture.CreateLoginQuery(); + query = query with { TotpCode = totpCode }; + + // Act + TestValidationResult result = _validator.TestValidate(query); + + // Assert + result.ShouldHaveValidationErrorFor(x => x.TotpCode) + .WithErrorMessage(Errors.Authentication.InvalidTotpCode.Description); + } + + [Theory] + [InlineData("123456")] + [InlineData("000000")] + [InlineData("999999")] + public void Validate_WhenTotpCodeIsValid_ShouldNotHaveValidationError(string totpCode) + { + // Arrange + LoginUserQuery query = LoginUserQueryFixture.CreateLoginQuery(); + query = query with { TotpCode = totpCode }; + + // Act + TestValidationResult result = _validator.TestValidate(query); + + // Assert + result.ShouldNotHaveValidationErrorFor(x => x.TotpCode); + } + + [Fact] + public void Validate_WhenTotpCodeIsNull_ShouldNotHaveValidationError() + { + // Arrange + LoginUserQuery query = LoginUserQueryFixture.CreateLoginQuery(); + query = query with { TotpCode = null }; + + // Act + TestValidationResult result = _validator.TestValidate(query); + + // Assert + result.ShouldNotHaveValidationErrorFor(x => x.TotpCode); + } + + [Fact] + public void Validate_WhenQueryIsValid_ShouldNotHaveValidationError() + { + // Arrange + LoginUserQuery query = LoginUserQueryFixture.CreateLoginQuery(true); + + // Act + TestValidationResult result = _validator.TestValidate(query); + + // Assert + result.ShouldNotHaveValidationErrorFor(x => x.Username); + result.ShouldNotHaveValidationErrorFor(x => x.Password); + result.ShouldNotHaveValidationErrorFor(x => x.TotpCode); + } +} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Lumina.Application.UnitTests.csproj b/tests/UnitTests/Lumina.Application.UnitTests/Lumina.Application.UnitTests.csproj index cc9065a2..f7ef7977 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Lumina.Application.UnitTests.csproj +++ b/tests/UnitTests/Lumina.Application.UnitTests/Lumina.Application.UnitTests.csproj @@ -9,20 +9,27 @@ true + + + <_Parameter1>DisableTestParallelization = true + <_Parameter1_IsLiteral>true + + + - + all runtime; build; native; contentfiles; analyzers; buildtransitive - - + + - + - + all runtime; build; native; contentfiles; analyzers; buildtransitive diff --git a/tests/UnitTests/Lumina.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..4a2c2588 100644 --- a/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Repositories/Books/BookRepositoryTests.cs +++ b/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Repositories/Books/BookRepositoryTests.cs @@ -2,12 +2,12 @@ using EntityFrameworkCore.Testing.NSubstitute; using ErrorOr; using FluentAssertions; -using Lumina.Contracts.Enums.BookLibrary; -using Lumina.Contracts.Models.Common; -using Lumina.Contracts.Models.WrittenContentLibrary.BookLibrary; +using Lumina.Application.Common.DataAccess.Entities.Common; +using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary; using Lumina.DataAccess.Core.Repositories.Books; using Lumina.DataAccess.Core.UoW; using Lumina.DataAccess.UnitTests.Core.Repositories.Books.Fixtures; +using Lumina.Domain.Common.Enums.BookLibrary; using Lumina.Domain.Common.Errors; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.ChangeTracking; @@ -28,7 +28,7 @@ public class BookRepositoryTests { private readonly LuminaDbContext _mockContext; private readonly BookRepository _sut; - private readonly BookModelFixture _bookModelFixture; + private readonly BookEntityFixture _bookEntityFixture; /// /// Initializes a new instance of the class. @@ -37,14 +37,14 @@ public class BookRepositoryTests { _mockContext = Create.MockedDbContextFor(); _sut = new BookRepository(_mockContext); - _bookModelFixture = new BookModelFixture(); + _bookEntityFixture = new BookEntityFixture(); } [Fact] public async Task InsertAsync_WhenBookDoesNotExist_ShouldAddBookToContextAndReturnCreated() { // Arrange - BookModel bookModel = _bookModelFixture.CreateBookModel(); + BookEntity bookModel = _bookEntityFixture.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 = _bookEntityFixture.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 = _bookEntityFixture.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 = _bookEntityFixture.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,17 +135,17 @@ public class BookRepositoryTests public async Task GetAllAsync_WhenCalled_ShouldReturnAllBooks() { // Arrange - List books = + List books = [ - _bookModelFixture.CreateBookModel(), - _bookModelFixture.CreateBookModel(), - _bookModelFixture.CreateBookModel() + _bookEntityFixture.CreateBookModel(), + _bookEntityFixture.CreateBookModel(), + _bookEntityFixture.CreateBookModel() ]; _mockContext.Books.AddRange(books); 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 = _bookEntityFixture.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/BookEntityFixture.cs similarity index 62% rename from tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Repositories/Books/Fixtures/BookModelFixture.cs rename to tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Repositories/Books/Fixtures/BookEntityFixture.cs index 59d653c6..29dc1e0b 100644 --- a/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Repositories/Books/Fixtures/BookModelFixture.cs +++ b/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Repositories/Books/Fixtures/BookEntityFixture.cs @@ -1,32 +1,34 @@ #region ========================================================================= USING ===================================================================================== using AutoFixture; using Bogus; -using Lumina.Contracts.Enums.BookLibrary; -using Lumina.Contracts.Models.Common; -using Lumina.Contracts.Models.WrittenContentLibrary.BookLibrary; +using Lumina.Application.Common.DataAccess.Entities.Common; +using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary; +using Lumina.Domain.Common.Enums.BookLibrary; using Lumina.DataAccess.UnitTests.Common.Setup; using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Linq; +using Lumina.Contracts.DTO.Common; +using Lumina.Contracts.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary; #endregion namespace Lumina.DataAccess.UnitTests.Core.Repositories.Books.Fixtures; /// -/// Fixture class for the class. +/// Fixture class for the class. /// [ExcludeFromCodeCoverage] -public class BookModelFixture +public class BookEntityFixture { private readonly Fixture _fixture; private readonly Random _random = new(); private readonly Faker _faker; /// - /// Initializes a new instance of the class. + /// Initializes a new instance of the class. /// - public BookModelFixture() + public BookEntityFixture() { _fixture = new Fixture(); _fixture.Customizations.Add(new DateOnlySpecimenBuilder()); @@ -36,15 +38,15 @@ public class BookModelFixture } /// - /// Creates a random valid BookModel. + /// Creates a random valid . /// - /// The created BookModel. - public BookModel CreateBookModel() + /// The created . + 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,11 +63,11 @@ 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()) + .RuleFor(x => x.Format, f => f.PickRandom()) .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)) @@ -84,20 +86,35 @@ public class BookModelFixture .Generate(); } - private List CreateTags(int count) + /// + /// Creates a list of tag entities with random data. + /// + /// The number of tags to create. + /// A list of randomly generated tag entities. + 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) + /// + /// Creates a list of genre entities with random data. + /// + /// The number of genres to create. + /// A list of randomly generated genre entities. + 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); } + /// + /// Creates a valid Library of Congress Control Number (LCCN). + /// + /// The Faker instance used for generating random data. + /// A properly formatted LCCN string. private string CreateLCCN(Faker f) { string letters = new(Enumerable.Range(0, f.Random.Number(0, 3)) @@ -107,6 +124,11 @@ public class BookModelFixture return letters + digits; } + /// + /// Creates a valid OCLC (Online Computer Library Center) number. + /// + /// The Faker instance used for generating random data. + /// A properly formatted OCLC number string with valid prefix. private string CreateOCLCNumber(Faker f) { string[] prefixes = ["ocm", "ocn", "on", "(OCoLC)"]; @@ -122,6 +144,11 @@ public class BookModelFixture return prefix + number; } + /// + /// Creates a valid Open Library ID. + /// + /// The Faker instance used for generating random data. + /// A properly formatted Open Library ID string. private string CreateOpenLibraryId(Faker f) { int firstDigit = f.Random.Number(1, 9); @@ -130,6 +157,11 @@ public class BookModelFixture return $"OL{firstDigit}{remainingDigits}{suffix}"; } + /// + /// Creates a valid Google Books ID. + /// + /// The Faker instance used for generating random data. + /// A properly formatted Google Books ID string. private string CreateGoogleBooksId(Faker f) { const string VALID_CHARS = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_"; @@ -138,14 +170,24 @@ public class BookModelFixture .ToArray()); } - private List CreateIsbns(int count) + /// + /// Creates a list of ISBN entities with random data. + /// + /// The number of ISBNs to create. + /// A list of randomly generated ISBN entities. + 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) + /// + /// Creates a valid ISBN (International Standard Book Number). + /// + /// The Faker instance used for generating random data. + /// A properly formatted ISBN-10 or ISBN-13 string with valid checksum. + private static string CreateIsbn(Faker f) { bool isIsbn13 = f.Random.Bool(); if (isIsbn13) @@ -175,10 +217,15 @@ public class BookModelFixture } } - private List CreateBookRatings(int count) + // + /// Creates a list of book rating entities with random data. + /// + /// The number of ratings to create. + /// A list of randomly generated book rating entities. + 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(), @@ -187,12 +234,15 @@ public class BookModelFixture .Generate(count); } + /// + /// Configures custom type generation rules for the AutoFixture instance. + /// 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/Core/Repositories/Users/Fixtures/UserEntityFixture.cs b/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Repositories/Users/Fixtures/UserEntityFixture.cs new file mode 100644 index 00000000..e2c5e194 --- /dev/null +++ b/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Repositories/Users/Fixtures/UserEntityFixture.cs @@ -0,0 +1,114 @@ +#region ========================================================================= USING ===================================================================================== +using AutoFixture; +using Bogus; +using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management; +using Lumina.Application.Common.DataAccess.Entities.UsersManagement; +using Lumina.Domain.Common.Enums.MediaLibrary; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.DataAccess.UnitTests.Core.Repositories.Users.Fixtures; + +/// +/// Fixture class for the class. +/// +[ExcludeFromCodeCoverage] +public class UserEntityFixture +{ + private readonly Fixture _fixture; + private readonly Faker _faker; + + /// + /// Initializes a new instance of the class. + /// + public UserEntityFixture() + { + _fixture = new Fixture(); + _faker = new Faker(); + ConfigureCustomTypes(); + } + + /// + /// Creates a random valid . + /// + /// The created . + public UserEntity CreateUserModel() + { + Guid userId = _faker.Random.Guid(); + + return new Faker() + .RuleFor(x => x.Id, _ => userId) + .RuleFor(x => x.Username, f => f.Internet.UserName()) + .RuleFor(x => x.Password, f => f.Internet.Password(12)) + .RuleFor(x => x.TempPassword, f => f.Random.Bool() ? f.Internet.Password(8) : null) + .RuleFor(x => x.TotpSecret, f => f.Random.Bool() ? f.Random.String2(32, "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567") : null) + .RuleFor(x => x.VerificationToken, f => f.Random.Bool() ? f.Random.Guid().ToString() : null) + .RuleFor(x => x.VerificationTokenCreated, (f, u) => u.VerificationToken != null ? f.Date.Past() : null) + .RuleFor(x => x.TempPasswordCreated, (f, u) => u.TempPassword != null ? f.Date.Past() : null) + .RuleFor(x => x.Libraries, _ => CreateLibraries(_faker.Random.Number(1, 3), userId)) + .RuleFor(x => x.Created, f => f.Date.Past()) + .RuleFor(x => x.Updated, f => f.Random.Bool() ? f.Date.Recent() : null) + .Generate(); + } + + /// + /// Creates a valid collection of user libraries. + /// + /// The number of user libraries to create. + /// The Id of the user for whom to create the libraries. + /// A collection of . + private static List CreateLibraries(int count, Guid userId) + { + return new Faker() + .CustomInstantiator(f => new LibraryEntity + { + Id = f.Random.Guid(), + UserId = userId, + Title = f.Random.String2(f.Random.Number(1, 50)), + LibraryType = f.PickRandom(), + ContentLocations = CreateContentLocations(f.Random.Number(1, 3)), + Created = f.Date.Past(), + Updated = f.Random.Bool() ? f.Date.Recent() : null + }) + .Generate(count); + } + + /// + /// Creates a valid collection of media paths for a library. + /// + /// The number of media library contents to create. + /// A collection of . + private static List CreateContentLocations(int count) + { + return new Faker() + .CustomInstantiator(f => new LibraryContentLocationEntity + { + Path = f.System.FilePath() + }) + .Generate(count); + } + + /// + /// Configures custom type generation rules for the AutoFixture instance. + /// + private void ConfigureCustomTypes() + { + _fixture.Register(() => new LibraryEntity + { + Id = _fixture.Create(), + UserId = _fixture.Create(), + Title = _fixture.Create(), + LibraryType = _fixture.Create(), + ContentLocations = new List(), + Created = _fixture.Create(), + Updated = _fixture.Create() + }); + + _fixture.Register(() => new LibraryContentLocationEntity + { + Path = _fixture.Create() + }); + } +} diff --git a/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Repositories/Users/UserRepositoryTests.cs b/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Repositories/Users/UserRepositoryTests.cs new file mode 100644 index 00000000..4a346657 --- /dev/null +++ b/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Repositories/Users/UserRepositoryTests.cs @@ -0,0 +1,189 @@ +#region ========================================================================= USING ===================================================================================== +using EntityFrameworkCore.Testing.NSubstitute; +using ErrorOr; +using FluentAssertions; +using Lumina.Application.Common.DataAccess.Entities.UsersManagement; +using Lumina.DataAccess.Core.Repositories.Users; +using Lumina.DataAccess.Core.UoW; +using Lumina.DataAccess.UnitTests.Core.Repositories.Users.Fixtures; +using Lumina.Domain.Common.Errors; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.ChangeTracking; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.DataAccess.UnitTests.Core.Repositories.Users; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class UserRepositoryTests +{ + private readonly LuminaDbContext _mockContext; + private readonly UserRepository _sut; + private readonly UserEntityFixture _userEntityFixture; + + /// + /// Initializes a new instance of the class. + /// + public UserRepositoryTests() + { + _mockContext = Create.MockedDbContextFor(); + _sut = new UserRepository(_mockContext); + _userEntityFixture = new UserEntityFixture(); + } + + [Fact] + public async Task InsertAsync_WhenUserDoesNotExist_ShouldAddUserToContextAndReturnCreated() + { + // Arrange + UserEntity userModel = _userEntityFixture.CreateUserModel(); + + // Act + ErrorOr result = await _sut.InsertAsync(userModel, CancellationToken.None); + + // Assert + result.IsError.Should().BeFalse(); + result.Value.Should().Be(Result.Created); + + EntityEntry? addedUser = _mockContext.ChangeTracker.Entries() + .FirstOrDefault(e => e.State == EntityState.Added && e.Entity.Id == userModel.Id); + addedUser.Should().NotBeNull(); + } + + [Fact] + public async Task InsertAsync_WhenUserAlreadyExists_ShouldReturnError() + { + // Arrange + UserEntity userModel = _userEntityFixture.CreateUserModel(); + + _mockContext.Users.Add(userModel); + await _mockContext.SaveChangesAsync(); + + // Act + ErrorOr result = await _sut.InsertAsync(userModel, CancellationToken.None); + + // Assert + result.IsError.Should().BeTrue(); + result.FirstError.Should().Be(Errors.Users.UserAlreadyExists); + _mockContext.ChangeTracker.Entries().Should().HaveCount(1); + } + + [Fact] + public async Task GetAllAsync_WhenCalled_ShouldReturnAllUsers() + { + // Arrange + List users = + [ + _userEntityFixture.CreateUserModel(), + _userEntityFixture.CreateUserModel(), + _userEntityFixture.CreateUserModel() + ]; + _mockContext.Users.AddRange(users); + await _mockContext.SaveChangesAsync(); + + // Act + ErrorOr> result = await _sut.GetAllAsync(CancellationToken.None); + + // Assert + result.IsError.Should().BeFalse(); + result.Value.Should().NotBeNull(); + result.Value.Should().HaveCount(3); + result.Value.Should().BeEquivalentTo(users); + } + + [Fact] + public async Task GetAllAsync_WhenNoUsersExist_ShouldReturnEmptyList() + { + // Act + ErrorOr> result = await _sut.GetAllAsync(CancellationToken.None); + + // Assert + result.IsError.Should().BeFalse(); + result.Value.Should().NotBeNull(); + result.Value.Should().BeEmpty(); + } + + [Fact] + public async Task GetByUsernameAsync_WhenUserExists_ShouldReturnUser() + { + // Arrange + UserEntity userModel = _userEntityFixture.CreateUserModel(); + _mockContext.Users.Add(userModel); + await _mockContext.SaveChangesAsync(); + + // Act + ErrorOr result = await _sut.GetByUsernameAsync(userModel.Username, CancellationToken.None); + + // Assert + result.IsError.Should().BeFalse(); + result.Value.Should().NotBeNull(); + result.Value.Should().BeEquivalentTo(userModel); + } + + [Fact] + public async Task GetByUsernameAsync_WhenUserDoesNotExist_ShouldReturnNull() + { + // Act + ErrorOr result = await _sut.GetByUsernameAsync("nonexistent", CancellationToken.None); + + // Assert + result.IsError.Should().BeFalse(); + result.Value.Should().BeNull(); + } + + [Fact] + public async Task UpdateAsync_WhenUserExists_ShouldUpdateUserAndReturnUpdated() + { + // Arrange + UserEntity existingUser = _userEntityFixture.CreateUserModel(); + _mockContext.Users.Add(existingUser); + await _mockContext.SaveChangesAsync(); + + // Create updated user with same Id but different properties + UserEntity updatedUser = new() + { + Id = existingUser.Id, + Username = existingUser.Username, // Keep username as it's used for lookup + Password = "NewPassword123", + TempPassword = "TempPass456", + TotpSecret = "NewSecret", + Libraries = [], + Created = existingUser.Created, + Updated = DateTime.UtcNow + }; + + // Act + ErrorOr result = await _sut.UpdateAsync(updatedUser, CancellationToken.None); + + // Assert + result.IsError.Should().BeFalse(); + result.Value.Should().Be(Result.Updated); + + UserEntity? modifiedUser = await _mockContext.Users.FirstOrDefaultAsync(u => u.Username == existingUser.Username); + modifiedUser.Should().NotBeNull(); + modifiedUser!.Password.Should().Be(updatedUser.Password); + modifiedUser.TempPassword.Should().Be(updatedUser.TempPassword); + modifiedUser.TotpSecret.Should().Be(updatedUser.TotpSecret); + } + + [Fact] + public async Task UpdateAsync_WhenUserDoesNotExist_ShouldReturnError() + { + // Arrange + UserEntity userModel = _userEntityFixture.CreateUserModel(); + + // Act + ErrorOr result = await _sut.UpdateAsync(userModel, CancellationToken.None); + + // Assert + result.IsError.Should().BeTrue(); + result.FirstError.Should().Be(Errors.Users.UserDoesNotExist); + } +} diff --git a/tests/UnitTests/Lumina.DataAccess.UnitTests/Lumina.DataAccess.UnitTests.csproj b/tests/UnitTests/Lumina.DataAccess.UnitTests/Lumina.DataAccess.UnitTests.csproj index 81693cdd..39736949 100644 --- a/tests/UnitTests/Lumina.DataAccess.UnitTests/Lumina.DataAccess.UnitTests.csproj +++ b/tests/UnitTests/Lumina.DataAccess.UnitTests/Lumina.DataAccess.UnitTests.csproj @@ -9,22 +9,29 @@ true + + + <_Parameter1>DisableTestParallelization = true + <_Parameter1_IsLiteral>true + + + - + all runtime; build; native; contentfiles; analyzers; buildtransitive - - - + + + - + - + all runtime; build; native; contentfiles; analyzers; buildtransitive diff --git a/tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/FileManagementAggregate/Entities/DirectoryTests.cs b/tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/FileSystemManagementAggregate/Entities/DirectoryTests.cs similarity index 88% 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..37a76287 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 @@ -1,18 +1,18 @@ #region ========================================================================= USING ===================================================================================== using ErrorOr; using FluentAssertions; -using Lumina.Contracts.Enums.FileSystem; +using Lumina.Domain.Common.Enums.FileSystem; +using Lumina.Domain.Common.Errors; using Lumina.Domain.Common.Primitives; -using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.Entities; +using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate; +using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.ValueObjects; +using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Entities; +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 90% 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..1674e645 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 @@ -1,16 +1,16 @@ #region ========================================================================= USING ===================================================================================== using ErrorOr; using FluentAssertions; -using Lumina.Contracts.Enums.FileSystem; +using Lumina.Domain.Common.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.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Entities; +using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.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 93% 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..996971db 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 @@ -1,17 +1,17 @@ #region ========================================================================= USING ===================================================================================== using Bogus; using ErrorOr; -using Lumina.Contracts.Enums.FileSystem; +using Lumina.Domain.Common.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.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate; +using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.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 90% 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..2f023fb5 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 @@ -1,16 +1,16 @@ #region ========================================================================= USING ===================================================================================== using Bogus; using ErrorOr; -using Lumina.Contracts.Enums.FileSystem; +using Lumina.Domain.Common.Enums.FileSystem; using Lumina.Domain.Common.Primitives; -using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.Entities; +using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.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 87% 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..6d983198 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 @@ -1,15 +1,15 @@ #region ========================================================================= USING ===================================================================================== using ErrorOr; using FluentAssertions; -using Lumina.Contracts.Enums.FileSystem; +using Lumina.Domain.Common.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.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate; +using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.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 87% 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..07e27ecd 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 @@ -1,16 +1,16 @@ #region ========================================================================= USING ===================================================================================== using ErrorOr; using FluentAssertions; -using Lumina.Contracts.Enums.FileSystem; +using Lumina.Domain.Common.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.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate; +using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Entities; +using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.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 88% 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..649c78b5 100644 --- a/tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/FileManagementAggregate/FileSystemItemTests.cs +++ b/tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/FileSystemManagementAggregate/FileSystemItemTests.cs @@ -3,18 +3,17 @@ using AutoFixture; using AutoFixture.AutoNSubstitute; using ErrorOr; using FluentAssertions; -using Lumina.Contracts.Enums.FileSystem; +using Lumina.Domain.Common.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.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate; +using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.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 71% 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..6bb31ac8 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.Common.Enums.FileSystem; +using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate; +using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.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 87% 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..7a323ad8 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 @@ -3,12 +3,12 @@ using AutoFixture; using AutoFixture.AutoNSubstitute; using ErrorOr; using FluentAssertions; -using Lumina.Contracts.Enums.FileSystem; +using Lumina.Domain.Common.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.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Services; +using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.ValueObjects; +using Lumina.Domain.UnitTests.Core.Aggregates.FileSystemManagementAggregate.ValueObjects.Fixtures; using NSubstitute; using NSubstitute.ExceptionExtensions; using System; @@ -18,11 +18,9 @@ using System.IO; using System.IO.Abstractions; using System.Linq; using System.Runtime.InteropServices; -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. @@ -35,29 +33,29 @@ public class DirectoryProviderServiceTests private readonly IFileSystemPermissionsService _mockFileSystemPermissionsService; private readonly DirectoryProviderService _sut; private readonly FileSystemPathIdFixture _fileSystemPathIdFixture; - private static readonly bool s_isLinux = RuntimeInformation.IsOSPlatform(OSPlatform.Linux); - private readonly string _pathSource = s_isLinux ? "/Source" : @"C:\Source"; - private readonly string _pathSourceSubDir = s_isLinux ? "/Source/SubDir" : @"C:\Source\SubDir"; - private readonly string _pathSourceSubDir1 = s_isLinux ? "/Source/SubDir1" : @"C:\Source\SubDir1"; - private readonly string _pathSourceSubDir2 = s_isLinux ? "/Source/SubDir2" : @"C:\Source\SubDir2"; - private readonly string _pathSourceFile1 = s_isLinux ? "/Source/file1.txt" : @"C:\Source\file1.txt"; - private readonly string _pathSourceFile2 = s_isLinux ? "/Source/file2.txt" : @"C:\Source\file2.txt"; - private readonly string _pathDestinationFile1 = s_isLinux ? "/Destination/file1.txt" : @"C:\Destination\file1.txt"; - private readonly string _pathDestinationFile2 = s_isLinux ? "/Destination/file2.txt" : @"C:\Destination\file2.txt"; - private readonly string _pathDestination = s_isLinux ? "/Destination" : @"C:\Destination"; - private readonly string _pathDestinationSubDir = s_isLinux ? "/Destination/SubDir" : @"C:\Destination\SubDir"; - private readonly string _pathDestinationSubDir1 = s_isLinux ? "/Destination/SubDir1" : @"C:\Destination\SubDir1"; - private readonly string _pathDestinationSubDir2 = s_isLinux ? "/Destination/SubDir2" : @"C:\Destination\SubDir2"; - private readonly string _pathDestinationFile = s_isLinux ? "/Destination/file.txt" : @"C:\Destination\file.txt"; - private readonly string _pathVisible1 = s_isLinux ? "/Visible" : @"C:\Visible"; - private readonly string _pathHidden1 = s_isLinux ? "/Hidden" : @"C:\Hidden"; - private readonly string _pathVisible2 = s_isLinux ? "/Visible/" : @"C:\Visible\"; - private readonly string _pathHidden2 = s_isLinux ? "/Hidden/" : @"C:\Hidden\"; - private readonly string _pathValid1 = s_isLinux ? "/Valid" : @"C:\Valid"; - private readonly string _pathInvalid1 = s_isLinux ? "/Invalid" : @"C:\Invalid"; - private readonly string _pathValid2 = s_isLinux ? "/Valid/" : @"C:\Valid\"; - private readonly string _pathInvalid2 = s_isLinux ? "/Invalid/" : @"C:\Invalid\"; - private readonly char _dirSeparator = s_isLinux ? '/' : '\\'; + private static readonly bool s_isUnix = RuntimeInformation.IsOSPlatform(OSPlatform.Linux) || RuntimeInformation.IsOSPlatform(OSPlatform.OSX); + private readonly string _pathSource = s_isUnix ? "/Source" : @"C:\Source"; + private readonly string _pathSourceSubDir = s_isUnix ? "/Source/SubDir" : @"C:\Source\SubDir"; + private readonly string _pathSourceSubDir1 = s_isUnix ? "/Source/SubDir1" : @"C:\Source\SubDir1"; + private readonly string _pathSourceSubDir2 = s_isUnix ? "/Source/SubDir2" : @"C:\Source\SubDir2"; + private readonly string _pathSourceFile1 = s_isUnix ? "/Source/file1.txt" : @"C:\Source\file1.txt"; + private readonly string _pathSourceFile2 = s_isUnix ? "/Source/file2.txt" : @"C:\Source\file2.txt"; + private readonly string _pathDestinationFile1 = s_isUnix ? "/Destination/file1.txt" : @"C:\Destination\file1.txt"; + private readonly string _pathDestinationFile2 = s_isUnix ? "/Destination/file2.txt" : @"C:\Destination\file2.txt"; + private readonly string _pathDestination = s_isUnix ? "/Destination" : @"C:\Destination"; + private readonly string _pathDestinationSubDir = s_isUnix ? "/Destination/SubDir" : @"C:\Destination\SubDir"; + private readonly string _pathDestinationSubDir1 = s_isUnix ? "/Destination/SubDir1" : @"C:\Destination\SubDir1"; + private readonly string _pathDestinationSubDir2 = s_isUnix ? "/Destination/SubDir2" : @"C:\Destination\SubDir2"; + private readonly string _pathDestinationFile = s_isUnix ? "/Destination/file.txt" : @"C:\Destination\file.txt"; + private readonly string _pathVisible1 = s_isUnix ? "/Visible" : @"C:\Visible"; + private readonly string _pathHidden1 = s_isUnix ? "/Hidden" : @"C:\Hidden"; + private readonly string _pathVisible2 = s_isUnix ? "/Visible/" : @"C:\Visible\"; + private readonly string _pathHidden2 = s_isUnix ? "/Hidden/" : @"C:\Hidden\"; + private readonly string _pathValid1 = s_isUnix ? "/Valid" : @"C:\Valid"; + private readonly string _pathInvalid1 = s_isUnix ? "/Invalid" : @"C:\Invalid"; + private readonly string _pathValid2 = s_isUnix ? "/Valid/" : @"C:\Valid\"; + private readonly string _pathInvalid2 = s_isUnix ? "/Invalid/" : @"C:\Invalid\"; + private readonly char _dirSeparator = s_isUnix ? '/' : '\\'; /// /// Initializes a new instance of the class. @@ -174,16 +172,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_isUnix + ? ["/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_isUnix + ? ["/A/", "/B/", "/C/"] + : [@"C:\A\", @"C:\B\", @"C:\C\"]; // Act ErrorOr> result = _sut.GetSubdirectoryPaths(path, false); @@ -243,8 +241,8 @@ public class DirectoryProviderServiceTests public void GetFileName_WhenPathIsValid_ShouldReturnFileName() { // Arrange - string fullPath = s_isLinux - ? "/folder/subfolder/file.txt" + string fullPath = s_isUnix + ? "/folder/subfolder/file.txt" : @"C:\folder\subfolder\file.txt"; FileSystemPathId path = _fileSystemPathIdFixture.CreateFileSystemPathId(fullPath); _mockFileSystem.Path.GetFileName(fullPath).Returns("file.txt"); @@ -261,8 +259,8 @@ public class DirectoryProviderServiceTests public void GetFileName_WhenPathEndsWithDirectorySeparator_ShouldReturnLastSegment() { // Arrange - string fullPath = s_isLinux - ? "/folder/subfolder/" + string fullPath = s_isUnix + ? "/folder/subfolder/" : @"C:\folder\subfolder\"; FileSystemPathId path = _fileSystemPathIdFixture.CreateFileSystemPathId(fullPath); _mockFileSystem.Path.GetFileName(fullPath[..^1]).Returns("subfolder"); @@ -280,8 +278,8 @@ public class DirectoryProviderServiceTests public void GetFileName_WhenPathIsRoot_ShouldReturnEmptyString() { // Arrange - string fullPath = s_isLinux - ? "/C/" + string fullPath = s_isUnix + ? "/C/" : @"/"; FileSystemPathId path = _fileSystemPathIdFixture.CreateFileSystemPathId(fullPath); _mockFileSystem.Path.GetFileName(fullPath[..^1]).Returns(string.Empty); @@ -367,8 +365,8 @@ public class DirectoryProviderServiceTests // Arrange FileSystemPathId parentPath = _fileSystemPathIdFixture.CreateFileSystemPathId(@"C:\Parent"); string directoryName = "NewDirectory"; - string fullPath = s_isLinux - ? "/Parent/NewDirectory" + string fullPath = s_isUnix + ? "/Parent/NewDirectory" : @"C:\Parent\NewDirectory"; _mockFileSystemPermissionsService.CanAccessPath(parentPath, FileAccessMode.Write, false).Returns(true); @@ -484,7 +482,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 +491,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_isUnix + ? "/Destination - Copy (1)" : @"C:\Destination - Copy (1)"; bool overrideExisting = false; @@ -528,13 +526,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 +590,7 @@ public class DirectoryProviderServiceTests // Assert result.IsError.Should().BeTrue(); - result.FirstError.Should().Be(Errors.FileManagement.DirectoryCopyError); + result.FirstError.Should().Be(Errors.FileSystemManagement.DirectoryCopyError); } [Fact] @@ -599,7 +598,7 @@ public class DirectoryProviderServiceTests { // Arrange FileSystemPathId sourcePath = _fileSystemPathIdFixture.CreateFileSystemPathId( - s_isLinux ? "/NonExistentSource" : @"C:\NonExistentSource" + s_isUnix ? "/NonExistentSource" : @"C:\NonExistentSource" ); FileSystemPathId destinationPath = _fileSystemPathIdFixture.CreateFileSystemPathId(_pathDestination); bool overrideExisting = false; @@ -611,7 +610,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,8 +666,8 @@ public class DirectoryProviderServiceTests result.Value.Path.Should().Be(destinationPath.Path); _mockFileSystem.File.Received(1).Move(_pathSourceFile1, _pathDestinationFile1); _mockFileSystem.Directory.Received(1).Move( - _pathSourceSubDir, - s_isLinux ? "/Destination/SubDir" : @"C:\Destination\SubDir" + _pathSourceSubDir, + s_isUnix ? "/Destination/SubDir" : @"C:\Destination\SubDir" ); _mockFileSystem.Directory.Received(1).Delete(sourcePath.Path); } @@ -691,7 +690,7 @@ public class DirectoryProviderServiceTests // Assert result.IsError.Should().BeTrue(); - result.FirstError.Should().Be(Errors.FileManagement.DirectoryMoveError); + result.FirstError.Should().Be(Errors.FileSystemManagement.DirectoryMoveError); } [Fact] @@ -807,20 +806,20 @@ public class DirectoryProviderServiceTests _mockFileSystem.Directory.Exists(destPath.Path).Returns(true); _mockFileSystem.Directory.Exists(_pathSourceSubDir).Returns(true); - _mockFileSystem.Directory.Exists(s_isLinux ? "/Destination/SubDir" : @"C:\Destination\SubDir").Returns(true); + _mockFileSystem.Directory.Exists(s_isUnix ? "/Destination/SubDir" : @"C:\Destination\SubDir").Returns(true); _mockFileSystem.Directory.GetFiles(sourcePath.Path).Returns([]); _mockFileSystem.Directory.GetDirectories(sourcePath.Path).Returns([_pathSourceSubDir]); _mockFileSystem.Directory.GetFiles(_pathSourceSubDir).Returns( - s_isLinux ? ["/Source/SubDir/file.txt"] : [@"C:\Source\SubDir\file.txt"] + s_isUnix ? ["/Source/SubDir/file.txt"] : [@"C:\Source\SubDir\file.txt"] ); _mockFileSystem.Directory.GetDirectories(_pathSourceSubDir).Returns([]); _mockFileSystem.Path.GetFileName(_pathSourceSubDir).Returns("SubDir"); - _mockFileSystem.Path.GetFileName(s_isLinux ? "/Source/SubDir/file.txt" : @"C:\Source\SubDir\file.txt").Returns("file.txt"); + _mockFileSystem.Path.GetFileName(s_isUnix ? "/Source/SubDir/file.txt" : @"C:\Source\SubDir\file.txt").Returns("file.txt"); - _mockFileSystem.File.Exists(s_isLinux ? "/Destination/SubDir/file.txt" : @"C:\Destination\SubDir\file.txt").Returns(false); + _mockFileSystem.File.Exists(s_isUnix ? "/Destination/SubDir/file.txt" : @"C:\Destination\SubDir\file.txt").Returns(false); _mockFileSystem.Path.Combine(Arg.Any(), Arg.Any()) .Returns(callInfo => Path.Combine(callInfo.ArgAt(0), callInfo.ArgAt(1))); @@ -835,8 +834,8 @@ 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 ? "/Destination/SubDir/file.txt" : @"C:\Destination\SubDir\file.txt" + s_isUnix ? "/Source/SubDir/file.txt" : @"C:\Source\SubDir\file.txt", + s_isUnix ? "/Destination/SubDir/file.txt" : @"C:\Destination\SubDir\file.txt" ); _mockFileSystem.Directory.Received(1).Delete(_pathSourceSubDir); _mockFileSystem.Directory.DidNotReceive().Delete(sourcePath.Path); @@ -847,11 +846,11 @@ public class DirectoryProviderServiceTests { // Arrange FileSystemPathId path = _fileSystemPathIdFixture.CreateFileSystemPathId( - s_isLinux ? "/OldName" : @"C:\OldName" + s_isUnix ? "/OldName" : @"C:\OldName" ); string newName = "NewName"; - string parentPath = s_isLinux ? "/" : @"C:\"; - string newPath = s_isLinux ? "/NewName" : @"C:\NewName"; + string parentPath = s_isUnix ? "/" : @"C:\"; + string newPath = s_isUnix ? "/NewName" : @"C:\NewName"; IDirectoryInfo parentDirectoryInfo = Substitute.For(); parentDirectoryInfo.FullName.Returns(parentPath); @@ -874,11 +873,11 @@ public class DirectoryProviderServiceTests { // Arrange FileSystemPathId path = _fileSystemPathIdFixture.CreateFileSystemPathId( - s_isLinux ? "/OldName" : @"C:\OldName" + s_isUnix ? "/OldName" : @"C:\OldName" ); string newName = "NewName"; - string parentPath = s_isLinux ? "/" : @"C:\"; - string newPath = s_isLinux ? "/NewName" : @"C:\NewName"; + string parentPath = s_isUnix ? "/" : @"C:\"; + string newPath = s_isUnix ? "/NewName" : @"C:\NewName"; IDirectoryInfo parentDirectoryInfo = Substitute.For(); parentDirectoryInfo.FullName.Returns(parentPath); @@ -900,11 +899,11 @@ public class DirectoryProviderServiceTests { // Arrange FileSystemPathId path = _fileSystemPathIdFixture.CreateFileSystemPathId( - s_isLinux ? "/OldName" : @"C:\OldName" + s_isUnix ? "/OldName" : @"C:\OldName" ); string newName = "NewName"; - string parentPath = s_isLinux ? "/" : @"C:\"; - string newPath = s_isLinux ? "/NewName" : @"C:\NewName"; + string parentPath = s_isUnix ? "/" : @"C:\"; + string newPath = s_isUnix ? "/NewName" : @"C:\NewName"; IDirectoryInfo parentDirectoryInfo = Substitute.For(); parentDirectoryInfo.FullName.Returns(parentPath); @@ -927,7 +926,7 @@ public class DirectoryProviderServiceTests { // Arrange FileSystemPathId path = _fileSystemPathIdFixture.CreateFileSystemPathId( - s_isLinux ? "/OldName" : @"C:\OldName" + s_isUnix ? "/OldName" : @"C:\OldName" ); string newName = "NewName"; @@ -938,7 +937,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()); } @@ -947,10 +946,10 @@ public class DirectoryProviderServiceTests { // Arrange FileSystemPathId path = _fileSystemPathIdFixture.CreateFileSystemPathId( - s_isLinux ? "/OldName" : @"C:\OldName" + s_isUnix ? "/OldName" : @"C:\OldName" ); string newName = "NewName"; - string parentPath = s_isLinux ? "/" : @"C:\"; + string parentPath = s_isUnix ? "/" : @"C:\"; IDirectoryInfo parentDirectoryInfo = Substitute.For(); parentDirectoryInfo.FullName.Returns(parentPath); @@ -962,7 +961,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()); } @@ -971,7 +970,7 @@ public class DirectoryProviderServiceTests { // Arrange FileSystemPathId path = _fileSystemPathIdFixture.CreateFileSystemPathId( - s_isLinux ? "/DirectoryToDelete" : @"C:\DirectoryToDelete" + s_isUnix ? "/DirectoryToDelete" : @"C:\DirectoryToDelete" ); _mockFileSystemPermissionsService.CanAccessPath(path, FileAccessMode.Delete, false).Returns(true); IDirectoryInfo mockDirectoryInfo = Substitute.For(); @@ -991,7 +990,7 @@ public class DirectoryProviderServiceTests { // Arrange FileSystemPathId path = _fileSystemPathIdFixture.CreateFileSystemPathId( - s_isLinux ? "/DirectoryToDelete" : @"C:\DirectoryToDelete" + s_isUnix ? "/DirectoryToDelete" : @"C:\DirectoryToDelete" ); _mockFileSystemPermissionsService.CanAccessPath(path, FileAccessMode.Delete, false).Returns(false); 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 89% 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..049f91f9 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 @@ -1,16 +1,16 @@ #region ========================================================================= USING ===================================================================================== using ErrorOr; using FluentAssertions; -using Lumina.Contracts.Enums.FileSystem; +using Lumina.Domain.Common.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.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Services; +using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Strategies.Environment; +using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Strategies.Platform; +using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.ValueObjects; +using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Entities; +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. @@ -34,11 +34,10 @@ public class DirectoryServiceTests private readonly DirectoryService _sut; private readonly FileSystemPathIdFixture _fileSystemPathIdFixture; private readonly DirectoryFixture _directoryFixture; - private static readonly bool s_isLinux = RuntimeInformation.IsOSPlatform(OSPlatform.Linux); - 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 ? '/' : '\\'; + private static readonly bool s_isUnix = RuntimeInformation.IsOSPlatform(OSPlatform.Linux) || RuntimeInformation.IsOSPlatform(OSPlatform.OSX); + private readonly string _pathDirTest = s_isUnix ? "/TestDir" : @"C:\TestDir"; + private readonly string _pathDirTestSubDir1 = s_isUnix ? "/TestDir/Sub1" : @"C:\TestDir\Sub1"; + private readonly string _pathDirTestSubDir2 = s_isUnix ? "/TestDir/Sub2" : @"C:\TestDir\Sub2"; /// /// 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] @@ -131,7 +130,7 @@ public class DirectoryServiceTests bool includeHiddenElements = false; FileSystemPathId pathId = _fileSystemPathIdFixture.CreateFileSystemPathId(path); FileSystemPathId subPath = _fileSystemPathIdFixture.CreateFileSystemPathId( - s_isLinux ? "/TestDir/InaccessibleSub" : @"C:\TestDir\InaccessibleSub" + s_isUnix ? "/TestDir/InaccessibleSub" : @"C:\TestDir\InaccessibleSub" ); _mockEnvironmentContext.DirectoryProviderService.GetSubdirectoryPaths(pathId, includeHiddenElements) @@ -212,7 +211,7 @@ public class DirectoryServiceTests Directory parentDirectory = _directoryFixture.CreateDirectory(); bool includeHiddenElements = false; FileSystemPathId subPath = _fileSystemPathIdFixture.CreateFileSystemPathId( - s_isLinux ? "/TestDir/InaccessibleSub" : @"C:\TestDir\InaccessibleSub" + s_isUnix ? "/TestDir/InaccessibleSub" : @"C:\TestDir\InaccessibleSub" ); _mockEnvironmentContext.DirectoryProviderService.GetSubdirectoryPaths(parentDirectory.Id, includeHiddenElements) @@ -293,7 +292,7 @@ public class DirectoryServiceTests FileSystemPathId pathId = _fileSystemPathIdFixture.CreateFileSystemPathId(_pathDirTest); bool includeHiddenElements = false; FileSystemPathId subPath = _fileSystemPathIdFixture.CreateFileSystemPathId( - s_isLinux ? "/TestDir/InaccessibleSub" : @"C:\TestDir\InaccessibleSub" + s_isUnix ? "/TestDir/InaccessibleSub" : @"C:\TestDir\InaccessibleSub" ); _mockEnvironmentContext.DirectoryProviderService.GetSubdirectoryPaths(pathId, includeHiddenElements) @@ -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()); @@ -493,11 +492,11 @@ public class DirectoryServiceTests public void RenameDirectory_WithValidStringPath_ShouldReturnRenamedDirectory() { // Arrange - string oldPath = s_isLinux ? "/TestDir/OldName" : @"C:\TestDir\OldName"; + string oldPath = s_isUnix ? "/TestDir/OldName" : @"C:\TestDir\OldName"; string newName = "NewName"; FileSystemPathId oldPathId = _fileSystemPathIdFixture.CreateFileSystemPathId(oldPath); FileSystemPathId newPathId = _fileSystemPathIdFixture.CreateFileSystemPathId( - s_isLinux ? "/TestDir/NewName" : @"C:\TestDir\NewName" + s_isUnix ? "/TestDir/NewName" : @"C:\TestDir\NewName" ); _mockEnvironmentContext.DirectoryProviderService.RenameDirectory(oldPathId, newName) @@ -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] @@ -538,11 +537,11 @@ public class DirectoryServiceTests { // Arrange FileSystemPathId oldPathId = _fileSystemPathIdFixture.CreateFileSystemPathId( - s_isLinux ? "/TestDir/OldName" : @"C:\TestDir\OldName" + s_isUnix ? "/TestDir/OldName" : @"C:\TestDir\OldName" ); string newName = "NewName"; FileSystemPathId newPathId = _fileSystemPathIdFixture.CreateFileSystemPathId( - s_isLinux ? "/TestDir/NewName" : @"C:\TestDir\NewName" + s_isUnix ? "/TestDir/NewName" : @"C:\TestDir\NewName" ); _mockEnvironmentContext.DirectoryProviderService.RenameDirectory(oldPathId, newName) @@ -568,7 +567,7 @@ public class DirectoryServiceTests { // Arrange FileSystemPathId oldPathId = _fileSystemPathIdFixture.CreateFileSystemPathId( - s_isLinux ? "/TestDir/OldName" : @"C:\TestDir\OldName" + s_isUnix ? "/TestDir/OldName" : @"C:\TestDir\OldName" ); string newName = "NewName"; @@ -588,11 +587,11 @@ public class DirectoryServiceTests { // Arrange FileSystemPathId oldPathId = _fileSystemPathIdFixture.CreateFileSystemPathId( - s_isLinux ? "/TestDir/OldName" : @"C:\TestDir\OldName" + s_isUnix ? "/TestDir/OldName" : @"C:\TestDir\OldName" ); string newName = "NewName"; FileSystemPathId newPathId = _fileSystemPathIdFixture.CreateFileSystemPathId( - s_isLinux ? "/TestDir/NewName" : @"C:\TestDir\NewName" + s_isUnix ? "/TestDir/NewName" : @"C:\TestDir\NewName" ); _mockEnvironmentContext.DirectoryProviderService.RenameDirectory(oldPathId, newName) @@ -621,11 +620,11 @@ public class DirectoryServiceTests { // Arrange FileSystemPathId oldPathId = _fileSystemPathIdFixture.CreateFileSystemPathId( - s_isLinux ? "/TestDir/OldName" : @"C:\TestDir\OldName" + s_isUnix ? "/TestDir/OldName" : @"C:\TestDir\OldName" ); string newName = "ExistingDirectory"; FileSystemPathId newPathId = _fileSystemPathIdFixture.CreateFileSystemPathId( - s_isLinux ? "/TestDir/ExistingDirectory" : @"C:\TestDir\ExistingDirectory" + s_isUnix ? "/TestDir/ExistingDirectory" : @"C:\TestDir\ExistingDirectory" ); _mockPlatformContext.PathStrategy.CombinePath(Arg.Any(), newName) @@ -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] @@ -646,19 +645,19 @@ public class DirectoryServiceTests { // Arrange FileSystemPathId oldPathId = _fileSystemPathIdFixture.CreateFileSystemPathId( - s_isLinux ? "/TestDir/OldName" : @"C:\TestDir\OldName" + s_isUnix ? "/TestDir/OldName" : @"C:\TestDir\OldName" ); 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()); @@ -670,11 +669,11 @@ public class DirectoryServiceTests { // Arrange FileSystemPathId oldPathId = _fileSystemPathIdFixture.CreateFileSystemPathId( - s_isLinux ? "/TestDir/OldName" : @"C:\TestDir\OldName" + s_isUnix ? "/TestDir/OldName" : @"C:\TestDir\OldName" ); string newName = "NewName"; FileSystemPathId newPathId = _fileSystemPathIdFixture.CreateFileSystemPathId( - s_isLinux ? "/TestDir/NewName" : @"C:\TestDir\NewName" + s_isUnix ? "/TestDir/NewName" : @"C:\TestDir\NewName" ); _mockPlatformContext.PathStrategy.CombinePath(Arg.Any(), newName) .Returns(ErrorOrFactory.From(newPathId)); @@ -697,7 +696,7 @@ public class DirectoryServiceTests public void DeleteDirectory_WithValidStringPath_ShouldReturnDeleted() { // Arrange - string path = s_isLinux ? "/TestDir/ToDelete" : @"C:\TestDir\ToDelete"; + string path = s_isUnix ? "/TestDir/ToDelete" : @"C:\TestDir\ToDelete"; FileSystemPathId pathId = _fileSystemPathIdFixture.CreateFileSystemPathId(path); _mockEnvironmentContext.DirectoryProviderService.DeleteDirectory(pathId) @@ -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] @@ -730,7 +729,7 @@ public class DirectoryServiceTests { // Arrange FileSystemPathId pathId = _fileSystemPathIdFixture.CreateFileSystemPathId( - s_isLinux ? "/TestDir/ToDelete" : @"C:\TestDir\ToDelete" + s_isUnix ? "/TestDir/ToDelete" : @"C:\TestDir\ToDelete" ); _mockEnvironmentContext.DirectoryProviderService.DeleteDirectory(pathId) @@ -749,7 +748,7 @@ public class DirectoryServiceTests { // Arrange FileSystemPathId pathId = _fileSystemPathIdFixture.CreateFileSystemPathId( - s_isLinux ? "/TestDir/ToDelete" : @"C:\TestDir\ToDelete" + s_isUnix ? "/TestDir/ToDelete" : @"C:\TestDir\ToDelete" ); _mockEnvironmentContext.DirectoryProviderService.DeleteDirectory(pathId) @@ -768,17 +767,17 @@ public class DirectoryServiceTests { // Arrange FileSystemPathId pathId = _fileSystemPathIdFixture.CreateFileSystemPathId( - s_isLinux ? "/TestDir/NonExistent" : @"C:\TestDir\NonExistent" + s_isUnix ? "/TestDir/NonExistent" : @"C:\TestDir\NonExistent" ); _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 82% 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..d9dcdacd 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 @@ -1,12 +1,11 @@ #region ========================================================================= USING ===================================================================================== 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.Common.Enums.FileSystem; +using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate; +using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Entities; +using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Services; +using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.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 91% 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..68f77ca6 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 @@ -3,12 +3,12 @@ using AutoFixture; using AutoFixture.AutoNSubstitute; using ErrorOr; using FluentAssertions; -using Lumina.Contracts.Enums.FileSystem; +using Lumina.Domain.Common.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.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Services; +using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.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. @@ -34,17 +34,15 @@ public class FileProviderServiceTests private readonly IFileSystemPermissionsService _mockFileSystemPermissionsService; 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"; - private readonly string _pathInvalid1 = s_isLinux ? "/Invalid.txt" : @"C:\Invalid.txt"; - private readonly string _pathSourceFile = s_isLinux ? "/Source/file.txt" : @"C:\Source\file.txt"; - 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 ? '/' : '\\'; + private static readonly bool s_isUnix = RuntimeInformation.IsOSPlatform(OSPlatform.Linux) || RuntimeInformation.IsOSPlatform(OSPlatform.OSX); + private readonly string _pathVisible1 = s_isUnix ? "/Visible.txt" : @"C:\Visible.txt"; + private readonly string _pathHidden1 = s_isUnix ? "/Hidden.txt" : @"C:\Hidden.txt"; + private readonly string _pathValid1 = s_isUnix ? "/Valid.txt" : @"C:\Valid.txt"; + private readonly string _pathInvalid1 = s_isUnix ? "/Invalid.txt" : @"C:\Invalid.txt"; + private readonly string _pathSourceFile = s_isUnix ? "/Source/file.txt" : @"C:\Source\file.txt"; + private readonly string _pathDestinationFile = s_isUnix ? "/Destination/file.txt" : @"C:\Destination\file.txt"; + private readonly string _pathSource = s_isUnix ? "/Source" : @"C:\Source"; + private readonly string _pathDestination = s_isUnix ? "/Destination" : @"C:\Destination"; /// /// 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_isUnix ? ["/C.txt", "/A.txt", "/B.txt"] : [@"C:\C.txt", @"C:\A.txt", @"C:\B.txt"]; - string[] expectedFiles = s_isLinux + string[] expectedFiles = s_isUnix ? ["/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; @@ -626,7 +625,7 @@ public class FileProviderServiceTests { // Arrange FileSystemPathId sourcePath = _fileSystemPathIdFixture.CreateFileSystemPathId( - s_isLinux ? "/NonExistentSource.txt" : @"C:\NonExistentSource.txt" + s_isUnix ? "/NonExistentSource.txt" : @"C:\NonExistentSource.txt" ); FileSystemPathId destinationPath = _fileSystemPathIdFixture.CreateFileSystemPathId(_pathDestination); bool overrideExisting = 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] @@ -738,11 +737,11 @@ public class FileProviderServiceTests { // Arrange FileSystemPathId path = _fileSystemPathIdFixture.CreateFileSystemPathId( - s_isLinux ? "/OldName.txt" : @"C:\OldName.txt" + s_isUnix ? "/OldName.txt" : @"C:\OldName.txt" ); string newName = "NewName.txt"; - string parentPath = s_isLinux ? "/" : @"C:\"; - string newPath = s_isLinux ? "/NewName.txt" : @"C:\NewName.txt"; + string parentPath = s_isUnix ? "/" : @"C:\"; + string newPath = s_isUnix ? "/NewName.txt" : @"C:\NewName.txt"; IFileInfo fileInfo = Substitute.For(); fileInfo.DirectoryName.Returns(parentPath); @@ -765,11 +764,11 @@ public class FileProviderServiceTests { // Arrange FileSystemPathId path = _fileSystemPathIdFixture.CreateFileSystemPathId( - s_isLinux ? "/OldName.txt" : @"C:\OldName.txt" + s_isUnix ? "/OldName.txt" : @"C:\OldName.txt" ); string newName = "NewName.txt"; - string parentPath = s_isLinux ? "/" : @"C:\"; - string newPath = s_isLinux ? "/NewName.txt" : @"C:\NewName.txt"; + string parentPath = s_isUnix ? "/" : @"C:\"; + string newPath = s_isUnix ? "/NewName.txt" : @"C:\NewName.txt"; IFileInfo fileInfo = Substitute.For(); fileInfo.DirectoryName.Returns(parentPath); @@ -791,11 +790,11 @@ public class FileProviderServiceTests { // Arrange FileSystemPathId path = _fileSystemPathIdFixture.CreateFileSystemPathId( - s_isLinux ? "/OldName.txt" : @"C:\OldName.txt" + s_isUnix ? "/OldName.txt" : @"C:\OldName.txt" ); string newName = "NewName.txt"; - string parentPath = s_isLinux ? "/" : @"C:\"; - string newPath = s_isLinux ? "/NewName.txt" : @"C:\NewName.txt"; + string parentPath = s_isUnix ? "/" : @"C:\"; + string newPath = s_isUnix ? "/NewName.txt" : @"C:\NewName.txt"; IFileInfo fileInfo = Substitute.For(); fileInfo.DirectoryName.Returns(parentPath); @@ -818,7 +817,7 @@ public class FileProviderServiceTests { // Arrange FileSystemPathId path = _fileSystemPathIdFixture.CreateFileSystemPathId( - s_isLinux ? "/OldName.txt" : @"C:\OldName.txt" + s_isUnix ? "/OldName.txt" : @"C:\OldName.txt" ); string newName = "NewName.txt"; @@ -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()); } @@ -838,10 +837,10 @@ public class FileProviderServiceTests { // Arrange FileSystemPathId path = _fileSystemPathIdFixture.CreateFileSystemPathId( - s_isLinux ? "/OldName.txt" : @"C:\OldName.txt" + s_isUnix ? "/OldName.txt" : @"C:\OldName.txt" ); string newName = "NewName.txt"; - string parentPath = s_isLinux ? "/" : @"C:\"; + string parentPath = s_isUnix ? "/" : @"C:\"; IFileInfo fileInfo = Substitute.For(); fileInfo.DirectoryName.Returns(parentPath); @@ -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()); } @@ -862,12 +861,12 @@ public class FileProviderServiceTests { // Arrange FileSystemPathId path = _fileSystemPathIdFixture.CreateFileSystemPathId( - s_isLinux ? "/OldName.txt" : @"C:\OldName.txt" + s_isUnix ? "/OldName.txt" : @"C:\OldName.txt" ); string newName = "NewName.txt"; - string parentPath = s_isLinux ? "/" : @"C:\"; - string newPath = s_isLinux ? "/NewName.txt" : @"C:\NewName.txt"; - + string parentPath = s_isUnix ? "/" : @"C:\"; + string newPath = s_isUnix ? "/NewName.txt" : @"C:\NewName.txt"; + IFileInfo fileInfo = Substitute.For(); fileInfo.DirectoryName.Returns(parentPath); _mockFileSystem.FileInfo.New(path.Path).Returns(fileInfo); @@ -895,7 +894,7 @@ public class FileProviderServiceTests { // Arrange FileSystemPathId path = _fileSystemPathIdFixture.CreateFileSystemPathId( - s_isLinux ? "/FileToDelete.txt" : @"C:\FileToDelete.txt" + s_isUnix ? "/FileToDelete.txt" : @"C:\FileToDelete.txt" ); _mockFileSystemPermissionsService.CanAccessPath(path, FileAccessMode.Delete).Returns(true); _mockFileSystem.File.Exists(path.Path).Returns(true); @@ -914,7 +913,7 @@ public class FileProviderServiceTests { // Arrange FileSystemPathId path = _fileSystemPathIdFixture.CreateFileSystemPathId( - s_isLinux ? "/FileToDelete.txt" : @"C:\FileToDelete.txt" + s_isUnix ? "/FileToDelete.txt" : @"C:\FileToDelete.txt" ); _mockFileSystemPermissionsService.CanAccessPath(path, FileAccessMode.Delete).Returns(false); 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 93% 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..f2945b53 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 @@ -1,16 +1,16 @@ #region ========================================================================= USING ===================================================================================== using ErrorOr; using FluentAssertions; -using Lumina.Contracts.Enums.FileSystem; +using Lumina.Domain.Common.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.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Entities; +using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Services; +using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Strategies.Environment; +using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Strategies.Platform; +using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.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. @@ -34,20 +34,20 @@ public class FileServiceTests private readonly FileService _sut; 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 _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"; - private readonly string _pathDestination1 = s_isLinux ? "/Destination/" : @"C:\Destination\"; - private readonly string _pathDestination2 = s_isLinux ? "/Destination" : @"C:\Destination"; - private readonly string _pathSourceFile = s_isLinux ? "/Source/file.txt" : @"C:\Source\file.txt"; - private readonly string _pathDestinationFile = s_isLinux ? "/Destination/file.txt" : @"C:\Destination\file.txt"; - private readonly string _pathSourceOldFile = s_isLinux ? "/Source/oldfile.txt" : @"C:\Source\oldfile.txt"; - private readonly string _pathSourceNewFile = s_isLinux ? "/Source/newfile.txt" : @"C:\Source\newfile.txt"; - private readonly string _pathSourceExistingFile = s_isLinux ? "/Source/existingfile.txt" : @"C:\Source\existingfile.txt"; - private readonly string _pathSourceNonExistingFile = s_isLinux ? "/Source/nonexistent.txt" : @"C:\Source\nonexistent.txt"; - private readonly char _dirSeparator = s_isLinux ? '/' : '\\'; + private static readonly bool s_isUnix = RuntimeInformation.IsOSPlatform(OSPlatform.Linux) || RuntimeInformation.IsOSPlatform(OSPlatform.OSX); + private readonly string _pathTestDir = s_isUnix ? "/TestDir" : @"C:\TestDir"; + private readonly string _pathTestDirFile1 = s_isUnix ? "/TestDir/File1.txt" : @"C:\TestDir\File1.txt"; + private readonly string _pathTestDirFile2 = s_isUnix ? "/TestDir/File2.txt" : @"C:\TestDir\File2.txt"; + private readonly string _pathTestDirInaccessible = s_isUnix ? "/TestDir/InaccessibleFile.txt" : @"C:\TestDir\InaccessibleFile.txt"; + private readonly string _pathDestination1 = s_isUnix ? "/Destination/" : @"C:\Destination\"; + private readonly string _pathDestination2 = s_isUnix ? "/Destination" : @"C:\Destination"; + private readonly string _pathSourceFile = s_isUnix ? "/Source/file.txt" : @"C:\Source\file.txt"; + private readonly string _pathDestinationFile = s_isUnix ? "/Destination/file.txt" : @"C:\Destination\file.txt"; + private readonly string _pathSourceOldFile = s_isUnix ? "/Source/oldfile.txt" : @"C:\Source\oldfile.txt"; + private readonly string _pathSourceNewFile = s_isUnix ? "/Source/newfile.txt" : @"C:\Source\newfile.txt"; + private readonly string _pathSourceExistingFile = s_isUnix ? "/Source/existingfile.txt" : @"C:\Source\existingfile.txt"; + private readonly string _pathSourceNonExistingFile = s_isUnix ? "/Source/nonexistent.txt" : @"C:\Source\nonexistent.txt"; + private readonly char _dirSeparator = s_isUnix ? '/' : '\\'; /// /// Initializes a new instance of the class. @@ -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] @@ -742,7 +742,7 @@ public class FileServiceTests { // Arrange FileSystemPathId sourcePathId = _fileSystemPathIdFixture.CreateFileSystemPathId( - s_isLinux ? "/Source/nonexistent.txt" : _pathSourceNonExistingFile + s_isUnix ? "/Source/nonexistent.txt" : _pathSourceNonExistingFile ); FileSystemPathId destinationPathId = _fileSystemPathIdFixture.CreateFileSystemPathId(_pathDestination2); bool overrideExisting = true; @@ -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 92% 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..8a27dcce 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 @@ -1,14 +1,14 @@ #region ========================================================================= USING ===================================================================================== using ErrorOr; using FluentAssertions; -using Lumina.Contracts.Enums.FileSystem; -using Lumina.Contracts.Enums.PhotoLibrary; +using Lumina.Domain.Common.Enums.FileSystem; +using Lumina.Domain.Common.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.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Entities; +using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Services; +using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.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 91% 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..1f7d47d0 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 @@ -1,5 +1,5 @@ #region ========================================================================= USING ===================================================================================== -using Lumina.Contracts.Enums.PhotoLibrary; +using Lumina.Domain.Common.Enums.PhotoLibrary; using SixLabors.ImageSharp; using SixLabors.ImageSharp.Formats; using SixLabors.ImageSharp.Formats.Bmp; @@ -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..591600f8 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.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Services; +using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Strategies.Path; +using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Strategies.Platform; +using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.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 89% 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..710fadfd 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 @@ -1,13 +1,13 @@ #region ========================================================================= USING ===================================================================================== using ErrorOr; using FluentAssertions; -using Lumina.Contracts.Enums.PhotoLibrary; +using Lumina.Domain.Common.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.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Services; +using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Strategies.Environment; +using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.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 89% 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..8bdd05d4 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.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Services; +using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.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..4360599e 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.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Strategies.Path; +using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.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..7c031272 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.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Strategies.Path; +using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.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 59% 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..2bcfe0f5 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.BoundedContexts.FileSystemManagementBoundedContext.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 83% 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..b8cd56bd 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.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Strategies.Path; +using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.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 95% 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..e086aba6 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.Common.Enums.FileSystem; +using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.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 91% 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..1ec23ea1 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.Common.Enums.FileSystem; +using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Strategies.Path; +using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.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..8ed72171 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.BoundedContexts.FileSystemManagementBoundedContext.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..904ed1bc --- /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.BoundedContexts.FileSystemManagementBoundedContext.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 88% 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..76b465c9 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.BoundedContexts.FileSystemManagementBoundedContext.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 94% 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..3ba05f6c 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.BoundedContexts.FileSystemManagementBoundedContext.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 86% 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..2f5d04cc 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.Common.Enums.PhotoLibrary; +using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.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..c6a8256c 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.BoundedContexts.FileSystemManagementBoundedContext.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..c47f50df 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.BoundedContexts.FileSystemManagementBoundedContext.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 90% 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..399afeea 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.Common.Enums.PhotoLibrary; +using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.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 fa08a23e..4ba2430e 100644 --- a/tests/UnitTests/Lumina.Domain.UnitTests/Lumina.Domain.UnitTests.csproj +++ b/tests/UnitTests/Lumina.Domain.UnitTests/Lumina.Domain.UnitTests.csproj @@ -9,21 +9,28 @@ true + + + <_Parameter1>DisableTestParallelization = true + <_Parameter1_IsLiteral>true + + + - + - + all runtime; build; native; contentfiles; analyzers; buildtransitive - - + + - + - + all runtime; build; native; contentfiles; analyzers; buildtransitive diff --git a/tests/UnitTests/Lumina.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..d1345b66 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/Common/Validators/EncryptionSettingsModelValidatorTests.cs b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Common/Validators/EncryptionSettingsModelValidatorTests.cs new file mode 100644 index 00000000..4161fb7d --- /dev/null +++ b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Common/Validators/EncryptionSettingsModelValidatorTests.cs @@ -0,0 +1,83 @@ +#region ========================================================================= USING ===================================================================================== +using AutoFixture; +using AutoFixture.AutoNSubstitute; +using FluentAssertions; +using Lumina.Infrastructure.Common.Errors; +using Lumina.Infrastructure.Common.Models.Configuration; +using Lumina.Infrastructure.Common.Validators; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Infrastructure.UnitTests.Common.Validators; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class EncryptionSettingsModelValidatorTests +{ + private readonly EncryptionSettingsModelValidator _validator; + private readonly IFixture _fixture; + + /// + /// Initializes a new instance of the class. + /// + public EncryptionSettingsModelValidatorTests() + { + _fixture = new Fixture().Customize(new AutoNSubstituteCustomization()); + _validator = new(); + } + + [Fact] + public void EncryptionSettingsModelValidator_WhenValidBase64SecretKeyProvided_ShouldNotHaveValidationError() + { + // Arrange + EncryptionSettingsModel model = _fixture.Build() + .With(x => x.SecretKey, "dGhpcyBpcyBhIHZhbGlkIGJhc2U2NCBzdHJpbmc=") // "this is a valid base64 string" in base64 + .Create(); + + // Act + FluentValidation.Results.ValidationResult result = _validator.Validate(model); + + // Assert + result.IsValid.Should().BeTrue(); + result.Errors.Should().BeEmpty(); + } + + [Fact] + public void EncryptionSettingsModelValidator_WhenSecretKeyIsEmpty_ShouldHaveValidationError() + { + // Arrange + EncryptionSettingsModel model = _fixture.Build() + .With(x => x.SecretKey, string.Empty) + .Create(); + + // Act + FluentValidation.Results.ValidationResult result = _validator.Validate(model); + + // Assert + result.IsValid.Should().BeFalse(); + result.Errors.Should().ContainSingle() + .Which.ErrorMessage.Should().Be(Errors.Configuration.EncryptionSecretKeyCannotBeEmpty.Description); + } + + [Theory] + [InlineData("not-a-base64-string")] + [InlineData("invalid!base64")] + [InlineData("123")] + public void EncryptionSettingsModelValidator_WhenSecretKeyIsNotBase64_ShouldHaveValidationError(string invalidBase64) + { + // Arrange + EncryptionSettingsModel model = _fixture.Build() + .With(x => x.SecretKey, invalidBase64) + .Create(); + + // Act + FluentValidation.Results.ValidationResult result = _validator.Validate(model); + + // Assert + result.IsValid.Should().BeFalse(); + result.Errors.Should().ContainSingle() + .Which.ErrorMessage.Should().Be(Errors.Configuration.EncryptionSecretKeyMustBeABase64String.Description); + } +} diff --git a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Common/Validators/JwtSettingsModelValidatorTests.cs b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Common/Validators/JwtSettingsModelValidatorTests.cs new file mode 100644 index 00000000..d12653c4 --- /dev/null +++ b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Common/Validators/JwtSettingsModelValidatorTests.cs @@ -0,0 +1,157 @@ +#region ========================================================================= USING ===================================================================================== +using AutoFixture; +using AutoFixture.AutoNSubstitute; +using FluentAssertions; +using Lumina.Infrastructure.Common.Errors; +using Lumina.Infrastructure.Common.Models.Configuration; +using Lumina.Infrastructure.Common.Validators; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Infrastructure.UnitTests.Common.Validators; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class JwtSettingsModelValidatorTests +{ + private readonly JwtSettingsModelValidator _validator; + private readonly IFixture _fixture; + + /// + /// Initializes a new instance of the class. + /// + public JwtSettingsModelValidatorTests() + { + _fixture = new Fixture().Customize(new AutoNSubstituteCustomization()); + _validator = new(); + } + + [Fact] + public void JwtSettingsModelValidator_WhenAllPropertiesValid_ShouldNotHaveValidationError() + { + // Arrange + JwtSettingsModel model = _fixture.Build() + .With(x => x.SecretKey, "this-is-a-very-long-secret-key-for-testing") + .With(x => x.ExpiryMinutes, 30) + .With(x => x.Issuer, "test-issuer") + .With(x => x.Audience, "test-audience") + .Create(); + + // Act + FluentValidation.Results.ValidationResult result = _validator.Validate(model); + + // Assert + result.IsValid.Should().BeTrue(); + result.Errors.Should().BeEmpty(); + } + + [Fact] + public void JwtSettingsModelValidator_WhenSecretKeyIsEmpty_ShouldHaveValidationErrors() + { + // Arrange + JwtSettingsModel model = _fixture.Build() + .With(x => x.SecretKey, string.Empty) + .With(x => x.ExpiryMinutes, 30) + .With(x => x.Issuer, "test-issuer") + .With(x => x.Audience, "test-audience") + .Create(); + + // Act + FluentValidation.Results.ValidationResult result = _validator.Validate(model); + + // Assert + result.IsValid.Should().BeFalse(); + result.Errors.Should().HaveCount(2); + result.Errors.Select(e => e.ErrorMessage).Should().Contain(new[] + { + Errors.Configuration.JwtSecretKeyCannotBeEmpty.Description, + Errors.Configuration.JwtSecretKeyTooShort.Description + }); + } + + [Fact] + public void JwtSettingsModelValidator_WhenSecretKeyTooShort_ShouldHaveValidationError() + { + // Arrange + JwtSettingsModel model = _fixture.Build() + .With(x => x.SecretKey, "short-key") + .With(x => x.ExpiryMinutes, 30) + .With(x => x.Issuer, "test-issuer") + .With(x => x.Audience, "test-audience") + .Create(); + + // Act + FluentValidation.Results.ValidationResult result = _validator.Validate(model); + + // Assert + result.IsValid.Should().BeFalse(); + result.Errors.Should().ContainSingle() + .Which.ErrorMessage.Should().Be(Errors.Configuration.JwtSecretKeyTooShort.Description); + } + + [Theory] + [InlineData(0)] + [InlineData(-1)] + [InlineData(-60)] + public void JwtSettingsModelValidator_WhenExpiryMinutesNotPositive_ShouldHaveValidationError(int minutes) + { + // Arrange + JwtSettingsModel model = _fixture.Build() + .With(x => x.SecretKey, "this-is-a-very-long-secret-key-for-testing") + .With(x => x.ExpiryMinutes, minutes) + .With(x => x.Issuer, "test-issuer") + .With(x => x.Audience, "test-audience") + .Create(); + + // Act + FluentValidation.Results.ValidationResult result = _validator.Validate(model); + + // Assert + result.IsValid.Should().BeFalse(); + result.Errors.Should().ContainSingle() + .Which.ErrorMessage.Should().Be(Errors.Configuration.JwtExpiryMinutesMustBePositive.Description); + } + + [Fact] + public void JwtSettingsModelValidator_WhenIssuerIsEmpty_ShouldHaveValidationError() + { + // Arrange + JwtSettingsModel model = _fixture.Build() + .With(x => x.SecretKey, "this-is-a-very-long-secret-key-for-testing") + .With(x => x.ExpiryMinutes, 30) + .With(x => x.Issuer, string.Empty) + .With(x => x.Audience, "test-audience") + .Create(); + + // Act + FluentValidation.Results.ValidationResult result = _validator.Validate(model); + + // Assert + result.IsValid.Should().BeFalse(); + result.Errors.Should().ContainSingle() + .Which.ErrorMessage.Should().Be(Errors.Configuration.JwtIssuerCannotBeEmpty.Description); + } + + [Fact] + public void JwtSettingsModelValidator_WhenAudienceIsEmpty_ShouldHaveValidationError() + { + // Arrange + JwtSettingsModel model = _fixture.Build() + .With(x => x.SecretKey, "this-is-a-very-long-secret-key-for-testing") + .With(x => x.ExpiryMinutes, 30) + .With(x => x.Issuer, "test-issuer") + .With(x => x.Audience, string.Empty) + .Create(); + + // Act + FluentValidation.Results.ValidationResult result = _validator.Validate(model); + + // Assert + result.IsValid.Should().BeFalse(); + result.Errors.Should().ContainSingle() + .Which.ErrorMessage.Should().Be(Errors.Configuration.JwtAudienceCannotBeEmpty.Description); + } +} diff --git a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Common/Validators/MediaSettingsModelValidatorTests.cs b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Common/Validators/MediaSettingsModelValidatorTests.cs new file mode 100644 index 00000000..d44b6a43 --- /dev/null +++ b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Common/Validators/MediaSettingsModelValidatorTests.cs @@ -0,0 +1,80 @@ +#region ========================================================================= USING ===================================================================================== +using AutoFixture; +using AutoFixture.AutoNSubstitute; +using FluentAssertions; +using Lumina.Infrastructure.Common.Errors; +using Lumina.Infrastructure.Common.Models.Configuration; +using Lumina.Infrastructure.Common.Validators; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Infrastructure.UnitTests.Common.Validators; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class MediaSettingsModelValidatorTests +{ + private readonly MediaSettingsModelValidator _validator; + private readonly IFixture _fixture; + + /// + /// Initializes a new instance of the class. + /// + public MediaSettingsModelValidatorTests() + { + _fixture = new Fixture().Customize(new AutoNSubstituteCustomization()); + _validator = new(); + } + + [Fact] + public void MediaSettingsModelValidator_WhenRootDirectoryProvided_ShouldNotHaveValidationError() + { + // Arrange + MediaSettingsModel model = _fixture.Build() + .With(x => x.RootDirectory, "/path/to/media") + .Create(); + + // Act + FluentValidation.Results.ValidationResult result = _validator.Validate(model); + + // Assert + result.IsValid.Should().BeTrue(); + result.Errors.Should().BeEmpty(); + } + + [Fact] + public void MediaSettingsModelValidator_WhenRootDirectoryIsEmpty_ShouldHaveValidationError() + { + // Arrange + MediaSettingsModel model = _fixture.Build() + .With(x => x.RootDirectory, string.Empty) + .Create(); + + // Act + FluentValidation.Results.ValidationResult result = _validator.Validate(model); + + // Assert + result.IsValid.Should().BeFalse(); + result.Errors.Should().ContainSingle() + .Which.ErrorMessage.Should().Be(Errors.Configuration.MediaRootDirectoryCannotBeEmpty.Description); + } + + [Fact] + public void MediaSettingsModelValidator_WhenRootDirectoryIsWhitespace_ShouldHaveValidationError() + { + // Arrange + MediaSettingsModel model = _fixture.Build() + .With(x => x.RootDirectory, " ") + .Create(); + + // Act + FluentValidation.Results.ValidationResult result = _validator.Validate(model); + + // Assert + result.IsValid.Should().BeFalse(); + result.Errors.Should().ContainSingle() + .Which.ErrorMessage.Should().Be(Errors.Configuration.MediaRootDirectoryCannotBeEmpty.Description); + } +} diff --git a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Authentication/Fixtures/JwtTokenGeneratorFixture.cs b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Authentication/Fixtures/JwtTokenGeneratorFixture.cs new file mode 100644 index 00000000..3695aa84 --- /dev/null +++ b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Authentication/Fixtures/JwtTokenGeneratorFixture.cs @@ -0,0 +1,41 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Infrastructure.Common.Models.Configuration; +using System; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Infrastructure.UnitTests.Core.Authentication.Fixtures; + +/// +/// Fixture class for JWT token generation tests. +/// +[ExcludeFromCodeCoverage] +public class JwtTokenGeneratorFixture +{ + /// + /// Creates a valid JWT settings model for testing. + /// + /// The created settings model. + public static JwtSettingsModel CreateJwtSettings() + { + return new Faker() + .CustomInstantiator(f => new JwtSettingsModel + { + SecretKey = "this-is-a-very-long-secret-key-for-testing-jwt-tokens", + ExpiryMinutes = 30, + Issuer = "test-issuer", + Audience = "test-audience" + }) + .Generate(); + } + + /// + /// Creates test user credentials. + /// + /// A tuple containing the user ID and username. + public static (string Id, string Username) CreateUserCredentials() + { + return (Guid.NewGuid().ToString(), new Faker().Person.UserName); + } +} diff --git a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Authentication/Fixtures/QRCodeGeneratorFixture.cs b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Authentication/Fixtures/QRCodeGeneratorFixture.cs new file mode 100644 index 00000000..d9a27946 --- /dev/null +++ b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Authentication/Fixtures/QRCodeGeneratorFixture.cs @@ -0,0 +1,37 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using System; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Infrastructure.UnitTests.Core.Authentication.Fixtures; + +/// +/// Fixture class for QR code generation tests. +/// +[ExcludeFromCodeCoverage] +public class QRCodeGeneratorFixture +{ + /// + /// Creates test data for QR code generation. + /// + /// A tuple containing username and secret bytes. + public static (string Username, byte[] Secret) CreateQrCodeTestData() + { + string username = new Faker().Person.UserName; + byte[] secret = new byte[20]; // Standard TOTP secret length + new Random().NextBytes(secret); + return (username, secret); + } + + /// + /// Gets the expected otpauth URI format for validation. + /// + /// The username to use in the URI. + /// The Base32 encoded secret. + /// The formatted otpauth URI. + public static string GetExpectedOtpauthUri(string username, string base32Secret) + { + return $"otpauth://totp/Lumina:{Uri.EscapeDataString(username)}?secret={base32Secret}&issuer=Lumina"; + } +} diff --git a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Authentication/JwtTokenGeneratorTests.cs b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Authentication/JwtTokenGeneratorTests.cs new file mode 100644 index 00000000..0d2f404f --- /dev/null +++ b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Authentication/JwtTokenGeneratorTests.cs @@ -0,0 +1,137 @@ +#region ========================================================================= USING ===================================================================================== +using FluentAssertions; +using Lumina.Application.Common.Infrastructure.Time; +using Lumina.Infrastructure.Common.Models.Configuration; +using Lumina.Infrastructure.Core.Authentication; +using Lumina.Infrastructure.UnitTests.Core.Authentication.Fixtures; +using Microsoft.Extensions.Options; +using Microsoft.IdentityModel.Tokens; +using NSubstitute; +using System; +using System.Diagnostics.CodeAnalysis; +using System.IdentityModel.Tokens.Jwt; +using System.Security.Claims; +using System.Text; +#endregion + +namespace Lumina.Infrastructure.UnitTests.Core.Authentication; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class JwtTokenGeneratorTests +{ + private readonly IDateTimeProvider _mockDateTimeProvider; + private readonly JwtSettingsModel _jwtSettings; + private readonly JwtTokenGenerator _sut; + private readonly DateTime _fixedUtcNow; + + /// + /// Initializes a new instance of the class. + /// + public JwtTokenGeneratorTests() + { + _mockDateTimeProvider = Substitute.For(); + _jwtSettings = JwtTokenGeneratorFixture.CreateJwtSettings(); + _fixedUtcNow = new DateTime(2024, 1, 1, 12, 0, 0, DateTimeKind.Utc); + + _mockDateTimeProvider.UtcNow.Returns(_fixedUtcNow); + + IOptions options = Substitute.For>(); + options.Value.Returns(_jwtSettings); + + _sut = new JwtTokenGenerator(_mockDateTimeProvider, options); + } + + [Fact] + public void GenerateToken_WhenCalled_ShouldCreateValidJwtToken() + { + // Arrange + (string userId, string username) = JwtTokenGeneratorFixture.CreateUserCredentials(); + JwtSecurityTokenHandler tokenHandler = new(); + + // Act + string token = _sut.GenerateToken(userId, username); + + // Assert + token.Should().NotBeNullOrEmpty(); + + JwtSecurityToken jwtToken = tokenHandler.ReadJwtToken(token); + + // verify token properties + jwtToken.Issuer.Should().Be(_jwtSettings.Issuer); + jwtToken.Audiences.Should().ContainSingle().Which.Should().Be(_jwtSettings.Audience); + jwtToken.ValidTo.Should().Be(_fixedUtcNow.AddMinutes(_jwtSettings.ExpiryMinutes)); + + // verify claims + jwtToken.Claims.Should().Contain(c => c.Type == JwtRegisteredClaimNames.Sub && c.Value == userId); + jwtToken.Claims.Should().Contain(c => c.Type == JwtRegisteredClaimNames.UniqueName && c.Value == username); + jwtToken.Claims.Should().Contain(c => c.Type == JwtRegisteredClaimNames.Jti && c.Value == userId); + + // verify the token is actually valid + TokenValidationParameters validationParameters = new() + { + ValidateIssuerSigningKey = true, + IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_jwtSettings.SecretKey)), + ValidateIssuer = true, + ValidIssuer = _jwtSettings.Issuer, + ValidateAudience = true, + ValidAudience = _jwtSettings.Audience, + ValidateLifetime = true, + ClockSkew = TimeSpan.Zero, + // override the current time to match our fixed test time + LifetimeValidator = (notBefore, expires, token, parameters) => expires > _fixedUtcNow + }; + + ClaimsPrincipal principal = tokenHandler.ValidateToken(token, validationParameters, out SecurityToken validatedToken); + + principal.Should().NotBeNull(); + validatedToken.Should().NotBeNull(); + } + + [Fact] + public void GenerateToken_WhenCalled_ShouldUseProvidedDateTimeForExpiration() + { + // Arrange + (string userId, string username) = JwtTokenGeneratorFixture.CreateUserCredentials(); + JwtSecurityTokenHandler tokenHandler = new(); + + // Act + string token = _sut.GenerateToken(userId, username); + JwtSecurityToken jwtToken = tokenHandler.ReadJwtToken(token); + + // Assert + jwtToken.ValidTo.Should().Be(_fixedUtcNow.AddMinutes(_jwtSettings.ExpiryMinutes)); + _ = _mockDateTimeProvider.Received(1).UtcNow; + } + + [Fact] + public void GenerateToken_WhenCalledWithDifferentUsers_ShouldCreateUniqueTokens() + { + // Arrange + (string userId1, string username1) = JwtTokenGeneratorFixture.CreateUserCredentials(); + (string userId2, string username2) = JwtTokenGeneratorFixture.CreateUserCredentials(); + + // Act + string token1 = _sut.GenerateToken(userId1, username1); + string token2 = _sut.GenerateToken(userId2, username2); + + // Assert + token1.Should().NotBe(token2); + } + + [Fact] + public void GenerateToken_WhenCalledMultipleTimesForSameUser_ShouldCreateIdenticalTokens() + { + // Arrange + (string userId, string username) = JwtTokenGeneratorFixture.CreateUserCredentials(); + + // Act + string token1 = _sut.GenerateToken(userId, username); + string token2 = _sut.GenerateToken(userId, username); + + // Assert + token1.Should().Be(token2); + } +} diff --git a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Authentication/QRCodeGeneratorTests.cs b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Authentication/QRCodeGeneratorTests.cs new file mode 100644 index 00000000..1a6158a5 --- /dev/null +++ b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Authentication/QRCodeGeneratorTests.cs @@ -0,0 +1,151 @@ +#region ========================================================================= USING ===================================================================================== +using AutoFixture; +using AutoFixture.AutoNSubstitute; +using FluentAssertions; +using Lumina.Infrastructure.Common.Errors; +using Lumina.Infrastructure.Common.Models.Configuration; +using Lumina.Infrastructure.Common.Validators; +using Lumina.Infrastructure.Core.Authentication; +using Lumina.Infrastructure.UnitTests.Core.Authentication.Fixtures; +using System; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Infrastructure.UnitTests.Core.Authentication; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class QRCodeGeneratorTests +{ + private readonly QRCodeGenerator _sut; + + /// + /// Initializes a new instance of the class. + /// + public QRCodeGeneratorTests() + { + _sut = new QRCodeGenerator(); + } + + [Fact] + public void GenerateQrCodeDataUri_WhenCalled_ShouldReturnValidDataUri() + { + // Arrange + (string username, byte[] secret) = QRCodeGeneratorFixture.CreateQrCodeTestData(); + + // Act + string result = _sut.GenerateQrCodeDataUri(username, secret); + + // Assert + result.Should().StartWith("data:image/png;base64,"); + result.Should().Match(uri => IsBase64String(uri.Substring(22))); // Skip "data:image/png;base64," + } + + [Fact] + public void GenerateQrCodeDataUri_WhenUsernameContainsSpecialCharacters_ShouldEscapeUsername() + { + // Arrange + string username = "user@example.com"; + (_, byte[] secret) = QRCodeGeneratorFixture.CreateQrCodeTestData(); + + // Act + string result = _sut.GenerateQrCodeDataUri(username, secret); + + // Assert + result.Should().StartWith("data:image/png;base64,"); + result.Should().Match(uri => IsBase64String(uri.Substring(22))); + } + + [Fact] + public void GenerateQrCodeDataUri_WhenCalled_ShouldGenerateUniqueQrCodesForDifferentUsers() + { + // Arrange + (string username1, byte[] secret) = QRCodeGeneratorFixture.CreateQrCodeTestData(); + string username2 = username1 + "_different"; + + // Act + string result1 = _sut.GenerateQrCodeDataUri(username1, secret); + string result2 = _sut.GenerateQrCodeDataUri(username2, secret); + + // Assert + result1.Should().NotBe(result2); + } + + [Fact] + public void GenerateQrCodeDataUri_WhenCalledWithSameInput_ShouldGenerateIdenticalQrCodes() + { + // Arrange + (string username, byte[] secret) = QRCodeGeneratorFixture.CreateQrCodeTestData(); + + // Act + string result1 = _sut.GenerateQrCodeDataUri(username, secret); + string result2 = _sut.GenerateQrCodeDataUri(username, secret); + + // Assert + result1.Should().Be(result2); + } + + [Theory] + [InlineData("")] + [InlineData(" ")] + public void GenerateQrCodeDataUri_WhenUsernameIsInvalid_ShouldStillGenerateQrCode(string? invalidUsername) + { + // Arrange + (_, byte[] secret) = QRCodeGeneratorFixture.CreateQrCodeTestData(); + + // Act + string result = _sut.GenerateQrCodeDataUri(invalidUsername!, secret); + + // Assert + result.Should().StartWith("data:image/png;base64,"); + result.Should().Match(uri => IsBase64String(uri.Substring(22))); + } + + [Theory] + [InlineData("user@example.com")] + [InlineData("user name with spaces")] + [InlineData("user+with+plus")] + [InlineData("user/with/slashes")] + public void GenerateQrCodeDataUri_WhenUsernameHasSpecialCharacters_ShouldStillGenerateQrCode(string username) + { + // Arrange + (_, byte[] secret) = QRCodeGeneratorFixture.CreateQrCodeTestData(); + + // Act + string result = _sut.GenerateQrCodeDataUri(username, secret); + + // Assert + result.Should().StartWith("data:image/png;base64,"); + result.Should().Match(uri => IsBase64String(uri.Substring(22))); + } + + [Fact] + public void GenerateQrCodeDataUri_WhenSecretIsTooShort_ShouldStillGenerateQrCode() + { + // Arrange + (string username, _) = QRCodeGeneratorFixture.CreateQrCodeTestData(); + byte[] shortSecret = [1]; // minimum length for Base32 encoding + + // Act + string result = _sut.GenerateQrCodeDataUri(username, shortSecret); + + // Assert + result.Should().StartWith("data:image/png;base64,"); + result.Should().Match(uri => IsBase64String(uri.Substring(22))); + } + + private static bool IsBase64String(string base64) + { + try + { + Convert.FromBase64String(base64); + return true; + } + catch + { + return false; + } + } +} diff --git a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Authentication/TokenGeneratorTests.cs b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Authentication/TokenGeneratorTests.cs new file mode 100644 index 00000000..3fce0289 --- /dev/null +++ b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Authentication/TokenGeneratorTests.cs @@ -0,0 +1,71 @@ +#region ========================================================================= USING ===================================================================================== +using FluentAssertions; +using Lumina.Infrastructure.Core.Authentication; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Infrastructure.UnitTests.Core.Authentication; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class TokenGeneratorTests +{ + private readonly TokenGenerator _sut; + + /// + /// Initializes a new instance of the class. + /// + public TokenGeneratorTests() + { + _sut = new TokenGenerator(); + } + + [Fact] + public void GenerateToken_WhenCalled_ShouldGenerateNonEmptyToken() + { + // Act + string token = _sut.GenerateToken(); + + // Assert + token.Should().NotBeNullOrEmpty(); + } + + [Fact] + public void GenerateToken_WhenCalled_ShouldGenerateUrlSafeToken() + { + // Act + string token = _sut.GenerateToken(); + + // Assert + token.Should().NotContain("+", "Token should not contain '+'"); + token.Should().NotContain("/", "Token should not contain '/'"); + token.Should().NotContain("=", "Token should not contain '='"); + } + + [Fact] + public void GenerateToken_WhenCalledMultipleTimes_ShouldGenerateUniqueTokens() + { + // Act + string token1 = _sut.GenerateToken(); + string token2 = _sut.GenerateToken(); + string token3 = _sut.GenerateToken(); + + // Assert + token1.Should().NotBe(token2); + token1.Should().NotBe(token3); + token2.Should().NotBe(token3); + } + + [Fact] + public void GenerateToken_WhenCalled_ShouldGenerateTokenOfCorrectLength() + { + // Act + string token = _sut.GenerateToken(); + + // Assert + // 32 bytes in Base64 without padding should be 43 characters + token.Length.Should().Be(43); + } +} diff --git a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Authentication/TotpTokenGeneratorTests.cs b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Authentication/TotpTokenGeneratorTests.cs new file mode 100644 index 00000000..143a5e98 --- /dev/null +++ b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Authentication/TotpTokenGeneratorTests.cs @@ -0,0 +1,109 @@ +#region ========================================================================= USING ===================================================================================== +using FluentAssertions; +using Lumina.Infrastructure.Core.Authentication; +using OtpNet; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Infrastructure.UnitTests.Core.Authentication; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class TotpTokenGeneratorTests +{ + private readonly TotpTokenGenerator _sut; + + /// + /// Initializes a new instance of the class. + /// + public TotpTokenGeneratorTests() + { + _sut = new TotpTokenGenerator(); + } + + [Fact] + public void GenerateSecret_WhenCalled_ShouldGenerateNonEmptySecret() + { + // Act + byte[] secret = _sut.GenerateSecret(); + + // Assert + secret.Should().NotBeEmpty(); + } + + [Fact] + public void GenerateSecret_WhenCalledMultipleTimes_ShouldGenerateUniqueSecrets() + { + // Act + byte[] secret1 = _sut.GenerateSecret(); + byte[] secret2 = _sut.GenerateSecret(); + byte[] secret3 = _sut.GenerateSecret(); + + // Assert + secret1.Should().NotBeEquivalentTo(secret2); + secret1.Should().NotBeEquivalentTo(secret3); + secret2.Should().NotBeEquivalentTo(secret3); + } + + [Fact] + public void ValidateToken_WhenTokenIsValid_ShouldReturnTrue() + { + // Arrange + byte[] secret = _sut.GenerateSecret(); + Totp totp = new(secret); + string validToken = totp.ComputeTotp(); + + // Act + bool result = _sut.ValidateToken(secret, validToken); + + // Assert + result.Should().BeTrue(); + } + + [Theory] + [InlineData("")] + [InlineData(" ")] + [InlineData("123456")] // Valid format but wrong token + [InlineData("abcdef")] // Invalid format + [InlineData("12345")] // Too short + [InlineData("1234567")] // Too long + public void ValidateToken_WhenTokenIsInvalid_ShouldReturnFalse(string invalidToken) + { + // Arrange + byte[] secret = _sut.GenerateSecret(); + + // Act + bool result = _sut.ValidateToken(secret, invalidToken); + + // Assert + result.Should().BeFalse(); + } + + [Fact] + public void ValidateToken_WhenSecretIsWrong_ShouldReturnFalse() + { + // Arrange + byte[] secret1 = _sut.GenerateSecret(); + byte[] secret2 = _sut.GenerateSecret(); + Totp totp = new(secret1); + string token = totp.ComputeTotp(); + + // Act + bool result = _sut.ValidateToken(secret2, token); + + // Assert + result.Should().BeFalse(); + } + + [Fact] + public void GenerateSecret_WhenCalled_ShouldGenerateSecretOfCorrectLength() + { + // Act + byte[] secret = _sut.GenerateSecret(); + + // Assert + secret.Length.Should().Be(20); // Standard TOTP secret length + } +} diff --git a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Security/CryptographyServiceTests.cs b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Security/CryptographyServiceTests.cs new file mode 100644 index 00000000..9c950f21 --- /dev/null +++ b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Security/CryptographyServiceTests.cs @@ -0,0 +1,161 @@ +#region ========================================================================= USING ===================================================================================== +using FluentAssertions; +using Lumina.Infrastructure.Common.Models.Configuration; +using Lumina.Infrastructure.Core.Security; +using Lumina.Infrastructure.UnitTests.Core.Security.Fixtures; +using Microsoft.Extensions.Options; +using System; +using System.Diagnostics.CodeAnalysis; +using System.Security.Cryptography; +#endregion + +namespace Lumina.Infrastructure.UnitTests.Core.Security; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class CryptographyServiceTests +{ + private readonly CryptographyService _sut; + private readonly IOptions _encryptionSettings; + + /// + /// Initializes a new instance of the class. + /// + public CryptographyServiceTests() + { + _encryptionSettings = CryptographyServiceFixture.CreateEncryptionSettings(); + _sut = new CryptographyService(_encryptionSettings); + } + + [Fact] + public void Encrypt_WhenCalledWithValidData_ShouldReturnNonEmptyString() + { + // Arrange + string plaintext = CryptographyServiceFixture.CreateTestData(); + + // Act + string result = _sut.Encrypt(plaintext); + + // Assert + result.Should().NotBeNullOrEmpty(); + result.Should().NotBe(plaintext); + } + + [Fact] + public void Encrypt_WhenCalledMultipleTimesWithSameInput_ShouldReturnDifferentResults() + { + // Arrange + string plaintext = CryptographyServiceFixture.CreateTestData(); + + // Act + string result1 = _sut.Encrypt(plaintext); + string result2 = _sut.Encrypt(plaintext); + + // Assert + result1.Should().NotBe(result2); + } + + [Theory] + [InlineData(null)] + [InlineData("")] + public void Encrypt_WhenInputIsNullOrEmpty_ShouldThrowArgumentException(string? invalidInput) + { + // Act + Action act = () => _sut.Encrypt(invalidInput!); + + // Assert + act.Should().Throw() + .WithParameterName("plaintext") + .WithMessage("Value cannot be null or empty*"); + } + + [Fact] + public void Decrypt_WhenCalledWithValidData_ShouldReturnOriginalText() + { + // Arrange + string originalText = CryptographyServiceFixture.CreateTestData(); + string encrypted = _sut.Encrypt(originalText); + + // Act + string decrypted = _sut.Decrypt(encrypted); + + // Assert + decrypted.Should().Be(originalText); + } + + [Theory] + [InlineData(null)] + [InlineData("")] + public void Decrypt_WhenInputIsNullOrEmpty_ShouldThrowArgumentException(string? invalidInput) + { + // Act + Action act = () => _sut.Decrypt(invalidInput!); + + // Assert + act.Should().Throw() + .WithParameterName("ciphertext") + .WithMessage("Value cannot be null or empty*"); + } + + [Theory] + [InlineData("invalid")] + [InlineData("not-base64-!@#")] + public void Decrypt_WhenInputIsNotBase64_ShouldThrowFormatException(string invalidInput) + { + // Act + Action act = () => _sut.Decrypt(invalidInput); + + // Assert + act.Should().Throw(); + } + + [Fact] + public void Decrypt_WhenInputIsTooShort_ShouldThrowArgumentException() + { + // Arrange + string shortCiphertext = Convert.ToBase64String(new byte[8]); // less than required 16 bytes + + // Act + Action act = () => _sut.Decrypt(shortCiphertext); + + // Assert + act.Should().Throw() + .WithMessage("Invalid ciphertext"); + } + + [Fact] + public void Decrypt_WhenInputIsCorrupted_ShouldThrowCryptographicException() + { + // Arrange + string originalText = CryptographyServiceFixture.CreateTestData(); + string encrypted = _sut.Encrypt(originalText); + + // decode the Base64 string, modify one byte, then re-encode + byte[] encryptedBytes = Convert.FromBase64String(encrypted); + encryptedBytes[^1] ^= 0xFF; // flip all bits in the last byte + string corrupted = Convert.ToBase64String(encryptedBytes); + + // Act + Action act = () => _sut.Decrypt(corrupted); + + // Assert + act.Should().Throw(); + } + + [Fact] + public void Dispose_WhenCalled_ShouldClearKey() + { + // Arrange + string plaintext = CryptographyServiceFixture.CreateTestData(); + string encrypted = _sut.Encrypt(plaintext); + + // Act + _sut.Dispose(); + + // Assert + Action act = () => _sut.Decrypt(encrypted); + act.Should().Throw(); + } +} diff --git a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Security/Fixtures/CryptographyServiceFixture.cs b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Security/Fixtures/CryptographyServiceFixture.cs new file mode 100644 index 00000000..b998aa1e --- /dev/null +++ b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Security/Fixtures/CryptographyServiceFixture.cs @@ -0,0 +1,49 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Infrastructure.Common.Models.Configuration; +using Microsoft.Extensions.Options; +using NSubstitute; +using System; +using System.Diagnostics.CodeAnalysis; +using System.Security.Cryptography; +#endregion + +namespace Lumina.Infrastructure.UnitTests.Core.Security.Fixtures; + +/// +/// Fixture class for cryptography service tests. +/// +[ExcludeFromCodeCoverage] +public class CryptographyServiceFixture +{ + /// + /// Creates a valid encryption settings model for testing. + /// + /// The configured options. + public static IOptions CreateEncryptionSettings() + { + // Generate a valid 256-bit (32 byte) key for AES-256 + byte[] key = new byte[32]; + RandomNumberGenerator.Fill(key); + string base64Key = Convert.ToBase64String(key); + + EncryptionSettingsModel settings = new() + { + SecretKey = base64Key + }; + + IOptions options = Substitute.For>(); + options.Value.Returns(settings); + + return options; + } + + /// + /// Creates test data for encryption/decryption. + /// + /// A string to be encrypted/decrypted. + public static string CreateTestData() + { + return new Faker().Lorem.Sentence(); + } +} diff --git a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Security/HashServiceTests.cs b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Security/HashServiceTests.cs new file mode 100644 index 00000000..5b762896 --- /dev/null +++ b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Security/HashServiceTests.cs @@ -0,0 +1,165 @@ +#region ========================================================================= USING ===================================================================================== +using FluentAssertions; +using Lumina.Infrastructure.Core.Security; +using System; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Infrastructure.UnitTests.Core.Security; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class HashServiceTests +{ + private readonly HashService _sut; + + /// + /// Initializes a new instance of the class. + /// + public HashServiceTests() + { + _sut = new HashService(); + } + + [Fact] + public void HashString_WhenCalled_ShouldReturnNonEmptyHash() + { + // Arrange + string password = "TestPassword123!"; + + // Act + string result = _sut.HashString(password); + + // Assert + result.Should().NotBeNullOrEmpty(); + result.Should().NotBe(password); + } + + [Fact] + public void HashString_WhenCalledMultipleTimesWithSameInput_ShouldReturnDifferentHashes() + { + // Arrange + string password = "TestPassword123!"; + + // Act + string hash1 = _sut.HashString(password); + string hash2 = _sut.HashString(password); + + // Assert + hash1.Should().NotBe(hash2); + } + + [Theory] + [InlineData(" ")] + [InlineData("short")] + [InlineData("verylongpasswordwithlotsofcharactersbutnostringformatting")] + [InlineData("Password123!")] + [InlineData("@#$%^&*()")] + public void HashString_WhenCalledWithDifferentInputs_ShouldGenerateValidHashes(string input) + { + // Act + string hash = _sut.HashString(input); + + // Assert + hash.Should().NotBeNullOrEmpty(); + // verify it's a valid Base64 string + Action decode = () => Convert.FromBase64String(hash); + decode.Should().NotThrow(); + } + + [Fact] + public void CheckStringAgainstHash_WhenPasswordMatches_ShouldReturnTrue() + { + // Arrange + string password = "TestPassword123!"; + string hash = _sut.HashString(password); + + // Act + bool result = _sut.CheckStringAgainstHash(password, hash); + + // Assert + result.Should().BeTrue(); + } + + [Fact] + public void CheckStringAgainstHash_WhenPasswordDoesNotMatch_ShouldReturnFalse() + { + // Arrange + string password = "TestPassword123!"; + string wrongPassword = "WrongPassword123!"; + string hash = _sut.HashString(password); + + // Act + bool result = _sut.CheckStringAgainstHash(wrongPassword, hash); + + // Assert + result.Should().BeFalse(); + } + + [Theory] + [InlineData("")] + [InlineData("dGVzdA==")] // valid base64 but wrong length + [InlineData("YWJjZGVmZ2hpamtsbW5vcHFyc3R1dnd4eXo=")] // valid base64 but wrong length + public void CheckStringAgainstHash_WhenHashIsInvalidLength_ShouldReturnFalse(string invalidHash) + { + // Arrange + string password = "TestPassword123!"; + + // Act + bool result = _sut.CheckStringAgainstHash(password, invalidHash); + + // Assert + result.Should().BeFalse(); + } + + [Fact] + public void CheckStringAgainstHash_WhenHashIsNotBase64_ShouldThrowFormatException() + { + // Arrange + string password = "TestPassword123!"; + string invalidHash = "not-base64-string"; + + // Act + Action act = () => _sut.CheckStringAgainstHash(password, invalidHash); + + // Assert + act.Should().Throw(); + } + + [Theory] + [InlineData(null)] + public void HashString_WhenPasswordIsNull_ShouldThrowArgumentNullException(string? nullPassword) + { + // Act + Action act = () => _sut.HashString(nullPassword!); + + // Assert + act.Should().Throw(); + } + + [Theory] + [InlineData(null)] + public void CheckStringAgainstHash_WhenPasswordIsNull_ShouldThrowArgumentNullException(string? nullPassword) + { + // Arrange + string hash = _sut.HashString("somepassword"); + + // Act + Action act = () => _sut.CheckStringAgainstHash(nullPassword!, hash); + + // Assert + act.Should().Throw(); + } + + [Fact] + public void CheckStringAgainstHash_WhenHashIsNull_ShouldThrowArgumentNullException() + { + // Act + Action act = () => _sut.CheckStringAgainstHash("password", null!); + + // Assert + act.Should().Throw(); + } +} diff --git a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Lumina.Infrastructure.UnitTests.csproj b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Lumina.Infrastructure.UnitTests.csproj index 6bc50059..555feed6 100644 --- a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Lumina.Infrastructure.UnitTests.csproj +++ b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Lumina.Infrastructure.UnitTests.csproj @@ -9,19 +9,27 @@ true + + + <_Parameter1>DisableTestParallelization = true + <_Parameter1_IsLiteral>true + + + + all runtime; build; native; contentfiles; analyzers; buildtransitive - - + + - + - + all runtime; build; native; contentfiles; analyzers; buildtransitive diff --git a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/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..3e993be1 --- /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.Domain.Common.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 92% 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..5c08885d 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.Domain.Common.Enums.FileSystem; +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 81% 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..59cdaf52 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.Domain.Common.Enums.PhotoLibrary; +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/Maintenance/ApplicationSetup/CheckInitializationEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Maintenance/ApplicationSetup/CheckInitializationEndpointTests.cs new file mode 100644 index 00000000..681c8a75 --- /dev/null +++ b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Maintenance/ApplicationSetup/CheckInitializationEndpointTests.cs @@ -0,0 +1,91 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using FluentAssertions; +using Lumina.Application.Core.Maintenance.ApplicationSetup.Queries.CheckInitialization; +using Lumina.Contracts.Responses.UsersManagement; +using Lumina.Presentation.Api.Core.Endpoints.Maintenance.ApplicationSetup; +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.Maintenance.ApplicationSetup; + +[ExcludeFromCodeCoverage] +public class CheckInitializationEndpointTests +{ + private readonly ISender _mockSender; + private readonly CheckInitializationEndpoint _sut; + + public CheckInitializationEndpointTests() + { + _mockSender = Substitute.For(); + _sut = Factory.Create(_mockSender); + } + + [Fact] + public async Task ExecuteAsync_WhenCalled_ShouldReturnOkResultWithInitializationResponse() + { + // Arrange + CancellationToken cancellationToken = CancellationToken.None; + InitializationResponse expectedResponse = new(IsInitialized: true); + _mockSender.Send(Arg.Any(), Arg.Any()) + .Returns(expectedResponse); + + // Act + IResult result = await _sut.ExecuteAsync(new EmptyRequest(), cancellationToken); + + // Assert + InitializationResponse actualResponse = result.Should().BeOfType>().Subject.Value!; + actualResponse.Should().BeEquivalentTo(expectedResponse); + } + + [Fact] + public async Task ExecuteAsync_WhenCalled_ShouldSendCheckInitializationQueryToMediator() + { + // Arrange + CancellationToken cancellationToken = CancellationToken.None; + _mockSender.Send(Arg.Any(), Arg.Any()) + .Returns(new InitializationResponse(IsInitialized: true)); + + // 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 InitializationResponse(IsInitialized: true); + }, 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/Maintenance/ApplicationSetup/Fixtures/RegistrationRequestFixture.cs b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Maintenance/ApplicationSetup/Fixtures/RegistrationRequestFixture.cs new file mode 100644 index 00000000..2b4bbd5a --- /dev/null +++ b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Maintenance/ApplicationSetup/Fixtures/RegistrationRequestFixture.cs @@ -0,0 +1,39 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Contracts.Requests.Authentication; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Presentation.Api.UnitTests.Core.Endpoints.Maintenance.ApplicationSetup.Fixtures; + +/// +/// Fixture class for the record. +/// +[ExcludeFromCodeCoverage] +public class RegistrationRequestFixture +{ + private readonly Faker _faker = new(); + + /// + /// Creates a with default or random values. + /// + /// The username for registration. + /// The password for registration. + /// The password confirmation. + /// Whether to use two-factor authentication. + /// The created . + public RegistrationRequest Create( + string? username = null, + string? password = null, + string? passwordConfirm = null, + bool? use2fa = null) + { + string generatedPassword = password ?? _faker.Internet.Password(); + return new RegistrationRequest( + Username: username ?? _faker.Internet.UserName(), + Password: generatedPassword, + PasswordConfirm: passwordConfirm ?? generatedPassword, + Use2fa: use2fa ?? _faker.Random.Bool() + ); + } +} diff --git a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Maintenance/ApplicationSetup/SetupApplicationEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Maintenance/ApplicationSetup/SetupApplicationEndpointTests.cs new file mode 100644 index 00000000..8ba0700d --- /dev/null +++ b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Maintenance/ApplicationSetup/SetupApplicationEndpointTests.cs @@ -0,0 +1,139 @@ +#region ========================================================================= USING ===================================================================================== +using ErrorOr; +using FastEndpoints; +using FluentAssertions; +using Lumina.Application.Core.Maintenance.ApplicationSetup.Commands.SetupApplication; +using Lumina.Application.Core.Maintenance.ApplicationSetup.Queries.CheckInitialization; +using Lumina.Contracts.Requests.Authentication; +using Lumina.Contracts.Responses.Authentication; +using Lumina.Contracts.Responses.UsersManagement; +using Lumina.Presentation.Api.Core.Endpoints.Maintenance.ApplicationSetup; +using Lumina.Presentation.Api.UnitTests.Core.Endpoints.Maintenance.ApplicationSetup.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.Maintenance.ApplicationSetup; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class SetupApplicationEndpointTests +{ + private readonly ISender _mockSender; + private readonly SetupApplicationEndpoint _sut; + private readonly RegistrationRequestFixture _registrationRequestFixture; + + /// + /// Initializes a new instance of the class. + /// + public SetupApplicationEndpointTests() + { + _mockSender = Substitute.For(); + _sut = Factory.Create(_mockSender); + _registrationRequestFixture = new RegistrationRequestFixture(); + } + + [Fact] + public async Task ExecuteAsync_WhenSuccessful_ShouldReturnCreatedResultWithRegistrationResponse() + { + // Arrange + RegistrationRequest request = _registrationRequestFixture.Create(); + CancellationToken cancellationToken = CancellationToken.None; + RegistrationResponse expectedResponse = new(Guid.NewGuid(), "testUser", "TOTP123"); + _mockSender.Send(Arg.Any(), Arg.Any()) + .Returns(ErrorOrFactory.From(expectedResponse)); + + // Act + IResult result = await _sut.ExecuteAsync(request, cancellationToken); + + // Assert + Created createdResult = result.Should().BeOfType>().Subject; + createdResult.Value.Should().BeEquivalentTo(expectedResponse); + createdResult.Location.Should().EndWith(expectedResponse.Id.ToString()); + } + + [Fact] + public async Task ExecuteAsync_WhenMediatorReturnsError_ShouldReturnProblemResult() + { + // Arrange + RegistrationRequest request = _registrationRequestFixture.Create(); + CancellationToken cancellationToken = CancellationToken.None; + Error expectedError = Error.Conflict("Registration.Failed", "The application is already initialized."); + _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.Status409Conflict); + problemDetails.ContentType.Should().Be("application/problem+json"); + problemDetails.ProblemDetails.Should().BeOfType(); + + problemDetails.ProblemDetails.Title.Should().Be("Registration.Failed"); + problemDetails.ProblemDetails.Detail.Should().Be("The application is already initialized."); + problemDetails.ProblemDetails.Status.Should().Be(StatusCodes.Status409Conflict); + problemDetails.ProblemDetails.Type.Should().Be("https://tools.ietf.org/html/rfc9110#section-15.5.10"); + problemDetails.ProblemDetails.Extensions["traceId"].Should().NotBeNull(); + } + + [Fact] + public async Task ExecuteAsync_WhenCalled_ShouldSendSetupApplicationCommandToSender() + { + // Arrange + RegistrationRequest request = _registrationRequestFixture.Create(); + CancellationToken cancellationToken = CancellationToken.None; + _mockSender.Send(Arg.Any(), Arg.Any()) + .Returns(ErrorOrFactory.From(new RegistrationResponse(Guid.NewGuid(), "testUser", "TOTP123"))); + + // Act + await _sut.ExecuteAsync(request, cancellationToken); + + // Assert + await _mockSender.Received(1).Send( + Arg.Is(cmd => + cmd.Username == request.Username && + cmd.Password == request.Password && + cmd.PasswordConfirm == request.PasswordConfirm && + cmd.Use2fa == request.Use2fa), + Arg.Is(cancellationToken)); + } + + [Fact] + public async Task ExecuteAsync_WhenCancellationRequested_ShouldCancelOperation() + { + // Arrange + RegistrationRequest request = _registrationRequestFixture.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(new RegistrationResponse(Guid.NewGuid(), "testUser", "TOTP123")); + }, 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/UsersManagement/Authentication/ChangePassword/ChangePasswordEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/UsersManagement/Authentication/ChangePassword/ChangePasswordEndpointTests.cs new file mode 100644 index 00000000..3892f8fa --- /dev/null +++ b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/UsersManagement/Authentication/ChangePassword/ChangePasswordEndpointTests.cs @@ -0,0 +1,140 @@ +#region ========================================================================= USING ===================================================================================== +using ErrorOr; +using FastEndpoints; +using FluentAssertions; +using Lumina.Application.Core.UsersManagement.Authentication.Commands.ChangePassword; +using Lumina.Contracts.Requests.Authentication; +using Lumina.Contracts.Responses.Authentication; +using Lumina.Presentation.Api.Core.Endpoints.UsersManagement.Authentication.ChangePassword; +using Lumina.Presentation.Api.UnitTests.Core.Endpoints.UsersManagement.Authentication.ChangePassword.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.UsersManagement.Authentication.ChangePassword; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class ChangePasswordEndpointTests +{ + private readonly ISender _mockSender; + private readonly ChangePasswordEndpoint _sut; + private readonly ChangePasswordRequestFixture _changePasswordRequestFixture; + + /// + /// Initializes a new instance of the class. + /// + public ChangePasswordEndpointTests() + { + _mockSender = Substitute.For(); + _sut = Factory.Create(_mockSender); + _changePasswordRequestFixture = new ChangePasswordRequestFixture(); + } + + [Fact] + public async Task ExecuteAsync_WhenSuccessful_ShouldReturnOkResultWithChangePasswordResponse() + { + // Arrange + ChangePasswordRequest request = _changePasswordRequestFixture.Create(); + CancellationToken cancellationToken = CancellationToken.None; + ChangePasswordResponse expectedResponse = new(IsPasswordChanged: true); + _mockSender.Send(Arg.Any(), Arg.Any()) + .Returns(ErrorOrFactory.From(expectedResponse)); + + // Act + IResult result = await _sut.ExecuteAsync(request, cancellationToken); + + // Assert + Ok okResult = result.Should().BeOfType>().Subject; + okResult.Value.Should().BeEquivalentTo(expectedResponse); + } + + [Fact] + public async Task ExecuteAsync_WhenMediatorReturnsError_ShouldReturnProblemResult() + { + // Arrange + ChangePasswordRequest request = _changePasswordRequestFixture.Create(); + CancellationToken cancellationToken = CancellationToken.None; + Error expectedError = Error.Validation("Password.Invalid", "The current password is incorrect."); + _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.Type.Should().Be("https://tools.ietf.org/html/rfc4918#section-11.2"); + validationProblemDetails.Errors.Should().ContainSingle() + .Which.Should().BeEquivalentTo(new + { + Key = "Password.Invalid", + Value = new[] { "The current password is incorrect." } + }); + } + + [Fact] + public async Task ExecuteAsync_WhenCalled_ShouldSendChangePasswordCommandToSender() + { + // Arrange + ChangePasswordRequest request = _changePasswordRequestFixture.Create(); + CancellationToken cancellationToken = CancellationToken.None; + _mockSender.Send(Arg.Any(), Arg.Any()) + .Returns(ErrorOrFactory.From(new ChangePasswordResponse(true))); + + // Act + await _sut.ExecuteAsync(request, cancellationToken); + + // Assert + await _mockSender.Received(1).Send( + Arg.Is(cmd => + cmd.Username == request.Username && + cmd.CurrentPassword == request.CurrentPassword && + cmd.NewPassword == request.NewPassword && + cmd.NewPasswordConfirm == request.NewPasswordConfirm), + Arg.Is(cancellationToken)); + } + + [Fact] + public async Task ExecuteAsync_WhenCancellationRequested_ShouldCancelOperation() + { + // Arrange + ChangePasswordRequest request = _changePasswordRequestFixture.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(new ChangePasswordResponse(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/UsersManagement/Authentication/ChangePassword/Fixtures/ChangePasswordRequestFixture.cs b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/UsersManagement/Authentication/ChangePassword/Fixtures/ChangePasswordRequestFixture.cs new file mode 100644 index 00000000..d37b5eba --- /dev/null +++ b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/UsersManagement/Authentication/ChangePassword/Fixtures/ChangePasswordRequestFixture.cs @@ -0,0 +1,39 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Contracts.Requests.Authentication; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Presentation.Api.UnitTests.Core.Endpoints.UsersManagement.Authentication.ChangePassword.Fixtures; + +/// +/// Fixture class for the record. +/// +[ExcludeFromCodeCoverage] +public class ChangePasswordRequestFixture +{ + private readonly Faker _faker = new(); + + /// + /// Creates a with default or random values. + /// + /// The username for the password change. + /// The current password. + /// The new password. + /// The new password confirmation. + /// The created . + public ChangePasswordRequest Create( + string? username = null, + string? currentPassword = null, + string? newPassword = null, + string? newPasswordConfirm = null) + { + string generatedNewPassword = newPassword ?? _faker.Internet.Password(); + return new ChangePasswordRequest( + Username: username ?? _faker.Internet.UserName(), + CurrentPassword: currentPassword ?? _faker.Internet.Password(), + NewPassword: generatedNewPassword, + NewPasswordConfirm: newPasswordConfirm ?? generatedNewPassword + ); + } +} diff --git a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/UsersManagement/Authentication/Login/Fixtures/LoginRequestFixture.cs b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/UsersManagement/Authentication/Login/Fixtures/LoginRequestFixture.cs new file mode 100644 index 00000000..4f706305 --- /dev/null +++ b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/UsersManagement/Authentication/Login/Fixtures/LoginRequestFixture.cs @@ -0,0 +1,35 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Contracts.Requests.Authentication; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Presentation.Api.UnitTests.Core.Endpoints.UsersManagement.Authentication.Login.Fixtures; + +/// +/// Fixture class for the record. +/// +[ExcludeFromCodeCoverage] +public class LoginRequestFixture +{ + private readonly Faker _faker = new(); + + /// + /// Creates a with default or random values. + /// + /// The username for login. + /// The password for login. + /// The TOTP code for two-factor authentication. + /// The created . + public LoginRequest Create( + string? username = null, + string? password = null, + string? totpCode = null) + { + return new LoginRequest( + Username: username ?? _faker.Internet.UserName(), + Password: password ?? _faker.Internet.Password(), + TotpCode: totpCode ?? _faker.Random.Number(100000, 999999).ToString() + ); + } +} diff --git a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/UsersManagement/Authentication/Login/LoginEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/UsersManagement/Authentication/Login/LoginEndpointTests.cs new file mode 100644 index 00000000..68938298 --- /dev/null +++ b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/UsersManagement/Authentication/Login/LoginEndpointTests.cs @@ -0,0 +1,139 @@ +#region ========================================================================= USING ===================================================================================== +using ErrorOr; +using FastEndpoints; +using FluentAssertions; +using Lumina.Application.Core.UsersManagement.Authentication.Queries.LoginUser; +using Lumina.Contracts.Requests.Authentication; +using Lumina.Contracts.Responses.Authentication; +using Lumina.Presentation.Api.Core.Endpoints.UsersManagement.Authentication.Login; +using Lumina.Presentation.Api.UnitTests.Core.Endpoints.UsersManagement.Authentication.Login.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.UsersManagement.Authentication.Login; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class LoginEndpointTests +{ + private readonly ISender _mockSender; + private readonly LoginEndpoint _sut; + private readonly LoginRequestFixture _loginRequestFixture; + + /// + /// Initializes a new instance of the class. + /// + public LoginEndpointTests() + { + _mockSender = Substitute.For(); + _sut = Factory.Create(_mockSender); + _loginRequestFixture = new LoginRequestFixture(); + } + + [Fact] + public async Task ExecuteAsync_WhenSuccessful_ShouldReturnOkResultWithLoginResponse() + { + // Arrange + LoginRequest request = _loginRequestFixture.Create(); + CancellationToken cancellationToken = CancellationToken.None; + LoginResponse expectedResponse = new(Guid.NewGuid(), "testUser", "jwt_token", true); + _mockSender.Send(Arg.Any(), Arg.Any()) + .Returns(ErrorOrFactory.From(expectedResponse)); + + // Act + IResult result = await _sut.ExecuteAsync(request, cancellationToken); + + // Assert + Ok okResult = result.Should().BeOfType>().Subject; + okResult.Value.Should().BeEquivalentTo(expectedResponse); + } + + [Fact] + public async Task ExecuteAsync_WhenMediatorReturnsError_ShouldReturnProblemResult() + { + // Arrange + LoginRequest request = _loginRequestFixture.Create(); + CancellationToken cancellationToken = CancellationToken.None; + Error expectedError = Error.Validation("Login.Failed", "Invalid username or password."); + _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.Type.Should().Be("https://tools.ietf.org/html/rfc4918#section-11.2"); + validationProblemDetails.Errors.Should().ContainSingle() + .Which.Should().BeEquivalentTo(new + { + Key = "Login.Failed", + Value = new[] { "Invalid username or password." } + }); + } + + [Fact] + public async Task ExecuteAsync_WhenCalled_ShouldSendLoginUserQueryToSender() + { + // Arrange + LoginRequest request = _loginRequestFixture.Create(); + CancellationToken cancellationToken = CancellationToken.None; + _mockSender.Send(Arg.Any(), Arg.Any()) + .Returns(ErrorOrFactory.From(new LoginResponse(Guid.NewGuid(), "testUser", "jwt_token", true))); + + // Act + await _sut.ExecuteAsync(request, cancellationToken); + + // Assert + await _mockSender.Received(1).Send( + Arg.Is(q => + q.Username == request.Username && + q.Password == request.Password && + q.TotpCode == request.TotpCode), + Arg.Is(cancellationToken)); + } + + [Fact] + public async Task ExecuteAsync_WhenCancellationRequested_ShouldCancelOperation() + { + // Arrange + LoginRequest request = _loginRequestFixture.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(new LoginResponse(Guid.NewGuid(), "testUser", "jwt_token", 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/UsersManagement/Authentication/RecoverPassword/Fixtures/RecoverPasswordRequestFixture.cs b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/UsersManagement/Authentication/RecoverPassword/Fixtures/RecoverPasswordRequestFixture.cs new file mode 100644 index 00000000..a8cb5d73 --- /dev/null +++ b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/UsersManagement/Authentication/RecoverPassword/Fixtures/RecoverPasswordRequestFixture.cs @@ -0,0 +1,32 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Contracts.Requests.Authentication; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Presentation.Api.UnitTests.Core.Endpoints.UsersManagement.Authentication.RecoverPassword.Fixtures; + +/// +/// Fixture class for the record. +/// +[ExcludeFromCodeCoverage] +public class RecoverPasswordRequestFixture +{ + private readonly Faker _faker = new(); + + /// + /// Creates a with default or random values. + /// + /// The username for password recovery. + /// The TOTP code for verification. + /// The created . + public RecoverPasswordRequest Create( + string? username = null, + string? totpCode = null) + { + return new RecoverPasswordRequest( + Username: username ?? _faker.Internet.UserName(), + TotpCode: totpCode ?? _faker.Random.Number(100000, 999999).ToString() + ); + } +} diff --git a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/UsersManagement/Authentication/RecoverPassword/RecoverPasswordEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/UsersManagement/Authentication/RecoverPassword/RecoverPasswordEndpointTests.cs new file mode 100644 index 00000000..24c18032 --- /dev/null +++ b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/UsersManagement/Authentication/RecoverPassword/RecoverPasswordEndpointTests.cs @@ -0,0 +1,138 @@ +#region ========================================================================= USING ===================================================================================== +using ErrorOr; +using FastEndpoints; +using FluentAssertions; +using Lumina.Application.Core.UsersManagement.Authentication.Commands.RecoverPassword; +using Lumina.Contracts.Requests.Authentication; +using Lumina.Contracts.Responses.Authentication; +using Lumina.Presentation.Api.Core.Endpoints.UsersManagement.Authentication.RecoverPassword; +using Lumina.Presentation.Api.UnitTests.Core.Endpoints.UsersManagement.Authentication.RecoverPassword.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.UsersManagement.Authentication.RecoverPassword; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class RecoverPasswordEndpointTests +{ + private readonly ISender _mockSender; + private readonly RecoverPasswordEndpoint _sut; + private readonly RecoverPasswordRequestFixture _recoverPasswordRequestFixture; + + /// + /// Initializes a new instance of the class. + /// + public RecoverPasswordEndpointTests() + { + _mockSender = Substitute.For(); + _sut = Factory.Create(_mockSender); + _recoverPasswordRequestFixture = new RecoverPasswordRequestFixture(); + } + + [Fact] + public async Task ExecuteAsync_WhenSuccessful_ShouldReturnOkResultWithRecoverPasswordResponse() + { + // Arrange + RecoverPasswordRequest request = _recoverPasswordRequestFixture.Create(); + CancellationToken cancellationToken = CancellationToken.None; + RecoverPasswordResponse expectedResponse = new(IsPasswordReset: true); + _mockSender.Send(Arg.Any(), Arg.Any()) + .Returns(ErrorOrFactory.From(expectedResponse)); + + // Act + IResult result = await _sut.ExecuteAsync(request, cancellationToken); + + // Assert + Ok okResult = result.Should().BeOfType>().Subject; + okResult.Value.Should().BeEquivalentTo(expectedResponse); + } + + [Fact] + public async Task ExecuteAsync_WhenMediatorReturnsError_ShouldReturnProblemResult() + { + // Arrange + RecoverPasswordRequest request = _recoverPasswordRequestFixture.Create(); + CancellationToken cancellationToken = CancellationToken.None; + Error expectedError = Error.Validation("Recovery.Failed", "Invalid username or TOTP code."); + _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.Type.Should().Be("https://tools.ietf.org/html/rfc4918#section-11.2"); + validationProblemDetails.Errors.Should().ContainSingle() + .Which.Should().BeEquivalentTo(new + { + Key = "Recovery.Failed", + Value = new[] { "Invalid username or TOTP code." } + }); + } + + [Fact] + public async Task ExecuteAsync_WhenCalled_ShouldSendRecoverPasswordCommandToSender() + { + // Arrange + RecoverPasswordRequest request = _recoverPasswordRequestFixture.Create(); + CancellationToken cancellationToken = CancellationToken.None; + _mockSender.Send(Arg.Any(), Arg.Any()) + .Returns(ErrorOrFactory.From(new RecoverPasswordResponse(true))); + + // Act + await _sut.ExecuteAsync(request, cancellationToken); + + // Assert + await _mockSender.Received(1).Send( + Arg.Is(cmd => + cmd.Username == request.Username && + cmd.TotpCode == request.TotpCode), + Arg.Is(cancellationToken)); + } + + [Fact] + public async Task ExecuteAsync_WhenCancellationRequested_ShouldCancelOperation() + { + // Arrange + RecoverPasswordRequest request = _recoverPasswordRequestFixture.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(new RecoverPasswordResponse(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/UsersManagement/Authentication/Register/Fixtures/RegistrationRequestFixture.cs b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/UsersManagement/Authentication/Register/Fixtures/RegistrationRequestFixture.cs new file mode 100644 index 00000000..ea6955fe --- /dev/null +++ b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/UsersManagement/Authentication/Register/Fixtures/RegistrationRequestFixture.cs @@ -0,0 +1,39 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Contracts.Requests.Authentication; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Presentation.Api.UnitTests.Core.Endpoints.UsersManagement.Authentication.Register.Fixtures; + +/// +/// Fixture class for the record. +/// +[ExcludeFromCodeCoverage] +public class RegistrationRequestFixture +{ + private readonly Faker _faker = new(); + + /// + /// Creates a with default or random values. + /// + /// The username for registration. + /// The password for registration. + /// The password confirmation. + /// Whether to use two-factor authentication. + /// The created . + public RegistrationRequest Create( + string? username = null, + string? password = null, + string? passwordConfirm = null, + bool? use2fa = null) + { + string generatedPassword = password ?? _faker.Internet.Password(); + return new RegistrationRequest( + Username: username ?? _faker.Internet.UserName(), + Password: generatedPassword, + PasswordConfirm: passwordConfirm ?? generatedPassword, + Use2fa: use2fa ?? _faker.Random.Bool() + ); + } +} diff --git a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/UsersManagement/Authentication/Register/RegisterEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/UsersManagement/Authentication/Register/RegisterEndpointTests.cs new file mode 100644 index 00000000..6bfb335f --- /dev/null +++ b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/UsersManagement/Authentication/Register/RegisterEndpointTests.cs @@ -0,0 +1,141 @@ +#region ========================================================================= USING ===================================================================================== +using ErrorOr; +using FastEndpoints; +using FluentAssertions; +using Lumina.Application.Core.UsersManagement.Authentication.Commands.RegisterUser; +using Lumina.Contracts.Requests.Authentication; +using Lumina.Contracts.Responses.Authentication; +using Lumina.Presentation.Api.Core.Endpoints.UsersManagement.Authentication.Register; +using Lumina.Presentation.Api.UnitTests.Core.Endpoints.Maintenance.ApplicationSetup.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.UsersManagement.Authentication.Register; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class RegisterEndpointTests +{ + private readonly ISender _mockSender; + private readonly RegisterEndpoint _sut; + private readonly RegistrationRequestFixture _registrationRequestFixture; + + /// + /// Initializes a new instance of the class. + /// + public RegisterEndpointTests() + { + _mockSender = Substitute.For(); + _sut = Factory.Create(_mockSender); + _registrationRequestFixture = new RegistrationRequestFixture(); + } + + [Fact] + public async Task ExecuteAsync_WhenSuccessful_ShouldReturnCreatedResultWithRegistrationResponse() + { + // Arrange + RegistrationRequest request = _registrationRequestFixture.Create(); + CancellationToken cancellationToken = CancellationToken.None; + RegistrationResponse expectedResponse = new(Guid.NewGuid(), "testUser", "TOTP123"); + _mockSender.Send(Arg.Any(), Arg.Any()) + .Returns(ErrorOrFactory.From(expectedResponse)); + + // Act + IResult result = await _sut.ExecuteAsync(request, cancellationToken); + + // Assert + Created createdResult = result.Should().BeOfType>().Subject; + createdResult.Value.Should().BeEquivalentTo(expectedResponse); + createdResult.Location.Should().EndWith(expectedResponse.Id.ToString()); + } + + [Fact] + public async Task ExecuteAsync_WhenMediatorReturnsError_ShouldReturnProblemResult() + { + // Arrange + RegistrationRequest request = _registrationRequestFixture.Create(); + CancellationToken cancellationToken = CancellationToken.None; + Error expectedError = Error.Validation("Registration.Failed", "Username is already taken."); + _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.Type.Should().Be("https://tools.ietf.org/html/rfc4918#section-11.2"); + validationProblemDetails.Errors.Should().ContainSingle() + .Which.Should().BeEquivalentTo(new + { + Key = "Registration.Failed", + Value = new[] { "Username is already taken." } + }); + } + + [Fact] + public async Task ExecuteAsync_WhenCalled_ShouldSendRegisterUserCommandToSender() + { + // Arrange + RegistrationRequest request = _registrationRequestFixture.Create(); + CancellationToken cancellationToken = CancellationToken.None; + _mockSender.Send(Arg.Any(), Arg.Any()) + .Returns(ErrorOrFactory.From(new RegistrationResponse(Guid.NewGuid(), "testUser", "TOTP123"))); + + // Act + await _sut.ExecuteAsync(request, cancellationToken); + + // Assert + await _mockSender.Received(1).Send( + Arg.Is(cmd => + cmd.Username == request.Username && + cmd.Password == request.Password && + cmd.PasswordConfirm == request.PasswordConfirm && + cmd.Use2fa == request.Use2fa), + Arg.Is(cancellationToken)); + } + + [Fact] + public async Task ExecuteAsync_WhenCancellationRequested_ShouldCancelOperation() + { + // Arrange + RegistrationRequest request = _registrationRequestFixture.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(new RegistrationResponse(Guid.NewGuid(), "testUser", "TOTP123")); + }, 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 35881bad..d13d1cd9 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 @@ -9,21 +9,28 @@ true + + + <_Parameter1>DisableTestParallelization = true + <_Parameter1_IsLiteral>true + + + - + all runtime; build; native; contentfiles; analyzers; buildtransitive - - + + - + - + all runtime; build; native; contentfiles; analyzers; buildtransitive