diff --git a/src/Lumina.Application/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/GetBookRequestMapping.cs b/src/Lumina.Application/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/GetBookRequestMapping.cs new file mode 100644 index 00000000..5a6445bc --- /dev/null +++ b/src/Lumina.Application/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/GetBookRequestMapping.cs @@ -0,0 +1,25 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Queries.GetBook; +using Lumina.Contracts.Requests.MediaLibrary.WrittenContentLibrary.BookLibrary.Books; +using System; +#endregion + +namespace Lumina.Application.Common.Mapping.MediaLibrary.WrittenContentLibrary.BookLibrary.Books; + +/// +/// Extension methods for converting . +/// +public static class GetBookRequestMapping +{ + /// + /// Converts to . + /// + /// The request to be converted. + /// The converted query. + public static GetBookQuery ToQuery(this GetBookRequest request) + { + return new GetBookQuery( + Guid.TryParse(request.Id, out Guid bookId) ? bookId : Guid.Empty + ); + } +} diff --git a/src/Lumina.Application/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/UpdateBookCommandMapping.cs b/src/Lumina.Application/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/UpdateBookCommandMapping.cs new file mode 100644 index 00000000..82de4c1c --- /dev/null +++ b/src/Lumina.Application/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/UpdateBookCommandMapping.cs @@ -0,0 +1,50 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Commands.UpdateBook; +using Lumina.Contracts.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary; +#endregion + +namespace Lumina.Application.Common.Mapping.MediaLibrary.WrittenContentLibrary.BookLibrary.Books; + +/// +/// Extension methods for converting . +/// +public static class UpdateBookCommandMapping +{ + /// + /// Converts to , so that the edited data can be applied to the domain book. + /// + /// The command containing the edited data of the book. + /// The built metadata. + public static BookMetadataDto ToBookMetadataDto(this UpdateBookCommand command) + { + return new BookMetadataDto( + Title: command.Metadata!.Title, + OriginalTitle: command.Metadata.OriginalTitle, + Description: command.Metadata.Description, + ReleaseInfo: command.Metadata.ReleaseInfo, + Genres: command.Metadata.Genres, + Tags: command.Metadata.Tags, + Language: command.Metadata.Language, + OriginalLanguage: command.Metadata.OriginalLanguage, + Publisher: command.Metadata.Publisher, + PageCount: command.Metadata.PageCount, + Format: command.Format, + Edition: command.Edition, + VolumeNumber: command.VolumeNumber, + Series: command.Series, + ASIN: command.ASIN, + GoodreadsId: command.GoodreadsId, + LCCN: command.LCCN, + OCLCNumber: command.OCLCNumber, + OpenLibraryId: command.OpenLibraryId, + LibraryThingId: command.LibraryThingId, + GoogleBooksId: command.GoogleBooksId, + BarnesAndNobleId: command.BarnesAndNobleId, + AppleBooksId: command.AppleBooksId, + Isbns: command.ISBNs, + Contributors: command.Contributors, + Ratings: command.Ratings, + CoverImagePath: null + ); + } +} diff --git a/src/Lumina.Application/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/UpdateBookRequestMapping.cs b/src/Lumina.Application/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/UpdateBookRequestMapping.cs new file mode 100644 index 00000000..6720e145 --- /dev/null +++ b/src/Lumina.Application/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/UpdateBookRequestMapping.cs @@ -0,0 +1,42 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Commands.UpdateBook; +using Lumina.Contracts.Requests.MediaLibrary.WrittenContentLibrary.BookLibrary.Books; +using System; +#endregion + +namespace Lumina.Application.Common.Mapping.MediaLibrary.WrittenContentLibrary.BookLibrary.Books; + +/// +/// Extension methods for converting . +/// +public static class UpdateBookRequestMapping +{ + /// + /// Converts to . + /// + /// The request to be converted. + /// The converted command. + public static UpdateBookCommand ToCommand(this UpdateBookRequest request) + { + return new UpdateBookCommand( + Guid.TryParse(request.Id, out Guid bookId) ? bookId : Guid.Empty, + 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/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Artwork/IBookArtworkService.cs b/src/Lumina.Application/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Artwork/IBookArtworkService.cs index 8db5934c..8da5d195 100644 --- a/src/Lumina.Application/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Artwork/IBookArtworkService.cs +++ b/src/Lumina.Application/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Artwork/IBookArtworkService.cs @@ -2,6 +2,7 @@ using Lumina.Contracts.DTO.Common; using Lumina.Domain.Common.Primitives; using System; +using System.IO; using System.Threading; using System.Threading.Tasks; #endregion @@ -26,6 +27,20 @@ public interface IBookArtworkService /// An containing either the relative path of the stored artwork, or an error. Task> SaveBookArtworkAsync(Guid libraryId, Guid bookId, string libraryName, string authorName, string bookTitle, ArtworkDto artwork, CancellationToken cancellationToken); + /// + /// Stores the artwork uploaded in the of the book into the internal media directory, and returns the relative path of the stored artwork. + /// + /// The Id of the media library the book belongs to. + /// The Id of the book. + /// The name of the media library the book belongs to. + /// The name of the author of the book. + /// The title of the book. + /// The stream of the uploaded artwork file. + /// The name of the uploaded artwork file. + /// Cancellation token that can be used to stop the execution. + /// An containing either the relative path of the stored artwork, or an error. + Task> SaveBookArtworkAsync(Guid libraryId, Guid bookId, string libraryName, string authorName, string bookTitle, Stream artworkStream, string fileName, CancellationToken cancellationToken); + /// /// Deletes the artwork of the book from the internal media directory. /// diff --git a/src/Lumina.Application/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Commands/AddBook/AddBookCommandHandler.cs b/src/Lumina.Application/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Commands/AddBook/AddBookCommandHandler.cs index ea190340..fa7e7e5c 100644 --- a/src/Lumina.Application/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Commands/AddBook/AddBookCommandHandler.cs +++ b/src/Lumina.Application/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Commands/AddBook/AddBookCommandHandler.cs @@ -1,26 +1,30 @@ #region ========================================================================= USING ===================================================================================== -using Lumina.Domain.Common.Primitives; using Lumina.Application.Common.CQRS; -using Lumina.Application.Common.DataAccess.Repositories.Books; -using Lumina.Application.Common.DataAccess.UoW; -using Lumina.Application.Common.Mapping.MediaLibrary.WrittenContentLibrary.BookLibrary.Books; +using Lumina.Application.Common.DataAccess.Entities.MediaContributors; using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary; +using Lumina.Application.Common.DataAccess.UoW; +using Lumina.Application.Common.Infrastructure.Authentication; +using Lumina.Application.Common.Infrastructure.Authorization; +using Lumina.Application.Common.Infrastructure.Authorization.Policies.LibraryOwnership; using Lumina.Application.Common.Infrastructure.Validation; -using Lumina.Domain.SharedKernel.Common.Enums.BookLibrary; +using Lumina.Application.Common.Mapping.MediaLibrary.WrittenContentLibrary.BookLibrary.Books; +using Lumina.Contracts.DTO.MediaContributors; using Lumina.Contracts.Responses.MediaLibrary.WrittenContentLibrary.BookLibrary.Books; - +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 Lumina.Domain.Core.BoundedContexts.WrittenContentLibraryBoundedContext.ExternalIdentifiers.LibraryManagementBoundedContext.LibraryAggregate; +using Lumina.Domain.SharedKernel.Common.Enums.BookLibrary; +using Lumina.Domain.SharedKernel.Common.Enums.MediaContributors; using System; using System.Collections.Generic; using System.Linq; using System.Threading; using System.Threading.Tasks; -using Lumina.Contracts.DTO.MediaContributors; +using ApplicationErrors = Lumina.Application.Common.Errors.Errors; #endregion namespace Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Commands.AddBook; @@ -31,16 +35,22 @@ namespace Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BookLibrary public class AddBookCommandHandler : ICommandHandler> { private readonly IUnitOfWork _unitOfWork; + private readonly IAuthorizationService _authorizationService; + private readonly ICurrentUserService _currentUserService; private readonly IValidator _validator; /// /// Initializes a new instance of the class. /// /// Injected unit of work for interacting with the data access layer repositories. + /// Injected service for authorization related functionality. + /// Injected service to retrieve the current user information. /// Injected validator for application validation rules. - public AddBookCommandHandler(IUnitOfWork unitOfWork, IValidator validator) + public AddBookCommandHandler(IUnitOfWork unitOfWork, IAuthorizationService authorizationService, ICurrentUserService currentUserService, IValidator validator) { _unitOfWork = unitOfWork; + _authorizationService = authorizationService; + _currentUserService = currentUserService; _validator = validator; } @@ -58,24 +68,31 @@ public class AddBookCommandHandler : ICommandHandler 0) return validationResult; - // TODO: update Api.Book.md documentation when the functionality is fully implemented - List contributorIds = []; - foreach (MediaContributorDto mediaContributor in command.Contributors!) - { - // TODO: add logic to search the media contributors repository for existing contributors, based on the provided names - } + // An authenticated request must always carry a user identity. + Guid? currentUserId = _currentUserService.UserId; + if (currentUserId is null) + return ApplicationErrors.Authorization.NotAuthorized; + Guid userId = currentUserId.Value; + + // Admins can add books to all libraries; for everyone else, only to the libraries they own. + bool canAccessLibrary = await _authorizationService.EvaluatePolicyAsync( + userId, new LibraryOwnershipPolicyContext(command.LibraryId), cancellationToken).ConfigureAwait(false); + if (!canAccessLibrary) + return ApplicationErrors.Authorization.NotAuthorized; + + // TODO: update Api.Book.md documentation when the functionality is fully implemented. BookSeries? bookSeries = null; if (command.Series != null) { - // TODO: add logic to search the book series repository for existing book series, based on the provided title - // TODO: uncomment integration and unit tests about series + // TODO: add logic to search the book series repository for existing book series, based on the provided title. + // TODO: uncomment integration and unit tests about series. } List> domainRatingsResult = command.Ratings!.ConvertAll(rating => BookRating.Create( rating.Value ?? default, rating.MaxValue ?? default, Optional.FromNullable(rating.Source.HasValue ? (BookRatingSource)(int)rating.Source : (BookRatingSource?)null), Optional.FromNullable(rating.VoteCount))); - // check if any of the results contain errors + // Check if any of the results contain errors. List errors = [.. domainRatingsResult.Where(ratingResult => ratingResult.IsFailure).SelectMany(ratingResult => ratingResult.Errors)]; if (errors.Count != 0) // if there are errors, return them return errors; @@ -147,6 +164,28 @@ public class AddBookCommandHandler : ICommandHandler contributorIds = []; + Dictionary contributorsByDisplayName = []; + foreach (MediaContributorDto contributor in command.Contributors!) + { + if (contributor.Name?.DisplayName is null) + continue; + + if (!contributorsByDisplayName.TryGetValue(contributor.Name.DisplayName, out MediaContributorEntity? contributorEntity)) + { + Result findOrCreateResult = await _unitOfWork.MediaContributorRepository.FindOrCreateByDisplayNameAsync(contributor.Name.DisplayName, contributor.Name.LegalName, cancellationToken).ConfigureAwait(false); + if (findOrCreateResult.IsFailure) + return findOrCreateResult.Errors; + contributorEntity = findOrCreateResult.Value; + contributorsByDisplayName.Add(contributor.Name.DisplayName, contributorEntity); + } + + contributorIds.Add(MediaContributorId.Create(contributorEntity.Id)); + } + Result createBookResult = Book.Create( LibraryId.Create(command.LibraryId), command.Path, @@ -171,12 +210,27 @@ public class AddBookCommandHandler : ICommandHandler contributor.Name?.DisplayName is not null) + .Select(contributor => new BookContributorEntity + { + Id = Guid.NewGuid(), + BookId = persistenceBook.Id, + MediaContributorId = contributorsByDisplayName[contributor.Name!.DisplayName!].Id, + RoleName = contributor.Role?.Name ?? "Contributor", + RoleCategory = contributor.Role?.Category ?? MediaContributorRoleCategory.Other, + CreatedOnUtc = DateTime.UtcNow, + CreatedBy = userId, + UpdatedBy = null + })]; Result insertBookResult = await _unitOfWork.BookRepository.InsertAsync(persistenceBook, cancellationToken).ConfigureAwait(false); if (insertBookResult.IsFailure) return insertBookResult.Errors; await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false); - return persistenceBook.ToResponse(); + return persistenceBook.ToResponse() with { Contributors = command.Contributors }; } } diff --git a/src/Lumina.Application/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Commands/AddBook/AddBookCommandValidator.cs b/src/Lumina.Application/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Commands/AddBook/AddBookCommandValidator.cs index bcad4b8a..498de529 100644 --- a/src/Lumina.Application/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Commands/AddBook/AddBookCommandValidator.cs +++ b/src/Lumina.Application/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Commands/AddBook/AddBookCommandValidator.cs @@ -104,15 +104,7 @@ public class AddBookCommandValidator : AbstractValidator !releaseInfoInstance.OriginalReleaseDate.HasValue || reReleaseDate >= releaseInfoInstance.OriginalReleaseDate) .When(r => r!.ReReleaseDate.HasValue && r.OriginalReleaseDate.HasValue) - .WithError(Errors.Metadata.ReReleaseDateCannotBeEarlierThanOriginalReleaseDate); - - releaseInfo.RuleFor(r => r!.ReReleaseYear) - .Must((releaseInfoInstance, reReleaseYear) => - !releaseInfoInstance!.ReReleaseDate.HasValue || - !releaseInfoInstance.ReReleaseYear.HasValue || - reReleaseYear == releaseInfoInstance.ReReleaseDate.Value.Year) - .When(r => r!.ReReleaseDate.HasValue && r.ReReleaseYear.HasValue) - .WithError(Errors.Metadata.ReReleaseDateAndYearMustMatch); + .WithError(Errors.Metadata.ReReleaseDateCannotBeEarlierThanOriginalReleaseDate); }); metadata.RuleFor(m => m!.Genres) diff --git a/src/Lumina.Application/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Commands/UpdateBook/UpdateBookCommand.cs b/src/Lumina.Application/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Commands/UpdateBook/UpdateBookCommand.cs new file mode 100644 index 00000000..f9650855 --- /dev/null +++ b/src/Lumina.Application/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Commands/UpdateBook/UpdateBookCommand.cs @@ -0,0 +1,55 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.CQRS; +using Lumina.Contracts.DTO.MediaContributors; +using Lumina.Contracts.DTO.MediaLibrary.WrittenContentLibrary; +using Lumina.Contracts.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary; +using Lumina.Domain.SharedKernel.Common.Enums.BookLibrary; +using System; +using System.Collections.Generic; +using System.Diagnostics; +#endregion + +namespace Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Commands.UpdateBook; + +/// +/// Command for updating an existing book. +/// +/// The Id of the book to update. +/// Written content metadata of the book. +/// The format of the book (e.g., Hardcover, Paperback), if applicable. +/// The edition of the book, if applicable. +/// The volume or book number in the series, if applicable. +/// The series name, if the book is part of a series. +/// The ASIN (Amazon Standard Identification Number) of the book, if applicable. +/// The Goodreads ID of the book, if applicable. +/// The Library of Congress Control Number (LCCN) of the book, if applicable. +/// The OCLC Number (WorldCat identifier) of the book, if applicable. +/// The Open Library ID of the book, if applicable. +/// The LibraryThing ID of the book, if applicable. +/// The Google Books ID of the book, if applicable. +/// The Barnes & Noble ID of the book, if applicable. +/// The Apple Books ID of the book, if applicable. +/// The list of ISBN (International Standard Book Number) of the book. +/// The list of media contributors (actors, directors, etc) starring in this book. +/// The list of ratings for this book. +[DebuggerDisplay("Title: {Metadata.Title}")] +public record UpdateBookCommand( + Guid Id, + WrittenContentMetadataDto? Metadata, + BookFormat? Format, + string? Edition, + float? 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 +) : ICommand; diff --git a/src/Lumina.Application/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Commands/UpdateBook/UpdateBookCommandHandler.cs b/src/Lumina.Application/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Commands/UpdateBook/UpdateBookCommandHandler.cs new file mode 100644 index 00000000..c844a210 --- /dev/null +++ b/src/Lumina.Application/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Commands/UpdateBook/UpdateBookCommandHandler.cs @@ -0,0 +1,154 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.CQRS; +using Lumina.Application.Common.DataAccess.Entities.MediaContributors; +using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary; +using Lumina.Application.Common.DataAccess.UoW; +using Lumina.Application.Common.Infrastructure.Authentication; +using Lumina.Application.Common.Infrastructure.Authorization; +using Lumina.Application.Common.Infrastructure.Authorization.Policies.LibraryOwnership; +using Lumina.Application.Common.Infrastructure.Validation; +using Lumina.Application.Common.Mapping.MediaLibrary.WrittenContentLibrary.BookLibrary.Books; +using Lumina.Contracts.DTO.MediaContributors; +using Lumina.Contracts.Responses.MediaLibrary.WrittenContentLibrary.BookLibrary.Books; +using Lumina.Domain.Common.Primitives; +using Lumina.Domain.Core.BoundedContexts.MediaContributorBoundedContext.MediaContributorAggregate.ValueObjects; +using Lumina.Domain.Core.BoundedContexts.WrittenContentLibraryBoundedContext.BookLibraryAggregate; +using Lumina.Domain.SharedKernel.Common.Enums.MediaContributors; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; +using ApplicationErrors = Lumina.Application.Common.Errors.Errors; +using DomainErrors = Lumina.Domain.Common.Errors.Errors; +#endregion + +namespace Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Commands.UpdateBook; + +/// +/// Handler for the command to update an existing book. +/// +public class UpdateBookCommandHandler : ICommandHandler> +{ + private readonly IUnitOfWork _unitOfWork; + private readonly IAuthorizationService _authorizationService; + private readonly ICurrentUserService _currentUserService; + private readonly IValidator _validator; + + /// + /// Initializes a new instance of the class. + /// + /// Injected unit of work for interacting with the data access layer repositories. + /// Injected service for authorization related functionality. + /// Injected service to retrieve the current user information. + /// Injected validator for application validation rules. + public UpdateBookCommandHandler(IUnitOfWork unitOfWork, IAuthorizationService authorizationService, ICurrentUserService currentUserService, IValidator validator) + { + _unitOfWork = unitOfWork; + _authorizationService = authorizationService; + _currentUserService = currentUserService; + _validator = validator; + } + + /// + /// Handles the command to update an existing book. + /// + /// The command to be handled. + /// Cancellation token that can be used to stop the execution. + /// + /// An containing either the updated , or an error message. + /// + public async Task> HandleAsync(UpdateBookCommand command, CancellationToken cancellationToken) + { + List validationResult = _validator.Validate(command); + if (validationResult.Count > 0) + return validationResult; + + // An authenticated request must always carry a user identity. + Guid? currentUserId = _currentUserService.UserId; + if (currentUserId is null) + return ApplicationErrors.Authorization.NotAuthorized; + Guid userId = currentUserId.Value; + + // Get the existing book with all its related data. + Result getBookResult = await _unitOfWork.BookRepository.GetByIdAsync(command.Id, cancellationToken).ConfigureAwait(false); + if (getBookResult.IsFailure) + return getBookResult.Errors; + if (getBookResult.Value is null) + return DomainErrors.WrittenContent.BookNotFound; + BookEntity existingBook = getBookResult.Value; + + // Admins can update the books of all libraries; for everyone else, only the books of the libraries they own. + bool canAccessLibrary = await _authorizationService.EvaluatePolicyAsync( + userId, new LibraryOwnershipPolicyContext(existingBook.LibraryId), cancellationToken).ConfigureAwait(false); + if (!canAccessLibrary) + return ApplicationErrors.Authorization.NotAuthorized; + + // Convert the book to a domain object and apply the edited metadata to it. + Result getDomainBookResult = existingBook.ToDomainEntity(); + if (getDomainBookResult.IsFailure) + return getDomainBookResult.Errors; + Book book = getDomainBookResult.Value; + + Result applyMetadataResult = book.ApplyMetadata(command.ToBookMetadataDto()); + if (applyMetadataResult.IsFailure) + return applyMetadataResult.Errors; + + // Link the media contributors typed by the user to the book, finding or creating a single contributor per person. + List linkedContributors = []; + // A person can be credited under several roles in the same book; each distinct display name must resolve to the same media + // contributor row, otherwise the duplicate inserts would violate the unique display name constraint when the changes are saved. + Dictionary contributorsByDisplayName = []; + foreach (MediaContributorDto contributor in command.Contributors!) + { + if (contributor.Name?.DisplayName is null) + continue; + + if (!contributorsByDisplayName.TryGetValue(contributor.Name.DisplayName, out MediaContributorEntity? contributorEntity)) + { + Result findOrCreateResult = await _unitOfWork.MediaContributorRepository.FindOrCreateByDisplayNameAsync(contributor.Name.DisplayName, contributor.Name.LegalName, cancellationToken).ConfigureAwait(false); + if (findOrCreateResult.IsFailure) + return findOrCreateResult.Errors; + contributorEntity = findOrCreateResult.Value; + contributorsByDisplayName.Add(contributor.Name.DisplayName, contributorEntity); + } + + string roleName = contributor.Role?.Name ?? "Contributor"; + MediaContributorRoleCategory roleCategory = contributor.Role?.Category ?? MediaContributorRoleCategory.Other; + linkedContributors.Add(new BookContributorEntity + { + Id = Guid.NewGuid(), + BookId = existingBook.Id, + MediaContributorId = contributorEntity.Id, + RoleName = roleName, + RoleCategory = roleCategory, + CreatedOnUtc = DateTime.UtcNow, + CreatedBy = userId, + UpdatedBy = null + }); + } + book.UpdateContributors([.. linkedContributors.Select(linkedContributor => MediaContributorId.Create(linkedContributor.MediaContributorId))]); + + // Map the updated domain book onto a fresh repository entity, ready for the repository to replace the stored data. + BookEntity updatedBook = book.ToRepositoryEntity(); + updatedBook.BookContributors = linkedContributors; + updatedBook.UpdatedOnUtc = DateTime.UtcNow; + updatedBook.UpdatedBy = userId; + + // The identity, enrichment and artwork columns are never overwritten by an edit, so they are copied onto the fresh entity that + // backs the response; without this, the response would report the fresh entity defaults (Pending metadata status, no cover path). + updatedBook.CreatedOnUtc = existingBook.CreatedOnUtc; + updatedBook.MetadataStatus = existingBook.MetadataStatus; + updatedBook.LastMetadataUpdateUtc = existingBook.LastMetadataUpdateUtc; + updatedBook.MetadataProvider = existingBook.MetadataProvider; + updatedBook.BookArtwork = existingBook.BookArtwork; + + Result updateResult = await _unitOfWork.BookRepository.UpdateAsync(updatedBook, cancellationToken).ConfigureAwait(false); + if (updateResult.IsFailure) + return updateResult.Errors; + + await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false); + + return updatedBook.ToResponse() with { Contributors = command.Contributors }; + } +} diff --git a/src/Lumina.Application/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Commands/UpdateBook/UpdateBookCommandValidator.cs b/src/Lumina.Application/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Commands/UpdateBook/UpdateBookCommandValidator.cs new file mode 100644 index 00000000..1d57e744 --- /dev/null +++ b/src/Lumina.Application/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Commands/UpdateBook/UpdateBookCommandValidator.cs @@ -0,0 +1,345 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.Infrastructure.Validation; +using Lumina.Application.Common.Utilities; +using Lumina.Domain.Common.Errors; +using Lumina.Domain.SharedKernel.Common.Enums.BookLibrary; +using System; +#endregion + +namespace Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Commands.UpdateBook; + +/// +/// Validates the needed validation rules for . +/// +public class UpdateBookCommandValidator : AbstractValidator +{ + /// + /// Initializes a new instance of the class. + /// + public UpdateBookCommandValidator() + { + RuleFor(command => command.Id) + .NotEmpty() + .WithError(Errors.WrittenContent.BookIdCannotBeEmpty) + .Must(id => id != Guid.Empty) + .WithError(Errors.WrittenContent.BookIdCannotBeEmpty); + + RuleFor(command => command.Metadata) + .NotNull() + .WithError(Errors.Metadata.MetadataCannotBeNull) + .ChildRules(metadata => + { + metadata.RuleFor(m => m!.Title) + .NotEmpty() + .WithError(Errors.Metadata.TitleCannotBeEmpty) + .MaximumLength(255) + .WithError(Errors.Metadata.TitleMustBeMaximum255CharactersLong); + + metadata.RuleFor(m => m!.OriginalTitle) + .MaximumLength(255) + .When(m => m!.OriginalTitle is not null) + .WithError(Errors.Metadata.OriginalTitleMustBeMaximum255CharactersLong); + + metadata.RuleFor(m => m!.Description) + .MaximumLength(2000) + .When(m => m!.Description is not null) + .WithError(Errors.Metadata.DescriptionMustBeMaximum2000CharactersLong); + + metadata.RuleFor(m => m!.ReleaseInfo) + .NotNull() + .WithError(Errors.Metadata.ReleaseInfoCannotBeNull) + .ChildRules(releaseInfo => + { + releaseInfo.RuleFor(r => r!.OriginalReleaseYear) + .InclusiveBetween(1, 9999) + .When(r => r!.OriginalReleaseYear.HasValue) + .WithError(Errors.Metadata.OriginalReleaseYearMustBeBetween1And9999); + + releaseInfo.RuleFor(r => r!.ReReleaseYear) + .InclusiveBetween(1, 9999) + .When(r => r!.ReReleaseYear.HasValue) + .WithError(Errors.Metadata.ReReleaseYearMustBeBetween1And9999); + + releaseInfo.RuleFor(r => r!.ReleaseCountry) + .Matches("^[A-Za-z]{2}$") + .When(r => r!.ReleaseCountry is not null) + .WithError(Errors.Metadata.CountryCodeMustBe2CharactersLong); + + releaseInfo.RuleFor(r => r!.ReleaseVersion) + .MaximumLength(50) + .When(r => r!.ReleaseVersion is not null) + .WithError(Errors.Metadata.ReleaseVersionMustBeMaximum50CharactersLong); + + releaseInfo.RuleFor(r => r!.OriginalReleaseYear) + .Must((releaseInfoInstance, originalReleaseYear) => + !releaseInfoInstance!.OriginalReleaseDate.HasValue || + !releaseInfoInstance.OriginalReleaseYear.HasValue || + originalReleaseYear == releaseInfoInstance.OriginalReleaseDate.Value.Year) + .When(r => r!.OriginalReleaseDate.HasValue && r.OriginalReleaseYear.HasValue) + .WithError(Errors.Metadata.OriginalReleaseDateAndYearMustMatch); + + releaseInfo.RuleFor(r => r!.ReReleaseYear) + .Must((releaseInfoInstance, reReleaseYear) => + !releaseInfoInstance!.ReReleaseDate.HasValue || + !releaseInfoInstance.ReReleaseYear.HasValue || + reReleaseYear == releaseInfoInstance.ReReleaseDate.Value.Year) + .When(r => r!.ReReleaseDate.HasValue && r.ReReleaseYear.HasValue) + .WithError(Errors.Metadata.ReReleaseDateAndYearMustMatch); + + releaseInfo.RuleFor(r => r!.ReReleaseYear) + .Must((releaseInfoInstance, reReleaseYear) => + !releaseInfoInstance!.ReReleaseYear.HasValue || + !releaseInfoInstance.OriginalReleaseYear.HasValue || + reReleaseYear >= releaseInfoInstance.OriginalReleaseYear) + .When(r => r!.ReReleaseYear.HasValue && r.OriginalReleaseYear.HasValue) + .WithError(Errors.Metadata.ReReleaseYearCannotBeEarlierThanOriginalReleaseYear); + + releaseInfo.RuleFor(r => r!.ReReleaseDate) + .Must((releaseInfoInstance, reReleaseDate) => + !releaseInfoInstance!.ReReleaseDate.HasValue || + !releaseInfoInstance.OriginalReleaseDate.HasValue || + reReleaseDate >= releaseInfoInstance.OriginalReleaseDate) + .When(r => r!.ReReleaseDate.HasValue && r.OriginalReleaseDate.HasValue) + .WithError(Errors.Metadata.ReReleaseDateCannotBeEarlierThanOriginalReleaseDate); + }); + + metadata.RuleFor(m => m!.Genres) + .NotNull() + .WithError(Errors.Metadata.GenresListCannotBeNull); + + metadata.RuleForEach(m => m!.Genres) + .ChildRules(genre => + genre.RuleFor(g => g.Name) + .NotEmpty() + .WithError(Errors.Metadata.GenreNameCannotBeEmpty) + .MaximumLength(50) + .WithError(Errors.Metadata.GenreNameMustBeMaximum50CharactersLong)); + + metadata.RuleFor(m => m!.Tags) + .NotNull() + .WithError(Errors.Metadata.TagsListCannotBeNull); + + metadata.RuleForEach(m => m!.Tags) + .ChildRules(tag => + tag.RuleFor(t => t.Name) + .NotEmpty() + .WithError(Errors.Metadata.TagNameCannotBeEmpty) + .MaximumLength(50) + .WithError(Errors.Metadata.TagNameMustBeMaximum50CharactersLong)); + + metadata.RuleFor(m => m!.Language!.LanguageCode) + .NotEmpty() + .WithError(Errors.Metadata.LanguageCodeCannotBeEmpty) + .MaximumLength(2) + .WithError(Errors.Metadata.LanguageCodeMustBe2CharactersLong) + .When(m => m!.Language is not null); + + metadata.RuleFor(m => m!.Language!.LanguageName) + .NotEmpty() + .WithError(Errors.Metadata.LanguageNameCannotBeEmpty) + .MaximumLength(50) + .WithError(Errors.Metadata.LanguageNameMustBeMaximum50CharactersLong) + .When(m => m!.Language is not null); + + metadata.RuleFor(m => m!.Language!.NativeName) + .MaximumLength(50) + .WithError(Errors.Metadata.LanguageNativeNameMustBeMaximum50CharactersLong) + .When(m => m!.Language is not null); + + metadata.RuleFor(m => m!.OriginalLanguage!.LanguageCode) + .NotEmpty() + .WithError(Errors.Metadata.LanguageCodeCannotBeEmpty) + .MaximumLength(2) + .WithError(Errors.Metadata.LanguageCodeMustBe2CharactersLong) + .When(m => m!.OriginalLanguage is not null); + + metadata.RuleFor(m => m!.OriginalLanguage!.LanguageName) + .NotEmpty() + .WithError(Errors.Metadata.LanguageNameCannotBeEmpty) + .MaximumLength(50) + .WithError(Errors.Metadata.LanguageNameMustBeMaximum50CharactersLong) + .When(m => m!.OriginalLanguage is not null); + + metadata.RuleFor(m => m!.OriginalLanguage!.NativeName) + .MaximumLength(50) + .WithError(Errors.Metadata.LanguageNativeNameMustBeMaximum50CharactersLong) + .When(m => m!.OriginalLanguage is not null); + + metadata.RuleFor(m => m!.Publisher) + .MaximumLength(100) + .When(m => m!.Publisher is not null) + .WithError(Errors.WrittenContent.PublisherMustBeMaximum100CharactersLong); + + metadata.RuleFor(m => m!.PageCount) + .GreaterThan(0) + .When(m => m!.PageCount.HasValue) + .WithError(Errors.WrittenContent.PageCountMustBeGreaterThanZero); + }); + + RuleFor(command => command.Format) + .IsInEnum() + .When(command => command.Format is not null) + .WithError(Errors.WrittenContent.UnknownBookFormat); + + RuleFor(command => command.Edition) + .MaximumLength(50) + .When(command => command.Edition is not null) + .WithError(Errors.WrittenContent.EditionMustBeMaximum50CharactersLong); + + RuleFor(command => command.VolumeNumber) + .GreaterThan(0) + .When(command => command.VolumeNumber.HasValue) + .WithError(Errors.WrittenContent.VolumeNumberMustBeGreaterThanZero); + + RuleFor(command => command.Series) + .ChildRules(series => + series.RuleFor(s => s!.Title) + .NotEmpty() + .WithError(Errors.Metadata.TitleCannotBeEmpty) + .MaximumLength(255) + .WithError(Errors.Metadata.TitleMustBeMaximum255CharactersLong)) + .When(command => command.Series is not null); + + RuleFor(command => command.ASIN) + .Length(10) + .When(command => command.ASIN is not null) + .WithError(Errors.WrittenContent.AsinMustBe10CharactersLong); + + RuleFor(command => command.GoodreadsId) + .Matches(@"^\d+$") + .When(command => command.GoodreadsId is not null) + .WithError(Errors.WrittenContent.GoodreadsIdMustBeNumeric); + + RuleFor(command => command.LCCN) + .Matches(@"^[a-z]{0,3}\d{8,10}$") + .When(command => command.LCCN is not null) + .WithError(Errors.WrittenContent.InvalidLccnFormat); + + RuleFor(command => command.OCLCNumber) + .Matches(@"^(ocm\d{8}|ocn\d{9,}|on\d{10,}|\(OCoLC\)\d{8,}|\d{8,})$") + .When(command => command.OCLCNumber is not null) + .WithError(Errors.WrittenContent.InvalidOclcFormat); + + RuleFor(command => command.OpenLibraryId) + .Matches(@"^OL[1-9]\d*[AMW]$") + .When(command => command.OpenLibraryId is not null) + .WithError(Errors.WrittenContent.InvalidOpenLibraryId); + + RuleFor(command => command.LibraryThingId) + .MaximumLength(50) + .When(command => command.LibraryThingId is not null) + .WithError(Errors.WrittenContent.LibraryThingIdMustBeMaximum50CharactersLong); + + RuleFor(command => command.GoogleBooksId) + .Length(12) + .When(command => command.GoogleBooksId is not null) + .WithError(Errors.WrittenContent.GoogleBooksIdMustBe12CharactersLong) + .Matches(@"^[A-Za-z0-9_-]{12}$") + .When(command => command.GoogleBooksId is not null) + .WithError(Errors.WrittenContent.InvalidGoogleBooksIdFormat); + + RuleFor(command => command.BarnesAndNobleId) + .Length(10) + .When(command => command.BarnesAndNobleId is not null) + .WithError(Errors.WrittenContent.BarnesAndNoblesIdMustBe10CharactersLong) + .Matches(@"^\d{10}$") + .When(command => command.BarnesAndNobleId is not null) + .WithError(Errors.WrittenContent.InvalidBarnesAndNoblesIdFormat); + + RuleFor(command => command.AppleBooksId) + .Matches(@"^id\d+$") + .When(command => command.AppleBooksId is not null) + .WithError(Errors.WrittenContent.InvalidAppleBooksIdFormat); + + RuleFor(command => command.ISBNs) + .NotNull() + .WithError(Errors.WrittenContent.IsbnListCannotBeNull); + + RuleForEach(command => command.ISBNs) + .ChildRules(isbn => + { + isbn.RuleFor(i => i.Value) + .NotEmpty() + .WithError(Errors.WrittenContent.IsbnValueCannotBeEmpty); + + isbn.RuleFor(i => i.Value) + .Matches(@"^(?:ISBN(?:-13)?:? )?(?=[0-9]{13}$|(?=(?:[0-9]+[-\ ]){4})[-\ 0-9]{17}$)97[89][-\ ]?[0-9]{1,5}[-\ ]?[0-9]+[-\ ]?[0-9]+[-\ ]?[0-9]$") + .When(i => i.Format == IsbnFormat.Isbn13) + .WithError(Errors.WrittenContent.InvalidIsbn13Format); + + isbn.RuleFor(i => i.Value) + .Matches(@"^(?:ISBN(?:-10)?:? )?(?=[0-9X]{10}$|(?=(?:[0-9]+[-\ ]){3})[-\ 0-9X]{13}$)[0-9]{1,5}[-\ ]?[0-9]+[-\ ]?[0-9]+[-\ ]?[0-9X]$") + .When(i => i.Format == IsbnFormat.Isbn10) + .WithError(Errors.WrittenContent.InvalidIsbn10Format); + + isbn.RuleFor(i => i.Format) + .IsInEnum() + .WithError(Errors.WrittenContent.UnknownIsbnFormat); + }); + + RuleFor(command => command.Contributors) + .NotNull() + .WithError(Errors.MediaContributor.ContributorsListCannotBeNull); + + RuleForEach(command => command.Contributors) + .ChildRules(contributor => + { + contributor.RuleFor(c => c.Name) + .NotNull() + .WithError(Errors.MediaContributor.ContributorNameCannotBeEmpty) + .ChildRules(name => + { + name.RuleFor(n => n!.DisplayName) + .NotNull() + .WithError(Errors.MediaContributor.ContributorDisplayNameCannotBeEmpty) + .NotEmpty() + .WithError(Errors.MediaContributor.ContributorDisplayNameCannotBeEmpty) + .MaximumLength(100) + .WithError(Errors.MediaContributor.ContributorDisplayNameMustBeMaximum100CharactersLong); + + name.RuleFor(n => n!.LegalName) + .MaximumLength(100) + .When(n => n!.LegalName is not null) + .WithError(Errors.MediaContributor.ContributorLegalNameMustBeMaximum100CharactersLong); + }); + + contributor.RuleFor(c => c.Role) + .NotNull() + .WithError(Errors.MediaContributor.ContributorRoleCannotBeNull) + .ChildRules(role => + { + role.RuleFor(r => r!.Name) + .NotEmpty() + .WithError(Errors.MediaContributor.RoleNameCannotBeEmpty) + .MaximumLength(50) + .WithError(Errors.MediaContributor.RoleNameMustBeMaximum50CharactersLong); + role.RuleFor(r => r!.Category) + .NotEmpty() + .WithError(Errors.MediaContributor.RoleCategoryCannotBeEmpty); + }); + }); + + RuleFor(command => command.Ratings) + .NotNull() + .WithError(Errors.Metadata.RatingsListCannotBeNull); + + RuleForEach(command => command.Ratings) + .ChildRules(rating => + { + rating.RuleFor(r => r.Value) + .GreaterThan(0) + .WithError(Errors.Metadata.RatingValueMustBePositive) + .Must((ratingInstance, value) => value <= ratingInstance.MaxValue) + .WithError(Errors.Metadata.RatingValueCannotBeGreaterThanMaxValue); + + rating.RuleFor(r => r.MaxValue) + .GreaterThan(0) + .WithError(Errors.Metadata.RatingMaxValueMustBePositive); + + rating.RuleFor(r => r.VoteCount) + .GreaterThanOrEqualTo(0) + .When(r => r.VoteCount.HasValue) + .WithError(Errors.Metadata.RatingVoteCountMustBePositive); + }); + } +} diff --git a/src/Lumina.Application/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Commands/UpdateBookCover/UpdateBookCoverCommand.cs b/src/Lumina.Application/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Commands/UpdateBookCover/UpdateBookCoverCommand.cs new file mode 100644 index 00000000..9921e03d --- /dev/null +++ b/src/Lumina.Application/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Commands/UpdateBookCover/UpdateBookCoverCommand.cs @@ -0,0 +1,21 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.CQRS; +using System; +using System.Diagnostics; +using System.IO; +#endregion + +namespace Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Commands.UpdateBookCover; + +/// +/// Command for updating the cover image of an existing book. +/// +/// The Id of the book whose cover image is updated. +/// The stream of the uploaded cover image file. +/// The name of the uploaded cover image file. +[DebuggerDisplay("BookId: {BookId} FileName: {FileName}")] +public record UpdateBookCoverCommand( + Guid BookId, + Stream? Cover, + string? FileName +) : ICommand; diff --git a/src/Lumina.Application/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Commands/UpdateBookCover/UpdateBookCoverCommandHandler.cs b/src/Lumina.Application/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Commands/UpdateBookCover/UpdateBookCoverCommandHandler.cs new file mode 100644 index 00000000..df4d26db --- /dev/null +++ b/src/Lumina.Application/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Commands/UpdateBookCover/UpdateBookCoverCommandHandler.cs @@ -0,0 +1,161 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.CQRS; +using Lumina.Application.Common.DataAccess.Entities.MediaContributors; +using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management; +using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary; +using Lumina.Application.Common.DataAccess.UoW; +using Lumina.Application.Common.Infrastructure.Authentication; +using Lumina.Application.Common.Infrastructure.Authorization; +using Lumina.Application.Common.Infrastructure.Authorization.Policies.LibraryOwnership; +using Lumina.Application.Common.Infrastructure.Validation; +using Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Artwork; +using Lumina.Domain.Common.Primitives; +using Lumina.Domain.SharedKernel.Common.Enums.BookLibrary; +using Lumina.Domain.SharedKernel.Common.Enums.MediaContributors; +using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; +using ApplicationErrors = Lumina.Application.Common.Errors.Errors; +using DomainErrors = Lumina.Domain.Common.Errors.Errors; +#endregion + +namespace Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Commands.UpdateBookCover; + +/// +/// Handler for the command to update the cover image of an existing book. +/// +public class UpdateBookCoverCommandHandler : ICommandHandler> +{ + private readonly IUnitOfWork _unitOfWork; + private readonly IBookArtworkService _bookArtworkService; + private readonly IAuthorizationService _authorizationService; + private readonly ICurrentUserService _currentUserService; + private readonly IValidator _validator; + + /// + /// Initializes a new instance of the class. + /// + /// Injected unit of work for interacting with the data access layer repositories. + /// Injected service for storing the artwork of a book. + /// Injected service for authorization related functionality. + /// Injected service to retrieve the current user information. + /// Injected validator for application validation rules. + public UpdateBookCoverCommandHandler(IUnitOfWork unitOfWork, IBookArtworkService bookArtworkService, IAuthorizationService authorizationService, ICurrentUserService currentUserService, IValidator validator) + { + _unitOfWork = unitOfWork; + _bookArtworkService = bookArtworkService; + _authorizationService = authorizationService; + _currentUserService = currentUserService; + _validator = validator; + } + + /// + /// Handles the command to update the cover image of an existing book. + /// + /// The command to be handled. + /// Cancellation token that can be used to stop the execution. + /// + /// An containing either the relative path of the stored cover image, or an error message. + /// + public async Task> HandleAsync(UpdateBookCoverCommand command, CancellationToken cancellationToken) + { + List validationResult = _validator.Validate(command); + if (validationResult.Count > 0) + return validationResult; + + // An authenticated request must always carry a user identity. + Guid? currentUserId = _currentUserService.UserId; + if (currentUserId is null) + return ApplicationErrors.Authorization.NotAuthorized; + Guid userId = currentUserId.Value; + + // Get the existing book with its artwork. + Result getBookResult = await _unitOfWork.BookRepository.GetByIdAsync(command.BookId, cancellationToken).ConfigureAwait(false); + if (getBookResult.IsFailure) + return getBookResult.Errors; + if (getBookResult.Value is null) + return DomainErrors.WrittenContent.BookNotFound; + BookEntity existingBook = getBookResult.Value; + + // Admins can update the books of all libraries; for everyone else, only the books of the libraries they own. + bool canAccessLibrary = await _authorizationService.EvaluatePolicyAsync( + userId, new LibraryOwnershipPolicyContext(existingBook.LibraryId), cancellationToken).ConfigureAwait(false); + if (!canAccessLibrary) + return ApplicationErrors.Authorization.NotAuthorized; + + // The artwork is stored under the library and author segments, so their names are resolved to keep the location consistent with the scanned artwork. + Result getLibraryResult = await _unitOfWork.LibraryRepository.GetByIdAsync(existingBook.LibraryId, cancellationToken).ConfigureAwait(false); + if (getLibraryResult.IsFailure) + return getLibraryResult.Errors; + if (getLibraryResult.Value is null) + return DomainErrors.Library.LibraryNotFound; + string libraryName = getLibraryResult.Value.Title; + string authorName = await GetAuthorNameAsync(existingBook, cancellationToken).ConfigureAwait(false); + + Result storeArtworkResult = await _bookArtworkService.SaveBookArtworkAsync( + existingBook.LibraryId, + existingBook.Id, + libraryName, + authorName, + existingBook.Title, + command.Cover!, + command.FileName!, + cancellationToken).ConfigureAwait(false); + if (storeArtworkResult.IsFailure) + return storeArtworkResult.Errors; + + // Update the stored cover artwork of the book with the newly stored image. + BookArtworkEntity? coverArtwork = existingBook.BookArtwork.FirstOrDefault(artwork => artwork.ArtworkType == ArtworkType.Cover); + if (coverArtwork is null) + { + existingBook.BookArtwork.Add(new BookArtworkEntity + { + Id = Guid.NewGuid(), + BookId = existingBook.Id, + ArtworkType = ArtworkType.Cover, + Ordinal = 0, + FileName = storeArtworkResult.Value, + Status = ArtworkStatus.Enriched, + CreatedOnUtc = DateTime.UtcNow, + CreatedBy = userId, + UpdatedBy = null + }); + } + else + { + coverArtwork.FileName = storeArtworkResult.Value; + coverArtwork.Status = ArtworkStatus.Enriched; + coverArtwork.LastUpdateUtc = DateTime.UtcNow; + coverArtwork.UpdatedOnUtc = DateTime.UtcNow; + coverArtwork.UpdatedBy = userId; + } + + await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false); + + return storeArtworkResult.Value; + } + + /// + /// Gets the display name of the author of the , used to build the artwork storage path, or an empty string when the book has no author. + /// + /// The book whose author is retrieved. + /// Cancellation token that can be used to stop the execution. + /// The display name of the author of the book, or an empty string. + private async Task GetAuthorNameAsync(BookEntity book, CancellationToken cancellationToken) + { + IReadOnlyCollection authorIds = [.. book.BookContributors + .Where(participation => participation.RoleCategory == MediaContributorRoleCategory.Author) + .Select(participation => participation.MediaContributorId) + .Distinct()]; + if (authorIds.Count == 0) + return string.Empty; + + Result> getContributorsResult = await _unitOfWork.MediaContributorRepository.GetByIdsAsync(authorIds, cancellationToken).ConfigureAwait(false); + if (getContributorsResult.IsFailure) + return string.Empty; + return getContributorsResult.Value.Select(contributor => contributor.DisplayName).FirstOrDefault() ?? string.Empty; + } +} diff --git a/src/Lumina.Application/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Commands/UpdateBookCover/UpdateBookCoverCommandValidator.cs b/src/Lumina.Application/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Commands/UpdateBookCover/UpdateBookCoverCommandValidator.cs new file mode 100644 index 00000000..3333a4e4 --- /dev/null +++ b/src/Lumina.Application/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Commands/UpdateBookCover/UpdateBookCoverCommandValidator.cs @@ -0,0 +1,30 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.Infrastructure.Validation; +using Lumina.Application.Common.Utilities; +using Lumina.Domain.Common.Errors; +using System; +#endregion + +namespace Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Commands.UpdateBookCover; + +/// +/// Validates the needed validation rules for . +/// +public class UpdateBookCoverCommandValidator : AbstractValidator +{ + /// + /// Initializes a new instance of the class. + /// + public UpdateBookCoverCommandValidator() + { + RuleFor(command => command.BookId) + .NotEmpty() + .WithError(Errors.WrittenContent.BookIdCannotBeEmpty) + .Must(id => id != Guid.Empty) + .WithError(Errors.WrittenContent.BookIdCannotBeEmpty); + + RuleFor(command => command.Cover) + .NotNull() + .WithError(Errors.WrittenContent.BookCoverCannotBeNull); + } +} diff --git a/src/Lumina.Application/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Queries/GetBook/GetBookQuery.cs b/src/Lumina.Application/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Queries/GetBook/GetBookQuery.cs new file mode 100644 index 00000000..e4ed13d0 --- /dev/null +++ b/src/Lumina.Application/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Queries/GetBook/GetBookQuery.cs @@ -0,0 +1,14 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.CQRS; +using System; +#endregion + +namespace Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Queries.GetBook; + +/// +/// Query for getting a book by its Id. +/// +/// The Id of the book to get. +public record GetBookQuery( + Guid Id +) : IQuery; diff --git a/src/Lumina.Application/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Queries/GetBook/GetBookQueryHandler.cs b/src/Lumina.Application/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Queries/GetBook/GetBookQueryHandler.cs new file mode 100644 index 00000000..683bd388 --- /dev/null +++ b/src/Lumina.Application/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Queries/GetBook/GetBookQueryHandler.cs @@ -0,0 +1,122 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.CQRS; +using Lumina.Application.Common.DataAccess.Entities.MediaContributors; +using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary; +using Lumina.Application.Common.DataAccess.UoW; +using Lumina.Application.Common.Infrastructure.Authentication; +using Lumina.Application.Common.Infrastructure.Authorization; +using Lumina.Application.Common.Infrastructure.Authorization.Policies.LibraryOwnership; +using Lumina.Application.Common.Infrastructure.Validation; +using Lumina.Application.Common.Mapping.MediaLibrary.WrittenContentLibrary.BookLibrary.Books; +using Lumina.Contracts.DTO.MediaContributors; +using Lumina.Contracts.Responses.MediaLibrary.WrittenContentLibrary.BookLibrary.Books; +using Lumina.Domain.Common.Primitives; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; +using ApplicationErrors = Lumina.Application.Common.Errors.Errors; +using DomainErrors = Lumina.Domain.Common.Errors.Errors; +#endregion + +namespace Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Queries.GetBook; + +/// +/// Handler for the query to get a book by its Id. +/// +public class GetBookQueryHandler : IQueryHandler> +{ + private readonly IUnitOfWork _unitOfWork; + private readonly IAuthorizationService _authorizationService; + private readonly ICurrentUserService _currentUserService; + private readonly IValidator _validator; + + /// + /// Initializes a new instance of the class. + /// + /// Injected unit of work for interacting with the data access layer repositories. + /// Injected service for authorization related functionality. + /// Injected service to retrieve the current user information. + /// Injected validator for application validation rules. + public GetBookQueryHandler(IUnitOfWork unitOfWork, IAuthorizationService authorizationService, ICurrentUserService currentUserService, IValidator validator) + { + _unitOfWork = unitOfWork; + _authorizationService = authorizationService; + _currentUserService = currentUserService; + _validator = validator; + } + + /// + /// Handles the query to get a book by its Id. + /// + /// The query to be handled. + /// Cancellation token that can be used to stop the execution. + /// + /// An containing either the requested , or an error message. + /// + public async Task> HandleAsync(GetBookQuery query, CancellationToken cancellationToken) + { + List validationResult = _validator.Validate(query); + if (validationResult.Count > 0) + return validationResult; + + // An authenticated request must always carry a user identity. + Guid? currentUserId = _currentUserService.UserId; + if (currentUserId is null) + return ApplicationErrors.Authorization.NotAuthorized; + Guid userId = currentUserId.Value; + + // Get the book with the specified id from the repository. + Result getBookResult = await _unitOfWork.BookRepository.GetByIdAsync(query.Id, cancellationToken).ConfigureAwait(false); + if (getBookResult.IsFailure) + return getBookResult.Errors; + if (getBookResult.Value is null) + return DomainErrors.WrittenContent.BookNotFound; + + // Admins can see the books of all libraries; for everyone else, only the books of the libraries they own. + bool canAccessLibrary = await _authorizationService.EvaluatePolicyAsync( + userId, new LibraryOwnershipPolicyContext(getBookResult.Value.LibraryId), cancellationToken).ConfigureAwait(false); + if (!canAccessLibrary) + return ApplicationErrors.Authorization.NotAuthorized; + + BookResponse response = getBookResult.Value.ToResponse(); + + // The response carries the resolved contributor names, so that the clients can display them without querying the contributors themselves. + List contributors = await GetContributorsAsync(getBookResult.Value, cancellationToken).ConfigureAwait(false); + if (contributors.Count == 0) + return response; + + Dictionary contributorsById = contributors.ToDictionary(contributor => contributor.Id); + List contributorResponses = []; + foreach (BookContributorEntity participation in getBookResult.Value.BookContributors) + { + if (!contributorsById.TryGetValue(participation.MediaContributorId, out MediaContributorEntity? contributor)) + continue; + contributorResponses.Add(new MediaContributorDto( + new MediaContributorNameDto(contributor.DisplayName, contributor.LegalName), + new MediaContributorRoleDto(participation.RoleName, participation.RoleCategory) + )); + } + + return response with { Contributors = contributorResponses }; + } + + /// + /// Gets the media contributors linked to the book of , by their unique identifiers. + /// + /// The book whose media contributors are retrieved. + /// Cancellation token that can be used to stop the execution. + /// An containing either the media contributors of the book, or an error. + private async Task> GetContributorsAsync(BookEntity book, CancellationToken cancellationToken) + { + IReadOnlyCollection contributorIds = [.. book.BookContributors.Select(participation => participation.MediaContributorId).Distinct()]; + if (contributorIds.Count == 0) + return []; + + Result> getContributorsResult = await _unitOfWork.MediaContributorRepository.GetByIdsAsync(contributorIds, cancellationToken).ConfigureAwait(false); + if (getContributorsResult.IsFailure) + return []; + return [.. getContributorsResult.Value]; + } +} diff --git a/src/Lumina.Application/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Queries/GetBook/GetBookQueryValidator.cs b/src/Lumina.Application/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Queries/GetBook/GetBookQueryValidator.cs new file mode 100644 index 00000000..43ba1eaa --- /dev/null +++ b/src/Lumina.Application/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Queries/GetBook/GetBookQueryValidator.cs @@ -0,0 +1,26 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.Infrastructure.Validation; +using Lumina.Application.Common.Utilities; +using Lumina.Domain.Common.Errors; +using System; +#endregion + +namespace Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Queries.GetBook; + +/// +/// Validates the needed validation rules for . +/// +public class GetBookQueryValidator : AbstractValidator +{ + /// + /// Initializes a new instance of the class. + /// + public GetBookQueryValidator() + { + RuleFor(query => query.Id) + .NotEmpty() + .WithError(Errors.WrittenContent.BookIdCannotBeEmpty) + .Must(id => id != Guid.Empty) + .WithError(Errors.WrittenContent.BookIdCannotBeEmpty); + } +} diff --git a/src/Lumina.Contracts/Requests/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/UpdateBookRequest.cs b/src/Lumina.Contracts/Requests/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/UpdateBookRequest.cs new file mode 100644 index 00000000..192ed038 --- /dev/null +++ b/src/Lumina.Contracts/Requests/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/UpdateBookRequest.cs @@ -0,0 +1,53 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Contracts.DTO.MediaContributors; +using Lumina.Contracts.DTO.MediaLibrary.WrittenContentLibrary; +using Lumina.Contracts.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary; +using Lumina.Domain.SharedKernel.Common.Enums.BookLibrary; +using System.Collections.Generic; +using System.Diagnostics; +#endregion + +namespace Lumina.Contracts.Requests.MediaLibrary.WrittenContentLibrary.BookLibrary.Books; + +/// +/// Represents a request to update an existing book. +/// +/// The Id of the book to update, taken from the route. Required. +/// Written content metadata of the book. Required. +/// The format of the book (e.g., Hardcover, Paperback). Optional. +/// The edition of the book. Optional. +/// The volume or book number in the series. Optional. +/// The series name, if the book is part of a series. Optional. +/// The ASIN (Amazon Standard Identification Number) of the book. Optional. +/// The Goodreads Id of the book. Optional. +/// The Library of Congress Control Number (LCCN) of the book. Optional. +/// The OCLC Number (WorldCat identifier) of the book. Optional. +/// The Open Library Id of the book. Optional. +/// The LibraryThing Id of the book. Optional. +/// The Google Books Id of the book. Optional. +/// The Barnes & Noble Id of the book. Optional. +/// The Apple Books Id of the book. Optional. +/// The list of ISBN (International Standard Book Number) of the book. Required. +/// The list of media contributors (actors, directors, etc) starring in this book. Required. +/// The list of ratings for this book. Required. +[DebuggerDisplay("Title: {Metadata.Title}")] +public record UpdateBookRequest( + string? Id, + WrittenContentMetadataDto? Metadata, + BookFormat? Format, + string? Edition, + float? 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 +); diff --git a/src/Lumina.DataAccess/Core/Repositories/Books/BookRepository.cs b/src/Lumina.DataAccess/Core/Repositories/Books/BookRepository.cs index 054a10f7..ecda2029 100644 --- a/src/Lumina.DataAccess/Core/Repositories/Books/BookRepository.cs +++ b/src/Lumina.DataAccess/Core/Repositories/Books/BookRepository.cs @@ -58,7 +58,7 @@ internal sealed class BookRepository : IBookRepository if (bookExists) return Errors.WrittenContent.BookAlreadyExists; - // fetch existing tags and genres + // Fetch existing tags and genres. List existingTags = await _luminaDbContext.Set() .Where(t => book.Tags.Select(bt => bt.Name).Contains(t.Name)) .ToListAsync(cancellationToken).ConfigureAwait(false); @@ -67,7 +67,7 @@ internal sealed class BookRepository : IBookRepository .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 + // Replace tags and genres in the book with existing ones. book.Tags = [.. book.Tags.Select(tag => existingTags.FirstOrDefault(existingTag => existingTag.Name == tag.Name) ?? tag)]; book.Genres = [.. book.Genres.Select(genre => existingGenres.FirstOrDefault(existingGenre => existingGenre.Name == genre.Name) ?? genre)]; @@ -87,6 +87,8 @@ internal sealed class BookRepository : IBookRepository .Include(book => book.Tags) .Include(book => book.Genres) .Include(book => book.ISBNs) + .Include(book => book.Ratings) + .Include(book => book.BookContributors) .Include(book => book.BookArtwork) .FirstOrDefaultAsync(book => book.Id == id, cancellationToken).ConfigureAwait(false); } @@ -102,6 +104,8 @@ internal sealed class BookRepository : IBookRepository .Include(book => book.Tags) .Include(book => book.Genres) .Include(book => book.ISBNs) + .Include(book => book.Ratings) + .Include(book => book.BookContributors) .Include(book => book.BookArtwork) .ToListAsync(cancellationToken).ConfigureAwait(false); } @@ -126,21 +130,21 @@ internal sealed class BookRepository : IBookRepository .Include(book => book.BookArtwork) .AsNoTracking(); - // books should always be retrieved only per owning libraries + // Books should always be retrieved only per owning libraries. if (filterModel is not LibraryFilterDto libraryFilter || libraryFilter.LibraryId == Guid.Empty) return Errors.Library.FilterMustIncludeLibraryId; booksQuery = booksQuery.Where(book => book.LibraryId == libraryFilter.LibraryId); FilterSpecification? filterSpecification = BuildFilterSpecification(libraryFilter); - // apply filtering + // Apply filtering. if (filterSpecification is not null) booksQuery = booksQuery.Where(filterSpecification.ToExpression()); - // apply sorting based on the specified sortBy and sortOrder parameters + // Apply sorting based on the specified sortBy and sortOrder parameters. booksQuery = ApplySorting(booksQuery, sortBy, sortOrder ?? SortOrder.Ascending, libraryFilter.ShouldIgnoreThePrefixForAlphaPicker); - // if no pagination was requested, return all the books of the library + // If no pagination was requested, return all the books of the library. if (paginationData is null) { IReadOnlyList allBooks = await booksQuery.ToListAsync(cancellationToken).ConfigureAwait(false); @@ -156,9 +160,9 @@ internal sealed class BookRepository : IBookRepository int count = await booksQuery.Select(book => book.Id).CountAsync(cancellationToken).ConfigureAwait(false); int numberOfPages = (int)Math.Ceiling((double)count / paginationData.PerPage); - int currentPage = Math.Min(paginationData.CurrentPage, Math.Max(1, numberOfPages)); // make sure current page doesn't exceed maximum number of pages + int currentPage = Math.Min(paginationData.CurrentPage, Math.Max(1, numberOfPages)); // Make sure current page doesn't exceed maximum number of pages. - // apply pagination + // Apply pagination. IReadOnlyList paginatedResult = await booksQuery .Skip((currentPage - 1) * paginationData.PerPage) .Take(paginationData.PerPage) @@ -359,7 +363,7 @@ internal sealed class BookRepository : IBookRepository return authorRows .GroupBy(row => row.BookId) - .ToDictionary(group => group.Key, group => (string?)group.Min(row => row.DisplayName)); + .ToDictionary(group => group.Key, group => group.Min(row => row.DisplayName)); } /// @@ -387,9 +391,9 @@ internal sealed class BookRepository : IBookRepository } /// - /// Updates a book. + /// Updates a book, replacing its editable data while preserving its identity, enrichment and audit columns. /// - /// The book to update. + /// The book whose editable data is applied to the stored book. /// Cancellation token that can be used to stop the execution. /// An representing either a successful operation, or an error. public async Task> UpdateAsync(BookEntity data, CancellationToken cancellationToken) @@ -398,11 +402,52 @@ internal sealed class BookRepository : IBookRepository .Include(book => book.Tags) .Include(book => book.Genres) .Include(book => book.ISBNs) + .Include(book => book.Ratings) + .Include(book => book.BookContributors) .FirstOrDefaultAsync(book => book.Id == data.Id, cancellationToken).ConfigureAwait(false); if (foundBook is null) return Errors.WrittenContent.BookNotFound; - // update the scalar properties of the book + + // The stored enrichment and identity columns are never overwritten by an edit: they are owned by the scan and by the record itself. + Guid libraryId = foundBook.LibraryId; + string path = foundBook.Path; + MetadataStatus metadataStatus = foundBook.MetadataStatus; + DateTime? lastMetadataUpdateUtc = foundBook.LastMetadataUpdateUtc; + string? metadataProvider = foundBook.MetadataProvider; + DateTime createdOnUtc = foundBook.CreatedOnUtc; + Guid createdBy = foundBook.CreatedBy; + + // Copy the editable scalar properties of the book, ignoring the unchanged collection and enrichment columns. _luminaDbContext.Entry(foundBook).CurrentValues.SetValues(data); + foundBook.LibraryId = libraryId; + foundBook.Path = path; + foundBook.MetadataStatus = metadataStatus; + foundBook.LastMetadataUpdateUtc = lastMetadataUpdateUtc; + foundBook.MetadataProvider = metadataProvider; + foundBook.CreatedOnUtc = createdOnUtc; + foundBook.CreatedBy = createdBy; + + // Reuse the stored tags and genres whose names already exist, so that the shared tables are not duplicated. + List existingTags = await _luminaDbContext.Set() + .Where(tag => data.Tags.Select(bookTag => bookTag.Name).Contains(tag.Name)) + .ToListAsync(cancellationToken).ConfigureAwait(false); + List existingGenres = await _luminaDbContext.Set() + .Where(genre => data.Genres.Select(bookGenre => bookGenre.Name).Contains(genre.Name)) + .ToListAsync(cancellationToken).ConfigureAwait(false); + + foundBook.Tags.Clear(); + foundBook.Tags.UnionWith(data.Tags.Select(tag => existingTags.FirstOrDefault(existingTag => existingTag.Name == tag.Name) ?? tag)); + foundBook.Genres.Clear(); + foundBook.Genres.UnionWith(data.Genres.Select(genre => existingGenres.FirstOrDefault(existingGenre => existingGenre.Name == genre.Name) ?? genre)); + + // Replace the owned collections of the book, so that removed entries are deleted and new entries are inserted. + foundBook.ISBNs.Clear(); + foundBook.ISBNs.AddRange(data.ISBNs); + foundBook.Ratings.Clear(); + foundBook.Ratings.AddRange(data.Ratings); + foundBook.BookContributors.Clear(); + foundBook.BookContributors.AddRange(data.BookContributors); + return Result.Updated; } @@ -445,7 +490,7 @@ internal sealed class BookRepository : IBookRepository Expression titleProperty = Expression.Property(book, nameof(BookEntity.Title)); - // the raw title: the title, unless it is null or empty, in which case the original title (or an empty string) is used + // The raw title: the title, unless it is null or empty, in which case the original title (or an empty string) is used. BinaryExpression isTitleMissing = Expression.OrElse( Expression.Equal(titleProperty, Expression.Constant(null, typeof(string))), Expression.Equal(titleProperty, Expression.Constant(string.Empty))); @@ -455,7 +500,7 @@ internal sealed class BookRepository : IBookRepository MethodCallExpression lowerTitle = Expression.Call(rawTitle, s_toLowerMethod); - // when ignoring the "The " prefix, strip a leading "the " from the lowercased title + // When ignoring the "The " prefix, strip a leading "the " from the lowercased title. Expression effectiveTitle = lowerTitle; if (shouldIgnoreThePrefixForAlphaPicker) { @@ -476,11 +521,11 @@ internal sealed class BookRepository : IBookRepository { FilterSpecification? filterSpecification = null; - // include the search term filter, if provided + // Include the search term filter, if provided. if (!string.IsNullOrWhiteSpace(libraryFilter.SearchTerm)) filterSpecification = new BookSearchSpecification(libraryFilter.SearchTerm); - // include the alpha key filter, if provided + // Include the alpha key filter, if provided. if (libraryFilter.FilterAlphaKey is not null) { BookAlphaFilterSpecification alphaFilterSpecification = new(libraryFilter.FilterAlphaKey, libraryFilter.ShouldIgnoreThePrefixForAlphaPicker); diff --git a/src/Lumina.Domain/Common/Errors/Errors.WrittenContent.cs b/src/Lumina.Domain/Common/Errors/Errors.WrittenContent.cs index ac637464..a31b8da5 100644 --- a/src/Lumina.Domain/Common/Errors/Errors.WrittenContent.cs +++ b/src/Lumina.Domain/Common/Errors/Errors.WrittenContent.cs @@ -37,6 +37,8 @@ public static partial class Errors public static Error VolumeNumberMustBeGreaterThanZero => Error.Validation(description: nameof(VolumeNumberMustBeGreaterThanZero)); public static Error BookLibraryCannotBeNull => Error.Validation(description: nameof(BookLibraryCannotBeNull)); public static Error BookPathCannotBeEmpty => Error.Validation(description: nameof(BookPathCannotBeEmpty)); + public static Error BookIdCannotBeEmpty => Error.Validation(description: nameof(BookIdCannotBeEmpty)); + public static Error BookCoverCannotBeNull => Error.Validation(description: nameof(BookCoverCannotBeNull)); public static Error BookNotFound => Error.NotFound(description: nameof(BookNotFound)); } } diff --git a/src/Lumina.Domain/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Services/FileProviderService.cs b/src/Lumina.Domain/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Services/FileProviderService.cs index 84eb7e05..452e3667 100644 --- a/src/Lumina.Domain/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Services/FileProviderService.cs +++ b/src/Lumina.Domain/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Services/FileProviderService.cs @@ -247,9 +247,7 @@ internal class FileProviderService : IFileProviderService Result newFilePathResult = FileSystemPathId.Create(newFile); if (newFilePathResult.IsFailure) return newFilePathResult.Errors; - // check if the user has access permissions to the provided path - if (!_fileSystemPermissionsService.CanAccessPath(path, FileAccessMode.Execute)) - return Errors.Permission.UnauthorizedAccess; + // renaming a file only requires write access to its parent directory, never execute access to the file itself if (!_fileSystemPermissionsService.CanAccessPath(parendDirectoryResult.Value, FileAccessMode.Write)) return Errors.Permission.UnauthorizedAccess; _fileSystem.File.Move(path.Path, newFilePathResult.Value.Path); diff --git a/src/Lumina.Infrastructure/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Artwork/BookArtworkService.cs b/src/Lumina.Infrastructure/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Artwork/BookArtworkService.cs index 8ce2aca8..efd252b3 100644 --- a/src/Lumina.Infrastructure/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Artwork/BookArtworkService.cs +++ b/src/Lumina.Infrastructure/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Artwork/BookArtworkService.cs @@ -60,7 +60,7 @@ internal sealed class BookArtworkService : IBookArtworkService /// An containing either the relative path of the stored artwork, or an error. public async Task> SaveBookArtworkAsync(Guid libraryId, Guid bookId, string libraryName, string authorName, string bookTitle, ArtworkDto artwork, CancellationToken cancellationToken) { - // resolve the local file path of the artwork, downloading it to a temporary file when it is remote + // Resolve the local file path of the artwork, downloading it to a temporary file when it is remote. Result resolveSourceResult = await ResolveArtworkSourceAsync(artwork, cancellationToken).ConfigureAwait(false); if (resolveSourceResult.IsFailure) return resolveSourceResult.Errors; @@ -75,7 +75,7 @@ internal sealed class BookArtworkService : IBookArtworkService } finally { - // remove the temporary file downloaded for the remote artwork, never a local file of the user + // Remove the temporary file downloaded for the remote artwork, never a local file of the user. if (resolveSourceResult.Value.IsTemporary && File.Exists(sourcePath)) { try @@ -84,11 +84,79 @@ internal sealed class BookArtworkService : IBookArtworkService } catch (IOException) { - // a failed cleanup of the temporary file must not mask the result of the operation + // A failed cleanup of the temporary file must not mask the result of the operation. } catch (UnauthorizedAccessException) { - // a failed cleanup of the temporary file must not mask the result of the operation + // A failed cleanup of the temporary file must not mask the result of the operation. + } + } + } + } + + /// + /// Stores the artwork uploaded in the of the book into the internal media directory, and returns the relative path of the stored artwork. + /// + /// The Id of the media library the book belongs to. + /// The Id of the book. + /// The name of the media library the book belongs to. + /// The name of the author of the book. + /// The title of the book. + /// The stream of the uploaded artwork file. + /// The name of the uploaded artwork file. + /// Cancellation token that can be used to stop the execution. + /// An containing either the relative path of the stored artwork, or an error. + public async Task> SaveBookArtworkAsync(Guid libraryId, Guid bookId, string libraryName, string authorName, string bookTitle, Stream artworkStream, string fileName, CancellationToken cancellationToken) + { + if (artworkStream is null || artworkStream.Length == 0) + return Errors.FileSystemManagement.FileNotFound; + if (artworkStream.Length > MAX_ARTWORK_SIZE_BYTES) + return Errors.FileSystemManagement.FileTooLarge; + + // Copy the uploaded artwork into a temporary file, so that the shared artwork storage can validate and copy it. + string temporaryPath = Path.Combine(Path.GetTempPath(), $"lumina-artwork-{Guid.NewGuid():N}{Path.GetExtension(fileName)}"); + bool written = false; + try + { + await using (FileStream fileStream = new(temporaryPath, FileMode.CreateNew, FileAccess.Write, FileShare.None, bufferSize: 81920, useAsync: true)) + await artworkStream.CopyToAsync(fileStream, cancellationToken).ConfigureAwait(false); + written = true; + } + catch (OperationCanceledException) + { + throw; + } + catch (Exception) + { + return Errors.FileSystemManagement.FileNotFound; + } + finally + { + // Remove the partially written temporary file when the upload failed. + if (!written && File.Exists(temporaryPath)) + File.Delete(temporaryPath); + } + + try + { + return await StoreArtworkAsync(libraryId, bookId, libraryName, authorName, bookTitle, temporaryPath, cancellationToken).ConfigureAwait(false); + } + finally + { + // Remove the temporary file after the artwork has been stored. + if (File.Exists(temporaryPath)) + { + try + { + File.Delete(temporaryPath); + } + catch (IOException) + { + // A failed cleanup of the temporary file must not mask the result of the operation. + } + catch (UnauthorizedAccessException) + { + // A failed cleanup of the temporary file must not mask the result of the operation. } } } @@ -135,16 +203,16 @@ internal sealed class BookArtworkService : IBookArtworkService if (!fileExistsResult.Value) return Errors.FileSystemManagement.FileNotFound; - // reject the artwork when it is a symbolic link or a reparse point, which could point to any file of the machine + // Reject the artwork when it is a symbolic link or a reparse point, which could point to any file of the machine. if (File.GetAttributes(sourcePath).HasFlag(FileAttributes.ReparsePoint)) return Errors.FileSystemManagement.InvalidPath; - // reject the artwork when it exceeds the maximum allowed size + // Reject the artwork when it exceeds the maximum allowed size. FileInfo sourceFileInfo = new(sourcePath); if (sourceFileInfo.Length > MAX_ARTWORK_SIZE_BYTES) return Errors.FileSystemManagement.FileTooLarge; - // make sure the file is an actual supported image + // Make sure the file is an actual supported image. Result imageTypeResult = await _environmentContext.FileTypeService.GetImageTypeAsync(sourcePathIdResult.Value, cancellationToken).ConfigureAwait(false); if (imageTypeResult.IsFailure) return imageTypeResult.Errors; @@ -159,24 +227,24 @@ internal sealed class BookArtworkService : IBookArtworkService if (ensureDirectoryResult.IsFailure) return ensureDirectoryResult.Errors; - // delete the previous cover of the book, so that a changed artwork does not leave orphaned files behind + // Delete the previous cover of the book, so that a changed artwork does not leave orphaned files behind. DeleteCover(artworkDirectoryPathResult.Value); Result artworkDirectoryPathIdResult = FileSystemPathId.Create(artworkDirectoryPathResult.Value); if (artworkDirectoryPathIdResult.IsFailure) return artworkDirectoryPathIdResult.Errors; - // copy the artwork file from the source location + // Copy the artwork file from the source location. Result copyFileResult = _environmentContext.FileProviderService.CopyFile(sourcePathIdResult.Value, artworkDirectoryPathIdResult.Value, true); if (copyFileResult.IsFailure) return copyFileResult.Errors; - // rename the copied file to the standard naming + // Rename the copied file to the standard naming. Result renameFileResult = _environmentContext.FileProviderService.RenameFile(copyFileResult.Value, $"cover.{imageTypeResult.Value.ToString().ToLowerInvariant()}"); if (renameFileResult.IsFailure) return renameFileResult.Errors; - // get the internal relative path for the copied file + // Get the internal relative path for the copied file. string relativePath = renameFileResult.Value.Path[AppContext.BaseDirectory.Length..]; if (!relativePath.StartsWith(_pathService.PathSeparator)) relativePath = $"{_pathService.PathSeparator}{relativePath}"; @@ -197,7 +265,7 @@ internal sealed class BookArtworkService : IBookArtworkService if (string.IsNullOrWhiteSpace(artwork.RemoteUrl)) return Errors.FileSystemManagement.FileNotFound; - // download the remote artwork into a temporary file, aborting when it exceeds the maximum allowed size + // Download the remote artwork into a temporary file, aborting when it exceeds the maximum allowed size. using HttpClient httpClient = _httpClientFactory.CreateClient(); string tempPath = Path.Combine(Path.GetTempPath(), $"lumina-artwork-{Guid.NewGuid():N}"); bool downloaded = false; @@ -233,7 +301,7 @@ internal sealed class BookArtworkService : IBookArtworkService } finally { - // remove the partially downloaded temporary file when the download failed + // Remove the partially downloaded temporary file when the download failed. if (!downloaded && File.Exists(tempPath)) File.Delete(tempPath); } 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 index 9ff7ea86..49959c37 100644 --- 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 @@ -14,6 +14,8 @@ public static partial class ApiRoutes public const string GET_BOOKS = "/books"; public const string GET_BOOKS_LITE = "/books/lite"; public const string ADD_BOOK = "/books"; + public const string UPDATE_BOOK = "/books/{id}"; + public const string UPDATE_BOOK_COVER = "/books/{id}/cover"; public const string GET_BOOK_READING_MANIFEST = "/books/{bookId}/reading/manifest"; public const string GET_BOOK_READING_AVAILABILITY = "/books/{bookId}/reading/availability"; public const string GET_BOOK_READING_SECTION = "/books/{bookId}/reading/sections/{locationRef}"; 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 index 9417c0fc..39350e75 100644 --- a/src/Lumina.Presentation.Api/Core/Endpoints/FileSystemManagement/Thumbnails/GetThumbnail/GetThumbnailEndpointSummary.cs +++ b/src/Lumina.Presentation.Api/Core/Endpoints/FileSystemManagement/Thumbnails/GetThumbnail/GetThumbnailEndpointSummary.cs @@ -88,7 +88,7 @@ public class GetThumbnailEndpointSummary : Summary API endpoint, for OpenAPI. /// [ExcludeFromCodeCoverage] -public class AddLibraryEndpointSummary : Summary +public class AddBookEndpointSummary : Summary { /// - /// Initializes a new instance of the class. + /// Initializes a new instance of the class. /// - public AddLibraryEndpointSummary() + public AddBookEndpointSummary() { Summary = "Adds a new book."; Description = "Creates a new book and returns its details, including the location of the newly created resource."; @@ -130,6 +130,8 @@ public class AddLibraryEndpointSummary : Summary r.LibraryId, "The Id of the media library this book belongs to. Required."); + RequestParam(r => r.Path, "The file system path of the book. Required."); RequestParam(r => r.Metadata, "Written content metadata of the book. Required."); RequestParam(r => r.Metadata!.Title, "The title of the written content. Required."); RequestParam(r => r.Metadata!.OriginalTitle, "The original title of the written content, if different from the current title. Optional."); @@ -171,13 +173,55 @@ public class AddLibraryEndpointSummary : Summary r.Contributors, "The list of media contributors (actors, directors, etc) starring in this book. Required."); RequestParam(r => r.Ratings, "The list of ratings for this book. Required."); - ResponseParam(r => r.Id, "The unique identifier of the entity."); - ResponseParam(r => r.CreatedOnUtc, "The date and time when the entity was created."); - ResponseParam(r => r.UpdatedOnUtc, "The date and time when the entity was last updated."); + ResponseParam(r => r.Id, "The unique identifier of the book."); + ResponseParam(r => r.LibraryId, "The Id of the media library the book belongs to."); + ResponseParam(r => r.Path, "The file system path of the book."); 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."); - // TODO: continue response params + ResponseParam(r => r.Metadata!.Title, "The title of the book."); + ResponseParam(r => r.Metadata!.OriginalTitle, "The original title of the book, if different from the current title."); + ResponseParam(r => r.Metadata!.Description, "A brief description or summary of the book."); + ResponseParam(r => r.Metadata!.ReleaseInfo, "The release information of the book, including its release date and other relevant details."); + ResponseParam(r => r.Metadata!.ReleaseInfo!.OriginalReleaseDate, "The original release date of the book."); + ResponseParam(r => r.Metadata!.ReleaseInfo!.OriginalReleaseYear, "The original release year of the book."); + ResponseParam(r => r.Metadata!.ReleaseInfo!.ReReleaseDate, "The re-release date of the book."); + ResponseParam(r => r.Metadata!.ReleaseInfo!.ReReleaseYear, "The re-release year of the book."); + ResponseParam(r => r.Metadata!.ReleaseInfo!.ReleaseCountry, "The country where the book was released."); + ResponseParam(r => r.Metadata!.ReleaseInfo!.ReleaseVersion, "The version or edition of the release of the book."); + ResponseParam(r => r.Metadata!.Genres, "The list of genres of the book."); + ResponseParam(r => r.Metadata!.Tags, "The list of tags of the book."); + ResponseParam(r => r.Metadata!.Language, "The language in which the book is written."); + ResponseParam(r => r.Metadata!.Language!.LanguageCode, "The ISO code of the language of the book."); + ResponseParam(r => r.Metadata!.Language!.LanguageName, "The name of the language of the book in English."); + ResponseParam(r => r.Metadata!.Language!.NativeName, "The native name of the language of the book."); + ResponseParam(r => r.Metadata!.OriginalLanguage, "The original language of the book, if it has been translated."); + ResponseParam(r => r.Metadata!.OriginalLanguage!.LanguageCode, "The ISO code of the original language of the book."); + ResponseParam(r => r.Metadata!.OriginalLanguage!.LanguageName, "The name of the original language of the book in English."); + ResponseParam(r => r.Metadata!.OriginalLanguage!.NativeName, "The native name of the original language of the book."); + ResponseParam(r => r.Metadata!.Publisher, "The publisher of the book."); + ResponseParam(r => r.Metadata!.PageCount, "The number of pages of the book."); + ResponseParam(r => r.Format, "The format of the book (e.g., Hardcover, Paperback), if applicable."); + ResponseParam(r => r.Edition, "The edition of the book, if applicable."); + ResponseParam(r => r.VolumeNumber, "The volume or book number in the series, if applicable."); + ResponseParam(r => r.Series, "The series the book is part of, if applicable."); + ResponseParam(r => r.Series!.Title, "The title of the series the book is part of."); + ResponseParam(r => r.ASIN, "The ASIN (Amazon Standard Identification Number) of the book, if applicable."); + ResponseParam(r => r.GoodreadsId, "The Goodreads ID of the book, if applicable."); + ResponseParam(r => r.LCCN, "The Library of Congress Control Number (LCCN) of the book, if applicable."); + ResponseParam(r => r.OCLCNumber, "The OCLC Number (WorldCat identifier) of the book, if applicable."); + ResponseParam(r => r.OpenLibraryId, "The Open Library ID of the book, if applicable."); + ResponseParam(r => r.LibraryThingId, "The LibraryThing ID of the book, if applicable."); + ResponseParam(r => r.GoogleBooksId, "The Google Books ID of the book, if applicable."); + ResponseParam(r => r.BarnesAndNobleId, "The Barnes & Noble ID of the book, if applicable."); + ResponseParam(r => r.AppleBooksId, "The Apple Books ID of the book, if applicable."); + ResponseParam(r => r.ISBNs, "The list of ISBN (International Standard Book Number) of the book."); + ResponseParam(r => r.Contributors, "The list of media contributors starring in this book."); + ResponseParam(r => r.Ratings, "The list of ratings for the book."); + ResponseParam(r => r.MetadataStatus, "The status of the metadata enrichment of the book."); + ResponseParam(r => r.LastMetadataUpdateUtc, "The date and time when the metadata of the book was last enriched, if applicable."); + ResponseParam(r => r.MetadataProvider, "The name of the plugin that enriched the metadata of the book, if applicable."); + ResponseParam(r => r.CreatedOnUtc, "The date and time when the book was created."); + ResponseParam(r => r.UpdatedOnUtc, "The date and time when the book was last updated, if applicable."); + ResponseParam(r => r.CoverPath, "The path of the cover image of the book, if available."); Response(201, "The new book is returned.", example: new BookResponse( @@ -196,16 +240,18 @@ public class AddLibraryEndpointSummary : Summary() { - { new(Name: "fantasy") }, - { new(Name: "adventure") }, - { new(Name: "classic") } - }, - Tags: new List() { - { new(Name: "epic fantasy") }, - { new(Name: "quest") }, - { new(Name: "middle-earth") } - }, + Genres: + [ + new(Name: "fantasy"), + new(Name: "adventure"), + new(Name: "classic") + ], + Tags: + [ + new(Name: "epic fantasy"), + new(Name: "quest"), + new(Name: "middle-earth") + ], Language: new( LanguageCode: "en", LanguageName: "English", @@ -321,6 +367,18 @@ public class AddLibraryEndpointSummary : Summary public class GetBookEndpoint : BaseEndpoint { + private readonly IQueryHandler> _getBookQueryHandler; + + /// + /// Initializes a new instance of the class. + /// + /// Injected service for handling get book queries. + public GetBookEndpoint(IQueryHandler> getBookQueryHandler) + { + _getBookQueryHandler = getBookQueryHandler; + } + /// /// Configures the API endpoint. /// @@ -22,19 +38,17 @@ public class GetBookEndpoint : BaseEndpoint Verbs(FastEndpoints.Http.GET); Routes(ApiRoutes.Books.GET_BOOK_BY_ID); Version(1); - AllowAnonymous(); DontCatchExceptions(); } /// - /// Adds a book stored in . + /// Gets the book identified by . /// - /// The request containing the book to be added. + /// The request containing the Id of the book to get. /// Cancellation token that can be used to stop the execution. public override async Task ExecuteAsync(GetBookRequest request, CancellationToken cancellationToken) { - //Result 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()); + Result result = await _getBookQueryHandler.HandleAsync(request.ToQuery(), cancellationToken).ConfigureAwait(false); + return result.Match(success => TypedResults.Ok(success), Problem); } } diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/GetBook/GetBookEndpointSummary.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/GetBook/GetBookEndpointSummary.cs new file mode 100644 index 00000000..86965b7f --- /dev/null +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/GetBook/GetBookEndpointSummary.cs @@ -0,0 +1,259 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +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.Contracts.Responses.MediaLibrary.WrittenContentLibrary.BookLibrary.Books; +using Lumina.Domain.SharedKernel.Common.Enums.BookLibrary; +using Lumina.Domain.SharedKernel.Common.Enums.MediaContributors; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Presentation.Api.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.Books.GetBook; + +/// +/// Class used for providing a textual description for the API endpoint, for OpenAPI. +/// +[ExcludeFromCodeCoverage] +public class GetBookEndpointSummary : Summary +{ + /// + /// Initializes a new instance of the class. + /// + public GetBookEndpointSummary() + { + Summary = "Gets a book by its Id."; + Description = "Gets the full details of the book identified by the request, including the resolved names of its media contributors."; + + ExampleRequest = new GetBookRequest( + Id: Guid.NewGuid().ToString() + ); + + RequestParam(r => r.Id, "The Id of the book to get. Required."); + + ResponseParam(r => r.Id, "The Id of the book."); + ResponseParam(r => r.LibraryId, "The Id of the media library the book belongs to."); + ResponseParam(r => r.Path, "The file system path of the book."); + ResponseParam(r => r.Metadata, "The written content metadata of the book."); + ResponseParam(r => r.Metadata!.Title, "The title of the book."); + ResponseParam(r => r.Metadata!.OriginalTitle, "The original title of the book, if different from the current title."); + ResponseParam(r => r.Metadata!.Description, "A brief description or summary of the book."); + ResponseParam(r => r.Metadata!.ReleaseInfo, "The release information of the book, including its release date and other relevant details."); + ResponseParam(r => r.Metadata!.ReleaseInfo!.OriginalReleaseDate, "The original release date of the book."); + ResponseParam(r => r.Metadata!.ReleaseInfo!.OriginalReleaseYear, "The original release year of the book."); + ResponseParam(r => r.Metadata!.ReleaseInfo!.ReReleaseDate, "The re-release date of the book."); + ResponseParam(r => r.Metadata!.ReleaseInfo!.ReReleaseYear, "The re-release year of the book."); + ResponseParam(r => r.Metadata!.ReleaseInfo!.ReleaseCountry, "The country where the book was released."); + ResponseParam(r => r.Metadata!.ReleaseInfo!.ReleaseVersion, "The version or edition of the release of the book."); + ResponseParam(r => r.Metadata!.Genres, "The list of genres of the book."); + ResponseParam(r => r.Metadata!.Tags, "The list of tags of the book."); + ResponseParam(r => r.Metadata!.Language, "The language in which the book is written."); + ResponseParam(r => r.Metadata!.Language!.LanguageCode, "The ISO code of the language of the book."); + ResponseParam(r => r.Metadata!.Language!.LanguageName, "The name of the language of the book in English."); + ResponseParam(r => r.Metadata!.Language!.NativeName, "The native name of the language of the book."); + ResponseParam(r => r.Metadata!.OriginalLanguage, "The original language of the book, if it has been translated."); + ResponseParam(r => r.Metadata!.OriginalLanguage!.LanguageCode, "The ISO code of the original language of the book."); + ResponseParam(r => r.Metadata!.OriginalLanguage!.LanguageName, "The name of the original language of the book in English."); + ResponseParam(r => r.Metadata!.OriginalLanguage!.NativeName, "The native name of the original language of the book."); + ResponseParam(r => r.Metadata!.Publisher, "The publisher of the book."); + ResponseParam(r => r.Metadata!.PageCount, "The number of pages of the book."); + ResponseParam(r => r.Format, "The format of the book (e.g., Hardcover, Paperback), if applicable."); + ResponseParam(r => r.Edition, "The edition of the book, if applicable."); + ResponseParam(r => r.VolumeNumber, "The volume or book number in the series, if applicable."); + ResponseParam(r => r.Series, "The series the book is part of, if applicable."); + ResponseParam(r => r.Series!.Title, "The title of the series the book is part of."); + ResponseParam(r => r.ASIN, "The ASIN (Amazon Standard Identification Number) of the book, if applicable."); + ResponseParam(r => r.GoodreadsId, "The Goodreads ID of the book, if applicable."); + ResponseParam(r => r.LCCN, "The Library of Congress Control Number (LCCN) of the book, if applicable."); + ResponseParam(r => r.OCLCNumber, "The OCLC Number (WorldCat identifier) of the book, if applicable."); + ResponseParam(r => r.OpenLibraryId, "The Open Library ID of the book, if applicable."); + ResponseParam(r => r.LibraryThingId, "The LibraryThing ID of the book, if applicable."); + ResponseParam(r => r.GoogleBooksId, "The Google Books ID of the book, if applicable."); + ResponseParam(r => r.BarnesAndNobleId, "The Barnes & Noble ID of the book, if applicable."); + ResponseParam(r => r.AppleBooksId, "The Apple Books ID of the book, if applicable."); + ResponseParam(r => r.ISBNs, "The list of ISBN (International Standard Book Number) of the book."); + ResponseParam(r => r.Contributors, "The list of media contributors starring in this book."); + ResponseParam(r => r.Ratings, "The list of ratings for the book."); + ResponseParam(r => r.MetadataStatus, "The status of the metadata enrichment of the book."); + ResponseParam(r => r.LastMetadataUpdateUtc, "The date and time when the metadata of the book was last enriched, if applicable."); + ResponseParam(r => r.MetadataProvider, "The name of the plugin that enriched the metadata of the book, if applicable."); + ResponseParam(r => r.CreatedOnUtc, "The date and time when the book was created."); + ResponseParam(r => r.UpdatedOnUtc, "The date and time when the book was last updated, if applicable."); + ResponseParam(r => r.CoverPath, "The path of the cover image of the book, if available."); + + Response(200, "The requested book is returned.", + example: new BookResponse( + Id: Guid.NewGuid(), + LibraryId: Guid.NewGuid(), + Path: "/books/the-fellowship-of-the-ring.epub", + Metadata: new WrittenContentMetadataDto( + Title: "The Fellowship of the Ring", + OriginalTitle: "The Fellowship of the Ring", + Description: "The first part of J.R.R. Tolkien's epic adventure The Lord of the Rings. In a sleepy village in the Shire, young Frodo Baggins finds himself faced with an immense task, as his elderly cousin Bilbo entrusts the Ring to his care. Frodo must leave his home and make a perilous journey across Middle-earth to the Cracks of Doom, there to destroy the Ring and foil the Dark Lord in his evil purpose.", + ReleaseInfo: new ReleaseInfoDto( + OriginalReleaseDate: DateOnly.ParseExact("1954-07-29", "yyyy-MM-dd", null), + OriginalReleaseYear: 1954, + ReReleaseDate: DateOnly.ParseExact("2001-09-06", "yyyy-MM-dd", null), + ReReleaseYear: 2001, + ReleaseCountry: "uk", + ReleaseVersion: "50th Anniversary Edition" + ), + Genres: + [ + new(Name: "fantasy"), + new(Name: "adventure"), + new(Name: "classic") + ], + Tags: + [ + new(Name: "epic fantasy"), + new(Name: "quest"), + new(Name: "middle-earth") + ], + Language: new LanguageInfoDto( + LanguageCode: "en", + LanguageName: "English", + NativeName: "English" + ), + OriginalLanguage: new LanguageInfoDto( + LanguageCode: "en", + LanguageName: "English", + NativeName: "English" + ), + Publisher: "Houghton Mifflin", + PageCount: 398 + ), + Format: BookFormat.Paperback, + Edition: "50th Anniversary Edition", + VolumeNumber: 1, + Series: new BookSeriesDto( + Title: "The Lord of the Rings" + ), + ASIN: "B007978NPG", + GoodreadsId: "3", + LCCN: "54009621", + OCLCNumber: "ocm00012345", + OpenLibraryId: "OL7603910M", + LibraryThingId: "3203347", + GoogleBooksId: "aWZzLPhY4o0C", + BarnesAndNobleId: "1100307790", + AppleBooksId: "id395211", + ISBNs: + [ + new IsbnDto( + Value: "0395272238", + Format: IsbnFormat.Isbn10 + ), + new IsbnDto( + Value: "9780395272237", + Format: IsbnFormat.Isbn13 + ) + ], + Contributors: + [ + new MediaContributorDto( + Name: new MediaContributorNameDto( + DisplayName: "J.R.R. Tolkien", + LegalName: "John Ronald Reuel Tolkien" + ), + Role: new MediaContributorRoleDto( + Name: "author", + Category: MediaContributorRoleCategory.Author + ) + ), + new MediaContributorDto( + Name: new MediaContributorNameDto( + DisplayName: "Alan Lee", + LegalName: "Alan Lee" + ), + Role: new MediaContributorRoleDto( + Name: "illustrator", + Category: MediaContributorRoleCategory.Illustrator + ) + ) + ], + Ratings: + [ + new BookRatingDto( + Source: BookRatingSource.GoogleBooks, + Value: 4.36M, + MaxValue: 5, + VoteCount: 2345678 + ), + new BookRatingDto( + Source: BookRatingSource.Amazon, + Value: 4.7M, + MaxValue: 5, + VoteCount: 87654 + ) + ], + MetadataStatus: MetadataStatus.Enriched, + LastMetadataUpdateUtc: DateTime.UtcNow, + MetadataProvider: "GoogleBooks", + CreatedOnUtc: DateTime.UtcNow, + UpdatedOnUtc: DateTime.UtcNow, + CoverPath: "/media/books/books-3f2504e0-4f89-41d3-9a0c-0305e82c3301/The Lord of the Rings-2b0e5f5a-0b3f-4b7e-8f4a-8c9e3d2f5a6b/cover.jpg" + ) + ); + + Response(401, "Authentication required.", "application/problem+json", + example: new + { + type = "https://tools.ietf.org/html/rfc7235#section-3.1", + status = 401, + title = "Unauthorized", + detail = "You are not authorized", + instance = "/api/v1/books/{id}" + } + ); + + Response(403, "The request failed because the user making the request is not an Admin, or the owner of the media library.", "application/problem+json", + example: new + { + type = "https://tools.ietf.org/html/rfc9110#section-15.5.4", + title = "General.Unauthorized", + status = 403, + detail = "NotAuthorized", + instance = "/api/v1/books/{id}", + traceId = "00-a712bbf99ca8ab485f86a762ae5ae74d-b3a2eb78813b0a5d-00" + } + ); + + Response(404, "The request failed because the book does not exist.", "application/problem+json", + example: new + { + type = "https://tools.ietf.org/html/rfc9110#section-15.5.5", + title = "General.NotFound", + status = 404, + detail = "BookNotFound", + instance = "/api/v1/books/{id}", + traceId = "00-57d15dadd702dbd4aeb5dc9b7cee68ee-9330237dbb2ce0e5-00" + } + ); + + Response(422, "The request did not pass validation checks.", "application/problem+json", + example: new + { + type = "https://tools.ietf.org/html/rfc4918#section-11.2", + title = "General.Validation", + status = 422, + detail = "OneOrMoreValidationErrorsOccurred", + instance = "/api/v1/books/{id}", + errors = new Dictionary + { + { + "General.Validation", new[] + { + "BookIdCannotBeEmpty" + } + } + }, + traceId = "00-2470be4248a2a5a0c6f70579975a6954-b9c3ba9544a03500-00" + } + ); + } +} diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/GetBooksLite/GetBooksLiteEndpointSummary.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/GetBooksLite/GetBooksLiteEndpointSummary.cs index 5ef15425..14be3df3 100644 --- a/src/Lumina.Presentation.Api/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/GetBooksLite/GetBooksLiteEndpointSummary.cs +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/GetBooksLite/GetBooksLiteEndpointSummary.cs @@ -112,7 +112,8 @@ public class GetBooksLiteEndpointSummary : Summary +/// API endpoint for the /books/{id} route. +/// +public class UpdateBookEndpoint : BaseEndpoint +{ + private readonly ICommandHandler> _updateBookCommandHandler; + + /// + /// Initializes a new instance of the class. + /// + /// Injected service for handling update book commands. + public UpdateBookEndpoint(ICommandHandler> updateBookCommandHandler) + { + _updateBookCommandHandler = updateBookCommandHandler; + } + + /// + /// Configures the API endpoint. + /// + public override void Configure() + { + Verbs(FastEndpoints.Http.PUT); + Routes(ApiRoutes.Books.UPDATE_BOOK); + Version(1); + DontCatchExceptions(); + } + + /// + /// Updates the book described in . + /// + /// The request containing the edited details of the book. + /// Cancellation token that can be used to stop the execution. + public override async Task ExecuteAsync(UpdateBookRequest request, CancellationToken cancellationToken) + { + // The book is identified by the {id} route value, not by the id of the request body, so that a mismatched or malicious id can never + // redirect the update to another book; the raw value is kept as a string, so that an unparseable id reaches the command validator, + // which reports it with a ProblemDetails validation error instead of failing the request binding. + request = request with { Id = HttpContext.Request.RouteValues["id"]?.ToString() }; + + Result result = await _updateBookCommandHandler.HandleAsync(request.ToCommand(), cancellationToken).ConfigureAwait(false); + return result.Match(success => TypedResults.Ok(success), Problem); + } +} diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/UpdateBook/UpdateBookEndpointSummary.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/UpdateBook/UpdateBookEndpointSummary.cs new file mode 100644 index 00000000..392faaf0 --- /dev/null +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/UpdateBook/UpdateBookEndpointSummary.cs @@ -0,0 +1,460 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +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.Contracts.Responses.MediaLibrary.WrittenContentLibrary.BookLibrary.Books; +using Lumina.Domain.SharedKernel.Common.Enums.BookLibrary; +using Lumina.Domain.SharedKernel.Common.Enums.MediaContributors; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Presentation.Api.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.Books.UpdateBook; + +/// +/// Class used for providing a textual description for the API endpoint, for OpenAPI. +/// +[ExcludeFromCodeCoverage] +public class UpdateBookEndpointSummary : Summary +{ + /// + /// Initializes a new instance of the class. + /// + public UpdateBookEndpointSummary() + { + Summary = "Updates a book."; + Description = "Updates the details of the book identified by the request."; + + RequestParam(r => r.Id, "The Id of the book to update. Required."); + RequestParam(r => r.Metadata, "The written content metadata of the book. Required."); + RequestParam(r => r.Metadata!.Title, "The title of the book. Required."); + RequestParam(r => r.Metadata!.OriginalTitle, "The original title of the book, if different from the current title. Optional."); + RequestParam(r => r.Metadata!.Description, "A brief description or summary of the book. Optional."); + RequestParam(r => r.Metadata!.ReleaseInfo, "The release information, including release date and other relevant details. Required."); + RequestParam(r => r.Metadata!.ReleaseInfo!.OriginalReleaseDate, "The original release date of the book. Optional."); + RequestParam(r => r.Metadata!.ReleaseInfo!.OriginalReleaseYear, "The original release year of the book. Optional."); + RequestParam(r => r.Metadata!.ReleaseInfo!.ReReleaseDate, "The re-release date of the book. Optional."); + RequestParam(r => r.Metadata!.ReleaseInfo!.ReReleaseYear, "The re-release year of the book. Optional."); + RequestParam(r => r.Metadata!.ReleaseInfo!.ReleaseCountry, "The country where the book was released. Optional."); + RequestParam(r => r.Metadata!.ReleaseInfo!.ReleaseVersion, "The version or edition of the release of the book. Optional."); + RequestParam(r => r.Metadata!.Genres, "The list of genres of the book. Required."); + RequestParam(r => r.Metadata!.Tags, "The list of tags of the book. Required."); + RequestParam(r => r.Metadata!.Language, "The language in which the book is written. Optional."); + RequestParam(r => r.Metadata!.Language!.LanguageCode, "The ISO code of the language of the book. Optional."); + RequestParam(r => r.Metadata!.Language!.LanguageName, "The name of the language of the book in English. Optional."); + RequestParam(r => r.Metadata!.Language!.NativeName, "The native name of the language of the book. Optional."); + RequestParam(r => r.Metadata!.OriginalLanguage, "The original language of the book, if it has been translated. Optional."); + RequestParam(r => r.Metadata!.OriginalLanguage!.LanguageCode, "The ISO code of the original language of the book. Optional."); + RequestParam(r => r.Metadata!.OriginalLanguage!.LanguageName, "The name of the original language of the book in English. Optional."); + RequestParam(r => r.Metadata!.OriginalLanguage!.NativeName, "The native name of the original language of the book. Optional."); + RequestParam(r => r.Metadata!.Publisher, "The publisher of the book. Optional."); + RequestParam(r => r.Metadata!.PageCount, "The number of pages of the book. Optional."); + RequestParam(r => r.Format, "The format of the book (e.g., Hardcover, Paperback). Optional."); + RequestParam(r => r.Edition, "The edition of the book. Optional."); + RequestParam(r => r.VolumeNumber, "The volume or book number in the series. Optional."); + RequestParam(r => r.Series, "The series the book is part of. Optional."); + RequestParam(r => r.Series!.Title, "The title of the series the book is part of. Optional."); + RequestParam(r => r.ASIN, "The ASIN (Amazon Standard Identification Number) of the book. Optional."); + RequestParam(r => r.GoodreadsId, "The Goodreads Id of the book. Optional."); + RequestParam(r => r.LCCN, "The Library of Congress Control Number (LCCN) of the book. Optional."); + RequestParam(r => r.OCLCNumber, "The OCLC Number (WorldCat identifier) of the book. Optional."); + RequestParam(r => r.OpenLibraryId, "The Open Library Id of the book. Optional."); + RequestParam(r => r.LibraryThingId, "The LibraryThing Id of the book. Optional."); + RequestParam(r => r.GoogleBooksId, "The Google Books Id of the book. Optional."); + RequestParam(r => r.BarnesAndNobleId, "The Barnes & Noble Id of the book. Optional."); + RequestParam(r => r.AppleBooksId, "The Apple Books Id of the book. Optional."); + RequestParam(r => r.ISBNs, "The list of ISBN (International Standard Book Number) of the book. Required."); + RequestParam(r => r.Contributors, "The list of media contributors of the book. Required."); + RequestParam(r => r.Ratings, "The list of ratings of the book. Required."); + + ExampleRequest = new UpdateBookRequest( + Id: Guid.NewGuid().ToString(), + Metadata: new WrittenContentMetadataDto( + Title: "The Fellowship of the Ring", + OriginalTitle: "The Fellowship of the Ring", + Description: "The first part of J.R.R. Tolkien's epic adventure The Lord of the Rings. In a sleepy village in the Shire, young Frodo Baggins finds himself faced with an immense task, as his elderly cousin Bilbo entrusts the Ring to his care. Frodo must leave his home and make a perilous journey across Middle-earth to the Cracks of Doom, there to destroy the Ring and foil the Dark Lord in his evil purpose.", + ReleaseInfo: new ReleaseInfoDto( + OriginalReleaseDate: DateOnly.ParseExact("1954-07-29", "yyyy-MM-dd", null), + OriginalReleaseYear: 1954, + ReReleaseDate: DateOnly.ParseExact("2001-09-06", "yyyy-MM-dd", null), + ReReleaseYear: 2001, + ReleaseCountry: "uk", + ReleaseVersion: "50th Anniversary Edition" + ), + Genres: + [ + new(Name: "fantasy"), + new(Name: "adventure"), + new(Name: "classic") + ], + Tags: + [ + new(Name: "epic fantasy"), + new(Name: "quest"), + new(Name: "middle-earth") + ], + Language: new LanguageInfoDto( + LanguageCode: "en", + LanguageName: "English", + NativeName: "English" + ), + OriginalLanguage: new LanguageInfoDto( + LanguageCode: "en", + LanguageName: "English", + NativeName: "English" + ), + Publisher: "Houghton Mifflin", + PageCount: 398 + ), + Format: BookFormat.Paperback, + Edition: "50th Anniversary Edition", + VolumeNumber: 1, + Series: new BookSeriesDto( + Title: "The Lord of the Rings" + ), + ASIN: "B007978NPG", + GoodreadsId: "3", + LCCN: "54009621", + OCLCNumber: "ocm00012345", + OpenLibraryId: "OL7603910M", + LibraryThingId: "3203347", + GoogleBooksId: "aWZzLPhY4o0C", + BarnesAndNobleId: "1100307790", + AppleBooksId: "id395211", + ISBNs: + [ + new IsbnDto( + Value: "0395272238", + Format: IsbnFormat.Isbn10 + ), + new IsbnDto( + Value: "9780395272237", + Format: IsbnFormat.Isbn13 + ) + ], + Contributors: + [ + new MediaContributorDto( + Name: new MediaContributorNameDto( + DisplayName: "J.R.R. Tolkien", + LegalName: "John Ronald Reuel Tolkien" + ), + Role: new MediaContributorRoleDto( + Name: "author", + Category: MediaContributorRoleCategory.Author + ) + ), + new MediaContributorDto( + Name: new MediaContributorNameDto( + DisplayName: "Alan Lee", + LegalName: "Alan Lee" + ), + Role: new MediaContributorRoleDto( + Name: "illustrator", + Category: MediaContributorRoleCategory.Illustrator + ) + ) + ], + Ratings: + [ + new BookRatingDto( + Source: BookRatingSource.GoogleBooks, + Value: 4.36M, + MaxValue: 5, + VoteCount: 2345678 + ), + new BookRatingDto( + Source: BookRatingSource.Amazon, + Value: 4.7M, + MaxValue: 5, + VoteCount: 87654 + ) + ] + ); + + ResponseParam(r => r.Id, "The Id of the book."); + ResponseParam(r => r.LibraryId, "The Id of the media library the book belongs to."); + ResponseParam(r => r.Path, "The file system path of the book."); + ResponseParam(r => r.Metadata, "The written content metadata of the book."); + ResponseParam(r => r.Metadata!.Title, "The title of the book."); + ResponseParam(r => r.Metadata!.OriginalTitle, "The original title of the book, if different from the current title."); + ResponseParam(r => r.Metadata!.Description, "A brief description or summary of the book."); + ResponseParam(r => r.Metadata!.ReleaseInfo, "The release information of the book, including its release date and other relevant details."); + ResponseParam(r => r.Metadata!.ReleaseInfo!.OriginalReleaseDate, "The original release date of the book."); + ResponseParam(r => r.Metadata!.ReleaseInfo!.OriginalReleaseYear, "The original release year of the book."); + ResponseParam(r => r.Metadata!.ReleaseInfo!.ReReleaseDate, "The re-release date of the book."); + ResponseParam(r => r.Metadata!.ReleaseInfo!.ReReleaseYear, "The re-release year of the book."); + ResponseParam(r => r.Metadata!.ReleaseInfo!.ReleaseCountry, "The country where the book was released."); + ResponseParam(r => r.Metadata!.ReleaseInfo!.ReleaseVersion, "The version or edition of the release of the book."); + ResponseParam(r => r.Metadata!.Genres, "The list of genres of the book."); + ResponseParam(r => r.Metadata!.Tags, "The list of tags of the book."); + ResponseParam(r => r.Metadata!.Language, "The language in which the book is written."); + ResponseParam(r => r.Metadata!.Language!.LanguageCode, "The ISO code of the language of the book."); + ResponseParam(r => r.Metadata!.Language!.LanguageName, "The name of the language of the book in English."); + ResponseParam(r => r.Metadata!.Language!.NativeName, "The native name of the language of the book."); + ResponseParam(r => r.Metadata!.OriginalLanguage, "The original language of the book, if it has been translated."); + ResponseParam(r => r.Metadata!.OriginalLanguage!.LanguageCode, "The ISO code of the original language of the book."); + ResponseParam(r => r.Metadata!.OriginalLanguage!.LanguageName, "The name of the original language of the book in English."); + ResponseParam(r => r.Metadata!.OriginalLanguage!.NativeName, "The native name of the original language of the book."); + ResponseParam(r => r.Metadata!.Publisher, "The publisher of the book."); + ResponseParam(r => r.Metadata!.PageCount, "The number of pages of the book."); + ResponseParam(r => r.Format, "The format of the book (e.g., Hardcover, Paperback), if applicable."); + ResponseParam(r => r.Edition, "The edition of the book, if applicable."); + ResponseParam(r => r.VolumeNumber, "The volume or book number in the series, if applicable."); + ResponseParam(r => r.Series, "The series the book is part of, if applicable."); + ResponseParam(r => r.Series!.Title, "The title of the series the book is part of."); + ResponseParam(r => r.ASIN, "The ASIN (Amazon Standard Identification Number) of the book, if applicable."); + ResponseParam(r => r.GoodreadsId, "The Goodreads ID of the book, if applicable."); + ResponseParam(r => r.LCCN, "The Library of Congress Control Number (LCCN) of the book, if applicable."); + ResponseParam(r => r.OCLCNumber, "The OCLC Number (WorldCat identifier) of the book, if applicable."); + ResponseParam(r => r.OpenLibraryId, "The Open Library ID of the book, if applicable."); + ResponseParam(r => r.LibraryThingId, "The LibraryThing ID of the book, if applicable."); + ResponseParam(r => r.GoogleBooksId, "The Google Books ID of the book, if applicable."); + ResponseParam(r => r.BarnesAndNobleId, "The Barnes & Noble ID of the book, if applicable."); + ResponseParam(r => r.AppleBooksId, "The Apple Books ID of the book, if applicable."); + ResponseParam(r => r.ISBNs, "The list of ISBN (International Standard Book Number) of the book."); + ResponseParam(r => r.Contributors, "The list of media contributors starring in this book."); + ResponseParam(r => r.Ratings, "The list of ratings for the book."); + ResponseParam(r => r.MetadataStatus, "The status of the metadata enrichment of the book."); + ResponseParam(r => r.LastMetadataUpdateUtc, "The date and time when the metadata of the book was last enriched, if applicable."); + ResponseParam(r => r.MetadataProvider, "The name of the plugin that enriched the metadata of the book, if applicable."); + ResponseParam(r => r.CreatedOnUtc, "The date and time when the book was created."); + ResponseParam(r => r.UpdatedOnUtc, "The date and time when the book was last updated, if applicable."); + ResponseParam(r => r.CoverPath, "The path of the cover image of the book, if available."); + + Response(200, "The updated book is returned.", + example: new BookResponse( + Id: Guid.NewGuid(), + LibraryId: Guid.NewGuid(), + Path: "/books/the-fellowship-of-the-ring.epub", + Metadata: new WrittenContentMetadataDto( + Title: "The Fellowship of the Ring", + OriginalTitle: "The Fellowship of the Ring", + Description: "The first part of J.R.R. Tolkien's epic adventure The Lord of the Rings. In a sleepy village in the Shire, young Frodo Baggins finds himself faced with an immense task, as his elderly cousin Bilbo entrusts the Ring to his care. Frodo must leave his home and make a perilous journey across Middle-earth to the Cracks of Doom, there to destroy the Ring and foil the Dark Lord in his evil purpose.", + ReleaseInfo: new ReleaseInfoDto( + OriginalReleaseDate: DateOnly.ParseExact("1954-07-29", "yyyy-MM-dd", null), + OriginalReleaseYear: 1954, + ReReleaseDate: DateOnly.ParseExact("2001-09-06", "yyyy-MM-dd", null), + ReReleaseYear: 2001, + ReleaseCountry: "uk", + ReleaseVersion: "50th Anniversary Edition" + ), + Genres: + [ + new(Name: "fantasy"), + new(Name: "adventure"), + new(Name: "classic") + ], + Tags: + [ + new(Name: "epic fantasy"), + new(Name: "quest"), + new(Name: "middle-earth") + ], + Language: new LanguageInfoDto( + LanguageCode: "en", + LanguageName: "English", + NativeName: "English" + ), + OriginalLanguage: new LanguageInfoDto( + LanguageCode: "en", + LanguageName: "English", + NativeName: "English" + ), + Publisher: "Houghton Mifflin", + PageCount: 398 + ), + Format: BookFormat.Paperback, + Edition: "50th Anniversary Edition", + VolumeNumber: 1, + Series: new BookSeriesDto( + Title: "The Lord of the Rings" + ), + ASIN: "B007978NPG", + GoodreadsId: "3", + LCCN: "54009621", + OCLCNumber: "ocm00012345", + OpenLibraryId: "OL7603910M", + LibraryThingId: "3203347", + GoogleBooksId: "aWZzLPhY4o0C", + BarnesAndNobleId: "1100307790", + AppleBooksId: "id395211", + ISBNs: + [ + new IsbnDto( + Value: "0395272238", + Format: IsbnFormat.Isbn10 + ), + new IsbnDto( + Value: "9780395272237", + Format: IsbnFormat.Isbn13 + ) + ], + Contributors: + [ + new MediaContributorDto( + Name: new MediaContributorNameDto( + DisplayName: "J.R.R. Tolkien", + LegalName: "John Ronald Reuel Tolkien" + ), + Role: new MediaContributorRoleDto( + Name: "author", + Category: MediaContributorRoleCategory.Author + ) + ), + new MediaContributorDto( + Name: new MediaContributorNameDto( + DisplayName: "Alan Lee", + LegalName: "Alan Lee" + ), + Role: new MediaContributorRoleDto( + Name: "illustrator", + Category: MediaContributorRoleCategory.Illustrator + ) + ) + ], + Ratings: + [ + new BookRatingDto( + Source: BookRatingSource.GoogleBooks, + Value: 4.36M, + MaxValue: 5, + VoteCount: 2345678 + ), + new BookRatingDto( + Source: BookRatingSource.Amazon, + Value: 4.7M, + MaxValue: 5, + VoteCount: 87654 + ) + ], + MetadataStatus: MetadataStatus.Enriched, + LastMetadataUpdateUtc: DateTime.UtcNow, + MetadataProvider: "GoogleBooks", + CreatedOnUtc: DateTime.UtcNow, + UpdatedOnUtc: DateTime.UtcNow, + CoverPath: "/media/books/books-3f2504e0-4f89-41d3-9a0c-0305e82c3301/The Lord of the Rings-2b0e5f5a-0b3f-4b7e-8f4a-8c9e3d2f5a6b/cover.jpg" + ) + ); + + Response(401, "Authentication required.", "application/problem+json", + example: new + { + type = "https://tools.ietf.org/html/rfc7235#section-3.1", + status = 401, + title = "Unauthorized", + detail = "You are not authorized", + instance = "/api/v1/books/{id}" + } + ); + + Response(403, "The request failed because the user making the request is not an Admin, or the owner of the media library.", "application/problem+json", + example: new + { + type = "https://tools.ietf.org/html/rfc9110#section-15.5.4", + title = "General.Unauthorized", + status = 403, + detail = "NotAuthorized", + instance = "/api/v1/books/{id}", + traceId = "00-a712bbf99ca8ab485f86a762ae5ae74d-b3a2eb78813b0a5d-00" + } + ); + + Response(404, "The request failed because the book or its media library does not exist.", "application/problem+json", + example: new + { + type = "https://tools.ietf.org/html/rfc9110#section-15.5.5", + title = "General.NotFound", + status = 404, + detail = "BookNotFound", + instance = "/api/v1/books/{id}", + traceId = "00-57d15dadd702dbd4aeb5dc9b7cee68ee-9330237dbb2ce0e5-00" + } + ); + + Response(422, "The request did not pass validation checks.", "application/problem+json", + example: new + { + type = "https://tools.ietf.org/html/rfc4918#section-11.2", + title = "General.Validation", + status = 422, + detail = "OneOrMoreValidationErrorsOccurred", + instance = "/api/v1/books/{id}", + errors = new Dictionary + { + { + "General.Validation", new[] + { + "BookIdCannotBeEmpty", + "MetadataCannotBeNull", + "TitleCannotBeEmpty", + "TitleMustBeMaximum255CharactersLong", + "OriginalTitleMustBeMaximum255CharactersLong", + "DescriptionMustBeMaximum2000CharactersLong", + "ReleaseInfoCannotBeNull", + "OriginalReleaseYearMustBeBetween1And9999", + "ReReleaseYearMustBeBetween1And9999", + "CountryCodeMustBe2CharactersLong", + "ReleaseVersionMustBeMaximum50CharactersLong", + "OriginalReleaseDateAndYearMustMatch", + "ReReleaseDateAndYearMustMatch", + "ReReleaseYearCannotBeEarlierThanOriginalReleaseYear", + "ReReleaseDateCannotBeEarlierThanOriginalReleaseDate", + "GenresListCannotBeNull", + "GenreNameCannotBeEmpty", + "GenreNameMustBeMaximum50CharactersLong", + "TagsListCannotBeNull", + "TagNameCannotBeEmpty", + "TagNameMustBeMaximum50CharactersLong", + "LanguageCodeCannotBeEmpty", + "LanguageCodeMustBe2CharactersLong", + "LanguageNameCannotBeEmpty", + "LanguageNameMustBeMaximum50CharactersLong", + "LanguageNativeNameMustBeMaximum50CharactersLong", + "PublisherMustBeMaximum100CharactersLong", + "PageCountMustBeGreaterThanZero", + "UnknownBookFormat", + "EditionMustBeMaximum50CharactersLong", + "VolumeNumberMustBeGreaterThanZero", + "AsinMustBe10CharactersLong", + "GoodreadsIdMustBeNumeric", + "InvalidLccnFormat", + "InvalidOclcFormat", + "InvalidOpenLibraryId", + "LibraryThingIdMustBeMaximum50CharactersLong", + "GoogleBooksIdMustBe12CharactersLong", + "InvalidGoogleBooksIdFormat", + "BarnesAndNoblesIdMustBe10CharactersLong", + "InvalidBarnesAndNoblesIdFormat", + "InvalidAppleBooksIdFormat", + "IsbnListCannotBeNull", + "IsbnValueCannotBeEmpty", + "InvalidIsbn13Format", + "InvalidIsbn10Format", + "UnknownIsbnFormat", + "ContributorsListCannotBeNull", + "ContributorNameCannotBeEmpty", + "ContributorDisplayNameCannotBeEmpty", + "ContributorDisplayNameMustBeMaximum100CharactersLong", + "ContributorLegalNameMustBeMaximum100CharactersLong", + "ContributorRoleCannotBeNull", + "RoleNameCannotBeEmpty", + "RoleNameMustBeMaximum50CharactersLong", + "RoleCategoryCannotBeEmpty", + "RatingsListCannotBeNull", + "RatingValueMustBePositive", + "RatingValueCannotBeGreaterThanMaxValue", + "RatingMaxValueMustBePositive", + "RatingVoteCountMustBePositive" + } + } + }, + traceId = "00-2470be4248a2a5a0c6f70579975a6954-b9c3ba9544a03500-00" + } + ); + } +} diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/UpdateBookCover/UpdateBookCoverEndpoint.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/UpdateBookCover/UpdateBookCoverEndpoint.cs new file mode 100644 index 00000000..6c6d9b08 --- /dev/null +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/UpdateBookCover/UpdateBookCoverEndpoint.cs @@ -0,0 +1,81 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Commands.UpdateBookCover; +using Lumina.Domain.Common.Primitives; +using Lumina.Presentation.Api.Common.Routes.Library.WrittenContentLibrary.BookLibrary; +using Lumina.Presentation.Api.Core.Endpoints.Common; +using Microsoft.AspNetCore.Http; +using System; +using System.IO; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Api.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.Books.UpdateBookCover; + +/// +/// API endpoint for the /books/{id}/cover route. +/// +public class UpdateBookCoverEndpoint : BaseEndpoint +{ + private readonly Application.Common.CQRS.ICommandHandler> _updateBookCoverCommandHandler; + + /// + /// Initializes a new instance of the class. + /// + /// Injected service for handling update book cover commands. + public UpdateBookCoverEndpoint(Application.Common.CQRS.ICommandHandler> updateBookCoverCommandHandler) + { + _updateBookCoverCommandHandler = updateBookCoverCommandHandler; + } + + /// + /// Configures the API endpoint. + /// + public override void Configure() + { + Verbs(Http.PUT); + Routes(ApiRoutes.Books.UPDATE_BOOK_COVER); + Version(1); + DontCatchExceptions(); + } + + /// + /// Updates the cover image of the book with the image uploaded in the multipart form of the request. + /// + /// The request object. + /// Cancellation token that can be used to stop the execution. + public override async Task ExecuteAsync(EmptyRequest request, CancellationToken cancellationToken) + { + // The endpoint takes no typed request, because its body is a multipart file, so the book id is read from the {id} route + // value; an unparseable value becomes Guid.Empty, which the command validator reports as a missing book id. + Guid bookId = Guid.TryParse(HttpContext.Request.RouteValues["id"]?.ToString(), out Guid parsedBookId) ? parsedBookId : Guid.Empty; + + IFormFile? cover = null; + if (HttpContext.Request.HasFormContentType) + { + try + { + // The cover is the first file of the multipart form; a multipart body without any file cannot be parsed as a form, + // so a malformed upload is treated as a missing cover, which the command validator reports. + cover = HttpContext.Request.Form.Files.Count > 0 ? HttpContext.Request.Form.Files[0] : null; + } + catch (InvalidDataException) + { + cover = null; + } + } + + // The cover stream must stay open while the handler stores the image, and is disposed as soon as the handler returns. + UpdateBookCoverCommand command = new(bookId, cover?.OpenReadStream(), cover?.FileName); + try + { + Result result = await _updateBookCoverCommandHandler.HandleAsync(command, cancellationToken).ConfigureAwait(false); + return result.Match(success => TypedResults.Ok(success), Problem); + } + finally + { + command.Cover?.Dispose(); + } + } +} diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/UpdateBookCover/UpdateBookCoverEndpointSummary.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/UpdateBookCover/UpdateBookCoverEndpointSummary.cs new file mode 100644 index 00000000..a7f89cfe --- /dev/null +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/UpdateBookCover/UpdateBookCoverEndpointSummary.cs @@ -0,0 +1,86 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Presentation.Api.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.Books.UpdateBookCover; + +/// +/// Class used for providing a textual description for the API endpoint, for OpenAPI. +/// +[ExcludeFromCodeCoverage] +public class UpdateBookCoverEndpointSummary : Summary +{ + /// + /// Initializes a new instance of the class. + /// + public UpdateBookCoverEndpointSummary() + { + Summary = "Updates the cover image of a book."; + Description = "Updates the cover image of the book identified by the request, with the image uploaded in the multipart form of the request."; + + Response(200, "The relative path of the stored cover image is returned.", + example: "/media/books/books-3f2504e0-4f89-41d3-9a0c-0305e82c3301/The Lord of the Rings-2b0e5f5a-0b3f-4b7e-8f4a-8c9e3d2f5a6b/cover.jpg" + ); + + Response(401, "Authentication required.", "application/problem+json", + example: new + { + type = "https://tools.ietf.org/html/rfc7235#section-3.1", + status = 401, + title = "Unauthorized", + detail = "You are not authorized", + instance = "/api/v1/books/{id}/cover" + } + ); + + Response(403, "The request failed because the user making the request is not an Admin, or the owner of the media library.", "application/problem+json", + example: new + { + type = "https://tools.ietf.org/html/rfc9110#section-15.5.4", + title = "General.Unauthorized", + status = 403, + detail = "NotAuthorized", + instance = "/api/v1/books/{id}/cover", + traceId = "00-a712bbf99ca8ab485f86a762ae5ae74d-b3a2eb78813b0a5d-00" + } + ); + + Response(404, "The request failed because the book or its media library does not exist.", "application/problem+json", + example: new + { + type = "https://tools.ietf.org/html/rfc9110#section-15.5.5", + title = "General.NotFound", + status = 404, + detail = "BookNotFound", + instance = "/api/v1/books/{id}/cover", + traceId = "00-57d15dadd702dbd4aeb5dc9b7cee68ee-9330237dbb2ce0e5-00" + } + ); + + Response(422, "The request did not pass validation checks.", "application/problem+json", + example: new + { + type = "https://tools.ietf.org/html/rfc4918#section-11.2", + title = "General.Validation", + status = 422, + detail = "OneOrMoreValidationErrorsOccurred", + instance = "/api/v1/books/{id}/cover", + errors = new Dictionary + { + { + "General.Validation", new[] + { + "BookIdCannotBeEmpty", + "BookCoverCannotBeNull", + "FileTooLarge", + "CoverFileMustBeAnImage" + } + } + }, + traceId = "00-2470be4248a2a5a0c6f70579975a6954-b9c3ba9544a03500-00" + } + ); + } +} diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Maintenance/ApplicationSetup/SetupApplicationEndpointSummary.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Maintenance/ApplicationSetup/SetupApplicationEndpointSummary.cs index c3ee6d0f..667359ba 100644 --- a/src/Lumina.Presentation.Api/Core/Endpoints/Maintenance/ApplicationSetup/SetupApplicationEndpointSummary.cs +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Maintenance/ApplicationSetup/SetupApplicationEndpointSummary.cs @@ -74,7 +74,7 @@ public class SetupApplicationEndpointSummary : Summary(stream, _jsonOptions, cancellationToken).ConfigureAwait(false)) { if (cancellationToken.IsCancellationRequested) @@ -110,17 +110,17 @@ public class ApiHttpClient : IApiHttpClient using HttpResponseMessage response = await _httpClient.SendAsync(request, cancellationToken).ConfigureAwait(false); if (!response.IsSuccessStatusCode) { - // read the content as a string, for error messages + // Read the content as a string, for error messages. string content = await response.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); ProblemDetailsDto? problemDetails = null; try { problemDetails = JsonSerializer.Deserialize(content, _jsonOptions); } - catch { /* if we can't deserialize to ProblemDetails, we'll just use the status code */ } + catch { /* If we can't deserialize to ProblemDetails, we'll just use the status code. */ } throw new ApiException(problemDetails, response.StatusCode); } - // if the response is successful, read it as a byte array + // If the response is successful, read it as a byte array. byte[] responseContent = await response.Content.ReadAsByteArrayAsync(cancellationToken).ConfigureAwait(false); string contentType = response.Content.Headers.ContentType?.ToString() ?? "application/octet-stream"; return new BlobDataDto { Data = responseContent, ContentType = contentType }; @@ -137,19 +137,18 @@ public class ApiHttpClient : IApiHttpClient AuthenticationHeaderValue? authenticationHeader = GetAuthenticationHeader(); if (authenticationHeader is not null) request.Headers.Authorization = authenticationHeader; - //return await SendRequestAsync(request, cancellationToken).ConfigureAwait(false); - // send the HTTP request and read the response + // Send the HTTP request and read the response. HttpResponseMessage response = await _httpClient.SendAsync(request, cancellationToken).ConfigureAwait(false); if (!response.IsSuccessStatusCode) { ProblemDetailsDto? problemDetails = null; string content = await response.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); - // attempt to deserialize the response content to ProblemDetailsDto if the request fails + // Attempt to deserialize the response content to ProblemDetailsDto if the request fails. try { problemDetails = JsonSerializer.Deserialize(content, _jsonOptions); } - catch { /* if we can't deserialize to ProblemDetails, we'll just use the status code */ } + catch { /* If we can't deserialize to ProblemDetails, we'll just use the status code. */ } throw new ApiException(problemDetails, response.StatusCode, request.RequestUri?.AbsolutePath); } } @@ -204,7 +203,7 @@ public class ApiHttpClient : IApiHttpClient /// The deserialized response containing the result of the POST request. public async Task PostMultipartAsync(string endpoint, Stream fileStream, string fileName, string fieldName, CancellationToken cancellationToken = default) { - // the file is streamed as a generic binary part, since the exact content type of the uploaded file is not known + // The file is streamed as a generic binary part, since the exact content type of the uploaded file is not known. using MultipartFormDataContent form = []; using StreamContent fileContent = new(fileStream); fileContent.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream"); @@ -220,6 +219,34 @@ public class ApiHttpClient : IApiHttpClient return await SendRequestAsync(request, cancellationToken).ConfigureAwait(false); } + /// + /// Sends a PUT request with a multipart form containing a single file 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 stream of the file to upload. + /// The name of the file to upload. + /// The name of the form field carrying the file. + /// Cancellation token that can be used to stop the execution. + /// The deserialized response containing the result of the PUT request. + public async Task PutMultipartAsync(string endpoint, Stream fileStream, string fileName, string fieldName, CancellationToken cancellationToken = default) + { + // The file is streamed as a generic binary part, since the exact content type of the uploaded file is not known. + using MultipartFormDataContent form = []; + using StreamContent fileContent = new(fileStream); + fileContent.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream"); + form.Add(fileContent, fieldName, fileName); + + using HttpRequestMessage request = new(HttpMethod.Put, endpoint) + { + Content = form + }; + AuthenticationHeaderValue? authenticationHeader = GetAuthenticationHeader(); + if (authenticationHeader is not null) + request.Headers.Authorization = authenticationHeader; + return await SendRequestAsync(request, cancellationToken).ConfigureAwait(false); + } + /// /// Sends an HTTP request and deserializes the response into the specified type if the request is successful. /// If the request fails, it attempts to deserialize the response content into a and throws an . @@ -231,13 +258,13 @@ public class ApiHttpClient : IApiHttpClient /// Thrown if the response is not successful, with the if available. private async Task SendRequestAsync(HttpRequestMessage request, CancellationToken cancellationToken) { - // send the HTTP request and read the response + // Send the HTTP request and read the response. HttpResponseMessage response = await _httpClient.SendAsync(request, cancellationToken).ConfigureAwait(false); string content = await response.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); - // if the response is successful, deserialize the content to TResponse and return it + // If the response is successful, deserialize the content to TResponse and return it. if (response.IsSuccessStatusCode) { - // handle empty content case + // Handle empty content case. if (string.IsNullOrEmpty(content)) return default!; return JsonSerializer.Deserialize(content, _jsonOptions)!; @@ -245,12 +272,12 @@ public class ApiHttpClient : IApiHttpClient else { ProblemDetailsDto? problemDetails = null; - // attempt to deserialize the response content to ProblemDetailsDto if the request fails + // Attempt to deserialize the response content to ProblemDetailsDto if the request fails. try { problemDetails = JsonSerializer.Deserialize(content, _jsonOptions); } - catch { /* if we can't deserialize to ProblemDetails, we'll just use the status code */ } + catch { /* If we can't deserialize to ProblemDetails, we'll just use the status code. */ } throw new ApiException(problemDetails, response.StatusCode, request.RequestUri?.AbsolutePath); } } diff --git a/src/Lumina.Presentation.Web/Common/Api/IApiHttpClient.cs b/src/Lumina.Presentation.Web/Common/Api/IApiHttpClient.cs index fa208872..ae7d9d45 100644 --- a/src/Lumina.Presentation.Web/Common/Api/IApiHttpClient.cs +++ b/src/Lumina.Presentation.Web/Common/Api/IApiHttpClient.cs @@ -57,6 +57,18 @@ public interface IApiHttpClient /// The deserialized response containing the result of the PUT request. Task PutAsync(string endpoint, TModel data, CancellationToken cancellationToken = default); + /// + /// Sends a PUT request with a multipart form containing a single file 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 stream of the file to upload. + /// The name of the file to upload. + /// The name of the form field carrying the file. + /// Cancellation token that can be used to stop the execution. + /// The deserialized response containing the result of the PUT request. + Task PutMultipartAsync(string endpoint, Stream fileStream, string fileName, string fieldName, CancellationToken cancellationToken = default); + /// /// Sends a POST request with a multipart form containing a single file to the specified as an asynchronous operation and returns the result. /// diff --git a/src/Lumina.Presentation.Web/Common/DTO/WrittenContentLibrary/BookLibrary/BookDetailsDto.cs b/src/Lumina.Presentation.Web/Common/DTO/WrittenContentLibrary/BookLibrary/BookDetailsDto.cs new file mode 100644 index 00000000..087cdda6 --- /dev/null +++ b/src/Lumina.Presentation.Web/Common/DTO/WrittenContentLibrary/BookLibrary/BookDetailsDto.cs @@ -0,0 +1,143 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Common.DTO.MediaContributors; +using Lumina.Presentation.Web.Common.DTO.WrittenContentLibrary; +using Lumina.Presentation.Web.Common.DTO.WrittenContentLibrary.BookLibrary; +using Lumina.Presentation.Web.Common.Enums.BookLibrary; +using System; +using System.Collections.Generic; +using System.Diagnostics; +#endregion + +namespace Lumina.Presentation.Web.Common.DTO.WrittenContentLibrary.BookLibrary; + +/// +/// Data transfer object carrying the full details of a book, as stored in the media library. +/// +[DebuggerDisplay("Title: {Metadata?.Title}")] +public class BookDetailsDto +{ + /// + /// Gets or sets the Id of the book. + /// + public Guid Id { get; set; } + + /// + /// Gets or sets the Id of the media library this book belongs to. + /// + public Guid LibraryId { get; set; } + + /// + /// Gets or sets the file system path of the book. + /// + public string Path { get; set; } = null!; + + /// + /// Gets or sets the written content metadata of the book. + /// + public WrittenContentMetadataDto? 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 float? VolumeNumber { 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 of the book. + /// + public List? Contributors { get; set; } + + /// + /// Gets or sets the list of ratings of the book. + /// + public List? Ratings { get; set; } + + /// + /// Gets or sets the status of the metadata enrichment of the book. + /// + public string? MetadataStatus { get; set; } + + /// + /// Gets or sets the date and time when the metadata of the book was last enriched, if applicable. + /// + public DateTime? LastMetadataUpdateUtc { get; set; } + + /// + /// Gets or sets the name of the plugin that enriched the metadata of the book, if applicable. + /// + public string? MetadataProvider { get; set; } + + /// + /// Gets or sets the date and time when the book was created. + /// + public DateTime CreatedOnUtc { get; set; } + + /// + /// Gets or sets the optional date and time when the book was updated. + /// + public DateTime? UpdatedOnUtc { get; set; } + + /// + /// Gets or sets the path of the cover image of the book, if available. + /// + public string? CoverPath { get; set; } +} diff --git a/src/Lumina.Presentation.Web/Common/Requests/Library/WrittenContentLibrary/BookLibrary/Books/GetBookRequest.cs b/src/Lumina.Presentation.Web/Common/Requests/Library/WrittenContentLibrary/BookLibrary/Books/GetBookRequest.cs index d3596561..eff995d1 100644 --- a/src/Lumina.Presentation.Web/Common/Requests/Library/WrittenContentLibrary/BookLibrary/Books/GetBookRequest.cs +++ b/src/Lumina.Presentation.Web/Common/Requests/Library/WrittenContentLibrary/BookLibrary/Books/GetBookRequest.cs @@ -1,5 +1,4 @@ #region ========================================================================= USING ===================================================================================== -using System; using System.Diagnostics; #endregion @@ -8,8 +7,8 @@ namespace Lumina.Presentation.Web.Common.Requests.Library.WrittenContentLibrary. /// /// Represents a request to get a book by the specified Id. /// -/// The unique identifier of the book to retrieve. Required. +/// The unique identifier of the book to retrieve, taken from the route. Required. [DebuggerDisplay("Id: {Id}")] public record GetBookRequest( - Guid Id + string Id ); diff --git a/src/Lumina.Presentation.Web/Common/Requests/Library/WrittenContentLibrary/BookLibrary/Books/UpdateBookRequest.cs b/src/Lumina.Presentation.Web/Common/Requests/Library/WrittenContentLibrary/BookLibrary/Books/UpdateBookRequest.cs new file mode 100644 index 00000000..29ec1889 --- /dev/null +++ b/src/Lumina.Presentation.Web/Common/Requests/Library/WrittenContentLibrary/BookLibrary/Books/UpdateBookRequest.cs @@ -0,0 +1,107 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Common.DTO.MediaContributors; +using Lumina.Presentation.Web.Common.DTO.WrittenContentLibrary; +using Lumina.Presentation.Web.Common.DTO.WrittenContentLibrary.BookLibrary; +using Lumina.Presentation.Web.Common.Enums.BookLibrary; +using System.Collections.Generic; +using System.Diagnostics; +#endregion + +namespace Lumina.Presentation.Web.Common.Requests.Library.WrittenContentLibrary.BookLibrary.Books; + +/// +/// Represents a request to update an existing book. +/// +[DebuggerDisplay("Title: {Metadata?.Title}")] +public class UpdateBookRequest +{ + /// + /// Gets or sets the Id of the book to update, taken from the route. + /// + public string? Id { get; set; } + + /// + /// Gets or sets the written content metadata of the book. + /// + public WrittenContentMetadataDto? 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 float? VolumeNumber { get; set; } + + /// + /// Gets or sets the series name, if the book is part of a series. + /// + public BookSeriesDto? 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 of the book. + /// + public List? Contributors { get; set; } + + /// + /// Gets or sets the list of ratings of the book. + /// + public List? Ratings { get; set; } +} diff --git a/src/Lumina.Presentation.Web/Common/Routes/ApiRoutes.Books.cs b/src/Lumina.Presentation.Web/Common/Routes/ApiRoutes.Books.cs index e1363258..5956a3b3 100644 --- a/src/Lumina.Presentation.Web/Common/Routes/ApiRoutes.Books.cs +++ b/src/Lumina.Presentation.Web/Common/Routes/ApiRoutes.Books.cs @@ -11,6 +11,9 @@ public static partial class ApiRoutes public static class Books { public const string GET_BOOKS_LITE = "books/lite"; + public const string GET_BOOK = "books/{id}"; + public const string UPDATE_BOOK = "books/{id}"; + public const string UPDATE_BOOK_COVER = "books/{id}/cover"; public const string GET_BOOK_READING_MANIFEST = "books/{bookId}/reading/manifest"; public const string GET_BOOK_READING_AVAILABILITY = "books/{bookId}/reading/availability"; public const string GET_BOOK_READING_SECTION = "books/{bookId}/reading/sections/{locationRef}"; diff --git a/src/Lumina.Presentation.Web/Common/Routes/WebRoutes.Books.cs b/src/Lumina.Presentation.Web/Common/Routes/WebRoutes.Books.cs index 9d52a31e..1eed9199 100644 --- a/src/Lumina.Presentation.Web/Common/Routes/WebRoutes.Books.cs +++ b/src/Lumina.Presentation.Web/Common/Routes/WebRoutes.Books.cs @@ -13,6 +13,9 @@ public static partial class WebRoutes public const string INDEX = "{culture}/library/written-content-library/books-library/books"; public const string GET_LIBRARY_ITEMS = "{culture}/library/written-content-library/books-library/books/api-get-library-items"; public const string EDIT_BOOK = "{culture}/library/written-content-library/books-library/books/{id}"; + public const string GET_BOOK_DETAILS = "{culture}/library/written-content-library/books-library/books/{id}/api-get-book"; + public const string SAVE_BOOK = "{culture}/library/written-content-library/books-library/books/{id}/api-save-book"; + public const string UPDATE_BOOK_COVER = "{culture}/library/written-content-library/books-library/books/{id}/api-update-cover"; public const string READ = "{culture}/library/written-content-library/books-library/books/{bookId}/read"; public const string GET_READING_MANIFEST = "{culture}/library/written-content-library/books-library/books/{bookId}/api-get-reading-manifest"; public const string GET_READING_AVAILABILITY = "{culture}/library/written-content-library/books-library/books/{bookId}/api-get-reading-availability"; diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/EditBook/EditBookViewEndpoint.cs b/src/Lumina.Presentation.Web/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/EditBook/EditBookViewEndpoint.cs index a6fd1b71..dc80331c 100644 --- a/src/Lumina.Presentation.Web/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/EditBook/EditBookViewEndpoint.cs +++ b/src/Lumina.Presentation.Web/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/EditBook/EditBookViewEndpoint.cs @@ -1,10 +1,21 @@ #region ========================================================================= USING ===================================================================================== using FastEndpoints; +using Lumina.Presentation.Web.Common.Api; +using Lumina.Presentation.Web.Common.DTO.Themes; +using Lumina.Presentation.Web.Common.DTO.WrittenContentLibrary.BookLibrary; +using Lumina.Presentation.Web.Common.Primitives; using Lumina.Presentation.Web.Common.Requests.Library.WrittenContentLibrary.BookLibrary.Books; using Lumina.Presentation.Web.Common.Routes; +using Lumina.Presentation.Web.Common.Services; using Lumina.Presentation.Web.Core.Endpoints.Common; -using Microsoft.AspNetCore.Builder; +using Lumina.Presentation.Web.Core.Themes; +using Microsoft.AspNetCore.Antiforgery; using Microsoft.AspNetCore.Http; +using Microsoft.Extensions.Localization; +using System; +using System.Collections.Generic; +using System.Text.Json; +using System.Text.Json.Serialization; using System.Threading; using System.Threading.Tasks; #endregion @@ -16,6 +27,42 @@ namespace Lumina.Presentation.Web.Core.Endpoints.Library.WrittenContentLibrary.B /// public class EditBookViewEndpoint : BaseEndpoint { + // The resource base name deliberately excludes the "Core.Resources" segment: the localization factory re-roots it with the configured ResourcesPath, + // so "Lumina.Presentation.Web.Views.X" resolves to the embedded "Lumina.Presentation.Web.Core.Resources.Views.X" resource; including "Core" here would insert it twice. + private const string VIEW_RESOURCE_BASE_NAME = "Lumina.Presentation.Web.Views.Library.WrittenContentLibrary.BookLibrary.Books.Item"; + private const string VIEW_RESOURCE_LOCATION = "Lumina.Presentation.Web"; + // The page key mirrors the path of the Razor view under Core/Views, so that theme templates can override it at the page, section or default scope. + private const string VIEW_PAGE_KEY = "library/written-content-library/book-library/books/item"; + + private static readonly JsonSerializerOptions s_camelCaseJsonOptions = new() + { + PropertyNamingPolicy = JsonNamingPolicy.CamelCase, + Converters = { new JsonStringEnumConverter() } + }; + + private readonly IApiHttpClient _apiHttpClient; + private readonly IUrlService _urlService; + private readonly ThemePageRenderer _themePageRenderer; + private readonly IAntiforgery _antiforgery; + private readonly IStringLocalizer _localizer; + + /// + /// Initializes a new instance of the class. + /// + /// Injected service for interactions with the API. + /// Injected service for generating URLs from action and controller names, with localization. + /// Injected service for rendering themed pages. + /// Injected service for anti-forgery token handling. + /// Injected factory used to create the localizer of the view resources. + public EditBookViewEndpoint(IApiHttpClient apiHttpClient, IUrlService urlService, ThemePageRenderer themePageRenderer, IAntiforgery antiforgery, IStringLocalizerFactory stringLocalizerFactory) + { + _apiHttpClient = apiHttpClient; + _urlService = urlService; + _themePageRenderer = themePageRenderer; + _antiforgery = antiforgery; + _localizer = stringLocalizerFactory.Create(VIEW_RESOURCE_BASE_NAME, VIEW_RESOURCE_LOCATION); + } + /// /// Configures the endpoint. /// @@ -29,12 +76,58 @@ public class EditBookViewEndpoint : BaseEndpoint } /// - /// Displays the book editing view. + /// Displays the book editing view, rendered by the active theme with a fallback to the Razor view. /// - /// The request object. + /// The request containing the Id of the book to view. /// Cancellation token that can be used to stop the execution. - public override Task ExecuteAsync(GetBookRequest request, CancellationToken cancellationToken) + public override async Task ExecuteAsync(GetBookRequest request, CancellationToken cancellationToken) { - return Task.FromResult(View("/Core/Views/Library/WrittenContentLibrary/BookLibrary/Books/Item.cshtml")); + // The view needs the full details of the book to show its current values, so they are fetched from the API up front; the route + // value is normalized to a Guid before it is substituted into the upstream URL, so that a crafted route value can never escape + // its URL segment, and an unparseable id is reported by the API as a missing book id. + request = request with { Id = Guid.TryParse(request.Id, out Guid bookId) ? bookId.ToString() : Guid.Empty.ToString() }; + BookDetailsDto book = await _apiHttpClient.GetAsync(ApiRoutes.Books.GET_BOOK.Replace("{id}", request.Id), cancellationToken).ConfigureAwait(false); + string title = book.Metadata?.Title ?? string.Empty; + + // The themed view is a regular page that submits its own requests, so a fresh anti-forgery token must be issued for it. + AntiforgeryTokenSet antiforgeryTokens = _antiforgery.GetAndStoreTokens(HttpContext); + + // The theme template receives the book data, the URLs of the actions of the view and the localized strings as page data, + // serialized as JSON so that the template can bind them without executing server side code of its own. + ThemePageDto pageModel = new() + { + PageKey = VIEW_PAGE_KEY, + Title = title, + Description = string.Empty, + PageData = new Dictionary + { + ["bookId"] = book.Id.ToString(), + ["libraryId"] = book.LibraryId.ToString(), + ["antiforgeryToken"] = antiforgeryTokens.RequestToken, + ["saveUrl"] = _urlService.GetAbsoluteUrl(WebRoutes.Books.SAVE_BOOK, new { id = default(Guid) }) ?? string.Empty, + ["coverUrl"] = _urlService.GetAbsoluteUrl(WebRoutes.Books.UPDATE_BOOK_COVER, new { id = default(Guid) }) ?? string.Empty, + ["backUrl"] = (_urlService.GetAbsoluteUrl(WebRoutes.Books.INDEX) ?? string.Empty) + "?libraryId=" + book.LibraryId, + ["bookJson"] = JsonSerializer.Serialize(book, s_camelCaseJsonOptions), + ["strings"] = ThemePageDataFactory.CreateLocalizedStrings(_localizer), + ["stringsJson"] = JsonSerializer.Serialize(ThemePageDataFactory.CreateLocalizedStrings(_localizer), s_camelCaseJsonOptions) + } + }; + + // Themed rendering is best effort: when the active theme does not provide the item template, the plain Razor fallback is rendered instead. + Result sectionResult = await _themePageRenderer.RenderAsync(pageModel, requestedThemeId: null, cancellationToken).ConfigureAwait(false); + if (sectionResult.IsFailure) + { + Dictionary viewData = new() + { + ["Title"] = title + }; + return View("/Core/Views/Library/WrittenContentLibrary/BookLibrary/Books/Item.cshtml", book, viewData); + } + + // On a healthy site the page is composed by the theme, so the theme content and script are wrapped in the shared themed view. + return View( + "/Core/Views/Shared/_ThemedView.cshtml", + new ThemeViewDto(sectionResult.Value.Content, sectionResult.Value.Script), + new Dictionary { ["Title"] = title }); } } diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/EditBook/EditBookViewEndpointSummary.cs b/src/Lumina.Presentation.Web/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/EditBook/EditBookViewEndpointSummary.cs index 99d323d5..f00e4870 100644 --- a/src/Lumina.Presentation.Web/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/EditBook/EditBookViewEndpointSummary.cs +++ b/src/Lumina.Presentation.Web/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/EditBook/EditBookViewEndpointSummary.cs @@ -24,7 +24,7 @@ public class EditBookViewEndpointSummary : Summary r.Id, "The unique identifier of the book to edit. Required."); ExampleRequest = new GetBookRequest( - Id: Guid.NewGuid() + Id: Guid.NewGuid().ToString() ); Response(200, "The view for editing the book is rendered."); diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/GetBookDetails/GetBookDetailsEndpoint.cs b/src/Lumina.Presentation.Web/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/GetBookDetails/GetBookDetailsEndpoint.cs new file mode 100644 index 00000000..34c07891 --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/GetBookDetails/GetBookDetailsEndpoint.cs @@ -0,0 +1,59 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Presentation.Web.Common.Api; +using Lumina.Presentation.Web.Common.DTO.WrittenContentLibrary.BookLibrary; +using Lumina.Presentation.Web.Common.Requests.Library.WrittenContentLibrary.BookLibrary.Books; +using Lumina.Presentation.Web.Common.Routes; +using Lumina.Presentation.Web.Core.Endpoints.Common; +using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Http; +using System; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.Books.GetBookDetails; + +/// +/// API endpoint for the /{culture}/library/written-content-library/books-library/books/{id}/api-get-book route. +/// +public class GetBookDetailsEndpoint : BaseEndpoint +{ + private readonly IApiHttpClient _apiHttpClient; + + /// + /// Initializes a new instance of the class. + /// + /// Injected service for interactions with the API. + public GetBookDetailsEndpoint(IApiHttpClient apiHttpClient) + { + _apiHttpClient = apiHttpClient; + } + + /// + /// Configures the endpoint. + /// + public override void Configure() + { + base.Configure(); + Verbs(Http.GET); + Routes(WebRoutes.Books.GET_BOOK_DETAILS); + DontAutoTag(); + Options(options => options.WithTags("Books")); + } + + /// + /// Retrieves the full details of the book identified by . + /// + /// The request containing the Id of the book to retrieve. + /// Cancellation token that can be used to stop the execution. + public override async Task ExecuteAsync(GetBookRequest request, CancellationToken cancellationToken) + { + // The route value is normalized to a Guid before it is substituted into the upstream URL, so that a crafted route value can + // never escape its URL segment, and an unparseable id is reported by the API as a missing book id. + request = request with { Id = Guid.TryParse(request.Id, out Guid bookId) ? bookId.ToString() : Guid.Empty.ToString() }; + + BookDetailsDto book = await _apiHttpClient.GetAsync(ApiRoutes.Books.GET_BOOK.Replace("{id}", request.Id), cancellationToken).ConfigureAwait(false); + return JsonSuccess(book); + } +} diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/GetBookDetails/GetBookDetailsEndpointSummary.cs b/src/Lumina.Presentation.Web/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/GetBookDetails/GetBookDetailsEndpointSummary.cs new file mode 100644 index 00000000..c8a50e2f --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/GetBookDetails/GetBookDetailsEndpointSummary.cs @@ -0,0 +1,34 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Presentation.Web.Common.DTO.Common; +using Lumina.Presentation.Web.Common.DTO.WrittenContentLibrary.BookLibrary; +using Lumina.Presentation.Web.Common.Requests.Library.WrittenContentLibrary.BookLibrary.Books; +using System; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Presentation.Web.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.Books.GetBookDetails; + +/// +/// Class used for providing a textual description for the endpoint, for OpenAPI. +/// +[ExcludeFromCodeCoverage] +public class GetBookDetailsEndpointSummary : Summary +{ + /// + /// Initializes a new instance of the class. + /// + public GetBookDetailsEndpointSummary() + { + Summary = "Gets the details of a book."; + Description = "Gets the full details of the book identified by the request, for the details and editing view."; + + RequestParam(r => r.Id, "The unique identifier of the book to get. Required."); + + ExampleRequest = new GetBookRequest( + Id: Guid.NewGuid().ToString() + ); + + Response(200, "The details of the book are returned.", example: new SuccessResponse(true, default)); + } +} diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/Index/BooksIndexViewEndpoint.cs b/src/Lumina.Presentation.Web/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/Index/BooksIndexViewEndpoint.cs index 9874ba4b..851f1489 100644 --- a/src/Lumina.Presentation.Web/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/Index/BooksIndexViewEndpoint.cs +++ b/src/Lumina.Presentation.Web/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/Index/BooksIndexViewEndpoint.cs @@ -87,6 +87,7 @@ public class BooksIndexViewEndpoint : BaseEndpoint ["itemsUrl"] = _urlService.GetAbsoluteUrl(WebRoutes.Books.GET_LIBRARY_ITEMS) ?? string.Empty, ["settingsUrl"] = _urlService.GetAbsoluteUrl(WebRoutes.Settings.GET_USER_SETTINGS) ?? string.Empty, ["readUrl"] = _urlService.GetAbsoluteUrl(WebRoutes.Books.READ, new { bookId = default(Guid) }) ?? string.Empty, + ["detailsUrl"] = _urlService.GetAbsoluteUrl(WebRoutes.Books.EDIT_BOOK, new { id = default(Guid) }) ?? string.Empty, ["availabilityUrl"] = _urlService.GetAbsoluteUrl(WebRoutes.Books.GET_READING_AVAILABILITY, new { bookId = default(Guid) }) ?? string.Empty, ["strings"] = ThemePageDataFactory.CreateLocalizedStrings(_localizer) } diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/SaveBook/SaveBookEndpoint.cs b/src/Lumina.Presentation.Web/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/SaveBook/SaveBookEndpoint.cs new file mode 100644 index 00000000..e51e1720 --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/SaveBook/SaveBookEndpoint.cs @@ -0,0 +1,63 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Presentation.Web.Common.Api; +using Lumina.Presentation.Web.Common.DTO.WrittenContentLibrary.BookLibrary; +using Lumina.Presentation.Web.Common.Requests.Library.WrittenContentLibrary.BookLibrary.Books; +using Lumina.Presentation.Web.Common.Routes; +using Lumina.Presentation.Web.Core.Endpoints.Common; +using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Http; +using System; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.Books.SaveBook; + +/// +/// API endpoint for the /{culture}/library/written-content-library/books-library/books/{id}/api-save-book route. +/// +public class SaveBookEndpoint : BaseEndpoint +{ + private readonly IApiHttpClient _apiHttpClient; + + /// + /// Initializes a new instance of the class. + /// + /// Injected service for interactions with the API. + public SaveBookEndpoint(IApiHttpClient apiHttpClient) + { + _apiHttpClient = apiHttpClient; + } + + /// + /// Configures the endpoint. + /// + public override void Configure() + { + base.Configure(); + Verbs(Http.PUT); + Routes(WebRoutes.Books.SAVE_BOOK); + DontAutoTag(); + Options(options => options.WithTags("Books")); + EnableAntiforgery(); + } + + /// + /// Updates the book described by . + /// + /// The request containing the edited details of the book. + /// Cancellation token that can be used to stop the execution. + public override async Task ExecuteAsync(UpdateBookRequest request, CancellationToken cancellationToken) + { + // The book is identified by the {id} route value, not by the id posted in the form, so that a mismatched id can never redirect + // the update to another book; the value is normalized to a Guid before it is substituted into the upstream URL, so that a crafted + // route value can never escape its URL segment, and an unparseable id is reported by the API as a missing book id. + string routeId = HttpContext.Request.RouteValues["id"]?.ToString() ?? string.Empty; + request.Id = Guid.TryParse(routeId, out Guid bookId) ? bookId.ToString() : Guid.Empty.ToString(); + + BookDetailsDto book = await _apiHttpClient.PutAsync( + ApiRoutes.Books.UPDATE_BOOK.Replace("{id}", request.Id), request, cancellationToken).ConfigureAwait(false); + return JsonSuccess(book); + } +} diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/SaveBook/SaveBookEndpointSummary.cs b/src/Lumina.Presentation.Web/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/SaveBook/SaveBookEndpointSummary.cs new file mode 100644 index 00000000..22a8b39c --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/SaveBook/SaveBookEndpointSummary.cs @@ -0,0 +1,159 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Presentation.Web.Common.DTO.Common; +using Lumina.Presentation.Web.Common.DTO.MediaContributors; +using Lumina.Presentation.Web.Common.DTO.WrittenContentLibrary; +using Lumina.Presentation.Web.Common.DTO.WrittenContentLibrary.BookLibrary; +using Lumina.Presentation.Web.Common.Enums.BookLibrary; +using Lumina.Presentation.Web.Common.Requests.Library.WrittenContentLibrary.BookLibrary.Books; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Presentation.Web.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.Books.SaveBook; + +/// +/// Class used for providing a textual description for the endpoint, for OpenAPI. +/// +[ExcludeFromCodeCoverage] +public class SaveBookEndpointSummary : Summary +{ + /// + /// Initializes a new instance of the class. + /// + public SaveBookEndpointSummary() + { + Summary = "Updates a book."; + Description = "Updates the details of the book identified by the request."; + + RequestParam(r => r.Id, "The unique identifier of the book to update. Required."); + RequestParam(r => r.Metadata, "The written content metadata of the book. Required."); + RequestParam(r => r.Metadata!.Title, "The title of the book. Required."); + RequestParam(r => r.Metadata!.OriginalTitle, "The original title of the book, if different from the current title. Optional."); + RequestParam(r => r.Metadata!.Description, "A brief description or summary of the book. Optional."); + RequestParam(r => r.Metadata!.ReleaseInfo, "The release information, including release date and other relevant details. Required."); + RequestParam(r => r.Metadata!.ReleaseInfo!.OriginalReleaseDate, "The original release date of the book. Optional."); + RequestParam(r => r.Metadata!.ReleaseInfo!.OriginalReleaseYear, "The original release year of the book. Optional."); + RequestParam(r => r.Metadata!.ReleaseInfo!.ReReleaseDate, "The re-release date of the book. Optional."); + RequestParam(r => r.Metadata!.ReleaseInfo!.ReReleaseYear, "The re-release year of the book. Optional."); + RequestParam(r => r.Metadata!.ReleaseInfo!.ReleaseCountry, "The country where the book was released. Optional."); + RequestParam(r => r.Metadata!.ReleaseInfo!.ReleaseVersion, "The version or edition of the release of the book. Optional."); + RequestParam(r => r.Metadata!.Genres, "The list of genres of the book. Required."); + RequestParam(r => r.Metadata!.Tags, "The list of tags of the book. Required."); + RequestParam(r => r.Metadata!.Language, "The language in which the book is written. Optional."); + RequestParam(r => r.Metadata!.Language!.LanguageCode, "The ISO code of the language of the book. Optional."); + RequestParam(r => r.Metadata!.Language!.LanguageName, "The name of the language of the book in English. Optional."); + RequestParam(r => r.Metadata!.Language!.NativeName, "The native name of the language of the book. Optional."); + RequestParam(r => r.Metadata!.OriginalLanguage, "The original language of the book, if it has been translated. Optional."); + RequestParam(r => r.Metadata!.OriginalLanguage!.LanguageCode, "The ISO code of the original language of the book. Optional."); + RequestParam(r => r.Metadata!.OriginalLanguage!.LanguageName, "The name of the original language of the book in English. Optional."); + RequestParam(r => r.Metadata!.OriginalLanguage!.NativeName, "The native name of the original language of the book. Optional."); + RequestParam(r => r.Metadata!.Publisher, "The publisher of the book. Optional."); + RequestParam(r => r.Metadata!.PageCount, "The number of pages of the book. Optional."); + RequestParam(r => r.Format, "The format of the book (e.g., Hardcover, Paperback). Optional."); + RequestParam(r => r.Edition, "The edition of the book. Optional."); + RequestParam(r => r.VolumeNumber, "The volume or book number in the series. Optional."); + RequestParam(r => r.Series, "The series the book is part of. Optional."); + RequestParam(r => r.Series!.Title, "The title of the series the book is part of. Optional."); + RequestParam(r => r.ASIN, "The ASIN (Amazon Standard Identification Number) of the book. Optional."); + RequestParam(r => r.GoodreadsId, "The Goodreads Id of the book. Optional."); + RequestParam(r => r.LCCN, "The Library of Congress Control Number (LCCN) of the book. Optional."); + RequestParam(r => r.OCLCNumber, "The OCLC Number (WorldCat identifier) of the book. Optional."); + RequestParam(r => r.OpenLibraryId, "The Open Library Id of the book. Optional."); + RequestParam(r => r.LibraryThingId, "The LibraryThing Id of the book. Optional."); + RequestParam(r => r.GoogleBooksId, "The Google Books Id of the book. Optional."); + RequestParam(r => r.BarnesAndNobleId, "The Barnes & Noble Id of the book. Optional."); + RequestParam(r => r.AppleBooksId, "The Apple Books Id of the book. Optional."); + RequestParam(r => r.ISBNs, "The list of ISBN (International Standard Book Number) of the book. Required."); + RequestParam(r => r.Contributors, "The list of media contributors of the book. Required."); + RequestParam(r => r.Ratings, "The list of ratings of the book. Required."); + + ExampleRequest = new UpdateBookRequest + { + Id = Guid.NewGuid().ToString(), + Metadata = new WrittenContentMetadataDto + { + Title = "The Fellowship of the Ring", + OriginalTitle = "The Fellowship of the Ring", + Description = "The first part of J.R.R. Tolkien's epic adventure The Lord of the Rings. In a sleepy village in the Shire, young Frodo Baggins finds himself faced with an immense task, as his elderly cousin Bilbo entrusts the Ring to his care. Frodo must leave his home and make a perilous journey across Middle-earth to the Cracks of Doom, there to destroy the Ring and foil the Dark Lord in his evil purpose.", + ReleaseInfo = new ReleaseInfoDto + { + OriginalReleaseDate = new DateOnly(1954, 7, 29), + OriginalReleaseYear = 1954, + ReReleaseDate = new DateOnly(2001, 9, 6), + ReReleaseYear = 2001, + ReleaseCountry = "uk", + ReleaseVersion = "50th Anniversary Edition" + }, + Genres = + [ + new GenreDto { Name = "fantasy" }, + new GenreDto { Name = "adventure" }, + new GenreDto { Name = "classic" } + ], + Tags = + [ + new TagDto { Name = "epic fantasy" }, + new TagDto { Name = "quest" }, + new TagDto { Name = "middle-earth" } + ], + Language = new LanguageInfoDto + { + LanguageCode = "en", + LanguageName = "English", + NativeName = "English" + }, + OriginalLanguage = new LanguageInfoDto + { + LanguageCode = "en", + LanguageName = "English", + NativeName = "English" + }, + Publisher = "Houghton Mifflin", + PageCount = 398 + }, + Format = BookFormat.Paperback, + Edition = "50th Anniversary Edition", + VolumeNumber = 1, + Series = new BookSeriesDto + { + Title = "The Lord of the Rings" + }, + ASIN = "B007978NPG", + GoodreadsId = "3", + LCCN = "54009621", + OCLCNumber = "ocm00012345", + OpenLibraryId = "OL7603910M", + LibraryThingId = "3203347", + GoogleBooksId = "aWZzLPhY4o0C", + BarnesAndNobleId = "1100307790", + AppleBooksId = "id395211", + ISBNs = + [ + new IsbnDto { Value = "0395272238", Format = IsbnFormat.Isbn10 }, + new IsbnDto { Value = "9780395272237", Format = IsbnFormat.Isbn13 } + ], + Contributors = + [ + new MediaContributorDto + { + Name = new MediaContributorNameDto { DisplayName = "J.R.R. Tolkien", LegalName = "John Ronald Reuel Tolkien" }, + Role = new MediaContributorRoleDto { Name = "author", Category = "Author" } + }, + new MediaContributorDto + { + Name = new MediaContributorNameDto { DisplayName = "Alan Lee", LegalName = "Alan Lee" }, + Role = new MediaContributorRoleDto { Name = "illustrator", Category = "Illustrator" } + } + ], + Ratings = + [ + new BookRatingDto { Source = BookRatingSource.GoogleBooks, Value = 4.36M, MaxValue = 5, VoteCount = 2345678 }, + new BookRatingDto { Source = BookRatingSource.Amazon, Value = 4.7M, MaxValue = 5, VoteCount = 87654 } + ] + }; + + Response(200, "The updated book is returned.", example: new SuccessResponse(true, default)); + } +} diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/UpdateBookCover/UpdateBookCoverEndpoint.cs b/src/Lumina.Presentation.Web/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/UpdateBookCover/UpdateBookCoverEndpoint.cs new file mode 100644 index 00000000..d6a5ee7b --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/UpdateBookCover/UpdateBookCoverEndpoint.cs @@ -0,0 +1,68 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Presentation.Web.Common.Api; +using Lumina.Presentation.Web.Common.Routes; +using Lumina.Presentation.Web.Core.Endpoints.Common; +using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Http; +using System; +using System.IO; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.Books.UpdateBookCover; + +/// +/// API endpoint for the /{culture}/library/written-content-library/books-library/books/{id}/api-update-cover route. +/// +public class UpdateBookCoverEndpoint : BaseEndpoint +{ + private readonly IApiHttpClient _apiHttpClient; + + /// + /// Initializes a new instance of the class. + /// + /// Injected service for interactions with the API. + public UpdateBookCoverEndpoint(IApiHttpClient apiHttpClient) + { + _apiHttpClient = apiHttpClient; + } + + /// + /// Configures the endpoint. + /// + public override void Configure() + { + base.Configure(); + Verbs(Http.PUT); + Routes(WebRoutes.Books.UPDATE_BOOK_COVER); + DontAutoTag(); + Options(options => options.WithTags("Books")); + EnableAntiforgery(); + } + + /// + /// Updates the cover image of the book with the image uploaded in the multipart form of the request. + /// + /// The request object. + /// Cancellation token that can be used to stop the execution. + public override async Task ExecuteAsync(EmptyRequest request, CancellationToken cancellationToken) + { + // The endpoint takes no typed request, because its body is a multipart file, so the book id is read from the {id} route + // value; an unparseable value becomes Guid.Empty, which the upstream API reports as a missing book id. + Guid bookId = Guid.TryParse(HttpContext.Request.RouteValues["id"]?.ToString(), out Guid parsedBookId) ? parsedBookId : Guid.Empty; + + // The cover is the first file of the multipart form, and without it the request cannot update anything. + IFormFile? cover = HttpContext.Request.Form.Files.Count > 0 ? HttpContext.Request.Form.Files[0] : null; + if (cover is null) + return Results.Problem(statusCode: StatusCodes.Status400BadRequest, detail: "The uploaded cover image is missing."); + + // The cover stream must stay open while the file is streamed to the API, and is disposed when the request completes. + await using Stream coverStream = cover.OpenReadStream(); + string? coverPath = await _apiHttpClient.PutMultipartAsync( + ApiRoutes.Books.UPDATE_BOOK_COVER.Replace("{id}", bookId.ToString()), coverStream, cover.FileName, "cover", cancellationToken).ConfigureAwait(false); + return JsonSuccess(coverPath); + } +} diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/UpdateBookCover/UpdateBookCoverEndpointSummary.cs b/src/Lumina.Presentation.Web/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/UpdateBookCover/UpdateBookCoverEndpointSummary.cs new file mode 100644 index 00000000..d86133f0 --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/UpdateBookCover/UpdateBookCoverEndpointSummary.cs @@ -0,0 +1,25 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Presentation.Web.Common.DTO.Common; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Presentation.Web.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.Books.UpdateBookCover; + +/// +/// Class used for providing a textual description for the endpoint, for OpenAPI. +/// +[ExcludeFromCodeCoverage] +public class UpdateBookCoverEndpointSummary : Summary +{ + /// + /// Initializes a new instance of the class. + /// + public UpdateBookCoverEndpointSummary() + { + Summary = "Updates the cover image of a book."; + Description = "Updates the cover image of the book identified by the request, with the image uploaded in the multipart form of the request."; + + Response(200, "The relative path of the stored cover image is returned.", example: new SuccessResponse(true, default)); + } +} diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/WrittenContentLibrary/BookLibrary/Books/Index.ar-SA.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/WrittenContentLibrary/BookLibrary/Books/Index.ar-SA.resx index ca9830c2..d3ef82d9 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/WrittenContentLibrary/BookLibrary/Books/Index.ar-SA.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/WrittenContentLibrary/BookLibrary/Books/Index.ar-SA.resx @@ -1,4 +1,4 @@ - + text/microsoft-resx @@ -51,4 +51,10 @@ قارئ الكتب الذي يفتح هذا الكتاب معطل لهذه المكتبة. قم بتمكينه في إعدادات المكتبة لقراءة الكتاب. + + اقرأ + + + عرض التفاصيل + diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/WrittenContentLibrary/BookLibrary/Books/Index.de-DE.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/WrittenContentLibrary/BookLibrary/Books/Index.de-DE.resx index 2fba039b..af0edfce 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/WrittenContentLibrary/BookLibrary/Books/Index.de-DE.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/WrittenContentLibrary/BookLibrary/Books/Index.de-DE.resx @@ -1,4 +1,4 @@ - + text/microsoft-resx @@ -51,4 +51,10 @@ Der Buchleser, der dieses Buch öffnet, ist für diese Mediathek deaktiviert. Aktivieren Sie ihn in den Mediathek-Einstellungen, um das Buch zu lesen. + + Lesen + + + Details anzeigen + diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/WrittenContentLibrary/BookLibrary/Books/Index.en-US.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/WrittenContentLibrary/BookLibrary/Books/Index.en-US.resx index 93f29cbc..7effa290 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/WrittenContentLibrary/BookLibrary/Books/Index.en-US.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/WrittenContentLibrary/BookLibrary/Books/Index.en-US.resx @@ -1,4 +1,4 @@ - + text/microsoft-resx @@ -51,4 +51,10 @@ The book reader that opens this book is disabled for this library. Enable it in the library settings to read the book. + + Read + + + View details + diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/WrittenContentLibrary/BookLibrary/Books/Index.es-ES.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/WrittenContentLibrary/BookLibrary/Books/Index.es-ES.resx index 7af89bbb..a9f6ee25 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/WrittenContentLibrary/BookLibrary/Books/Index.es-ES.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/WrittenContentLibrary/BookLibrary/Books/Index.es-ES.resx @@ -1,4 +1,4 @@ - + text/microsoft-resx @@ -51,4 +51,10 @@ El lector de libros que abre este libro está deshabilitado para esta biblioteca. Habilítelo en la configuración de la biblioteca para leer el libro. + + Leer + + + Ver detalles + diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/WrittenContentLibrary/BookLibrary/Books/Index.fr-FR.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/WrittenContentLibrary/BookLibrary/Books/Index.fr-FR.resx index 79d38825..29e1131e 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/WrittenContentLibrary/BookLibrary/Books/Index.fr-FR.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/WrittenContentLibrary/BookLibrary/Books/Index.fr-FR.resx @@ -1,4 +1,4 @@ - + text/microsoft-resx @@ -51,4 +51,10 @@ Le lecteur de livres qui ouvre ce livre est désactivé pour cette bibliothèque. Activez-le dans les paramètres de la bibliothèque pour lire le livre. + + Lire + + + Voir les détails + diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/WrittenContentLibrary/BookLibrary/Books/Index.it-IT.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/WrittenContentLibrary/BookLibrary/Books/Index.it-IT.resx index bdf944bd..4ba88908 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/WrittenContentLibrary/BookLibrary/Books/Index.it-IT.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/WrittenContentLibrary/BookLibrary/Books/Index.it-IT.resx @@ -1,4 +1,4 @@ - + text/microsoft-resx @@ -51,4 +51,10 @@ Il lettore di libri che apre questo libro è disabilitato per questa biblioteca. Abilitalo nelle impostazioni della biblioteca per leggere il libro. + + Leggi + + + Visualizza dettagli + diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/WrittenContentLibrary/BookLibrary/Books/Index.ja-JP.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/WrittenContentLibrary/BookLibrary/Books/Index.ja-JP.resx index cf1308f1..87fc1d44 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/WrittenContentLibrary/BookLibrary/Books/Index.ja-JP.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/WrittenContentLibrary/BookLibrary/Books/Index.ja-JP.resx @@ -1,4 +1,4 @@ - + text/microsoft-resx @@ -51,4 +51,10 @@ この本を開くブックリーダーは、このライブラリで無効になっています。ライブラリ設定で有効にすると本を読めます。 + + 読む + + + 詳細を表示 + diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/WrittenContentLibrary/BookLibrary/Books/Index.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/WrittenContentLibrary/BookLibrary/Books/Index.resx index 93f29cbc..7effa290 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/WrittenContentLibrary/BookLibrary/Books/Index.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/WrittenContentLibrary/BookLibrary/Books/Index.resx @@ -1,4 +1,4 @@ - + text/microsoft-resx @@ -51,4 +51,10 @@ The book reader that opens this book is disabled for this library. Enable it in the library settings to read the book. + + Read + + + View details + diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/WrittenContentLibrary/BookLibrary/Books/Index.ro-RO.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/WrittenContentLibrary/BookLibrary/Books/Index.ro-RO.resx index 244e911c..49c172e6 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/WrittenContentLibrary/BookLibrary/Books/Index.ro-RO.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/WrittenContentLibrary/BookLibrary/Books/Index.ro-RO.resx @@ -1,4 +1,4 @@ - + text/microsoft-resx @@ -51,4 +51,10 @@ Cititorul de cărți care deschide această carte este dezactivat pentru această bibliotecă. Activați-l în setările bibliotecii pentru a citi cartea. + + Citește + + + Vezi detalii + diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/WrittenContentLibrary/BookLibrary/Books/Index.uk-UA.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/WrittenContentLibrary/BookLibrary/Books/Index.uk-UA.resx index e20352f4..32a25ba4 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/WrittenContentLibrary/BookLibrary/Books/Index.uk-UA.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/WrittenContentLibrary/BookLibrary/Books/Index.uk-UA.resx @@ -1,4 +1,4 @@ - + text/microsoft-resx @@ -51,4 +51,10 @@ Читач книг, який відкриває цю книгу, вимкнено для цієї бібліотеки. Увімкніть його в налаштуваннях бібліотеки, щоб читати книгу. + + Читати + + + Переглянути деталі + diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/WrittenContentLibrary/BookLibrary/Books/Index.zh-CN.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/WrittenContentLibrary/BookLibrary/Books/Index.zh-CN.resx index de258336..5b5e8e0f 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/WrittenContentLibrary/BookLibrary/Books/Index.zh-CN.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/WrittenContentLibrary/BookLibrary/Books/Index.zh-CN.resx @@ -1,4 +1,4 @@ - + text/microsoft-resx @@ -51,4 +51,10 @@ 打开此图书的图书阅读器已在此媒体库中禁用。在媒体库设置中启用它即可阅读该图书。 + + 阅读 + + + 查看详情 + diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/WrittenContentLibrary/BookLibrary/Books/Item.ar-SA.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/WrittenContentLibrary/BookLibrary/Books/Item.ar-SA.resx new file mode 100644 index 00000000..c868feea --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/WrittenContentLibrary/BookLibrary/Books/Item.ar-SA.resx @@ -0,0 +1,381 @@ + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + إضافة مساهم + + + إضافة تقييم + + + إضافة + + + معرّف الكتاب على Apple Books. + + + رقم التعريف القياسي لأمازون الخاص بالكتاب. + + + كتاب صوتي + + + مؤلف + + + العودة إلى المكتبة + + + معرّف الكتاب على Barnes & Noble. + + + كتاب من الورق المقوى + + + تفاصيل الكتاب + + + تم حفظ الكتاب. + + + تغيير الغلاف + + + الاسم + + + الأشخاص الذين ساهموا في الكتاب، مثل مؤلفيه. + + + صورة الغلاف + + + تم تحديث صورة الغلاف. + + + تعذر رفع صورة الغلاف. + + + الوصف + + + ملخص قصير أو وصف للكتاب. + + + كتاب إلكتروني + + + الطبعة + + + طبعة الكتاب. + + + الصيغة + + + الصيغة المادية أو الرقمية للكتاب. + + + معلومات عامة + + + الأنواع + + + أنواع الكتاب، مفصولة بفواصل. + + + المعرّف الرقمي للكتاب على Goodreads. + + + معرّف الكتاب على Google Books. + + + غلاف مقوى + + + المعرّفات + + + رسام + + + صيغة ISBN + + + أرقام الكتاب الدولية المعيارية (ISBN). + + + قيمة ISBN + + + اللغة + + + رمز اللغة + + + رمز الحرفين للغة الكتاب. + + + اسم اللغة + + + اسم لغة الكتاب. + + + حرف كبير + + + رقم ضبط مكتبة الكونغرس للكتاب. + + + تجليد جلدي + + + تجليد مكتبي + + + معرّف الكتاب على LibraryThing. + + + ورقي للسوق الشامل + + + راوٍ + + + الاسم الأصلي للغة + + + الاسم الأصلي للغة الكتاب. + + + لا يوجد غلاف + + + رقم OCLC + + + رقم OCLC للكتاب. + + + معرّف الكتاب على Open Library. + + + اللغة الأصلية + + + رمز اللغة الأصلية + + + رمز الحرفين للغة الأصلية للكتاب. + + + اسم اللغة الأصلية + + + اسم اللغة الأصلية للكتاب. + + + الاسم الأصلي للغة الأصلية + + + الاسم الأصلي للغة الأصلية للكتاب. + + + تاريخ الإصدار الأصلي + + + التاريخ الذي صدر فيه الكتاب لأول مرة. + + + سنة الإصدار الأصلي + + + السنة التي صدر فيها الكتاب لأول مرة. + + + العنوان الأصلي + + + العنوان الأصلي للكتاب، عندما يختلف عن العنوان الحالي. + + + أخرى + + + عدد الصفحات + + + عدد صفحات الكتاب. + + + غلاف ورقي + + + كتاب منبثق + + + الناشر + + + ناشر الكتاب. + + + ناشر + + + أقصى تقييم + + + التقييمات + + + تقييمات الكتاب من مصادر مختلفة. + + + المصدر + + + التقييم + + + عدد الأصوات + + + بلد الإصدار + + + رمز الحرفين لبلد الإصدار. + + + معلومات الإصدار + + + نسخة الإصدار + + + نسخة الإصدار، مثل النسخة الأصلية. + + + إزالة + + + تاريخ إعادة الإصدار + + + التاريخ الذي أعيد فيه إصدار الكتاب. + + + سنة إعادة الإصدار + + + السنة التي أعيد فيها إصدار الكتاب. + + + فئة الدور + + + الدور + + + حفظ + + + تعذر حفظ الكتاب. + + + تجليد حلزوني + + + الوسوم + + + وسوم الكتاب، مفصولة بفواصل. + + + العنوان + + + العنوان الرئيسي للكتاب. + + + ورقي تجاري + + + مترجم + + + مستخدم + + + رقم المجلد + + + رقم مجلد الكتاب ضمن سلسلته. + + + ISBN-13 + + + LCCN + + + Calibre + + + معرّف Apple Books + + + Open Library + + + Google Books + + + ASIN + + + ISBN-10 + + + معرّف Google Books + + + معرّف LibraryThing + + + Goodreads + + + Amazon + + + معرّف Barnes & Noble + + + معرّف Open Library + + + ISBN + + + المساهمون + + + معرّف Goodreads + + diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/WrittenContentLibrary/BookLibrary/Books/Item.de-DE.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/WrittenContentLibrary/BookLibrary/Books/Item.de-DE.resx new file mode 100644 index 00000000..60701ae8 --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/WrittenContentLibrary/BookLibrary/Books/Item.de-DE.resx @@ -0,0 +1,381 @@ + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + Mitwirkenden hinzufügen + + + Bewertung hinzufügen + + + Hinzufügen + + + Die Kennung des Buches bei Apple Books. + + + Die Amazon-Standard-Identifikationsnummer des Buches. + + + Hörbuch + + + Autor + + + Zurück zur Bibliothek + + + Die Kennung des Buches bei Barnes & Noble. + + + Pappbilderbuch + + + Buchdetails + + + Das Buch wurde gespeichert. + + + Titelbild ändern + + + Name + + + Die Personen, die zum Buch beigetragen haben, wie seine Autoren. + + + Titelbild + + + Das Titelbild wurde aktualisiert. + + + Das Titelbild konnte nicht hochgeladen werden. + + + Beschreibung + + + Eine kurze Zusammenfassung oder Beschreibung des Buches. + + + eBook + + + Ausgabe + + + Die Ausgabe des Buches. + + + Format + + + Das physische oder digitale Format des Buches. + + + Allgemeine Informationen + + + Genres + + + Die Genres des Buches, durch Kommas getrennt. + + + Die numerische Kennung des Buches bei Goodreads. + + + Die Kennung des Buches bei Google Books. + + + Gebundene Ausgabe + + + Kennungen + + + Illustrator + + + ISBN-Format + + + Die Internationalen Standardbuchnummern des Buches. + + + ISBN-Wert + + + Sprache + + + Sprachcode + + + Der zweibuchstabige Code der Sprache des Buches. + + + Sprachname + + + Der Name der Sprache des Buches. + + + Großdruck + + + Die Library-of-Congress-Kontrollnummer des Buches. + + + Ledereinband + + + Bibliothekseinband + + + Die Kennung des Buches bei LibraryThing. + + + Massenmarkt-Taschenbuch + + + Erzähler + + + Muttersprachlicher Name + + + Der muttersprachliche Name der Sprache des Buches. + + + Kein Titelbild + + + OCLC-Nummer + + + Die OCLC-Nummer des Buches. + + + Die Kennung des Buches bei Open Library. + + + Originalsprache + + + Code der Originalsprache + + + Der zweibuchstabige Code der Originalsprache des Buches. + + + Name der Originalsprache + + + Der Name der Originalsprache des Buches. + + + Muttersprachlicher Name der Originalsprache + + + Der muttersprachliche Name der Originalsprache des Buches. + + + Datum der Erstveröffentlichung + + + Das Datum, an dem das Buch ursprünglich veröffentlicht wurde. + + + Jahr der Erstveröffentlichung + + + Das Jahr, in dem das Buch ursprünglich veröffentlicht wurde. + + + Originaltitel + + + Der Originaltitel des Buches, wenn er vom aktuellen Titel abweicht. + + + Sonstige + + + Seitenzahl + + + Die Seitenzahl des Buches. + + + Taschenbuch + + + Pop-up-Buch + + + Verlag + + + Der Verlag des Buches. + + + Verlag + + + Höchstbewertung + + + Bewertungen + + + Die Bewertungen des Buches aus verschiedenen Quellen. + + + Quelle + + + Bewertung + + + Stimmenzahl + + + Erscheinungsland + + + Der zweibuchstabige Code des Erscheinungslandes. + + + Veröffentlichungsinformationen + + + Veröffentlichungsversion + + + Die Version der Veröffentlichung, wie die ursprüngliche. + + + Entfernen + + + Datum der Neuveröffentlichung + + + Das Datum, an dem das Buch erneut veröffentlicht wurde. + + + Jahr der Neuveröffentlichung + + + Das Jahr, in dem das Buch erneut veröffentlicht wurde. + + + Rollenkategorie + + + Rolle + + + Speichern + + + Das Buch konnte nicht gespeichert werden. + + + Spiralbindung + + + Schlagwörter + + + Die Schlagwörter des Buches, durch Kommas getrennt. + + + Titel + + + Der Haupttitel des Buches. + + + Trade-Taschenbuch + + + Übersetzer + + + Benutzer + + + Bandnummer + + + Die Bandnummer des Buches innerhalb seiner Reihe. + + + ISBN-13 + + + LCCN + + + Calibre + + + Apple-Books-ID + + + Open Library + + + Google Books + + + ASIN + + + ISBN-10 + + + Google-Books-ID + + + LibraryThing-ID + + + Goodreads + + + Amazon + + + Barnes-&-Noble-ID + + + Open-Library-ID + + + ISBNs + + + Mitwirkende + + + Goodreads-ID + + diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/WrittenContentLibrary/BookLibrary/Books/Item.en-US.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/WrittenContentLibrary/BookLibrary/Books/Item.en-US.resx new file mode 100644 index 00000000..53d224d1 --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/WrittenContentLibrary/BookLibrary/Books/Item.en-US.resx @@ -0,0 +1,381 @@ + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + Book details + + + Back to library + + + Save + + + Add + + + General information + + + Title + + + Original title + + + Description + + + Publisher + + + Page count + + + Format + + + Edition + + + Volume number + + + Release information + + + Original release date + + + Original release year + + + Re-release date + + + Re-release year + + + Release country + + + Release version + + + Language + + + Language code + + + Language name + + + Native name + + + Original language + + + Original language code + + + Original language name + + + Original language native name + + + Genres + + + Tags + + + Identifiers + + + ASIN + + + Goodreads Id + + + LCCN + + + OCLC number + + + Open Library Id + + + LibraryThing Id + + + Google Books Id + + + Barnes & Noble Id + + + Apple Books Id + + + ISBNs + + + ISBN value + + + ISBN format + + + ISBN-10 + + + ISBN-13 + + + Contributors + + + Name + + + Role + + + Role category + + + Add contributor + + + Ratings + + + Rating + + + Maximum rating + + + Source + + + Vote count + + + Add rating + + + Cover image + + + Change cover + + + No cover + + + Remove + + + The main title of the book. + + + The original title of the book, when it differs from the current one. + + + A short summary or description of the book. + + + The publisher of the book. + + + The number of pages of the book. + + + The physical or digital format of the book. + + + The edition of the book. + + + The volume number of the book within its series. + + + The date when the book was originally released. + + + The year when the book was originally released. + + + The date when the book was released again. + + + The year when the book was released again. + + + The two letter code of the country of release. + + + The version of the release, like the original one. + + + The two letter code of the language of the book. + + + The name of the language of the book. + + + The native name of the language of the book. + + + The two letter code of the original language of the book. + + + The name of the original language of the book. + + + The native name of the original language of the book. + + + The genres of the book, separated by commas. + + + The tags of the book, separated by commas. + + + The Amazon Standard Identification Number of the book. + + + The numeric identifier of the book on Goodreads. + + + The Library of Congress Control Number of the book. + + + The OCLC number of the book. + + + The identifier of the book on Open Library. + + + The identifier of the book on LibraryThing. + + + The identifier of the book on Google Books. + + + The identifier of the book on Barnes & Noble. + + + The identifier of the book on Apple Books. + + + The International Standard Book Numbers of the book. + + + The people that contributed to the book, like its authors. + + + The ratings of the book from different sources. + + + Other + + + Author + + + Translator + + + Illustrator + + + Publisher + + + Narrator + + + User + + + Open Library + + + Goodreads + + + Amazon + + + Google Books + + + Calibre + + + Hardcover + + + Paperback + + + Mass market paperback + + + Trade paperback + + + eBook + + + Audiobook + + + Large print + + + Board book + + + Spiral bound + + + Library binding + + + Leather bound + + + Pop-up book + + + The book was saved. + + + The cover image was updated. + + + The book could not be saved. + + + The cover image could not be uploaded. + + diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/WrittenContentLibrary/BookLibrary/Books/Item.es-ES.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/WrittenContentLibrary/BookLibrary/Books/Item.es-ES.resx new file mode 100644 index 00000000..de95fe36 --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/WrittenContentLibrary/BookLibrary/Books/Item.es-ES.resx @@ -0,0 +1,381 @@ + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + Añadir colaborador + + + Añadir valoración + + + Añadir + + + El identificador del libro en Apple Books. + + + El número de identificación estándar de Amazon del libro. + + + Audiolibro + + + Autor + + + Volver a la biblioteca + + + El identificador del libro en Barnes & Noble. + + + Libro de cartón + + + Detalles del libro + + + El libro se ha guardado. + + + Cambiar portada + + + Nombre + + + Las personas que contribuyeron al libro, como sus autores. + + + Imagen de portada + + + La imagen de portada se ha actualizado. + + + La imagen de portada no se ha podido subir. + + + Descripción + + + Un breve resumen o descripción del libro. + + + Libro electrónico + + + Edición + + + La edición del libro. + + + Formato + + + El formato físico o digital del libro. + + + Información general + + + Géneros + + + Los géneros del libro, separados por comas. + + + El identificador numérico del libro en Goodreads. + + + El identificador del libro en Google Books. + + + Tapa dura + + + Identificadores + + + Ilustrador + + + Formato ISBN + + + Los números internacionales normalizados del libro (ISBN). + + + Valor ISBN + + + Idioma + + + Código de idioma + + + El código de dos letras del idioma del libro. + + + Nombre del idioma + + + El nombre del idioma del libro. + + + Letra grande + + + El número de control de la Biblioteca del Congreso del libro. + + + Encuadernación en piel + + + Encuadernación de biblioteca + + + El identificador del libro en LibraryThing. + + + Bolsillo + + + Narrador + + + Nombre nativo + + + El nombre nativo del idioma del libro. + + + Sin portada + + + Número OCLC + + + El número OCLC del libro. + + + El identificador del libro en Open Library. + + + Idioma original + + + Código del idioma original + + + El código de dos letras del idioma original del libro. + + + Nombre del idioma original + + + El nombre del idioma original del libro. + + + Nombre nativo del idioma original + + + El nombre nativo del idioma original del libro. + + + Fecha de publicación original + + + La fecha en la que el libro se publicó originalmente. + + + Año de publicación original + + + El año en el que el libro se publicó originalmente. + + + Título original + + + El título original del libro, cuando difiere del actual. + + + Otro + + + Número de páginas + + + El número de páginas del libro. + + + Tapa blanda + + + Libro pop-up + + + Editorial + + + La editorial del libro. + + + Editorial + + + Valoración máxima + + + Valoraciones + + + Las valoraciones del libro de distintas fuentes. + + + Fuente + + + Valoración + + + Número de votos + + + País de publicación + + + El código de dos letras del país de publicación. + + + Información de publicación + + + Versión de publicación + + + La versión de la publicación, como la original. + + + Eliminar + + + Fecha de reedición + + + La fecha en la que el libro se volvió a publicar. + + + Año de reedición + + + El año en el que el libro se volvió a publicar. + + + Categoría de rol + + + Rol + + + Guardar + + + El libro no se ha podido guardar. + + + Encuadernación en espiral + + + Etiquetas + + + Las etiquetas del libro, separadas por comas. + + + Título + + + El título principal del libro. + + + Rústica + + + Traductor + + + Usuario + + + Número de volumen + + + El número de volumen del libro dentro de su serie. + + + ISBN-13 + + + LCCN + + + Calibre + + + ID de Apple Books + + + Open Library + + + Google Books + + + ASIN + + + ISBN-10 + + + ID de Google Books + + + ID de LibraryThing + + + Goodreads + + + Amazon + + + ID de Barnes & Noble + + + ID de Open Library + + + ISBNs + + + Colaboradores + + + ID de Goodreads + + diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/WrittenContentLibrary/BookLibrary/Books/Item.fr-FR.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/WrittenContentLibrary/BookLibrary/Books/Item.fr-FR.resx new file mode 100644 index 00000000..24f103cc --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/WrittenContentLibrary/BookLibrary/Books/Item.fr-FR.resx @@ -0,0 +1,381 @@ + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + Ajouter un contributeur + + + Ajouter une évaluation + + + Ajouter + + + L'identifiant du livre sur Apple Books. + + + Le numéro d'identification standard Amazon du livre. + + + Livre audio + + + Auteur + + + Retour à la bibliothèque + + + L'identifiant du livre sur Barnes & Noble. + + + Livre cartonné + + + Détails du livre + + + Le livre a été enregistré. + + + Changer la couverture + + + Nom + + + Les personnes ayant contribué au livre, comme ses auteurs. + + + Image de couverture + + + L'image de couverture a été mise à jour. + + + L'image de couverture n'a pas pu être téléchargée. + + + Description + + + Un bref résumé ou une description du livre. + + + Livre numérique + + + Édition + + + L'édition du livre. + + + Format + + + Le format physique ou numérique du livre. + + + Informations générales + + + Genres + + + Les genres du livre, séparés par des virgules. + + + L'identifiant numérique du livre sur Goodreads. + + + L'identifiant du livre sur Google Books. + + + Couverture rigide + + + Identifiants + + + Illustrateur + + + Format ISBN + + + Les numéros internationaux normalisés du livre (ISBN). + + + Valeur ISBN + + + Langue + + + Code de langue + + + Le code à deux lettres de la langue du livre. + + + Nom de la langue + + + Le nom de la langue du livre. + + + Gros caractères + + + Le numéro de contrôle de la Library of Congress du livre. + + + Reliure cuir + + + Reliure de bibliothèque + + + L'identifiant du livre sur LibraryThing. + + + Poche + + + Narrateur + + + Nom natif + + + Le nom natif de la langue du livre. + + + Aucune couverture + + + Numéro OCLC + + + Le numéro OCLC du livre. + + + L'identifiant du livre sur Open Library. + + + Langue originale + + + Code de la langue originale + + + Le code à deux lettres de la langue originale du livre. + + + Nom de la langue originale + + + Le nom de la langue originale du livre. + + + Nom natif de la langue originale + + + Le nom natif de la langue originale du livre. + + + Date de publication originale + + + La date de publication originale du livre. + + + Année de publication originale + + + L'année de publication originale du livre. + + + Titre original + + + Le titre original du livre, lorsqu'il diffère du titre actuel. + + + Autre + + + Nombre de pages + + + Le nombre de pages du livre. + + + Broché + + + Livre animé + + + Éditeur + + + L'éditeur du livre. + + + Éditeur + + + Évaluation maximale + + + Évaluations + + + Les évaluations du livre provenant de différentes sources. + + + Source + + + Évaluation + + + Nombre de votes + + + Pays de publication + + + Le code à deux lettres du pays de publication. + + + Informations de publication + + + Version de publication + + + La version de la publication, comme la version originale. + + + Supprimer + + + Date de réédition + + + La date de réédition du livre. + + + Année de réédition + + + L'année de réédition du livre. + + + Catégorie de rôle + + + Rôle + + + Enregistrer + + + Le livre n'a pas pu être enregistré. + + + Reliure spirale + + + Étiquettes + + + Les étiquettes du livre, séparées par des virgules. + + + Titre + + + Le titre principal du livre. + + + Grand format broché + + + Traducteur + + + Utilisateur + + + Numéro de volume + + + Le numéro de volume du livre au sein de sa série. + + + ISBN-13 + + + LCCN + + + Calibre + + + Identifiant Apple Books + + + Open Library + + + Google Books + + + ASIN + + + ISBN-10 + + + Identifiant Google Books + + + Identifiant LibraryThing + + + Goodreads + + + Amazon + + + Identifiant Barnes & Noble + + + Identifiant Open Library + + + ISBNs + + + Contributeurs + + + Identifiant Goodreads + + diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/WrittenContentLibrary/BookLibrary/Books/Item.it-IT.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/WrittenContentLibrary/BookLibrary/Books/Item.it-IT.resx new file mode 100644 index 00000000..cbd9098d --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/WrittenContentLibrary/BookLibrary/Books/Item.it-IT.resx @@ -0,0 +1,381 @@ + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + Aggiungi collaboratore + + + Aggiungi valutazione + + + Aggiungi + + + L'identificatore del libro su Apple Books. + + + Il numero di identificazione standard Amazon del libro. + + + Audiolibro + + + Autore + + + Torna alla biblioteca + + + L'identificatore del libro su Barnes & Noble. + + + Libro cartonato + + + Dettagli del libro + + + Il libro è stato salvato. + + + Cambia copertina + + + Nome + + + Le persone che hanno contribuito al libro, come i suoi autori. + + + Immagine di copertina + + + L'immagine di copertina è stata aggiornata. + + + L'immagine di copertina non è stato possibile caricarla. + + + Descrizione + + + Un breve riassunto o descrizione del libro. + + + Libro elettronico + + + Edizione + + + L'edizione del libro. + + + Formato + + + Il formato fisico o digitale del libro. + + + Informazioni generali + + + Generi + + + I generi del libro, separati da virgole. + + + L'identificatore numerico del libro su Goodreads. + + + L'identificatore del libro su Google Books. + + + Copertina rigida + + + Identificatori + + + Illustratore + + + Formato ISBN + + + I numeri internazionali normalizzati del libro (ISBN). + + + Valore ISBN + + + Lingua + + + Codice lingua + + + Il codice di due lettere della lingua del libro. + + + Nome della lingua + + + Il nome della lingua del libro. + + + Caratteri grandi + + + Il numero di controllo della Library of Congress del libro. + + + Legatura in pelle + + + Legatura da biblioteca + + + L'identificatore del libro su LibraryThing. + + + Tascabile + + + Narratore + + + Nome nativo + + + Il nome nativo della lingua del libro. + + + Nessuna copertina + + + Numero OCLC + + + Il numero OCLC del libro. + + + L'identificatore del libro su Open Library. + + + Lingua originale + + + Codice della lingua originale + + + Il codice di due lettere della lingua originale del libro. + + + Nome della lingua originale + + + Il nome della lingua originale del libro. + + + Nome nativo della lingua originale + + + Il nome nativo della lingua originale del libro. + + + Data di pubblicazione originale + + + La data di pubblicazione originale del libro. + + + Anno di pubblicazione originale + + + L'anno di pubblicazione originale del libro. + + + Titolo originale + + + Il titolo originale del libro, quando differisce da quello attuale. + + + Altro + + + Numero di pagine + + + Il numero di pagine del libro. + + + Brossura + + + Libro animato + + + Editore + + + L'editore del libro. + + + Editore + + + Valutazione massima + + + Valutazioni + + + Le valutazioni del libro da diverse fonti. + + + Fonte + + + Valutazione + + + Numero di voti + + + Paese di pubblicazione + + + Il codice di due lettere del paese di pubblicazione. + + + Informazioni di pubblicazione + + + Versione di pubblicazione + + + La versione della pubblicazione, come quella originale. + + + Rimuovi + + + Data di ripubblicazione + + + La data di ripubblicazione del libro. + + + Anno di ripubblicazione + + + L'anno di ripubblicazione del libro. + + + Categoria del ruolo + + + Ruolo + + + Salva + + + Il libro non è stato possibile salvarlo. + + + Rilegatura a spirale + + + Etichette + + + Le etichette del libro, separate da virgole. + + + Titolo + + + Il titolo principale del libro. + + + Brossura editoriale + + + Traduttore + + + Utente + + + Numero del volume + + + Il numero del volume del libro all'interno della sua serie. + + + ISBN-13 + + + LCCN + + + Calibre + + + ID Apple Books + + + Open Library + + + Google Books + + + ASIN + + + ISBN-10 + + + ID Google Books + + + ID LibraryThing + + + Goodreads + + + Amazon + + + ID Barnes & Noble + + + ID Open Library + + + ISBN + + + Collaboratori + + + ID Goodreads + + diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/WrittenContentLibrary/BookLibrary/Books/Item.ja-JP.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/WrittenContentLibrary/BookLibrary/Books/Item.ja-JP.resx new file mode 100644 index 00000000..20364219 --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/WrittenContentLibrary/BookLibrary/Books/Item.ja-JP.resx @@ -0,0 +1,381 @@ + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + 貢献者を追加 + + + 評価を追加 + + + 追加 + + + Apple Books上の本のID。 + + + 本のAmazon標準識別番号。 + + + オーディオブック + + + 著者 + + + ライブラリに戻る + + + Barnes & Noble上の本のID。 + + + ボードブック + + + 本の詳細 + + + 本が保存されました。 + + + 表紙を変更 + + + 名前 + + + 著者など、本に貢献した人々。 + + + 表紙画像 + + + 表紙画像が更新されました。 + + + 表紙画像をアップロードできませんでした。 + + + 説明 + + + 本の簡単な要約または説明。 + + + 電子書籍 + + + 版 + + + 本の版。 + + + 形式 + + + 本の物理的またはデジタル形式。 + + + 一般情報 + + + ジャンル + + + 本のジャンル。カンマ区切り。 + + + Goodreads上の本の数値ID。 + + + Google Books上の本のID。 + + + ハードカバー + + + 識別子 + + + イラストレーター + + + ISBN形式 + + + 本の国際標準図書番号(ISBN)。 + + + ISBN + + + 言語 + + + 言語コード + + + 本の言語の2文字コード。 + + + 言語名 + + + 本の言語名。 + + + 大活字 + + + 本の米国議会図書館管理番号。 + + + 革装 + + + 図書館製本 + + + LibraryThing上の本のID。 + + + マスマーケットペーパーバック + + + ナレーター + + + 現地語名 + + + 本の言語の現地語名。 + + + 表紙なし + + + OCLC番号 + + + 本のOCLC番号。 + + + Open Library上の本のID。 + + + 原語 + + + 原語コード + + + 本の原語の2文字コード。 + + + 原語名 + + + 本の原語名。 + + + 原語の現地語名 + + + 本の原語の現地語名。 + + + 初版発売日 + + + 本が最初に発売された日付。 + + + 初版発売年 + + + 本が最初に発売された年。 + + + 原題 + + + 現在のタイトルと異なる場合の本の原題。 + + + その他 + + + ページ数 + + + 本のページ数。 + + + ペーパーバック + + + 飛び出す絵本 + + + 出版社 + + + 本の出版社。 + + + 出版社 + + + 最大評価 + + + 評価 + + + さまざまな出典による本の評価。 + + + 出典 + + + 評価 + + + 投票数 + + + 発売国 + + + 発売国の2文字コード。 + + + リリース情報 + + + リリース版 + + + オリジナル版など、リリースのバージョン。 + + + 削除 + + + 再発売日 + + + 本が再発売された日付。 + + + 再発売年 + + + 本が再発売された年。 + + + 役割カテゴリ + + + 役割 + + + 保存 + + + 本を保存できませんでした。 + + + リング製本 + + + タグ + + + 本のタグ。カンマ区切り。 + + + タイトル + + + 本の主タイトル。 + + + トレードペーパーバック + + + 翻訳者 + + + ユーザー + + + 巻数 + + + シリーズ内の本の巻数。 + + + ISBN-13 + + + LCCN + + + Calibre + + + Apple Books ID + + + Open Library + + + Google Books + + + ASIN + + + ISBN-10 + + + Google Books ID + + + LibraryThing ID + + + Goodreads + + + Amazon + + + Barnes & Noble ID + + + Open Library ID + + + ISBN + + + 貢献者 + + + Goodreads ID + + diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/WrittenContentLibrary/BookLibrary/Books/Item.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/WrittenContentLibrary/BookLibrary/Books/Item.resx new file mode 100644 index 00000000..53d224d1 --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/WrittenContentLibrary/BookLibrary/Books/Item.resx @@ -0,0 +1,381 @@ + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + Book details + + + Back to library + + + Save + + + Add + + + General information + + + Title + + + Original title + + + Description + + + Publisher + + + Page count + + + Format + + + Edition + + + Volume number + + + Release information + + + Original release date + + + Original release year + + + Re-release date + + + Re-release year + + + Release country + + + Release version + + + Language + + + Language code + + + Language name + + + Native name + + + Original language + + + Original language code + + + Original language name + + + Original language native name + + + Genres + + + Tags + + + Identifiers + + + ASIN + + + Goodreads Id + + + LCCN + + + OCLC number + + + Open Library Id + + + LibraryThing Id + + + Google Books Id + + + Barnes & Noble Id + + + Apple Books Id + + + ISBNs + + + ISBN value + + + ISBN format + + + ISBN-10 + + + ISBN-13 + + + Contributors + + + Name + + + Role + + + Role category + + + Add contributor + + + Ratings + + + Rating + + + Maximum rating + + + Source + + + Vote count + + + Add rating + + + Cover image + + + Change cover + + + No cover + + + Remove + + + The main title of the book. + + + The original title of the book, when it differs from the current one. + + + A short summary or description of the book. + + + The publisher of the book. + + + The number of pages of the book. + + + The physical or digital format of the book. + + + The edition of the book. + + + The volume number of the book within its series. + + + The date when the book was originally released. + + + The year when the book was originally released. + + + The date when the book was released again. + + + The year when the book was released again. + + + The two letter code of the country of release. + + + The version of the release, like the original one. + + + The two letter code of the language of the book. + + + The name of the language of the book. + + + The native name of the language of the book. + + + The two letter code of the original language of the book. + + + The name of the original language of the book. + + + The native name of the original language of the book. + + + The genres of the book, separated by commas. + + + The tags of the book, separated by commas. + + + The Amazon Standard Identification Number of the book. + + + The numeric identifier of the book on Goodreads. + + + The Library of Congress Control Number of the book. + + + The OCLC number of the book. + + + The identifier of the book on Open Library. + + + The identifier of the book on LibraryThing. + + + The identifier of the book on Google Books. + + + The identifier of the book on Barnes & Noble. + + + The identifier of the book on Apple Books. + + + The International Standard Book Numbers of the book. + + + The people that contributed to the book, like its authors. + + + The ratings of the book from different sources. + + + Other + + + Author + + + Translator + + + Illustrator + + + Publisher + + + Narrator + + + User + + + Open Library + + + Goodreads + + + Amazon + + + Google Books + + + Calibre + + + Hardcover + + + Paperback + + + Mass market paperback + + + Trade paperback + + + eBook + + + Audiobook + + + Large print + + + Board book + + + Spiral bound + + + Library binding + + + Leather bound + + + Pop-up book + + + The book was saved. + + + The cover image was updated. + + + The book could not be saved. + + + The cover image could not be uploaded. + + diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/WrittenContentLibrary/BookLibrary/Books/Item.ro-RO.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/WrittenContentLibrary/BookLibrary/Books/Item.ro-RO.resx new file mode 100644 index 00000000..ed005b8d --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/WrittenContentLibrary/BookLibrary/Books/Item.ro-RO.resx @@ -0,0 +1,381 @@ + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + Adaugă contributor + + + Adaugă rating + + + Adaugă + + + Identificatorul cărții pe Apple Books. + + + Numărul standard de identificare Amazon al cărții. + + + Carte audio + + + Autor + + + Înapoi la bibliotecă + + + Identificatorul cărții pe Barnes & Noble. + + + Carte de carton + + + Detalii carte + + + Cartea a fost salvată. + + + Schimbă coperta + + + Nume + + + Persoanele care au contribuit la carte, precum autorii ei. + + + Imagine de copertă + + + Imaginea de copertă a fost actualizată. + + + Imaginea de copertă nu a putut fi încărcată. + + + Descriere + + + Un scurt rezumat sau o descriere a cărții. + + + Carte electronică + + + Ediție + + + Ediția cărții. + + + Format + + + Formatul fizic sau digital al cărții. + + + Informații generale + + + Genuri + + + Genurile cărții, separate prin virgule. + + + Identificatorul numeric al cărții pe Goodreads. + + + Identificatorul cărții pe Google Books. + + + Copertă cartonată + + + Identificatori + + + Ilustrator + + + Format ISBN + + + Numerele internaționale standardizate ale cărții (ISBN). + + + Valoare ISBN + + + Limbă + + + Codul limbii + + + Codul din două litere al limbii cărții. + + + Denumirea limbii + + + Denumirea limbii cărții. + + + Tipar mare + + + Numărul de control al Library of Congress al cărții. + + + Legare în piele + + + Legare de bibliotecă + + + Identificatorul cărții pe LibraryThing. + + + Ediție de buzunar + + + Narator + + + Denumire nativă + + + Denumirea nativă a limbii cărții. + + + Fără copertă + + + Număr OCLC + + + Numărul OCLC al cărții. + + + Identificatorul cărții pe Open Library. + + + Limba originală + + + Codul limbii originale + + + Codul din două litere al limbii originale a cărții. + + + Denumirea limbii originale + + + Denumirea limbii originale a cărții. + + + Denumirea nativă a limbii originale + + + Denumirea nativă a limbii originale a cărții. + + + Data lansării originale + + + Data la care cartea a fost lansată inițial. + + + Anul lansării originale + + + Anul în care cartea a fost lansată inițial. + + + Titlu original + + + Titlul original al cărții, când diferă de cel actual. + + + Altul + + + Număr de pagini + + + Numărul de pagini al cărții. + + + Copertă broșată + + + Carte pop-up + + + Editură + + + Editura cărții. + + + Editură + + + Rating maxim + + + Ratinguri + + + Ratingurile cărții din diferite surse. + + + Sursă + + + Rating + + + Număr de voturi + + + Țara de lansare + + + Codul din două litere al țării de lansare. + + + Informații de lansare + + + Versiunea lansării + + + Versiunea lansării, precum cea originală. + + + Elimină + + + Data relansării + + + Data la care cartea a fost relansată. + + + Anul relansării + + + Anul în care cartea a fost relansată. + + + Categoria rolului + + + Rol + + + Salvează + + + Cartea nu a putut fi salvată. + + + Legare spirală + + + Etichete + + + Etichetele cărții, separate prin virgule. + + + Titlu + + + Titlul principal al cărții. + + + Broșat trade + + + Traducător + + + Utilizator + + + Număr volum + + + Numărul volumului cărții în cadrul seriei sale. + + + ISBN-13 + + + LCCN + + + Calibre + + + ID Apple Books + + + Open Library + + + Google Books + + + ASIN + + + ISBN-10 + + + ID Google Books + + + ID LibraryThing + + + Goodreads + + + Amazon + + + ID Barnes & Noble + + + ID Open Library + + + ISBN-uri + + + Contribuitori + + + ID Goodreads + + diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/WrittenContentLibrary/BookLibrary/Books/Item.uk-UA.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/WrittenContentLibrary/BookLibrary/Books/Item.uk-UA.resx new file mode 100644 index 00000000..34a49dc7 --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/WrittenContentLibrary/BookLibrary/Books/Item.uk-UA.resx @@ -0,0 +1,381 @@ + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + Додати учасника + + + Додати оцінку + + + Додати + + + Ідентифікатор книги на Apple Books. + + + Стандартний ідентифікаційний номер Amazon книги. + + + Аудіокнига + + + Автор + + + Повернутися до бібліотеки + + + Ідентифікатор книги на Barnes & Noble. + + + Картонна книга + + + Деталі книги + + + Книгу збережено. + + + Змінити обкладинку + + + Ім'я + + + Люди, які долучилися до створення книги, як-от її автори. + + + Зображення обкладинки + + + Зображення обкладинки оновлено. + + + Не вдалося завантажити зображення обкладинки. + + + Опис + + + Короткий зміст або опис книги. + + + Електронна книга + + + Видання + + + Видання книги. + + + Формат + + + Фізичний або цифровий формат книги. + + + Загальна інформація + + + Жанри + + + Жанри книги, розділені комами. + + + Числовий ідентифікатор книги на Goodreads. + + + Ідентифікатор книги на Google Books. + + + Тверда палітурка + + + Ідентифікатори + + + Ілюстратор + + + Формат ISBN + + + Міжнародні стандартні номери книги (ISBN). + + + Значення ISBN + + + Мова + + + Код мови + + + Дволітерний код мови книги. + + + Назва мови + + + Назва мови книги. + + + Великий шрифт + + + Контрольний номер Бібліотеки Конгресу книги. + + + Шкіряна палітурка + + + Бібліотечна палітурка + + + Ідентифікатор книги на LibraryThing. + + + Кишеньковий формат + + + Оповідач + + + Власна назва + + + Власна назва мови книги. + + + Без обкладинки + + + Номер OCLC + + + Номер OCLC книги. + + + Ідентифікатор книги на Open Library. + + + Оригінальна мова + + + Код оригінальної мови + + + Дволітерний код оригінальної мови книги. + + + Назва оригінальної мови + + + Назва оригінальної мови книги. + + + Власна назва оригінальної мови + + + Власна назва оригінальної мови книги. + + + Дата першого випуску + + + Дата першого випуску книги. + + + Рік першого випуску + + + Рік першого випуску книги. + + + Оригінальна назва + + + Оригінальна назва книги, якщо вона відрізняється від поточної. + + + Інше + + + Кількість сторінок + + + Кількість сторінок книги. + + + М'яка палітурка + + + Книга-панорама + + + Видавництво + + + Видавництво книги. + + + Видавництво + + + Максимальна оцінка + + + Оцінки + + + Оцінки книги з різних джерел. + + + Джерело + + + Оцінка + + + Кількість голосів + + + Країна випуску + + + Дволітерний код країни випуску. + + + Інформація про випуск + + + Версія випуску + + + Версія випуску, як-от оригінальна. + + + Видалити + + + Дата перевипуску + + + Дата перевипуску книги. + + + Рік перевипуску + + + Рік перевипуску книги. + + + Категорія ролі + + + Роль + + + Зберегти + + + Не вдалося зберегти книгу. + + + Спіральна палітурка + + + Теги + + + Теги книги, розділені комами. + + + Назва + + + Основна назва книги. + + + Трейд-пап’пербек + + + Перекладач + + + Користувач + + + Номер тому + + + Номер тому книги в межах її серії. + + + ISBN-13 + + + LCCN + + + Calibre + + + ID на Apple Books + + + Open Library + + + Google Books + + + ASIN + + + ISBN-10 + + + ID на Google Books + + + ID на LibraryThing + + + Goodreads + + + Amazon + + + ID на Barnes & Noble + + + ID на Open Library + + + ISBN + + + Учасники + + + ID на Goodreads + + diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/WrittenContentLibrary/BookLibrary/Books/Item.zh-CN.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/WrittenContentLibrary/BookLibrary/Books/Item.zh-CN.resx new file mode 100644 index 00000000..2d9aff0a --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/WrittenContentLibrary/BookLibrary/Books/Item.zh-CN.resx @@ -0,0 +1,381 @@ + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + 添加贡献者 + + + 添加评分 + + + 添加 + + + 图书在 Apple Books 上的标识。 + + + 图书的亚马逊标准识别号。 + + + 有声书 + + + 作者 + + + 返回图书馆 + + + 图书在 Barnes & Noble 上的标识。 + + + 纸板书 + + + 图书详情 + + + 图书已保存。 + + + 更换封面 + + + 姓名 + + + 为图书作出贡献的人,例如其作者。 + + + 封面图片 + + + 封面图片已更新。 + + + 无法上传封面图片。 + + + 简介 + + + 图书的简短摘要或简介。 + + + 电子书 + + + 版本 + + + 图书的版本。 + + + 格式 + + + 图书的实体或数字格式。 + + + 常规信息 + + + 体裁 + + + 图书的体裁,以逗号分隔。 + + + 图书在 Goodreads 上的数字标识。 + + + 图书在 Google Books 上的标识。 + + + 精装本 + + + 标识符 + + + 插画师 + + + ISBN 格式 + + + 图书的国际标准书号(ISBN)。 + + + ISBN 值 + + + 语言 + + + 语言代码 + + + 图书语言的两位代码。 + + + 语言名称 + + + 图书语言的名称。 + + + 大字版 + + + 图书的美国国会图书馆控制号。 + + + 皮面装订 + + + 图书馆装订 + + + 图书在 LibraryThing 上的标识。 + + + 大众平装本 + + + 叙述者 + + + 本地语名称 + + + 图书语言的本地语名称。 + + + 无封面 + + + OCLC 编号 + + + 图书的 OCLC 编号。 + + + 图书在 Open Library 上的标识。 + + + 原语言 + + + 原语言代码 + + + 图书原语言的两位代码。 + + + 原语言名称 + + + 图书原语言的名称。 + + + 原语言本地语名称 + + + 图书原语言的本地语名称。 + + + 首次发行日期 + + + 图书首次发行的日期。 + + + 首次发行年份 + + + 图书首次发行的年份。 + + + 原标题 + + + 图书的原标题,如果与当前标题不同。 + + + 其他 + + + 页数 + + + 图书的页数。 + + + 平装本 + + + 立体书 + + + 出版社 + + + 图书的出版社。 + + + 出版者 + + + 最高评分 + + + 评分 + + + 不同来源对图书的评分。 + + + 来源 + + + 评分 + + + 票数 + + + 发行国家 + + + 发行国家的两位代码。 + + + 发行信息 + + + 发行版本 + + + 发行版本,例如原版。 + + + 移除 + + + 再发行日期 + + + 图书再次发行的日期。 + + + 再发行年份 + + + 图书再次发行的年份。 + + + 角色类别 + + + 角色 + + + 保存 + + + 无法保存图书。 + + + 螺旋装订 + + + 标签 + + + 图书的标签,以逗号分隔。 + + + 标题 + + + 图书的主标题。 + + + 贸易平装本 + + + 译者 + + + 用户 + + + 卷号 + + + 图书在其系列中的卷号。 + + + ISBN-13 + + + LCCN + + + Calibre + + + Apple Books ID + + + Open Library + + + Google Books + + + ASIN + + + ISBN-10 + + + Google Books ID + + + LibraryThing ID + + + Goodreads + + + Amazon + + + Barnes & Noble ID + + + Open Library ID + + + ISBN + + + 贡献者 + + + Goodreads ID + + diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/WrittenContentLibrary/BookLibrary/Books/Read.ar-SA.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/WrittenContentLibrary/BookLibrary/Books/Read.ar-SA.resx index b06b1dad..d927d760 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/WrittenContentLibrary/BookLibrary/Books/Read.ar-SA.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/WrittenContentLibrary/BookLibrary/Books/Read.ar-SA.resx @@ -1,4 +1,4 @@ - + +
@@ -48,7 +48,7 @@
- +
@@ -72,7 +72,7 @@
- +
@@ -95,7 +95,7 @@
- +
@@ -105,9 +105,10 @@ @section Scripts { +} diff --git a/src/Lumina.Presentation.Web/Core/Views/Library/WrittenContentLibrary/BookLibrary/Books/Read.cshtml b/src/Lumina.Presentation.Web/Core/Views/Library/WrittenContentLibrary/BookLibrary/Books/Read.cshtml index a44592ef..dd8e3272 100644 --- a/src/Lumina.Presentation.Web/Core/Views/Library/WrittenContentLibrary/BookLibrary/Books/Read.cshtml +++ b/src/Lumina.Presentation.Web/Core/Views/Library/WrittenContentLibrary/BookLibrary/Books/Read.cshtml @@ -18,7 +18,7 @@
- + @@ -54,6 +54,7 @@ return String(value).replace(/&/g, '&').replace(//g, '>').replace(/"/g, '"').replace(/'/g, '''); } + // The element references are captured once, so that the cleanup can unbind their listeners even after the AJAX navigator has swapped the content out of the document. const readerTitle = document.getElementById('reader-title'); const readerContent = document.getElementById('reader-content'); const readerStatus = document.getElementById('reader-status'); diff --git a/src/Lumina.Presentation.Web/Core/Views/Tools/Settings.cshtml b/src/Lumina.Presentation.Web/Core/Views/Tools/Settings.cshtml index 74328465..a4afdc8d 100644 --- a/src/Lumina.Presentation.Web/Core/Views/Tools/Settings.cshtml +++ b/src/Lumina.Presentation.Web/Core/Views/Tools/Settings.cshtml @@ -16,8 +16,8 @@ @model UserSettingsDto -
-
+
+
@@ -52,7 +52,7 @@
@_localizer["DescriptionItemsPerPage"]
- +
: @@ -118,6 +118,7 @@ const cleanupFunctions = []; let isInitialized = false; + // The element references are captured once, so that the cleanup can unbind their listeners even after the AJAX navigator has swapped the content out of the document. const form = document.getElementById('user-settings-form'); const checkboxIsPaginationEnabled = document.getElementById('IsPaginationEnabled'); const inputItemsPerPage = document.getElementById('ItemsPerPage'); diff --git a/src/global.json b/src/global.json new file mode 100644 index 00000000..f5215a6e --- /dev/null +++ b/src/global.json @@ -0,0 +1,6 @@ +{ + "sdk": { + "version": "10.0.100", + "rollForward": "disable" + } +} \ No newline at end of file diff --git a/tests/Common/Lumina.Application.Fixtures/Common/DataAccess/Entities/Authorization/RoleEntityFixture.cs b/tests/Common/Lumina.Application.Fixtures/Common/DataAccess/Entities/Authorization/RoleEntityFixture.cs index 3ffee2c1..234cc401 100644 --- a/tests/Common/Lumina.Application.Fixtures/Common/DataAccess/Entities/Authorization/RoleEntityFixture.cs +++ b/tests/Common/Lumina.Application.Fixtures/Common/DataAccess/Entities/Authorization/RoleEntityFixture.cs @@ -23,7 +23,7 @@ public class RoleEntityFixture /// Optional. The Id of the role. /// Optional. The name of the role. /// Optional. The role permission associations of the role. - /// Whether the role should include role permission associations or not. + /// Whether the role permission associations should be included, or forced to an empty collection. /// Optional. The Id of the user that created the role. /// Optional. The time and date when the role was added. /// The created . diff --git a/tests/Common/Lumina.Application.Fixtures/Common/DataAccess/Entities/MediaLibrary/Management/LibraryEntityFixture.cs b/tests/Common/Lumina.Application.Fixtures/Common/DataAccess/Entities/MediaLibrary/Management/LibraryEntityFixture.cs index ecc55b88..4d7afec4 100644 --- a/tests/Common/Lumina.Application.Fixtures/Common/DataAccess/Entities/MediaLibrary/Management/LibraryEntityFixture.cs +++ b/tests/Common/Lumina.Application.Fixtures/Common/DataAccess/Entities/MediaLibrary/Management/LibraryEntityFixture.cs @@ -87,9 +87,10 @@ public class LibraryEntityFixture /// Creates a list of instances with randomized test data. /// /// Number of instances to create. + /// Optional. The Id of the user that owns the created media libraries. /// List of configured instances. - public List CreateMany(int count = 3) + public List CreateMany(int count = 3, Guid? userId = null) { - return [.. Enumerable.Range(0, count).Select(_ => Create())]; + return [.. Enumerable.Range(0, count).Select(_ => Create(userId: userId))]; } } diff --git a/tests/Common/Lumina.Application.Fixtures/Common/DataAccess/Entities/MediaLibrary/WrittenContentLibrary/BookLibrary/BookEntityFixture.cs b/tests/Common/Lumina.Application.Fixtures/Common/DataAccess/Entities/MediaLibrary/WrittenContentLibrary/BookLibrary/BookEntityFixture.cs index fe191177..0a4ed757 100644 --- a/tests/Common/Lumina.Application.Fixtures/Common/DataAccess/Entities/MediaLibrary/WrittenContentLibrary/BookLibrary/BookEntityFixture.cs +++ b/tests/Common/Lumina.Application.Fixtures/Common/DataAccess/Entities/MediaLibrary/WrittenContentLibrary/BookLibrary/BookEntityFixture.cs @@ -28,7 +28,7 @@ public class BookEntityFixture /// Optional. The file system path of the book. /// Optional. The title of the book. /// Optional. The original title of the book. - /// Whether the book should include its owned metadata collections (Tags, Genres, ISBNs, Ratings) or not. + /// Whether the owned metadata collections (Tags, Genres, ISBNs, Ratings) should be included, or forced to empty collections. /// The created . public BookEntity Create( Guid? id = null, diff --git a/tests/Common/Lumina.Application.Fixtures/Common/DataAccess/Entities/MediaLibrary/WrittenContentLibrary/BookLibrary/BookRatingEntityFixture.cs b/tests/Common/Lumina.Application.Fixtures/Common/DataAccess/Entities/MediaLibrary/WrittenContentLibrary/BookLibrary/BookRatingEntityFixture.cs index e06ad74d..c5c2ddda 100644 --- a/tests/Common/Lumina.Application.Fixtures/Common/DataAccess/Entities/MediaLibrary/WrittenContentLibrary/BookLibrary/BookRatingEntityFixture.cs +++ b/tests/Common/Lumina.Application.Fixtures/Common/DataAccess/Entities/MediaLibrary/WrittenContentLibrary/BookLibrary/BookRatingEntityFixture.cs @@ -26,7 +26,7 @@ public class BookRatingEntityFixture /// Optional. The maximum possible rating value. /// Optional. The rating source. /// Optional. The number of votes. - /// Whether the rating properties should be populated. Set to to create an invalid entity. + /// Whether the rating properties should be included, or forced to . /// The created book rating entity. public BookRatingEntity Create( decimal? value = null, diff --git a/tests/Common/Lumina.Application.Fixtures/Common/DataAccess/Entities/Themes/ThemeEntityFixture.cs b/tests/Common/Lumina.Application.Fixtures/Common/DataAccess/Entities/Themes/ThemeEntityFixture.cs index f51fec10..6208cb12 100644 --- a/tests/Common/Lumina.Application.Fixtures/Common/DataAccess/Entities/Themes/ThemeEntityFixture.cs +++ b/tests/Common/Lumina.Application.Fixtures/Common/DataAccess/Entities/Themes/ThemeEntityFixture.cs @@ -26,18 +26,18 @@ public class ThemeEntityFixture /// Optional author of the theme. /// Optional version of the theme. /// Optional preview image path of the theme, or when the theme has no preview. - /// Whether to set , or when . + /// Whether the preview path should be included, or forced to . /// Optional source the theme was installed from. /// Optional value indicating whether the theme is the currently active one. - /// Whether to set , or when . + /// Whether the currently active flag should be included, or forced to . /// Optional value indicating whether the theme was soft deleted. /// Optional UTC timestamp when the theme was installed. /// Optional UTC timestamp when the entity was created. /// Optional Id of the user that created the entity. /// Optional UTC timestamp when the entity was updated. - /// Whether to set , or when . + /// Whether the updated-on timestamp should be included, or forced to . /// Optional Id of the user that updated the entity. - /// Whether to set , or when . + /// Whether the updated-by user Id should be included, or forced to . /// A configured instance. public ThemeEntity Create( Guid? id = null, diff --git a/tests/Common/Lumina.Application.Fixtures/Common/DataAccess/Entities/UsersManagement/UserEntityFixture.cs b/tests/Common/Lumina.Application.Fixtures/Common/DataAccess/Entities/UsersManagement/UserEntityFixture.cs index ee757fb6..61710769 100644 --- a/tests/Common/Lumina.Application.Fixtures/Common/DataAccess/Entities/UsersManagement/UserEntityFixture.cs +++ b/tests/Common/Lumina.Application.Fixtures/Common/DataAccess/Entities/UsersManagement/UserEntityFixture.cs @@ -3,7 +3,7 @@ using Bogus; using Lumina.Application.Common.DataAccess.Entities.Authorization; using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management; using Lumina.Application.Common.DataAccess.Entities.UsersManagement; -using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management; using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; @@ -18,6 +18,8 @@ namespace Lumina.Application.Fixtures.Common.DataAccess.Entities.UsersManagement [ExcludeFromCodeCoverage] public class UserEntityFixture { + private readonly LibraryEntityFixture _libraryEntityFixture = new(); + /// /// Creates a random valid . /// @@ -27,8 +29,8 @@ public class UserEntityFixture /// Optional Id to pin, or to generate a random one. /// Optional user role association to pin when including it. /// Optional user permission associations to pin when including them. - /// Whether the user should include a user role association or not. - /// Whether the user should include user permission associations or not. + /// Whether the user role association should be included, or forced to . + /// Whether the user permission associations should be included, or forced to an empty collection. /// Optional collection of libraries to pin for the user, or to generate them based on . /// The created user entity. public UserEntity Create( @@ -44,7 +46,7 @@ public class UserEntityFixture { Guid userId = id ?? Guid.NewGuid(); ICollection resolvedLibraries = libraries ?? (libraryCount > 0 - ? CreateLibraries(libraryCount, userId) + ? _libraryEntityFixture.CreateMany(libraryCount, userId) : []); return new Faker() @@ -77,28 +79,4 @@ public class UserEntityFixture { return [.. Enumerable.Range(0, count).Select(_ => Create(libraryCount))]; } - - /// - /// Creates a valid collection of user libraries. - /// - /// The number of user libraries to create. - /// The unique identifier 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 = Guid.NewGuid(), - UserId = userId, - Title = f.Commerce.ProductName(), - LibraryType = f.PickRandom(), - ContentLocations = [], - CreatedOnUtc = f.Date.Past(), - CreatedBy = userId, - UpdatedOnUtc = null, - UpdatedBy = null - }) - .Generate(count); - } } diff --git a/tests/Common/Lumina.Application.Fixtures/Common/Infrastructure/Models/DTO/Themes/ThemeManifestDtoFixture.cs b/tests/Common/Lumina.Application.Fixtures/Common/Infrastructure/Models/DTO/Themes/ThemeManifestDtoFixture.cs index de55b6c4..2e912ee2 100644 --- a/tests/Common/Lumina.Application.Fixtures/Common/Infrastructure/Models/DTO/Themes/ThemeManifestDtoFixture.cs +++ b/tests/Common/Lumina.Application.Fixtures/Common/Infrastructure/Models/DTO/Themes/ThemeManifestDtoFixture.cs @@ -25,7 +25,7 @@ public class ThemeManifestDtoFixture /// Optional author of the theme. /// Optional version of the theme. /// Optional preview image path of the theme, or when the theme has no preview. - /// Whether to set , or when . + /// Whether the preview path should be included, or forced to . /// Optional template mappings of the theme. /// A configured instance. public ThemeManifestDto Create( diff --git a/tests/Common/Lumina.Application.Fixtures/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Commands/AddBook/AddBookCommandFixture.cs b/tests/Common/Lumina.Application.Fixtures/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Commands/AddBook/AddBookCommandFixture.cs index a327cea3..86eabf20 100644 --- a/tests/Common/Lumina.Application.Fixtures/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Commands/AddBook/AddBookCommandFixture.cs +++ b/tests/Common/Lumina.Application.Fixtures/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Commands/AddBook/AddBookCommandFixture.cs @@ -1,15 +1,15 @@ #region ========================================================================= USING ===================================================================================== -using AutoFixture; using Bogus; using Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Commands.AddBook; -using Lumina.Application.Fixtures.Common.Setup; -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.Fixtures.Core.DTO.MediaContributors; +using Lumina.Contracts.Fixtures.Core.DTO.MediaLibrary.WrittenContentLibrary; +using Lumina.Contracts.Fixtures.Core.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary; using Lumina.Domain.SharedKernel.Common.Enums.BookLibrary; -using Lumina.Domain.SharedKernel.Common.Enums.MediaContributors; using System; +using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Linq; #endregion @@ -22,173 +22,59 @@ namespace Lumina.Application.Fixtures.Core.MediaLibrary.WrittenContentLibrary.Bo [ExcludeFromCodeCoverage] public class AddBookCommandFixture { - private readonly Fixture _fixture = new(); - private readonly Random _random = new(); - private readonly Faker _faker = new(); - - /// - /// Initializes a new instance of the class. - /// - public AddBookCommandFixture() - { - _fixture.Customizations.Add(new DateOnlySpecimenBuilder()); - _fixture.Customizations.Add(new NullableDateOnlySpecimenBuilder()); - } + private readonly IsbnDtoFixture _isbnDtoFixture = new(); + private readonly BookRatingDtoFixture _bookRatingDtoFixture = new(); + private readonly MediaContributorDtoFixture _mediaContributorDtoFixture = new(); + private readonly WrittenContentMetadataDtoFixture _writtenContentMetadataDtoFixture = new(); /// /// Creates a random valid command to add a book. /// + /// Optional. The Id of the media library the book belongs to. + /// Optional. The file system path of the book. + /// Optional. The written content metadata of the book. + /// Optional. The format of the book. + /// Optional. The edition of the book. + /// Optional. The volume or book number in the series. + /// Optional. The series the book is part of. + /// Optional. The ASIN of the book. + /// Optional. The Goodreads Id of the book. + /// Optional. The LCCN of the book. + /// Optional. The OCLC number of the book. + /// Optional. The Open Library Id of the book. + /// Optional. The LibraryThing Id of the book. + /// Optional. The Google Books Id of the book. + /// Optional. The Barnes and Noble Id of the book. + /// Optional. The Apple Books Id of the book. + /// Optional. The ISBNs of the book. + /// Optional. The contributors of the book. + /// Optional. The ratings of the book. + /// Whether the metadata should be included, or forced to . + /// Whether the properties that are not explicitly provided should be randomized, or forced to . /// The created command to add a book. - public AddBookCommand Create() + public AddBookCommand Create( + Guid? libraryId = null, + string? path = null, + WrittenContentMetadataDto? metadata = null, + BookFormat? format = null, + string? edition = null, + float? volumeNumber = null, + BookSeriesDto? series = null, + string? asin = null, + string? goodreadsId = null, + string? lccn = null, + string? oclcNumber = null, + string? openLibraryId = null, + string? libraryThingId = null, + string? googleBooksId = null, + string? barnesAndNobleId = null, + string? appleBooksId = null, + List? isbns = null, + List? contributors = null, + List? ratings = null, + bool includeMetadata = true, + bool includeOptionalProperties = true) { - 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.PickRandom()); - - 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 AddBookCommand( default, @@ -211,62 +97,101 @@ public class AddBookCommandFixture default!, default! )) - .RuleFor(x => x.LibraryId, _fixture.Create()) - .RuleFor(x => x.Path, f => f.System.FilePath()) - .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'))]); - 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(['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)])]); - }) - .RuleFor(x => x.BarnesAndNobleId, f => f.Random.String2(10, "0123456789")) - .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))); + .RuleFor(x => x.LibraryId, libraryId ?? Guid.NewGuid()) + .RuleFor(x => x.Path, f => path ?? f.System.FilePath()) + .RuleFor(x => x.Metadata, includeMetadata ? (metadata ?? _writtenContentMetadataDtoFixture.Create()) : null) + .RuleFor(x => x.Format, f => format ?? (includeOptionalProperties ? f.PickRandom() : null)) + .RuleFor(x => x.Edition, f => edition ?? (includeOptionalProperties ? f.Random.String2(f.Random.Number(1, 50)) : null)) + .RuleFor(x => x.VolumeNumber, f => volumeNumber ?? (includeOptionalProperties ? (float?)f.Random.Number(1, 3) : null)) + .RuleFor(x => x.Series, series) + .RuleFor(x => x.ASIN, f => asin ?? (includeOptionalProperties ? f.Random.String2(10) : null)) + .RuleFor(x => x.GoodreadsId, f => goodreadsId ?? (includeOptionalProperties ? f.Random.Number(100000, 500000).ToString() : null)) + .RuleFor(x => x.LCCN, f => lccn ?? (includeOptionalProperties ? CreateLccn(f) : null)) + .RuleFor(x => x.OCLCNumber, f => oclcNumber ?? (includeOptionalProperties ? CreateOclcNumber(f) : null)) + .RuleFor(x => x.OpenLibraryId, f => openLibraryId ?? (includeOptionalProperties ? CreateOpenLibraryId(f) : null)) + .RuleFor(x => x.LibraryThingId, f => libraryThingId ?? (includeOptionalProperties ? f.Random.String2(f.Random.Number(1, 50)) : null)) + .RuleFor(x => x.GoogleBooksId, f => googleBooksId ?? (includeOptionalProperties ? CreateGoogleBooksId(f) : null)) + .RuleFor(x => x.BarnesAndNobleId, f => barnesAndNobleId ?? (includeOptionalProperties ? f.Random.String2(10, "0123456789") : null)) + .RuleFor(x => x.AppleBooksId, f => appleBooksId ?? (includeOptionalProperties ? $"id{f.Random.Number(1, 999999)}" : null)) + .RuleFor(p => p.ISBNs, f => isbns ?? (includeOptionalProperties ? [.. _isbnDtoFixture.CreateMany(f.Random.Number(1, 3))] : null)) + .RuleFor(p => p.Ratings, f => ratings ?? (includeOptionalProperties ? [.. _bookRatingDtoFixture.CreateMany(f.Random.Number(1, 3))] : null)) + .RuleFor(x => x.Contributors, f => contributors ?? (includeOptionalProperties ? [.. _mediaContributorDtoFixture.CreateMany(f.Random.Number(1, 3))] : null)); + } + + /// + /// Creates a list of . + /// + /// The number of elements to create. + /// The created list. + public List CreateMany(int count = 3) + { + return [.. Enumerable.Range(0, count).Select(_ => Create())]; + } + + /// + /// Generates a random LCCN (Library of Congress Control Number). + /// + /// The faker used to generate the value. + /// The generated LCCN. + private static string CreateLccn(Faker faker) + { + string letters = new([.. Enumerable.Range(0, faker.Random.Number(0, 3)).Select(_ => faker.Random.Char('a', 'z'))]); + string digits = faker.Random.String2(faker.Random.Number(8, 10), "0123456789"); + return letters + digits; + } + + /// + /// Generates a random OCLC number (WorldCat identifier). + /// + /// The faker used to generate the value. + /// The generated OCLC number. + private static string CreateOclcNumber(Faker faker) + { + string[] prefixes = ["ocm", "ocn", "on", "(OCoLC)"]; + string prefix = faker.Random.ArrayElement(prefixes); + string number; + switch (prefix) + { + case "ocm": + number = faker.Random.String2(8, "0123456789"); + break; + case "ocn": + number = faker.Random.String2(faker.Random.Number(9, 11), "0123456789"); + break; + case "on": + number = faker.Random.String2(10, "0123456789"); + break; + case "(OCoLC)": + number = faker.Random.String2(faker.Random.Number(8, 10), "0123456789"); + break; + default: + number = faker.Random.String2(faker.Random.Number(8, 10), "0123456789"); + return number; + } + return prefix + number; + } + + /// + /// Generates a random Open Library Id. + /// + /// The faker used to generate the value. + /// The generated Open Library Id. + private static string CreateOpenLibraryId(Faker faker) + { + int firstDigit = faker.Random.Number(1, 9); + string remainingDigits = faker.Random.String2(faker.Random.Number(0, 6), "0123456789"); + char suffix = faker.Random.ArrayElement(['A', 'M', 'W']); + return $"OL{firstDigit}{remainingDigits}{suffix}"; + } + + /// + /// Generates a random Google Books Id. + /// + /// The faker used to generate the value. + /// The generated Google Books Id. + private static string CreateGoogleBooksId(Faker faker) + { + const string VALID_CHARS = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_"; + return new string([.. Enumerable.Repeat(VALID_CHARS, 12).Select(s => s[faker.Random.Number(VALID_CHARS.Length - 1)])]); } } diff --git a/tests/Common/Lumina.Application.Fixtures/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Commands/UpdateBook/UpdateBookCommandFixture.cs b/tests/Common/Lumina.Application.Fixtures/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Commands/UpdateBook/UpdateBookCommandFixture.cs new file mode 100644 index 00000000..ffe50efa --- /dev/null +++ b/tests/Common/Lumina.Application.Fixtures/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Commands/UpdateBook/UpdateBookCommandFixture.cs @@ -0,0 +1,194 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Commands.UpdateBook; +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.Fixtures.Core.DTO.MediaContributors; +using Lumina.Contracts.Fixtures.Core.DTO.MediaLibrary.WrittenContentLibrary; +using Lumina.Contracts.Fixtures.Core.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary; +using Lumina.Domain.SharedKernel.Common.Enums.BookLibrary; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Application.Fixtures.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Commands.UpdateBook; + +/// +/// Fixture class for the class. +/// +[ExcludeFromCodeCoverage] +public class UpdateBookCommandFixture +{ + private readonly IsbnDtoFixture _isbnDtoFixture = new(); + private readonly BookRatingDtoFixture _bookRatingDtoFixture = new(); + private readonly MediaContributorDtoFixture _mediaContributorDtoFixture = new(); + private readonly WrittenContentMetadataDtoFixture _writtenContentMetadataDtoFixture = new(); + + /// + /// Creates a random valid command to update a book. + /// + /// Optional. The Id of the book to update. + /// Optional. The written content metadata of the book. + /// Optional. The format of the book. + /// Optional. The edition of the book. + /// Optional. The volume or book number in the series. + /// Optional. The series the book is part of. + /// Optional. The ASIN of the book. + /// Optional. The Goodreads Id of the book. + /// Optional. The LCCN of the book. + /// Optional. The OCLC number of the book. + /// Optional. The Open Library Id of the book. + /// Optional. The LibraryThing Id of the book. + /// Optional. The Google Books Id of the book. + /// Optional. The Barnes and Noble Id of the book. + /// Optional. The Apple Books Id of the book. + /// Optional. The ISBNs of the book. + /// Optional. The contributors of the book. + /// Optional. The ratings of the book. + /// Whether the metadata should be included, or forced to . + /// Whether the properties that are not explicitly provided should be randomized, or forced to . + /// The created command to update a book. + public UpdateBookCommand Create( + Guid? id = null, + WrittenContentMetadataDto? metadata = null, + BookFormat? format = null, + string? edition = null, + float? volumeNumber = null, + BookSeriesDto? series = null, + string? asin = null, + string? goodreadsId = null, + string? lccn = null, + string? oclcNumber = null, + string? openLibraryId = null, + string? libraryThingId = null, + string? googleBooksId = null, + string? barnesAndNobleId = null, + string? appleBooksId = null, + List? isbns = null, + List? contributors = null, + List? ratings = null, + bool includeMetadata = true, + bool includeOptionalProperties = true) + { + return new Faker() + .CustomInstantiator(f => new UpdateBookCommand( + default, + default!, + default, + default, + default, + default, + default, + default, + default, + default, + default, + default, + default, + default, + default, + default!, + default!, + default! + )) + .RuleFor(x => x.Id, id ?? Guid.NewGuid()) + .RuleFor(x => x.Metadata, includeMetadata ? (metadata ?? _writtenContentMetadataDtoFixture.Create()) : null) + .RuleFor(x => x.Format, f => format ?? (includeOptionalProperties ? f.PickRandom() : null)) + .RuleFor(x => x.Edition, f => edition ?? (includeOptionalProperties ? f.Random.String2(f.Random.Number(1, 50)) : null)) + .RuleFor(x => x.VolumeNumber, f => volumeNumber ?? (includeOptionalProperties ? (float?)f.Random.Number(1, 3) : null)) + .RuleFor(x => x.Series, series) + .RuleFor(x => x.ASIN, f => asin ?? (includeOptionalProperties ? f.Random.String2(10) : null)) + .RuleFor(x => x.GoodreadsId, f => goodreadsId ?? (includeOptionalProperties ? f.Random.Number(100000, 500000).ToString() : null)) + .RuleFor(x => x.LCCN, f => lccn ?? (includeOptionalProperties ? CreateLccn(f) : null)) + .RuleFor(x => x.OCLCNumber, f => oclcNumber ?? (includeOptionalProperties ? CreateOclcNumber(f) : null)) + .RuleFor(x => x.OpenLibraryId, f => openLibraryId ?? (includeOptionalProperties ? CreateOpenLibraryId(f) : null)) + .RuleFor(x => x.LibraryThingId, f => libraryThingId ?? (includeOptionalProperties ? f.Random.String2(f.Random.Number(1, 50)) : null)) + .RuleFor(x => x.GoogleBooksId, f => googleBooksId ?? (includeOptionalProperties ? CreateGoogleBooksId(f) : null)) + .RuleFor(x => x.BarnesAndNobleId, f => barnesAndNobleId ?? (includeOptionalProperties ? f.Random.String2(10, "0123456789") : null)) + .RuleFor(x => x.AppleBooksId, f => appleBooksId ?? (includeOptionalProperties ? $"id{f.Random.Number(1, 999999)}" : null)) + .RuleFor(p => p.ISBNs, f => isbns ?? (includeOptionalProperties ? [.. _isbnDtoFixture.CreateMany(f.Random.Number(1, 3))] : null)) + .RuleFor(p => p.Ratings, f => ratings ?? (includeOptionalProperties ? [.. _bookRatingDtoFixture.CreateMany(f.Random.Number(1, 3))] : null)) + .RuleFor(x => x.Contributors, f => contributors ?? (includeOptionalProperties ? [.. _mediaContributorDtoFixture.CreateMany(f.Random.Number(1, 3))] : null)); + } + + /// + /// Creates a list of . + /// + /// The number of elements to create. + /// The created list. + public List CreateMany(int count = 3) + { + return [.. Enumerable.Range(0, count).Select(_ => Create())]; + } + + /// + /// Generates a random LCCN (Library of Congress Control Number). + /// + /// The faker used to generate the value. + /// The generated LCCN. + private static string CreateLccn(Faker faker) + { + string letters = new([.. Enumerable.Range(0, faker.Random.Number(0, 3)).Select(_ => faker.Random.Char('a', 'z'))]); + string digits = faker.Random.String2(faker.Random.Number(8, 10), "0123456789"); + return letters + digits; + } + + /// + /// Generates a random OCLC number (WorldCat identifier). + /// + /// The faker used to generate the value. + /// The generated OCLC number. + private static string CreateOclcNumber(Faker faker) + { + string[] prefixes = ["ocm", "ocn", "on", "(OCoLC)"]; + string prefix = faker.Random.ArrayElement(prefixes); + string number; + switch (prefix) + { + case "ocm": + number = faker.Random.String2(8, "0123456789"); + break; + case "ocn": + number = faker.Random.String2(faker.Random.Number(9, 11), "0123456789"); + break; + case "on": + number = faker.Random.String2(10, "0123456789"); + break; + case "(OCoLC)": + number = faker.Random.String2(faker.Random.Number(8, 10), "0123456789"); + break; + default: + number = faker.Random.String2(faker.Random.Number(8, 10), "0123456789"); + return number; + } + return prefix + number; + } + + /// + /// Generates a random Open Library Id. + /// + /// The faker used to generate the value. + /// The generated Open Library Id. + private static string CreateOpenLibraryId(Faker faker) + { + int firstDigit = faker.Random.Number(1, 9); + string remainingDigits = faker.Random.String2(faker.Random.Number(0, 6), "0123456789"); + char suffix = faker.Random.ArrayElement(['A', 'M', 'W']); + return $"OL{firstDigit}{remainingDigits}{suffix}"; + } + + /// + /// Generates a random Google Books Id. + /// + /// The faker used to generate the value. + /// The generated Google Books Id. + private static string CreateGoogleBooksId(Faker faker) + { + const string VALID_CHARS = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_"; + return new string([.. Enumerable.Repeat(VALID_CHARS, 12).Select(s => s[faker.Random.Number(VALID_CHARS.Length - 1)])]); + } +} diff --git a/tests/Common/Lumina.Application.Fixtures/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Commands/UpdateBookCover/UpdateBookCoverCommandFixture.cs b/tests/Common/Lumina.Application.Fixtures/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Commands/UpdateBookCover/UpdateBookCoverCommandFixture.cs new file mode 100644 index 00000000..c86d20d4 --- /dev/null +++ b/tests/Common/Lumina.Application.Fixtures/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Commands/UpdateBookCover/UpdateBookCoverCommandFixture.cs @@ -0,0 +1,59 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Commands.UpdateBookCover; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.IO; +using System.Linq; +using System.Text; +#endregion + +namespace Lumina.Application.Fixtures.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Commands.UpdateBookCover; + +/// +/// Fixture class for the class. +/// +[ExcludeFromCodeCoverage] +public class UpdateBookCoverCommandFixture +{ + /// + /// Creates a random valid . + /// + /// Optional. The Id of the book whose cover is updated. + /// Optional. The stream of the uploaded cover image file. + /// Optional. The name of the uploaded cover image file. + /// Whether the cover stream should be included, or forced to . + /// The created . + public UpdateBookCoverCommand Create( + Guid? bookId = null, + Stream? cover = null, + string? fileName = null, + bool includeCover = true) + { + return new UpdateBookCoverCommand( + bookId ?? Guid.NewGuid(), + includeCover ? (cover ?? CreateCoverStream()) : null, + fileName ?? "cover.jpg" + ); + } + + /// + /// Creates a list of instances with randomized test data. + /// + /// Number of instances to create. + /// List of configured instances. + public List CreateMany(int count = 3) + { + return [.. Enumerable.Range(0, count).Select(_ => Create())]; + } + + /// + /// Creates an in-memory stream carrying a minimal file payload. + /// + /// A non-empty in-memory stream. + private static Stream CreateCoverStream() + { + byte[] payload = Encoding.UTF8.GetBytes("fake cover payload"); + return new MemoryStream(payload); + } +} diff --git a/tests/Common/Lumina.Application.Fixtures/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Queries/GetBook/GetBookQueryFixture.cs b/tests/Common/Lumina.Application.Fixtures/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Queries/GetBook/GetBookQueryFixture.cs new file mode 100644 index 00000000..70635887 --- /dev/null +++ b/tests/Common/Lumina.Application.Fixtures/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Queries/GetBook/GetBookQueryFixture.cs @@ -0,0 +1,37 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Queries.GetBook; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Application.Fixtures.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Queries.GetBook; + +/// +/// Fixture class for the class. +/// +[ExcludeFromCodeCoverage] +public class GetBookQueryFixture +{ + /// + /// Creates a random valid . + /// + /// Optional. The Id of the book to get. + /// The created . + public GetBookQuery Create( + Guid? id = null) + { + return new GetBookQuery(id ?? Guid.NewGuid()); + } + + /// + /// Creates a list of instances with randomized test data. + /// + /// Number of instances to create. + /// List of configured instances. + public List CreateMany(int count = 3) + { + return [.. Enumerable.Range(0, count).Select(_ => Create())]; + } +} diff --git a/tests/Common/Lumina.Application.Fixtures/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Queries/GetBooks/GetBooksQueryFixture.cs b/tests/Common/Lumina.Application.Fixtures/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Queries/GetBooks/GetBooksQueryFixture.cs index 1c105e6c..c57cfff0 100644 --- a/tests/Common/Lumina.Application.Fixtures/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Queries/GetBooks/GetBooksQueryFixture.cs +++ b/tests/Common/Lumina.Application.Fixtures/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Queries/GetBooks/GetBooksQueryFixture.cs @@ -28,7 +28,7 @@ public class GetBooksQueryFixture /// Optional. The search term used to filter results. /// Optional. The name of the field by which to sort the results. /// Optional. The direction in which to sort the results. - /// Whether the query should include pagination data or not. + /// Whether the pagination data should be included, or forced to . /// The created query to get books. public GetBooksQuery Create( Guid? libraryId = null, diff --git a/tests/Common/Lumina.Application.Fixtures/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Queries/GetBooksLite/GetBooksLiteQueryFixture.cs b/tests/Common/Lumina.Application.Fixtures/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Queries/GetBooksLite/GetBooksLiteQueryFixture.cs index 5949d253..1f2fce3c 100644 --- a/tests/Common/Lumina.Application.Fixtures/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Queries/GetBooksLite/GetBooksLiteQueryFixture.cs +++ b/tests/Common/Lumina.Application.Fixtures/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Queries/GetBooksLite/GetBooksLiteQueryFixture.cs @@ -30,7 +30,7 @@ public class GetBooksLiteQueryFixture /// Optional. Whether the leading "The " prefix of a title should be ignored when computing the alpha key, or not. /// Optional. The name of the field by which to sort the results. /// Optional. The direction in which to sort the results. - /// Whether the query should include pagination data or not. + /// Whether the pagination data should be included, or forced to . /// The created query to get the lightweight details of books. public GetBooksLiteQuery Create( Guid? libraryId = null, diff --git a/tests/Common/Lumina.Application.Fixtures/Core/Scheduling/Queries/GetScheduledJobHistory/GetScheduledJobHistoryQueryFixture.cs b/tests/Common/Lumina.Application.Fixtures/Core/Scheduling/Queries/GetScheduledJobHistory/GetScheduledJobHistoryQueryFixture.cs index 30778a36..bd8736b2 100644 --- a/tests/Common/Lumina.Application.Fixtures/Core/Scheduling/Queries/GetScheduledJobHistory/GetScheduledJobHistoryQueryFixture.cs +++ b/tests/Common/Lumina.Application.Fixtures/Core/Scheduling/Queries/GetScheduledJobHistory/GetScheduledJobHistoryQueryFixture.cs @@ -20,8 +20,8 @@ public class GetScheduledJobHistoryQueryFixture /// /// Optional. The inclusive lower bound of the requested interval. /// Optional. The inclusive upper bound of the requested interval. - /// Whether to include the lower bound in the query. When false, the lower bound is left unset. - /// Whether to include the upper bound in the query. When false, the upper bound is left unset. + /// Whether the lower bound should be included, or forced to . + /// Whether the upper bound should be included, or forced to . /// The created query. public GetScheduledJobHistoryQuery Create( DateTime? from = null, diff --git a/tests/Common/Lumina.Application.Fixtures/Core/UsersManagement/Authentication/Queries/LoginUser/LoginUserQueryFixture.cs b/tests/Common/Lumina.Application.Fixtures/Core/UsersManagement/Authentication/Queries/LoginUser/LoginUserQueryFixture.cs index 35832e33..30a02076 100644 --- a/tests/Common/Lumina.Application.Fixtures/Core/UsersManagement/Authentication/Queries/LoginUser/LoginUserQueryFixture.cs +++ b/tests/Common/Lumina.Application.Fixtures/Core/UsersManagement/Authentication/Queries/LoginUser/LoginUserQueryFixture.cs @@ -19,7 +19,7 @@ public class LoginUserQueryFixture /// /// Optional. The username. /// Optional. The password. - /// Whether to include a TOTP code in the query. + /// Whether the TOTP code should be included, or forced to . /// The created query. public LoginUserQuery Create( string? username = null, diff --git a/tests/Common/Lumina.Application.Fixtures/Lumina.Application.Fixtures.csproj b/tests/Common/Lumina.Application.Fixtures/Lumina.Application.Fixtures.csproj index 28395911..595cbfba 100644 --- a/tests/Common/Lumina.Application.Fixtures/Lumina.Application.Fixtures.csproj +++ b/tests/Common/Lumina.Application.Fixtures/Lumina.Application.Fixtures.csproj @@ -20,5 +20,6 @@ + diff --git a/tests/Common/Lumina.Contracts.Fixtures/Core/DTO/Common/LanguageInfoDtoFixture.cs b/tests/Common/Lumina.Contracts.Fixtures/Core/DTO/Common/LanguageInfoDtoFixture.cs index e67f358d..a07ef2d2 100644 --- a/tests/Common/Lumina.Contracts.Fixtures/Core/DTO/Common/LanguageInfoDtoFixture.cs +++ b/tests/Common/Lumina.Contracts.Fixtures/Core/DTO/Common/LanguageInfoDtoFixture.cs @@ -22,16 +22,22 @@ public class LanguageInfoDtoFixture /// Optional. The ISO code of the language. /// Optional. The name of the language in English. /// Optional. The native name of the language. + /// Whether the language code should be included, or forced to . + /// Whether the language name should be included, or forced to . + /// Whether the native name should be included, or forced to . /// The created . public LanguageInfoDto Create( - string? languageCode = null, - string? languageName = null, - string? nativeName = null) + string? languageCode = null, + string? languageName = null, + string? nativeName = null, + bool includeLanguageCode = true, + bool includeLanguageName = true, + bool includeNativeName = true) { return new LanguageInfoDto( - languageCode ?? _faker.Random.String2(2), - languageName ?? _faker.Lorem.Word(), - nativeName ?? _faker.Lorem.Word()); + includeLanguageCode ? (languageCode ?? _faker.Random.String2(2)) : null, + includeLanguageName ? (languageName ?? _faker.Lorem.Word()) : null, + includeNativeName ? (nativeName ?? _faker.Lorem.Word()) : null); } /// diff --git a/tests/Common/Lumina.Contracts.Fixtures/Core/DTO/Common/ReleaseInfoDtoFixture.cs b/tests/Common/Lumina.Contracts.Fixtures/Core/DTO/Common/ReleaseInfoDtoFixture.cs index 6de91897..656735e2 100644 --- a/tests/Common/Lumina.Contracts.Fixtures/Core/DTO/Common/ReleaseInfoDtoFixture.cs +++ b/tests/Common/Lumina.Contracts.Fixtures/Core/DTO/Common/ReleaseInfoDtoFixture.cs @@ -15,7 +15,7 @@ namespace Lumina.Contracts.Fixtures.Core.DTO.Common; public class ReleaseInfoDtoFixture { /// - /// Creates an , preserving the values that are not provided as . + /// Creates a , preserving the values that are not provided as . /// /// Optional. The original release date of the content. /// Optional. The original release year of the content. @@ -23,6 +23,12 @@ public class ReleaseInfoDtoFixture /// Optional. The re-release year of the content. /// Optional. The country where the content was released. /// Optional. The version or edition of the content's release. + /// Whether the original release date should be included, or forced to . + /// Whether the original release year should be included, or forced to . + /// Whether the re-release date should be included, or forced to . + /// Whether the re-release year should be included, or forced to . + /// Whether the release country should be included, or forced to . + /// Whether the release version should be included, or forced to . /// The created . public ReleaseInfoDto Create( DateOnly? originalReleaseDate = null, @@ -30,15 +36,21 @@ public class ReleaseInfoDtoFixture DateOnly? reReleaseDate = null, int? reReleaseYear = null, string? releaseCountry = null, - string? releaseVersion = null) + string? releaseVersion = null, + bool includeOriginalReleaseDate = true, + bool includeOriginalReleaseYear = true, + bool includeReReleaseDate = true, + bool includeReReleaseYear = true, + bool includeReleaseCountry = true, + bool includeReleaseVersion = true) { return new ReleaseInfoDto( - originalReleaseDate, - originalReleaseYear, - reReleaseDate, - reReleaseYear, - releaseCountry, - releaseVersion); + includeOriginalReleaseDate ? originalReleaseDate : null, + includeOriginalReleaseYear ? originalReleaseYear : null, + includeReReleaseDate ? reReleaseDate : null, + includeReReleaseYear ? reReleaseYear : null, + includeReleaseCountry ? releaseCountry : null, + includeReleaseVersion ? releaseVersion : null); } /// diff --git a/tests/Common/Lumina.Contracts.Fixtures/Core/DTO/MediaContributors/MediaContributorDtoFixture.cs b/tests/Common/Lumina.Contracts.Fixtures/Core/DTO/MediaContributors/MediaContributorDtoFixture.cs index 10440fca..e0f65c2c 100644 --- a/tests/Common/Lumina.Contracts.Fixtures/Core/DTO/MediaContributors/MediaContributorDtoFixture.cs +++ b/tests/Common/Lumina.Contracts.Fixtures/Core/DTO/MediaContributors/MediaContributorDtoFixture.cs @@ -23,15 +23,33 @@ public class MediaContributorDtoFixture /// Optional. The display name of the media contributor. /// Optional. The name of the role assigned to the media contributor. /// Optional. The category of the role. + /// Optional. The legal name of the media contributor. + /// Whether the name should be included, or forced to . + /// Whether the display name should be included, or forced to . + /// Whether the legal name should be included, or forced to . + /// Whether the role should be included, or forced to . + /// Whether the role name should be included, or forced to . + /// Whether the role category should be included, or forced to . /// The created . public MediaContributorDto Create( string? displayName = null, string? roleName = null, - MediaContributorRoleCategory? roleCategory = null) + MediaContributorRoleCategory? roleCategory = null, + string? legalName = null, + bool includeName = true, + bool includeDisplayName = true, + bool includeLegalName = true, + bool includeRole = true, + bool includeRoleName = true, + bool includeRoleCategory = true) { return new MediaContributorDto( - Name: new MediaContributorNameDto(DisplayName: displayName ?? _faker.Name.FullName(), LegalName: null), - Role: new MediaContributorRoleDto(Name: roleName ?? _faker.Commerce.Department(), Category: roleCategory ?? _faker.PickRandom())); + Name: includeName ? new MediaContributorNameDto( + DisplayName: includeDisplayName ? displayName ?? _faker.Name.FullName() : null, + LegalName: includeLegalName ? legalName : null) : null, + Role: includeRole ? new MediaContributorRoleDto( + Name: includeRoleName ? roleName ?? _faker.Commerce.Department() : null, + Category: includeRoleCategory ? roleCategory ?? _faker.PickRandom() : null) : null); } /// diff --git a/tests/Common/Lumina.Contracts.Fixtures/Core/DTO/MediaLibrary/WrittenContentLibrary/BookLibrary/BookMetadataDtoFixture.cs b/tests/Common/Lumina.Contracts.Fixtures/Core/DTO/MediaLibrary/WrittenContentLibrary/BookLibrary/BookMetadataDtoFixture.cs index 498147dc..d8cff480 100644 --- a/tests/Common/Lumina.Contracts.Fixtures/Core/DTO/MediaLibrary/WrittenContentLibrary/BookLibrary/BookMetadataDtoFixture.cs +++ b/tests/Common/Lumina.Contracts.Fixtures/Core/DTO/MediaLibrary/WrittenContentLibrary/BookLibrary/BookMetadataDtoFixture.cs @@ -3,6 +3,7 @@ using Bogus; using Lumina.Contracts.DTO.Common; using Lumina.Contracts.DTO.MediaContributors; using Lumina.Contracts.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary; +using Lumina.Contracts.Fixtures.Core.DTO.Common; using Lumina.Domain.SharedKernel.Common.Enums.BookLibrary; using System; using System.Collections.Generic; @@ -19,6 +20,10 @@ namespace Lumina.Contracts.Fixtures.Core.DTO.MediaLibrary.WrittenContentLibrary. public class BookMetadataDtoFixture { private readonly Faker _faker = new(); + private readonly ReleaseInfoDtoFixture _releaseInfoDtoFixture = new(); + private readonly GenreDtoFixture _genreDtoFixture = new(); + private readonly TagDtoFixture _tagDtoFixture = new(); + private readonly LanguageInfoDtoFixture _languageInfoDtoFixture = new(); /// /// Creates a random valid . @@ -51,7 +56,7 @@ public class BookMetadataDtoFixture /// Optional. The ratings of the book. /// Optional. The path of the cover image of the book. /// Whether the title should be included, or forced to . - /// Whether the properties that are not explicitly provided should be randomized, or left . + /// Whether the properties that are not explicitly provided should be randomized, or forced to . /// The created . public BookMetadataDto Create( string? title = null, @@ -89,10 +94,13 @@ public class BookMetadataDtoFixture includeTitle ? title ?? (includeOptionalProperties ? _faker.Lorem.Sentence(3) : null) : null, originalTitle, description, - releaseInfo ?? (includeOptionalProperties ? new ReleaseInfoDto(new DateOnly(releaseYear, 1, 1), releaseYear, null, null, _faker.Address.CountryCode(), null) : null), - genres ?? (includeOptionalProperties ? [new GenreDto(_faker.Lorem.Word())] : null), - tags ?? (includeOptionalProperties ? [new TagDto(_faker.Lorem.Word())] : null), - language ?? (includeOptionalProperties ? new LanguageInfoDto("en", "English", "English") : null), + releaseInfo ?? (includeOptionalProperties ? _releaseInfoDtoFixture.Create( + originalReleaseDate: new DateOnly(releaseYear, 1, 1), + originalReleaseYear: releaseYear, + releaseCountry: _faker.Address.CountryCode()) : null), + genres ?? (includeOptionalProperties ? [_genreDtoFixture.Create()] : null), + tags ?? (includeOptionalProperties ? [_tagDtoFixture.Create()] : null), + language ?? (includeOptionalProperties ? _languageInfoDtoFixture.Create() : null), originalLanguage, publisher, pageCount, diff --git a/tests/Common/Lumina.Contracts.Fixtures/Core/DTO/MediaLibrary/WrittenContentLibrary/BookLibrary/BookRatingDtoFixture.cs b/tests/Common/Lumina.Contracts.Fixtures/Core/DTO/MediaLibrary/WrittenContentLibrary/BookLibrary/BookRatingDtoFixture.cs index 4b6c7cec..cd594450 100644 --- a/tests/Common/Lumina.Contracts.Fixtures/Core/DTO/MediaLibrary/WrittenContentLibrary/BookLibrary/BookRatingDtoFixture.cs +++ b/tests/Common/Lumina.Contracts.Fixtures/Core/DTO/MediaLibrary/WrittenContentLibrary/BookLibrary/BookRatingDtoFixture.cs @@ -26,7 +26,7 @@ public class BookRatingDtoFixture /// Optional. The maximum possible rating value. /// Optional. The rating source. /// Optional. The number of votes. - /// Whether the optional source and vote count should be included. + /// Whether the optional source and vote count should be randomized, or forced to . /// The created . public BookRatingDto Create( decimal? value = null, @@ -38,8 +38,8 @@ public class BookRatingDtoFixture return new BookRatingDto( value ?? _random.Next(1, 5), maxValue ?? 5, - includeOptionalProperties ? (source ?? _fixture.Create()) : null, - includeOptionalProperties ? (voteCount ?? _random.Next(1, 1000)) : null + source ?? (includeOptionalProperties ? _fixture.Create() : null), + voteCount ?? (includeOptionalProperties ? _random.Next(1, 1000) : null) ); } diff --git a/tests/Common/Lumina.Contracts.Fixtures/Core/DTO/MediaLibrary/WrittenContentLibrary/BookLibrary/IsbnDtoFixture.cs b/tests/Common/Lumina.Contracts.Fixtures/Core/DTO/MediaLibrary/WrittenContentLibrary/BookLibrary/IsbnDtoFixture.cs index 2b3fd680..33184bca 100644 --- a/tests/Common/Lumina.Contracts.Fixtures/Core/DTO/MediaLibrary/WrittenContentLibrary/BookLibrary/IsbnDtoFixture.cs +++ b/tests/Common/Lumina.Contracts.Fixtures/Core/DTO/MediaLibrary/WrittenContentLibrary/BookLibrary/IsbnDtoFixture.cs @@ -28,7 +28,7 @@ public class IsbnDtoFixture string resolvedValue = value ?? (format == IsbnFormat.Isbn10 ? GenerateValidIsbn10() : GenerateValidIsbn13()); return new IsbnDto( resolvedValue, - format + format ?? (resolvedValue.Length > 13 ? IsbnFormat.Isbn13 : IsbnFormat.Isbn10) ); } @@ -42,6 +42,10 @@ public class IsbnDtoFixture return [.. Enumerable.Range(0, count).Select(_ => Create())]; } + /// + /// Generates a valid ISBN-10 with the correct checksum. + /// + /// A valid ISBN-10 value. private string GenerateValidIsbn10() { int[] digits = new int[9]; @@ -58,6 +62,10 @@ public class IsbnDtoFixture return $"{digits[0]}-{digits[1]}{digits[2]}-{digits[3]}{digits[4]}{digits[5]}{digits[6]}{digits[7]}{digits[8]}-{checkChar}"; } + /// + /// Generates a valid ISBN-13 with the correct checksum. + /// + /// A valid ISBN-13 value. private string GenerateValidIsbn13() { string prefix = _random.Next(2) == 0 ? "978" : "979"; diff --git a/tests/Common/Lumina.Contracts.Fixtures/Core/DTO/MediaLibrary/WrittenContentLibrary/WrittenContentMetadataDtoFixture.cs b/tests/Common/Lumina.Contracts.Fixtures/Core/DTO/MediaLibrary/WrittenContentLibrary/WrittenContentMetadataDtoFixture.cs index 6775e3d6..308d9bcd 100644 --- a/tests/Common/Lumina.Contracts.Fixtures/Core/DTO/MediaLibrary/WrittenContentLibrary/WrittenContentMetadataDtoFixture.cs +++ b/tests/Common/Lumina.Contracts.Fixtures/Core/DTO/MediaLibrary/WrittenContentLibrary/WrittenContentMetadataDtoFixture.cs @@ -1,6 +1,9 @@ #region ========================================================================= USING ===================================================================================== +using Bogus; using Lumina.Contracts.DTO.Common; using Lumina.Contracts.DTO.MediaLibrary.WrittenContentLibrary; +using Lumina.Contracts.Fixtures.Core.DTO.Common; +using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Linq; @@ -14,8 +17,14 @@ namespace Lumina.Contracts.Fixtures.Core.DTO.MediaLibrary.WrittenContentLibrary; [ExcludeFromCodeCoverage] public class WrittenContentMetadataDtoFixture { + private readonly Faker _faker = new(); + private readonly Random _random = new(); + private readonly GenreDtoFixture _genreDtoFixture = new(); + private readonly TagDtoFixture _tagDtoFixture = new(); + private readonly LanguageInfoDtoFixture _languageInfoDtoFixture = new(); + /// - /// Creates a with the requested values, leaving unspecified properties as . + /// Creates a random valid . /// /// Optional. The title of the written content. /// Optional. The original title of the written content. @@ -27,6 +36,16 @@ public class WrittenContentMetadataDtoFixture /// Optional. The original language of the written content. /// Optional. The name of the publisher of the written content. /// Optional. The number of pages in the written content. + /// Whether the title should be included, or forced to . + /// Whether the original title should be included, or forced to . + /// Whether the description should be included, or forced to . + /// Whether the release information should be included, or forced to . + /// Whether the genres should be included, or forced to . + /// Whether the tags should be included, or forced to . + /// Whether the language should be included, or forced to . + /// Whether the original language should be included, or forced to . + /// Whether the publisher should be included, or forced to . + /// Whether the page count should be included, or forced to . /// The created . public WrittenContentMetadataDto Create( string? title = null, @@ -38,19 +57,29 @@ public class WrittenContentMetadataDtoFixture LanguageInfoDto? language = null, LanguageInfoDto? originalLanguage = null, string? publisher = null, - int? pageCount = null) + int? pageCount = null, + bool includeTitle = true, + bool includeOriginalTitle = true, + bool includeDescription = true, + bool includeReleaseInfo = true, + bool includeGenres = true, + bool includeTags = true, + bool includeLanguage = true, + bool includeOriginalLanguage = true, + bool includePublisher = true, + bool includePageCount = true) { return new WrittenContentMetadataDto( - title, - originalTitle, - description, - releaseInfo, - genres, - tags, - language, - originalLanguage, - publisher, - pageCount); + includeTitle ? (title ?? _faker.Commerce.ProductName()) : null, + includeOriginalTitle ? (originalTitle ?? _faker.Commerce.ProductName()) : null, + includeDescription ? (description ?? _faker.Lorem.Paragraph()) : null, + includeReleaseInfo ? (releaseInfo ?? CreateReleaseInfo()) : null, + includeGenres ? (genres ?? CreateDistinctGenres()) : null, + includeTags ? (tags ?? CreateDistinctTags()) : null, + includeLanguage ? (language ?? _languageInfoDtoFixture.Create()) : null, + includeOriginalLanguage ? (originalLanguage ?? _languageInfoDtoFixture.Create()) : null, + includePublisher ? (publisher ?? _faker.Company.CompanyName()) : null, + includePageCount ? (pageCount ?? _faker.Random.Int(1, 1000)) : null); } /// @@ -62,4 +91,53 @@ public class WrittenContentMetadataDtoFixture { return [.. Enumerable.Range(0, count).Select(_ => Create())]; } + + /// + /// Creates a random valid with consistent dates and years. + /// + /// The created . + private ReleaseInfoDto CreateReleaseInfo() + { + int originalReleaseYear = _random.Next(1900, 2026); + int reReleaseYear = _random.Next(originalReleaseYear, 2026); + return new ReleaseInfoDto( + new DateOnly(originalReleaseYear, 1, 1), + originalReleaseYear, + new DateOnly(reReleaseYear, 1, 1), + reReleaseYear, + _faker.Address.CountryCode(), + _faker.Random.String2(_faker.Random.Number(1, 50))); + } + + /// + /// Creates two genres with distinct names, so that the storage deduplication never collapses them into one. + /// + /// The created genres. + private List CreateDistinctGenres() + { + List genres = []; + while (genres.Count < 2) + { + GenreDto genre = _genreDtoFixture.Create(); + if (genres.All(existing => existing.Name != genre.Name)) + genres.Add(genre); + } + return genres; + } + + /// + /// Creates two tags with distinct names, so that the storage deduplication never collapses them into one. + /// + /// The created tags. + private List CreateDistinctTags() + { + List tags = []; + while (tags.Count < 2) + { + TagDto tag = _tagDtoFixture.Create(); + if (tags.All(existing => existing.Name != tag.Name)) + tags.Add(tag); + } + return tags; + } } diff --git a/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/FileSystemManagement/Directories/GetDirectoriesRequestFixture.cs b/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/FileSystemManagement/Directories/GetDirectoriesRequestFixture.cs index 45ac2a64..683ac580 100644 --- a/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/FileSystemManagement/Directories/GetDirectoriesRequestFixture.cs +++ b/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/FileSystemManagement/Directories/GetDirectoriesRequestFixture.cs @@ -20,9 +20,11 @@ public class GetDirectoriesRequestFixture /// Creates a with default or random values. /// /// Optional. The file system path for which to get the directories. - /// Optional. Whether to include hidden file system elements. + /// Whether to include hidden file system elements or not. /// The created . - public GetDirectoriesRequest Create(string? path = null, bool? includeHiddenElements = null) + public GetDirectoriesRequest Create( + string? path = null, + bool? includeHiddenElements = null) { return new GetDirectoriesRequest( Path: path ?? _faker.System.FilePath(), diff --git a/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/FileSystemManagement/Files/GetFilesRequestFixture.cs b/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/FileSystemManagement/Files/GetFilesRequestFixture.cs index 27b8e0ff..aa139a6d 100644 --- a/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/FileSystemManagement/Files/GetFilesRequestFixture.cs +++ b/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/FileSystemManagement/Files/GetFilesRequestFixture.cs @@ -20,9 +20,11 @@ public class GetFilesRequestFixture /// Creates a with default or random values. /// /// Optional. The file system path for which to get the files. - /// Optional. Whether to include hidden file system elements. + /// Whether to include hidden file system elements or not. /// The created . - public GetFilesRequest Create(string? path = null, bool? includeHiddenElements = null) + public GetFilesRequest Create( + string? path = null, + bool? includeHiddenElements = null) { return new GetFilesRequest( Path: path ?? _faker.System.FilePath(), diff --git a/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/FileSystemManagement/Files/GetTreeFilesRequestFixture.cs b/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/FileSystemManagement/Files/GetTreeFilesRequestFixture.cs index a6892778..6f5c67d2 100644 --- a/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/FileSystemManagement/Files/GetTreeFilesRequestFixture.cs +++ b/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/FileSystemManagement/Files/GetTreeFilesRequestFixture.cs @@ -20,9 +20,11 @@ public class GetTreeFilesRequestFixture /// Creates a with default or random values. /// /// Optional. The file system path for which to get the tree files. - /// Optional. Whether to include hidden file system elements. + /// Whether to include hidden file system elements or not. /// The created . - public GetTreeFilesRequest Create(string? path = null, bool? includeHiddenElements = null) + public GetTreeFilesRequest Create( + string? path = null, + bool? includeHiddenElements = null) { return new GetTreeFilesRequest( Path: path ?? _faker.System.FilePath(), diff --git a/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/FileSystemManagement/Path/CheckPathExistsRequestFixture.cs b/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/FileSystemManagement/Path/CheckPathExistsRequestFixture.cs index 438e7065..41682d4b 100644 --- a/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/FileSystemManagement/Path/CheckPathExistsRequestFixture.cs +++ b/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/FileSystemManagement/Path/CheckPathExistsRequestFixture.cs @@ -20,9 +20,11 @@ public class CheckPathExistsRequestFixture /// Creates a with default or random values. /// /// Optional. The path to check. - /// Optional. Whether to include hidden elements. + /// Whether to include hidden file system elements or not. /// The created . - public CheckPathExistsRequest Create(string? path = null, bool? includeHiddenElements = null) + public CheckPathExistsRequest Create( + string? path = null, + bool? includeHiddenElements = null) { return new CheckPathExistsRequest( Path: path ?? _faker.System.FilePath(), diff --git a/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/AddBookRequestFixture.cs b/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/AddBookRequestFixture.cs index cdc04793..54b7f120 100644 --- a/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/AddBookRequestFixture.cs +++ b/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/AddBookRequestFixture.cs @@ -1,14 +1,13 @@ #region ========================================================================= USING ===================================================================================== -using AutoFixture; using Bogus; -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.Fixtures.Common.Setup; +using Lumina.Contracts.Fixtures.Core.DTO.MediaContributors; +using Lumina.Contracts.Fixtures.Core.DTO.MediaLibrary.WrittenContentLibrary; +using Lumina.Contracts.Fixtures.Core.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary; using Lumina.Contracts.Requests.MediaLibrary.WrittenContentLibrary.BookLibrary.Books; using Lumina.Domain.SharedKernel.Common.Enums.BookLibrary; -using Lumina.Domain.SharedKernel.Common.Enums.MediaContributors; using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; @@ -23,18 +22,10 @@ namespace Lumina.Contracts.Fixtures.Core.Requests.MediaLibrary.WrittenContentLib [ExcludeFromCodeCoverage] public class AddBookRequestFixture { - private readonly Fixture _fixture = new(); - private readonly Random _random = new(); - private readonly Faker _faker = new(); - - /// - /// Initializes a new instance of the class. - /// - public AddBookRequestFixture() - { - _fixture.Customizations.Add(new DateOnlySpecimenBuilder()); - _fixture.Customizations.Add(new NullableDateOnlySpecimenBuilder()); - } + private readonly IsbnDtoFixture _isbnDtoFixture = new(); + private readonly BookRatingDtoFixture _bookRatingDtoFixture = new(); + private readonly MediaContributorDtoFixture _mediaContributorDtoFixture = new(); + private readonly WrittenContentMetadataDtoFixture _writtenContentMetadataDtoFixture = new(); /// /// Creates a random valid request to add a book. @@ -58,7 +49,7 @@ public class AddBookRequestFixture /// Optional. The ISBNs of the book. /// Optional. The contributors of the book. /// Optional. The ratings of the book. - /// Whether the properties that are not explicitly provided should be randomized, or left . + /// Whether the properties that are not explicitly provided should be randomized, or forced to . /// The created request to add a book. public AddBookRequest Create( Guid? libraryId = null, @@ -82,154 +73,6 @@ public class AddBookRequestFixture List? ratings = null, bool includeOptionalProperties = true) { - 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.PickRandom()); - - 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 metadataFaker = 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, @@ -246,21 +89,21 @@ public class AddBookRequestFixture default, default, default, - default!, + default, default!, default!, default!, default! )) - .RuleFor(x => x.LibraryId, libraryId ?? _fixture.Create()) + .RuleFor(x => x.LibraryId, libraryId ?? Guid.NewGuid()) .RuleFor(x => x.Path, f => path ?? f.System.FilePath()) - .RuleFor(x => x.Metadata, metadata ?? metadataFaker) - .RuleFor(x => x.Format, format ?? (includeOptionalProperties ? _fixture.Create() : null)) + .RuleFor(x => x.Metadata, metadata ?? _writtenContentMetadataDtoFixture.Create()) + .RuleFor(x => x.Format, f => format ?? (includeOptionalProperties ? f.PickRandom() : null)) .RuleFor(x => x.Edition, f => edition ?? (includeOptionalProperties ? f.Random.String2(f.Random.Number(1, 50)) : null)) - .RuleFor(x => x.VolumeNumber, volumeNumber ?? (includeOptionalProperties ? (float?)_random.Next(1, 3) : null)) + .RuleFor(x => x.VolumeNumber, f => volumeNumber ?? (includeOptionalProperties ? (float?)f.Random.Number(1, 3) : null)) .RuleFor(x => x.Series, series) .RuleFor(x => x.ASIN, f => asin ?? (includeOptionalProperties ? f.Random.String2(10) : null)) - .RuleFor(x => x.GoodreadsId, goodreadsId ?? (includeOptionalProperties ? _random.Next(100000, 500000).ToString() : null)) + .RuleFor(x => x.GoodreadsId, f => goodreadsId ?? (includeOptionalProperties ? f.Random.Number(100000, 500000).ToString() : null)) .RuleFor(x => x.LCCN, f => lccn ?? (includeOptionalProperties ? CreateLccn(f) : null)) .RuleFor(x => x.OCLCNumber, f => oclcNumber ?? (includeOptionalProperties ? CreateOclcNumber(f) : null)) .RuleFor(x => x.OpenLibraryId, f => openLibraryId ?? (includeOptionalProperties ? CreateOpenLibraryId(f) : null)) @@ -268,9 +111,9 @@ public class AddBookRequestFixture .RuleFor(x => x.GoogleBooksId, f => googleBooksId ?? (includeOptionalProperties ? CreateGoogleBooksId(f) : null)) .RuleFor(x => x.BarnesAndNobleId, f => barnesAndNobleId ?? (includeOptionalProperties ? f.Random.String2(10, "0123456789") : null)) .RuleFor(x => x.AppleBooksId, f => appleBooksId ?? (includeOptionalProperties ? $"id{f.Random.Number(1, 999999)}" : null)) - .RuleFor(p => p.ISBNs, f => isbns ?? (includeOptionalProperties ? isbn.Generate(f.Random.Number(1, 5)) : null)) - .RuleFor(p => p.Ratings, f => ratings ?? (includeOptionalProperties ? rating.Generate(f.Random.Number(1, 5)) : null)) - .RuleFor(x => x.Contributors, f => contributors ?? (includeOptionalProperties ? mediaContributor.Generate(f.Random.Number(1, 5)) : null)); + .RuleFor(p => p.ISBNs, f => isbns ?? (includeOptionalProperties ? [.. _isbnDtoFixture.CreateMany(f.Random.Number(1, 3))] : null)) + .RuleFor(p => p.Ratings, f => ratings ?? (includeOptionalProperties ? [.. _bookRatingDtoFixture.CreateMany(f.Random.Number(1, 3))] : null)) + .RuleFor(x => x.Contributors, f => contributors ?? (includeOptionalProperties ? [.. _mediaContributorDtoFixture.CreateMany(f.Random.Number(1, 3))] : null)); } /// diff --git a/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/GetBooksLiteRequestFixture.cs b/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/GetBooksLiteRequestFixture.cs index b7ea3062..d532e90d 100644 --- a/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/GetBooksLiteRequestFixture.cs +++ b/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/GetBooksLiteRequestFixture.cs @@ -29,6 +29,8 @@ public class GetBooksLiteRequestFixture /// Optional. Whether the leading "The " prefix of a title should be ignored when computing the alpha key, or not. /// Optional. The name of the field by which to sort the results. /// Optional. The direction in which to sort the results. + /// Whether the current page should be included, or forced to . + /// Whether the per page count should be included, or forced to . /// The created . public GetBooksLiteRequest Create( Guid? libraryId = null, @@ -38,12 +40,14 @@ public class GetBooksLiteRequestFixture string? filterAlphaKey = null, bool shouldIgnoreThePrefixForAlphaPicker = false, string? sortBy = null, - SortOrder? sortOrder = null) + SortOrder? sortOrder = null, + bool includeCurrentPage = true, + bool includePerPage = true) { return new GetBooksLiteRequest( LibraryId: libraryId ?? _faker.Random.Guid(), - CurrentPage: currentPage ?? _faker.Random.Number(1, 100), - PerPage: perPage ?? _faker.Random.Number(1, 200), + CurrentPage: includeCurrentPage ? (currentPage ?? _faker.Random.Number(1, 100)) : null, + PerPage: includePerPage ? (perPage ?? _faker.Random.Number(1, 200)) : null, SearchTerm: searchTerm ?? _faker.Lorem.Word(), FilterAlphaKey: filterAlphaKey, ShouldIgnoreThePrefixForAlphaPicker: shouldIgnoreThePrefixForAlphaPicker, diff --git a/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/GetBooksRequestFixture.cs b/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/GetBooksRequestFixture.cs index cd898891..db6b9fe0 100644 --- a/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/GetBooksRequestFixture.cs +++ b/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/GetBooksRequestFixture.cs @@ -27,6 +27,8 @@ public class GetBooksRequestFixture /// Optional. The search term used to filter results. /// Optional. The name of the field by which to sort the results. /// Optional. The direction in which to sort the results. + /// Whether the current page should be included, or forced to . + /// Whether the per page count should be included, or forced to . /// The created . public GetBooksRequest Create( Guid? libraryId = null, @@ -34,12 +36,14 @@ public class GetBooksRequestFixture int? perPage = null, string? searchTerm = null, string? sortBy = null, - SortOrder? sortOrder = null) + SortOrder? sortOrder = null, + bool includeCurrentPage = true, + bool includePerPage = true) { return new GetBooksRequest( LibraryId: libraryId ?? _faker.Random.Guid(), - CurrentPage: currentPage ?? _faker.Random.Number(1, 100), - PerPage: perPage ?? _faker.Random.Number(1, 200), + CurrentPage: includeCurrentPage ? (currentPage ?? _faker.Random.Number(1, 100)) : null, + PerPage: includePerPage ? (perPage ?? _faker.Random.Number(1, 200)) : null, SearchTerm: searchTerm ?? _faker.Lorem.Word(), SortBy: sortBy ?? _faker.Lorem.Word(), SortOrder: sortOrder ?? _faker.PickRandom() diff --git a/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/UpdateBookRequestFixture.cs b/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/UpdateBookRequestFixture.cs new file mode 100644 index 00000000..f71ecc3f --- /dev/null +++ b/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/UpdateBookRequestFixture.cs @@ -0,0 +1,185 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Contracts.DTO.MediaContributors; +using Lumina.Contracts.DTO.MediaLibrary.WrittenContentLibrary; +using Lumina.Contracts.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary; +using Lumina.Contracts.Fixtures.Core.DTO.MediaContributors; +using Lumina.Contracts.Fixtures.Core.DTO.MediaLibrary.WrittenContentLibrary; +using Lumina.Contracts.Fixtures.Core.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary; +using Lumina.Contracts.Requests.MediaLibrary.WrittenContentLibrary.BookLibrary.Books; +using Lumina.Domain.SharedKernel.Common.Enums.BookLibrary; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Contracts.Fixtures.Core.Requests.MediaLibrary.WrittenContentLibrary.BookLibrary.Books; + +/// +/// Fixture class for the class. +/// +[ExcludeFromCodeCoverage] +public class UpdateBookRequestFixture +{ + private readonly IsbnDtoFixture _isbnDtoFixture = new(); + private readonly BookRatingDtoFixture _bookRatingDtoFixture = new(); + private readonly MediaContributorDtoFixture _mediaContributorDtoFixture = new(); + private readonly WrittenContentMetadataDtoFixture _writtenContentMetadataDtoFixture = new(); + + /// + /// Creates a random valid request to update a book. + /// + /// Optional. The Id of the book to update. + /// Optional. The written content metadata of the book. + /// Optional. The format of the book. + /// Optional. The edition of the book. + /// Optional. The volume or book number in the series. + /// Optional. The series the book is part of. + /// Optional. The ASIN of the book. + /// Optional. The Goodreads Id of the book. + /// Optional. The LCCN of the book. + /// Optional. The OCLC number of the book. + /// Optional. The Open Library Id of the book. + /// Optional. The LibraryThing Id of the book. + /// Optional. The Google Books Id of the book. + /// Optional. The Barnes and Noble Id of the book. + /// Optional. The Apple Books Id of the book. + /// Optional. The ISBNs of the book. + /// Optional. The contributors of the book. + /// Optional. The ratings of the book. + /// Whether the properties that are not explicitly provided should be randomized, or forced to . + /// Optional. The raw string value of the Id of the book to update. Takes precedence over . + /// Whether the Id should be included, or forced to . + /// The created request to update a book. + public UpdateBookRequest Create( + Guid? id = null, + WrittenContentMetadataDto? metadata = null, + BookFormat? format = null, + string? edition = null, + float? volumeNumber = null, + BookSeriesDto? series = null, + string? asin = null, + string? goodreadsId = null, + string? lccn = null, + string? oclcNumber = null, + string? openLibraryId = null, + string? libraryThingId = null, + string? googleBooksId = null, + string? barnesAndNobleId = null, + string? appleBooksId = null, + List? isbns = null, + List? contributors = null, + List? ratings = null, + bool includeOptionalProperties = true, + string? rawId = null, + bool includeId = true) + { + return new Faker() + .CustomInstantiator(f => new UpdateBookRequest( + default, + default!, + default, + default, + default, + default, + default, + default, + default, + default, + default, + default, + default, + default, + default, + default!, + default!, + default! + )) + .RuleFor(x => x.Id, f => includeId ? (rawId ?? id?.ToString() ?? Guid.NewGuid().ToString()) : null) + .RuleFor(x => x.Metadata, metadata ?? _writtenContentMetadataDtoFixture.Create()) + .RuleFor(x => x.Format, f => format ?? (includeOptionalProperties ? f.PickRandom() : null)) + .RuleFor(x => x.Edition, f => edition ?? (includeOptionalProperties ? f.Random.String2(f.Random.Number(1, 50)) : null)) + .RuleFor(x => x.VolumeNumber, f => volumeNumber ?? (includeOptionalProperties ? (float?)f.Random.Number(1, 3) : null)) + .RuleFor(x => x.Series, series) + .RuleFor(x => x.ASIN, f => asin ?? (includeOptionalProperties ? f.Random.String2(10) : null)) + .RuleFor(x => x.GoodreadsId, f => goodreadsId ?? (includeOptionalProperties ? f.Random.Number(100000, 500000).ToString() : null)) + .RuleFor(x => x.LCCN, f => lccn ?? (includeOptionalProperties ? CreateLccn(f) : null)) + .RuleFor(x => x.OCLCNumber, f => oclcNumber ?? (includeOptionalProperties ? CreateOclcNumber(f) : null)) + .RuleFor(x => x.OpenLibraryId, f => openLibraryId ?? (includeOptionalProperties ? CreateOpenLibraryId(f) : null)) + .RuleFor(x => x.LibraryThingId, f => libraryThingId ?? (includeOptionalProperties ? f.Random.String2(f.Random.Number(1, 50)) : null)) + .RuleFor(x => x.GoogleBooksId, f => googleBooksId ?? (includeOptionalProperties ? CreateGoogleBooksId(f) : null)) + .RuleFor(x => x.BarnesAndNobleId, f => barnesAndNobleId ?? (includeOptionalProperties ? f.Random.String2(10, "0123456789") : null)) + .RuleFor(x => x.AppleBooksId, f => appleBooksId ?? (includeOptionalProperties ? $"id{f.Random.Number(1, 999999)}" : null)) + .RuleFor(p => p.ISBNs, f => isbns ?? (includeOptionalProperties ? [.. _isbnDtoFixture.CreateMany(f.Random.Number(1, 3))] : null)) + .RuleFor(p => p.Ratings, f => ratings ?? (includeOptionalProperties ? [.. _bookRatingDtoFixture.CreateMany(f.Random.Number(1, 3))] : null)) + .RuleFor(x => x.Contributors, f => contributors ?? (includeOptionalProperties ? [.. _mediaContributorDtoFixture.CreateMany(f.Random.Number(1, 3))] : null)); + } + + /// + /// Generates a random LCCN (Library of Congress Control Number). + /// + /// The faker used to generate the value. + /// The generated LCCN. + private static string CreateLccn(Faker faker) + { + string letters = new([.. Enumerable.Range(0, faker.Random.Number(0, 3)).Select(_ => faker.Random.Char('a', 'z'))]); + string digits = faker.Random.String2(faker.Random.Number(8, 10), "0123456789"); + return letters + digits; + } + + /// + /// Generates a random OCLC number (WorldCat identifier). + /// + /// The faker used to generate the value. + /// The generated OCLC number. + private static string CreateOclcNumber(Faker faker) + { + string[] prefixes = ["ocm", "ocn", "on", "(OCoLC)"]; + string prefix = faker.Random.ArrayElement(prefixes); + string number; + switch (prefix) + { + case "ocm": + number = faker.Random.String2(8, "0123456789"); + break; + case "ocn": + number = faker.Random.String2(faker.Random.Number(9, 11), "0123456789"); + break; + case "on": + number = faker.Random.String2(10, "0123456789"); + break; + case "(OCoLC)": + number = faker.Random.String2(faker.Random.Number(8, 10), "0123456789"); + break; + default: + number = faker.Random.String2(faker.Random.Number(8, 10), "0123456789"); + return number; + } + return prefix + number; + } + + /// + /// Generates a random Open Library Id. + /// + /// The faker used to generate the value. + /// The generated Open Library Id. + private static string CreateOpenLibraryId(Faker faker) + { + int firstDigit = faker.Random.Number(1, 9); + string remainingDigits = faker.Random.String2(faker.Random.Number(0, 6), "0123456789"); + char suffix = faker.Random.ArrayElement(['A', 'M', 'W']); + return $"OL{firstDigit}{remainingDigits}{suffix}"; + } + + /// + /// Generates a random Google Books Id. + /// + /// The faker used to generate the value. + /// The generated Google Books Id. + private static string CreateGoogleBooksId(Faker faker) + { + const string VALID_CHARS = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_"; + return new string([.. Enumerable.Repeat(VALID_CHARS, 12).Select(s => s[faker.Random.Number(VALID_CHARS.Length - 1)])]); + } +} diff --git a/tests/Common/Lumina.Contracts.Fixtures/Core/Responses/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/BookLiteResponseFixture.cs b/tests/Common/Lumina.Contracts.Fixtures/Core/Responses/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/BookLiteResponseFixture.cs index dd23ff53..b834331d 100644 --- a/tests/Common/Lumina.Contracts.Fixtures/Core/Responses/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/BookLiteResponseFixture.cs +++ b/tests/Common/Lumina.Contracts.Fixtures/Core/Responses/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/BookLiteResponseFixture.cs @@ -24,18 +24,22 @@ public class BookLiteResponseFixture /// Optional. The title of the book. /// Optional. The release year of the book. /// Optional. The path of the image representing the cover of the book. + /// Whether the release year should be included, or forced to . + /// Whether the cover path should be included, or forced to . /// The created . public BookLiteResponse Create( Guid? id = null, string? title = null, int? releaseYear = null, - string? coverPath = null) + string? coverPath = null, + bool includeReleaseYear = true, + bool includeCoverPath = true) { return new BookLiteResponse( id ?? Guid.NewGuid(), title ?? _faker.Commerce.ProductName(), - releaseYear ?? _faker.Random.Int(1900, 2024), - coverPath ?? _faker.System.FilePath() + includeReleaseYear ? (releaseYear ?? _faker.Random.Int(1900, 2024)) : null, + includeCoverPath ? (coverPath ?? _faker.System.FilePath()) : null ); } diff --git a/tests/Common/Lumina.Contracts.Fixtures/Core/Responses/Themes/ThemeResponseFixture.cs b/tests/Common/Lumina.Contracts.Fixtures/Core/Responses/Themes/ThemeResponseFixture.cs index 780ed917..5913454b 100644 --- a/tests/Common/Lumina.Contracts.Fixtures/Core/Responses/Themes/ThemeResponseFixture.cs +++ b/tests/Common/Lumina.Contracts.Fixtures/Core/Responses/Themes/ThemeResponseFixture.cs @@ -28,10 +28,10 @@ public class ThemeResponseFixture /// Optional. The author of the theme. /// Optional. The version of the theme. /// Optional. The preview image path of the theme, or when the theme has no preview. - /// Whether to set , or when . + /// Whether the preview path should be included, or forced to . /// Optional. The source the theme was installed from. /// Optional. Whether the theme is the currently active one. - /// Whether to set , or when . + /// Whether the currently active flag should be included, or forced to . /// Optional. The UTC timestamp when the theme was installed. /// Optional. Whether the theme was deleted by the user. /// The created . diff --git a/tests/Common/Lumina.Domain.Fixtures/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Entities/FileFixture.cs b/tests/Common/Lumina.Domain.Fixtures/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Entities/FileFixture.cs index 5e730d0d..bf8ed020 100644 --- a/tests/Common/Lumina.Domain.Fixtures/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Entities/FileFixture.cs +++ b/tests/Common/Lumina.Domain.Fixtures/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Entities/FileFixture.cs @@ -28,7 +28,7 @@ public class FileFixture /// Optional. The file's modification date. If not provided, a recent date is generated. /// Optional. The file size. If not provided, a random size is generated. /// Optional. The file's status. If not provided, a random status is assigned. - /// Whether the file should include creation and modification dates. + /// Whether the creation and modification dates should be included, or left unset. /// The created . public File Create( string? path = null, diff --git a/tests/Common/Lumina.Domain.Fixtures/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryAggregate/LibraryFixture.cs b/tests/Common/Lumina.Domain.Fixtures/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryAggregate/LibraryFixture.cs index 449396f2..c786875c 100644 --- a/tests/Common/Lumina.Domain.Fixtures/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryAggregate/LibraryFixture.cs +++ b/tests/Common/Lumina.Domain.Fixtures/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryAggregate/LibraryFixture.cs @@ -2,9 +2,11 @@ using Bogus; using Lumina.Domain.Common.Primitives; using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate; -using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects; using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects; using Lumina.Domain.Core.BoundedContexts.UserManagementBoundedContext.UserAggregate.ValueObjects; +using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects; +using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects; +using Lumina.Domain.Fixtures.Core.BoundedContexts.UserManagementBoundedContext.UserAggregate.ValueObjects; using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; using System; using System.Collections.Generic; @@ -22,6 +24,9 @@ public class LibraryFixture { private readonly Faker _faker = new(); private readonly Random _random = new(); + private readonly LibraryIdFixture _libraryIdFixture = new(); + private readonly UserIdFixture _userIdFixture = new(); + private readonly ScanIdFixture _scanIdFixture = new(); /// /// Creates a random valid domain aggregate. @@ -32,7 +37,7 @@ public class LibraryFixture /// Optional. The library type. /// Optional. The content locations of the library. /// Optional. The cover image of the library. - /// Whether to include a cover image or not. + /// Whether the cover image should be included, or forced to . /// Whether the library is enabled. /// Whether the library is locked. /// Whether metadata download from the web is enabled. @@ -63,12 +68,13 @@ public class LibraryFixture "F:/Content" ]; - List resolvedScanIds = scanIds is null ? [ScanId.CreateUnique(), ScanId.CreateUnique()] : [.. scanIds.Select(scanId => ScanId.Create(scanId))]; + UserId resolvedUserId = userId is null ? _userIdFixture.Create() : _userIdFixture.Create(userId.Value); + List resolvedScanIds = scanIds is null ? [.. _scanIdFixture.CreateMany(2)] : [.. scanIds.Select(scanId => _scanIdFixture.Create(scanId))]; string? resolvedCoverImage = includeCoverImage ? (coverImage ?? _faker.System.FilePath()) : null; Result library = id is null ? Library.Create( - userId is not null ? UserId.Create(userId.Value) : UserId.CreateUnique(), + resolvedUserId, title ?? _faker.Random.String2(_faker.Random.Number(1, 50)), libraryType ?? _faker.PickRandom(), contentLocations ?? validPaths.Take(_random.Next(1, validPaths.Count)), @@ -81,8 +87,8 @@ public class LibraryFixture resolvedScanIds ) : Library.Create( - LibraryId.Create(id.Value), - userId is not null ? UserId.Create(userId.Value) : UserId.CreateUnique(), + _libraryIdFixture.Create(id.Value), + resolvedUserId, title ?? _faker.Random.String2(_faker.Random.Number(1, 50)), libraryType ?? _faker.PickRandom(), contentLocations ?? validPaths.Take(_random.Next(1, validPaths.Count)), diff --git a/tests/Common/Lumina.Domain.Fixtures/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Events/LibraryScanFailedDomainEventFixture.cs b/tests/Common/Lumina.Domain.Fixtures/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Events/LibraryScanFailedDomainEventFixture.cs index 1d28c60a..b99dd4cd 100644 --- a/tests/Common/Lumina.Domain.Fixtures/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Events/LibraryScanFailedDomainEventFixture.cs +++ b/tests/Common/Lumina.Domain.Fixtures/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Events/LibraryScanFailedDomainEventFixture.cs @@ -29,7 +29,7 @@ public class LibraryScanFailedDomainEventFixture /// Optional. The composite identifier of the media library scan that has failed. /// Optional. The date and time when the domain event occurred. /// Optional. The descriptive message of the failure. - /// Whether to include an error message in the domain event. When false, the error message is left unset. + /// Whether the error message should be included, or forced to . /// The created . public LibraryScanFailedDomainEvent Create( Guid? id = null, diff --git a/tests/Common/Lumina.Domain.Fixtures/Core/BoundedContexts/WrittenContentLibraryBoundedContext/BookLibraryAggregate/BookFixture.cs b/tests/Common/Lumina.Domain.Fixtures/Core/BoundedContexts/WrittenContentLibraryBoundedContext/BookLibraryAggregate/BookFixture.cs index 3b9873ed..331d81b0 100644 --- a/tests/Common/Lumina.Domain.Fixtures/Core/BoundedContexts/WrittenContentLibraryBoundedContext/BookLibraryAggregate/BookFixture.cs +++ b/tests/Common/Lumina.Domain.Fixtures/Core/BoundedContexts/WrittenContentLibraryBoundedContext/BookLibraryAggregate/BookFixture.cs @@ -1,13 +1,12 @@ #region ========================================================================= USING ===================================================================================== -using AutoFixture; +using Bogus; 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 Lumina.Domain.Core.BoundedContexts.WrittenContentLibraryBoundedContext.ExternalIdentifiers.LibraryManagementBoundedContext.LibraryAggregate; -using Lumina.Domain.Fixtures.Common.Setup; +using Lumina.Domain.Fixtures.Core.BoundedContexts.MediaContributorBoundedContext.MediaContributorAggregate.ValueObjects; using Lumina.Domain.Fixtures.Core.BoundedContexts.WrittenContentLibraryBoundedContext.BookLibraryAggregate.ValueObjects; using Lumina.Domain.SharedKernel.Common.Enums.BookLibrary; using System; @@ -24,46 +23,76 @@ namespace Lumina.Domain.Fixtures.Core.BoundedContexts.WrittenContentLibraryBound [ExcludeFromCodeCoverage] public class BookFixture { - private readonly Fixture _fixture = new(); + private readonly Faker _faker = new(); + private readonly WrittenContentMetadataFixture _writtenContentMetadataFixture = new(); private readonly IsbnFixture _isbnFixture = new(); private readonly BookRatingFixture _bookRatingFixture = new(); - - /// - /// Initializes a new instance of the class. - /// - public BookFixture() - { - _fixture.Customizations.Add(new DateOnlySpecimenBuilder()); - _fixture.Customizations.Add(new NullableDateOnlySpecimenBuilder()); - ConfigureCustomDomainTypes(); - } + private readonly MediaContributorIdFixture _mediaContributorIdFixture = new(); /// /// Creates a random valid domain aggregate. /// + /// Optional. The Id of the media library this book belongs to. + /// Optional. The file system path of the book. + /// Optional. The written content metadata of the book. + /// Optional. The format of the book. + /// Optional. The edition of the book. + /// Optional. The volume or book number in the series. + /// Optional. The series the book is part of. + /// Optional. The ASIN of the book. + /// Optional. The Goodreads Id of the book. + /// Optional. The LCCN of the book. + /// Optional. The OCLC number of the book. + /// Optional. The Open Library Id of the book. + /// Optional. The LibraryThing Id of the book. + /// Optional. The Google Books Id of the book. + /// Optional. The Barnes and Noble Id of the book. + /// Optional. The Apple Books Id of the book. + /// Optional. The ISBNs of the book. + /// Optional. The media contributors of the book. + /// Optional. The ratings of the book. /// The created domain aggregate. - public Book Create() + public Book Create( + Guid? libraryId = null, + string? path = null, + WrittenContentMetadata? metadata = null, + BookFormat? format = null, + string? edition = null, + float? volumeNumber = null, + BookSeries? series = null, + string? asin = null, + string? goodreadsId = null, + string? lccn = null, + string? oclcNumber = null, + string? openLibraryId = null, + string? libraryThingId = null, + string? googleBooksId = null, + string? barnesAndNobleId = null, + string? appleBooksId = null, + List? isbns = null, + List? contributors = null, + List? ratings = null) { return Book.Create( - LibraryId.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>(), - _fixture.Create>(), - _fixture.Create>() + libraryId is null ? LibraryId.Create(Guid.NewGuid()) : LibraryId.Create(libraryId.Value), + path ?? _faker.System.FilePath(), + metadata ?? _writtenContentMetadataFixture.Create(), + format ?? _faker.PickRandom(), + edition is null ? Optional.Some(_faker.Commerce.ProductName()) : Optional.Some(edition), + volumeNumber is null ? Optional.None() : Optional.Some(volumeNumber.Value), + series is null ? Optional.None() : Optional.Some(series), + asin is null ? Optional.Some(_faker.Random.String2(10)) : Optional.Some(asin), + goodreadsId is null ? Optional.Some(_faker.Random.Number(100000, 500000).ToString()) : Optional.Some(goodreadsId), + lccn is null ? Optional.Some(_faker.Random.String2(_faker.Random.Number(8, 10))) : Optional.Some(lccn), + oclcNumber is null ? Optional.Some($"ocm{_faker.Random.String2(8, "0123456789")}") : Optional.Some(oclcNumber), + openLibraryId is null ? Optional.Some($"OL{_faker.Random.Number(100000, 999999)}{_faker.Random.ArrayElement(['A', 'M', 'W'])}") : Optional.Some(openLibraryId), + libraryThingId is null ? Optional.Some(_faker.Random.String2(_faker.Random.Number(1, 50))) : Optional.Some(libraryThingId), + googleBooksId is null ? Optional.Some(_faker.Random.String2(12)) : Optional.Some(googleBooksId), + barnesAndNobleId is null ? Optional.Some(_faker.Random.String2(10, "0123456789")) : Optional.Some(barnesAndNobleId), + appleBooksId is null ? Optional.Some($"id{_faker.Random.Number(1, 999999)}") : Optional.Some(appleBooksId), + isbns ?? [.. Enumerable.Range(0, _faker.Random.Number(1, 4)).Select(_ => _isbnFixture.Create())], + contributors ?? [.. Enumerable.Range(0, _faker.Random.Number(1, 4)).Select(_ => _mediaContributorIdFixture.Create())], + ratings ?? [.. Enumerable.Range(0, _faker.Random.Number(1, 4)).Select(_ => _bookRatingFixture.Create())] ).Value; } @@ -76,50 +105,4 @@ public class BookFixture { return [.. Enumerable.Range(0, count).Select(_ => Create())]; } - - private void ConfigureCustomDomainTypes() - { - _fixture.Register(() => Optional.Some(_fixture.Create())); - _fixture.Register(() => Optional.Some(_fixture.Create())); - - _fixture.Register(() => - { - int originalYear = Random.Shared.Next(1900, 2026); - int reReleaseYear = Random.Shared.Next(originalYear, 2026); - - return ReleaseInfo.Create( - Optional.Some(DateOnly.FromDateTime(new DateTime(originalYear, 1, 1))), - 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(() => _isbnFixture.Create()); - - _fixture.Register(() => _bookRatingFixture.Create()); - } } diff --git a/tests/Common/Lumina.Infrastructure.Fixtures/Core/Themes/ThemePackFixture.cs b/tests/Common/Lumina.Infrastructure.Fixtures/Core/Themes/ThemePackFixture.cs index f87a516f..9347f4b9 100644 --- a/tests/Common/Lumina.Infrastructure.Fixtures/Core/Themes/ThemePackFixture.cs +++ b/tests/Common/Lumina.Infrastructure.Fixtures/Core/Themes/ThemePackFixture.cs @@ -28,7 +28,7 @@ public sealed class ThemePackFixture /// Optional template mappings written to the manifest. /// Optional preview path written to the manifest, or to omit the preview. /// Optional content for the default template file. - /// Whether to include the preview asset file in the archive. + /// Whether to include the preview asset file in the archive or not. /// Optional additional files written into the archive. /// The created theme pack ZIP archive. public byte[] Create( diff --git a/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Api/StubApiHttpClient.cs b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Api/StubApiHttpClient.cs index 2b3c67cf..ad6f31c8 100644 --- a/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Api/StubApiHttpClient.cs +++ b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Api/StubApiHttpClient.cs @@ -267,6 +267,24 @@ public class StubApiHttpClient : IApiHttpClient throw new InvalidOperationException($"No PUT response is registered for the endpoint '{endpoint}'."); } + /// + /// Sends a PUT request with a multipart form containing a single file 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 stream of the file to upload. + /// The name of the file to upload. + /// The name of the form field carrying the file. + /// Cancellation token that can be used to stop the execution. + /// The deserialized response containing the result of the PUT request. + public Task PutMultipartAsync(string endpoint, Stream fileStream, string fileName, string fieldName, CancellationToken cancellationToken = default) + { + PutRequests.Add((endpoint, fileName)); + if (_putResponseFactories.TryGetValue(endpoint, out Func? responseFactory)) + return Task.FromResult((TResponse)responseFactory(fileName)); + throw new InvalidOperationException($"No PUT response is registered for the endpoint '{endpoint}'."); + } + /// /// Sends a POST request with a multipart form containing a single file to the specified as an asynchronous operation and returns the result. /// diff --git a/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/Common/GenreDtoFixture.cs b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/Common/GenreDtoFixture.cs new file mode 100644 index 00000000..db5f4488 --- /dev/null +++ b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/Common/GenreDtoFixture.cs @@ -0,0 +1,41 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Presentation.Web.Common.DTO.Common; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Presentation.Web.Fixtures.Common.DTO.Common; + +/// +/// Fixture class for generating test data. +/// +[ExcludeFromCodeCoverage] +public class GenreDtoFixture +{ + private readonly Faker _faker = new(); + + /// + /// Creates a new instance with randomized test data. + /// + /// Optional. The name of the genre. + /// A configured instance. + public GenreDto Create(string? name = null) + { + return new GenreDto + { + Name = name ?? _faker.Lorem.Word() + }; + } + + /// + /// Creates multiple instances with randomized test data. + /// + /// Number of instances to create. + /// List of configured instances. + public List CreateMany(int count = 3) + { + return [.. Enumerable.Range(0, count).Select(_ => Create())]; + } +} diff --git a/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/Common/LanguageInfoDtoFixture.cs b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/Common/LanguageInfoDtoFixture.cs new file mode 100644 index 00000000..ab68b3b8 --- /dev/null +++ b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/Common/LanguageInfoDtoFixture.cs @@ -0,0 +1,48 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Presentation.Web.Common.DTO.Common; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Presentation.Web.Fixtures.Common.DTO.Common; + +/// +/// Fixture class for generating test data. +/// +[ExcludeFromCodeCoverage] +public class LanguageInfoDtoFixture +{ + private readonly Faker _faker = new(); + + /// + /// Creates a new instance with randomized test data. + /// + /// Optional. The ISO 639-1 two-letter language code. + /// Optional. The name of the language in English. + /// Optional. The native name of the language. + /// A configured instance. + public LanguageInfoDto Create( + string? languageCode = null, + string? languageName = null, + string? nativeName = null) + { + return new LanguageInfoDto + { + LanguageCode = languageCode ?? _faker.Random.String2(2, "abcdefghijklmnopqrstuvwxyz"), + LanguageName = languageName ?? _faker.Address.Country(), + NativeName = nativeName ?? _faker.Lorem.Word() + }; + } + + /// + /// Creates multiple instances with randomized test data. + /// + /// Number of instances to create. + /// List of configured instances. + public List CreateMany(int count = 3) + { + return [.. Enumerable.Range(0, count).Select(_ => Create())]; + } +} diff --git a/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/Common/ReleaseInfoDtoFixture.cs b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/Common/ReleaseInfoDtoFixture.cs new file mode 100644 index 00000000..f56c2dfc --- /dev/null +++ b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/Common/ReleaseInfoDtoFixture.cs @@ -0,0 +1,64 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Presentation.Web.Common.DTO.Common; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Presentation.Web.Fixtures.Common.DTO.Common; + +/// +/// Fixture class for generating test data. +/// +[ExcludeFromCodeCoverage] +public class ReleaseInfoDtoFixture +{ + private readonly Faker _faker = new(); + private readonly Random _random = new(); + + /// + /// Creates a new instance with randomized test data. + /// + /// Optional. The original release date of the content. + /// Optional. The original release year of the content. + /// Optional. The re-release date of the content. + /// Optional. The re-release year of the content. + /// Optional. The country where the content was released. + /// Optional. The version or edition of the content's release. + /// A configured instance. + public ReleaseInfoDto Create( + DateOnly? originalReleaseDate = null, + int? originalReleaseYear = null, + DateOnly? reReleaseDate = null, + int? reReleaseYear = null, + string? releaseCountry = null, + string? releaseVersion = null) + { + int resolvedOriginalReleaseYear = originalReleaseYear ?? (originalReleaseDate?.Year ?? _random.Next(1900, 2026)); + DateOnly resolvedOriginalReleaseDate = originalReleaseDate ?? new DateOnly(resolvedOriginalReleaseYear, 1, 1); + int resolvedReReleaseYear = reReleaseYear ?? (reReleaseDate?.Year ?? _random.Next(resolvedOriginalReleaseYear, resolvedOriginalReleaseYear + 100)); + DateOnly resolvedReReleaseDate = reReleaseDate ?? new DateOnly(resolvedReReleaseYear, 1, 1); + + return new ReleaseInfoDto + { + OriginalReleaseDate = resolvedOriginalReleaseDate, + OriginalReleaseYear = resolvedOriginalReleaseYear, + ReReleaseDate = resolvedReReleaseDate, + ReReleaseYear = resolvedReReleaseYear, + ReleaseCountry = releaseCountry ?? _faker.Address.CountryCode(), + ReleaseVersion = releaseVersion ?? _faker.Random.String2(_faker.Random.Number(1, 50)) + }; + } + + /// + /// Creates multiple instances with randomized test data. + /// + /// Number of instances to create. + /// List of configured instances. + public List CreateMany(int count = 3) + { + return [.. Enumerable.Range(0, count).Select(_ => Create())]; + } +} diff --git a/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/Common/TagDtoFixture.cs b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/Common/TagDtoFixture.cs new file mode 100644 index 00000000..4c85476a --- /dev/null +++ b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/Common/TagDtoFixture.cs @@ -0,0 +1,41 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Presentation.Web.Common.DTO.Common; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Presentation.Web.Fixtures.Common.DTO.Common; + +/// +/// Fixture class for generating test data. +/// +[ExcludeFromCodeCoverage] +public class TagDtoFixture +{ + private readonly Faker _faker = new(); + + /// + /// Creates a new instance with randomized test data. + /// + /// Optional. The name of the tag. + /// A configured instance. + public TagDto Create(string? name = null) + { + return new TagDto + { + Name = name ?? _faker.Lorem.Word() + }; + } + + /// + /// Creates multiple instances with randomized test data. + /// + /// Number of instances to create. + /// List of configured instances. + public List CreateMany(int count = 3) + { + return [.. Enumerable.Range(0, count).Select(_ => Create())]; + } +} diff --git a/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/FileSystemManagement/DirectoryDtoFixture.cs b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/FileSystemManagement/DirectoryDtoFixture.cs index ce8f3e32..c49df938 100644 --- a/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/FileSystemManagement/DirectoryDtoFixture.cs +++ b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/FileSystemManagement/DirectoryDtoFixture.cs @@ -23,7 +23,7 @@ public class DirectoryDtoFixture /// Optional. The full path to the directory. /// Optional. The name of the directory. /// Optional. The children items of the directory. - /// Whether the directory should include children items, or an empty collection. + /// Whether the children items should be included, or forced to an empty collection. /// The created . public DirectoryDto Create( string? path = null, diff --git a/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/MediaContributors/MediaContributorDtoFixture.cs b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/MediaContributors/MediaContributorDtoFixture.cs new file mode 100644 index 00000000..f7b858a7 --- /dev/null +++ b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/MediaContributors/MediaContributorDtoFixture.cs @@ -0,0 +1,59 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Presentation.Web.Common.DTO.MediaContributors; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Presentation.Web.Fixtures.Common.DTO.MediaContributors; + +/// +/// Fixture class for generating test data. +/// +[ExcludeFromCodeCoverage] +public class MediaContributorDtoFixture +{ + private static readonly string[] RoleCategories = ["Author", "Translator", "Illustrator", "Editor", "Narrator"]; + private readonly Faker _faker = new(); + + /// + /// Creates a new instance with randomized test data. + /// + /// Optional. The name by which the contributor is popularly known. + /// Optional. The legal name of the contributor. + /// Optional. The name of the role of the contributor. + /// Optional. The category of the role of the contributor. + /// A configured instance. + public MediaContributorDto Create( + string? displayName = null, + string? legalName = null, + string? roleName = null, + string? roleCategory = null) + { + string resolvedRoleCategory = roleCategory ?? _faker.Random.ArrayElement(RoleCategories); + return new MediaContributorDto + { + Name = new MediaContributorNameDto + { + DisplayName = displayName ?? _faker.Name.FullName(), + LegalName = legalName ?? _faker.Name.FullName() + }, + Role = new MediaContributorRoleDto + { + Name = roleName ?? resolvedRoleCategory.ToLowerInvariant(), + Category = resolvedRoleCategory + } + }; + } + + /// + /// Creates multiple instances with randomized test data. + /// + /// Number of instances to create. + /// List of configured instances. + public List CreateMany(int count = 3) + { + return [.. Enumerable.Range(0, count).Select(_ => Create())]; + } +} diff --git a/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/Plugins/PluginSettingsDtoFixture.cs b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/Plugins/PluginSettingsDtoFixture.cs index 7a06532e..a09d3974 100644 --- a/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/Plugins/PluginSettingsDtoFixture.cs +++ b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/Plugins/PluginSettingsDtoFixture.cs @@ -22,8 +22,8 @@ public class PluginSettingsDtoFixture /// Creates a new instance with randomized test data. /// /// Optional unique identifier of the plugin. - /// Whether to populate the current settings values, or leave them null. - /// Whether to populate the settings schema, or leave it empty. + /// Whether the current settings values should be included, or forced to . + /// Whether the settings schema should be included, or forced to an empty collection. /// A configured instance. public PluginSettingsDto Create( Guid? pluginId = null, diff --git a/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/Themes/ThemeNavEntryDtoFixture.cs b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/Themes/ThemeNavEntryDtoFixture.cs index 76cc62a7..bf3edb3c 100644 --- a/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/Themes/ThemeNavEntryDtoFixture.cs +++ b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/Themes/ThemeNavEntryDtoFixture.cs @@ -21,9 +21,9 @@ public class ThemeNavEntryDtoFixture /// /// Optional label of the entry. /// Optional URL of the link, or for a submenu. - /// Whether to set , or when . + /// Whether the URL should be included, or forced to . /// Optional CSS classes of the link. - /// Whether to set , or when . + /// Whether the CSS class should be included, or forced to . /// Optional child links of a submenu. /// The created . public ThemeNavEntryDto Create( diff --git a/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/Themes/ThemeResponseDtoFixture.cs b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/Themes/ThemeResponseDtoFixture.cs index 36901ca5..14ec2131 100644 --- a/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/Themes/ThemeResponseDtoFixture.cs +++ b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/Themes/ThemeResponseDtoFixture.cs @@ -28,10 +28,10 @@ public class ThemeResponseDtoFixture /// Optional author of the theme. /// Optional semantic version of the theme. /// Optional preview image path of the theme, or when the theme has no preview. - /// Whether to set , or when . + /// Whether the preview path should be included, or forced to . /// Optional source the theme was installed from. /// Optional value indicating whether the theme is the active one. - /// Whether to set , or when . + /// Whether the currently active flag should be included, or forced to . /// Optional UTC timestamp at which the theme was installed. /// Optional value indicating whether the theme was deleted by the user. /// A configured instance. diff --git a/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/WrittenContentLibrary/BookLibrary/BookDetailsDtoFixture.cs b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/WrittenContentLibrary/BookLibrary/BookDetailsDtoFixture.cs new file mode 100644 index 00000000..fdc2ba2b --- /dev/null +++ b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/WrittenContentLibrary/BookLibrary/BookDetailsDtoFixture.cs @@ -0,0 +1,94 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Presentation.Web.Common.DTO.WrittenContentLibrary; +using Lumina.Presentation.Web.Common.DTO.WrittenContentLibrary.BookLibrary; +using Lumina.Presentation.Web.Common.Enums.BookLibrary; +using Lumina.Presentation.Web.Fixtures.Common.DTO.MediaContributors; +using Lumina.Presentation.Web.Fixtures.Common.DTO.WrittenContentLibrary; +using Lumina.Presentation.Web.Fixtures.Common.DTO.WrittenContentLibrary.BookLibrary; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Presentation.Web.Fixtures.Common.DTO.WrittenContentLibrary.BookLibrary; + +/// +/// Fixture class for generating test data. +/// +[ExcludeFromCodeCoverage] +public class BookDetailsDtoFixture +{ + private readonly Faker _faker = new(); + private readonly WrittenContentMetadataDtoFixture _writtenContentMetadataDtoFixture = new(); + private readonly IsbnDtoFixture _isbnDtoFixture = new(); + private readonly MediaContributorDtoFixture _mediaContributorDtoFixture = new(); + private readonly BookRatingDtoFixture _bookRatingDtoFixture = new(); + + /// + /// Creates a new instance with randomized test data. + /// + /// Optional Id of the book. + /// Optional Id of the media library the book belongs to. + /// Optional file system path of the book. + /// Optional written content metadata of the book. + /// Whether the written content metadata should be included, or forced to . + /// A configured instance. + public BookDetailsDto Create( + Guid? id = null, + Guid? libraryId = null, + string? path = null, + WrittenContentMetadataDto? metadata = null, + bool includeMetadata = true) + { + return new BookDetailsDto + { + Id = id ?? _faker.Random.Guid(), + LibraryId = libraryId ?? _faker.Random.Guid(), + Path = path ?? _faker.System.FilePath(), + Metadata = metadata ?? (includeMetadata ? _writtenContentMetadataDtoFixture.Create() : null), + Format = _faker.PickRandom(), + Edition = _faker.Random.String2(_faker.Random.Number(1, 50)), + VolumeNumber = _faker.Random.Number(1, 3), + ASIN = _faker.Random.String2(10), + GoodreadsId = _faker.Random.Number(100000, 500000).ToString(), + LCCN = "n78890351", + OCLCNumber = "ocm12345678", + OpenLibraryId = "OL123456M", + LibraryThingId = _faker.Random.String2(_faker.Random.Number(1, 50)), + GoogleBooksId = CreateGoogleBooksId(), + BarnesAndNobleId = _faker.Random.String2(10, "0123456789"), + AppleBooksId = $"id{_faker.Random.Number(1, 999999)}", + ISBNs = [.. _isbnDtoFixture.CreateMany(_faker.Random.Number(1, 3))], + Contributors = [.. _mediaContributorDtoFixture.CreateMany(_faker.Random.Number(1, 3))], + Ratings = [.. _bookRatingDtoFixture.CreateMany(_faker.Random.Number(1, 3))], + MetadataStatus = _faker.Random.String2(_faker.Random.Number(1, 20)), + LastMetadataUpdateUtc = _faker.Date.Recent(), + MetadataProvider = _faker.Random.String2(_faker.Random.Number(1, 20)), + CreatedOnUtc = _faker.Date.Past(), + UpdatedOnUtc = _faker.Date.Recent(), + CoverPath = _faker.System.FilePath() + }; + } + + /// + /// Creates a list of instances with randomized test data. + /// + /// Number of instances to create. + /// List of configured instances. + public List CreateMany(int count = 3) + { + return [.. Enumerable.Range(0, count).Select(_ => Create())]; + } + + /// + /// Generates a valid Google Books Id. + /// + /// The generated Google Books Id. + private string CreateGoogleBooksId() + { + const string VALID_CHARS = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_"; + return new string([.. Enumerable.Repeat(VALID_CHARS, 12).Select(s => s[_faker.Random.Number(VALID_CHARS.Length - 1)])]); + } +} diff --git a/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/WrittenContentLibrary/BookLibrary/BookRatingDtoFixture.cs b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/WrittenContentLibrary/BookLibrary/BookRatingDtoFixture.cs new file mode 100644 index 00000000..49cb5256 --- /dev/null +++ b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/WrittenContentLibrary/BookLibrary/BookRatingDtoFixture.cs @@ -0,0 +1,53 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Presentation.Web.Common.DTO.WrittenContentLibrary.BookLibrary; +using Lumina.Presentation.Web.Common.Enums.BookLibrary; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Presentation.Web.Fixtures.Common.DTO.WrittenContentLibrary.BookLibrary; + +/// +/// Fixture class for generating test data. +/// +[ExcludeFromCodeCoverage] +public class BookRatingDtoFixture +{ + private readonly Faker _faker = new(); + + /// + /// Creates a new instance with randomized test data. + /// + /// Optional. The rating value. + /// Optional. The maximum possible rating value. + /// Optional. The number of votes the rating is based on. + /// Optional. The source of the rating. + /// A configured instance. + public BookRatingDto Create( + decimal? value = null, + decimal? maxValue = null, + int? voteCount = null, + BookRatingSource? source = null) + { + return new BookRatingDto + { + Value = value ?? _faker.Random.Decimal(1, 5), + MaxValue = maxValue ?? 5, + VoteCount = voteCount ?? _faker.Random.Number(1, 1000), + Source = source ?? _faker.PickRandom() + }; + } + + /// + /// Creates multiple instances with randomized test data. + /// + /// Number of instances to create. + /// List of configured instances. + public List CreateMany(int count = 3) + { + return [.. Enumerable.Range(0, count).Select(_ => Create())]; + } +} diff --git a/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/WrittenContentLibrary/BookLibrary/BookSeriesDtoFixture.cs b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/WrittenContentLibrary/BookLibrary/BookSeriesDtoFixture.cs new file mode 100644 index 00000000..c84c8be0 --- /dev/null +++ b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/WrittenContentLibrary/BookLibrary/BookSeriesDtoFixture.cs @@ -0,0 +1,41 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Presentation.Web.Common.DTO.WrittenContentLibrary.BookLibrary; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Presentation.Web.Fixtures.Common.DTO.WrittenContentLibrary.BookLibrary; + +/// +/// Fixture class for generating test data. +/// +[ExcludeFromCodeCoverage] +public class BookSeriesDtoFixture +{ + private readonly Faker _faker = new(); + + /// + /// Creates a new instance with randomized test data. + /// + /// Optional. The title of the book series. + /// A configured instance. + public BookSeriesDto Create(string? title = null) + { + return new BookSeriesDto + { + Title = title ?? _faker.Lorem.Sentence(3) + }; + } + + /// + /// Creates multiple instances with randomized test data. + /// + /// Number of instances to create. + /// List of configured instances. + public List CreateMany(int count = 3) + { + return [.. Enumerable.Range(0, count).Select(_ => Create())]; + } +} diff --git a/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/WrittenContentLibrary/BookLibrary/IsbnDtoFixture.cs b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/WrittenContentLibrary/BookLibrary/IsbnDtoFixture.cs new file mode 100644 index 00000000..f5185f35 --- /dev/null +++ b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/WrittenContentLibrary/BookLibrary/IsbnDtoFixture.cs @@ -0,0 +1,86 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Common.DTO.WrittenContentLibrary.BookLibrary; +using Lumina.Presentation.Web.Common.Enums.BookLibrary; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Presentation.Web.Fixtures.Common.DTO.WrittenContentLibrary.BookLibrary; + +/// +/// Fixture class for generating test data. +/// +[ExcludeFromCodeCoverage] +public class IsbnDtoFixture +{ + private readonly Random _random = new(); + + /// + /// Creates a new instance with a random or explicitly requested format. + /// + /// Optional. The ISBN value. If not provided, a valid ISBN is generated. + /// Optional. The ISBN format. If not provided, the format is derived from the value. + /// A configured instance. + public IsbnDto Create(string? value = null, IsbnFormat? format = null) + { + string resolvedValue = value ?? (format == IsbnFormat.Isbn10 ? GenerateValidIsbn10() : GenerateValidIsbn13()); + return new IsbnDto + { + Value = resolvedValue, + Format = format ?? (resolvedValue.Length > 13 ? IsbnFormat.Isbn13 : IsbnFormat.Isbn10) + }; + } + + /// + /// Creates multiple instances with randomized test data. + /// + /// Number of instances to create. + /// List of configured instances. + public List CreateMany(int count = 3) + { + return [.. Enumerable.Range(0, count).Select(_ => Create())]; + } + + /// + /// Generates a valid ISBN-10 with the correct checksum. + /// + /// A valid ISBN-10 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}"; + } + + /// + /// Generates a valid ISBN-13 with the correct checksum. + /// + /// A valid ISBN-13 value. + 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/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/WrittenContentLibrary/WrittenContentMetadataDtoFixture.cs b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/WrittenContentLibrary/WrittenContentMetadataDtoFixture.cs new file mode 100644 index 00000000..6695be24 --- /dev/null +++ b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/WrittenContentLibrary/WrittenContentMetadataDtoFixture.cs @@ -0,0 +1,75 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Presentation.Web.Common.DTO.Common; +using Lumina.Presentation.Web.Common.DTO.WrittenContentLibrary; +using Lumina.Presentation.Web.Fixtures.Common.DTO.Common; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Presentation.Web.Fixtures.Common.DTO.WrittenContentLibrary; + +/// +/// Fixture class for generating test data. +/// +[ExcludeFromCodeCoverage] +public class WrittenContentMetadataDtoFixture +{ + private readonly Faker _faker = new(); + private readonly GenreDtoFixture _genreDtoFixture = new(); + private readonly TagDtoFixture _tagDtoFixture = new(); + private readonly LanguageInfoDtoFixture _languageInfoDtoFixture = new(); + private readonly ReleaseInfoDtoFixture _releaseInfoDtoFixture = new(); + + /// + /// Creates a new instance with randomized test data. + /// + /// Optional. The title of the written content. + /// Optional. The original title of the written content. + /// Optional. A brief description or summary of the written content. + /// Optional. The release information of the written content. + /// Optional. The genres associated with the written content. + /// Optional. The tags that describe or categorize the written content. + /// Optional. The language in which the written content is written. + /// Optional. The original language of the written content. + /// Optional. The name of the publisher of the written content. + /// Optional. The number of pages in the written content. + /// A configured instance. + public WrittenContentMetadataDto Create( + string? title = null, + string? originalTitle = null, + string? description = null, + ReleaseInfoDto? releaseInfo = null, + List? genres = null, + List? tags = null, + LanguageInfoDto? language = null, + LanguageInfoDto? originalLanguage = null, + string? publisher = null, + int? pageCount = null) + { + return new WrittenContentMetadataDto + { + Title = title ?? _faker.Lorem.Sentence(3), + OriginalTitle = originalTitle ?? _faker.Lorem.Sentence(3), + Description = description ?? _faker.Lorem.Paragraph(), + ReleaseInfo = releaseInfo ?? _releaseInfoDtoFixture.Create(), + Genres = genres ?? [.. _genreDtoFixture.CreateMany(_faker.Random.Number(1, 3))], + Tags = tags ?? [.. _tagDtoFixture.CreateMany(_faker.Random.Number(1, 3))], + Language = language ?? _languageInfoDtoFixture.Create(), + OriginalLanguage = originalLanguage ?? _languageInfoDtoFixture.Create(), + Publisher = publisher ?? _faker.Company.CompanyName(), + PageCount = pageCount ?? _faker.Random.Int(100, 1000) + }; + } + + /// + /// Creates multiple instances with randomized test data. + /// + /// Number of instances to create. + /// List of configured instances. + public List CreateMany(int count = 3) + { + return [.. Enumerable.Range(0, count).Select(_ => Create())]; + } +} diff --git a/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/FileSystemManagement/Directories/GetDirectoriesRequestFixture.cs b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/FileSystemManagement/Directories/GetDirectoriesRequestFixture.cs index 3683b3a4..6c3c7575 100644 --- a/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/FileSystemManagement/Directories/GetDirectoriesRequestFixture.cs +++ b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/FileSystemManagement/Directories/GetDirectoriesRequestFixture.cs @@ -17,9 +17,11 @@ public class GetDirectoriesRequestFixture /// Creates a new instance with randomized test data. /// /// Optional file system path whose directories are retrieved. - /// Whether hidden file system elements are included or not. + /// Whether to include hidden file system elements or not. /// A configured instance. - public GetDirectoriesRequest Create(string? path = null, bool includeHiddenElements = false) + public GetDirectoriesRequest Create( + string? path = null, + bool includeHiddenElements = false) { return new GetDirectoriesRequest( Path: path ?? $"/media/{System.Guid.NewGuid():N}", diff --git a/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/Library/WrittenContentLibrary/BookLibrary/Books/GetBookRequestFixture.cs b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/Library/WrittenContentLibrary/BookLibrary/Books/GetBookRequestFixture.cs new file mode 100644 index 00000000..deca06c8 --- /dev/null +++ b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/Library/WrittenContentLibrary/BookLibrary/Books/GetBookRequestFixture.cs @@ -0,0 +1,37 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Common.Requests.Library.WrittenContentLibrary.BookLibrary.Books; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Presentation.Web.Fixtures.Common.Requests.Library.WrittenContentLibrary.BookLibrary.Books; + +/// +/// Fixture class for generating test data. +/// +[ExcludeFromCodeCoverage] +public class GetBookRequestFixture +{ + /// + /// Creates a new instance. + /// + /// Optional unique identifier of the book to retrieve. + /// A configured instance. + public GetBookRequest Create( + Guid? id = null) + { + return new GetBookRequest(id?.ToString() ?? Guid.NewGuid().ToString()); + } + + /// + /// Creates a list of instances. + /// + /// Number of instances to create. + /// List of configured instances. + public List CreateMany(int count = 3) + { + return [.. Enumerable.Range(0, count).Select(_ => Create())]; + } +} diff --git a/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/Library/WrittenContentLibrary/BookLibrary/Books/UpdateBookRequestFixture.cs b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/Library/WrittenContentLibrary/BookLibrary/Books/UpdateBookRequestFixture.cs new file mode 100644 index 00000000..675dc2f8 --- /dev/null +++ b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/Library/WrittenContentLibrary/BookLibrary/Books/UpdateBookRequestFixture.cs @@ -0,0 +1,84 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Presentation.Web.Common.DTO.WrittenContentLibrary; +using Lumina.Presentation.Web.Common.Enums.BookLibrary; +using Lumina.Presentation.Web.Common.Requests.Library.WrittenContentLibrary.BookLibrary.Books; +using Lumina.Presentation.Web.Fixtures.Common.DTO.MediaContributors; +using Lumina.Presentation.Web.Fixtures.Common.DTO.WrittenContentLibrary; +using Lumina.Presentation.Web.Fixtures.Common.DTO.WrittenContentLibrary.BookLibrary; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Presentation.Web.Fixtures.Common.Requests.Library.WrittenContentLibrary.BookLibrary.Books; + +/// +/// Fixture class for generating test data. +/// +[ExcludeFromCodeCoverage] +public class UpdateBookRequestFixture +{ + private readonly Faker _faker = new(); + private readonly WrittenContentMetadataDtoFixture _writtenContentMetadataDtoFixture = new(); + private readonly BookSeriesDtoFixture _bookSeriesDtoFixture = new(); + private readonly IsbnDtoFixture _isbnDtoFixture = new(); + private readonly MediaContributorDtoFixture _mediaContributorDtoFixture = new(); + private readonly BookRatingDtoFixture _bookRatingDtoFixture = new(); + + /// + /// Creates a new instance with randomized test data. + /// + /// Optional Id of the book to update. + /// Optional written content metadata of the book. + /// Whether the properties that are not explicitly provided should be randomized, or forced to . + /// A configured instance. + public UpdateBookRequest Create( + Guid? id = null, + WrittenContentMetadataDto? metadata = null, + bool includeOptionalProperties = true) + { + return new UpdateBookRequest + { + Id = id?.ToString() ?? Guid.NewGuid().ToString(), + Metadata = metadata ?? (includeOptionalProperties ? _writtenContentMetadataDtoFixture.Create() : null), + Format = includeOptionalProperties ? _faker.PickRandom() : null, + Edition = includeOptionalProperties ? _faker.Random.String2(_faker.Random.Number(1, 50)) : null, + VolumeNumber = includeOptionalProperties ? _faker.Random.Number(1, 3) : null, + Series = includeOptionalProperties ? _bookSeriesDtoFixture.Create() : null, + ASIN = includeOptionalProperties ? _faker.Random.String2(10) : null, + GoodreadsId = includeOptionalProperties ? _faker.Random.Number(100000, 500000).ToString() : null, + LCCN = includeOptionalProperties ? "n78890351" : null, + OCLCNumber = includeOptionalProperties ? "ocm12345678" : null, + OpenLibraryId = includeOptionalProperties ? "OL123456M" : null, + LibraryThingId = includeOptionalProperties ? _faker.Random.String2(_faker.Random.Number(1, 50)) : null, + GoogleBooksId = includeOptionalProperties ? CreateGoogleBooksId() : null, + BarnesAndNobleId = includeOptionalProperties ? _faker.Random.String2(10, "0123456789") : null, + AppleBooksId = includeOptionalProperties ? $"id{_faker.Random.Number(1, 999999)}" : null, + ISBNs = includeOptionalProperties ? [.. _isbnDtoFixture.CreateMany(_faker.Random.Number(1, 3))] : null, + Contributors = includeOptionalProperties ? [.. _mediaContributorDtoFixture.CreateMany(_faker.Random.Number(1, 3))] : null, + Ratings = includeOptionalProperties ? [.. _bookRatingDtoFixture.CreateMany(_faker.Random.Number(1, 3))] : null + }; + } + + /// + /// Creates a list of instances with randomized test data. + /// + /// Number of instances to create. + /// List of configured instances. + public List CreateMany(int count = 3) + { + return [.. Enumerable.Range(0, count).Select(_ => Create())]; + } + + /// + /// Generates a valid Google Books Id. + /// + /// The generated Google Books Id. + private string CreateGoogleBooksId() + { + const string VALID_CHARS = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_"; + return new string([.. Enumerable.Repeat(VALID_CHARS, 12).Select(s => s[_faker.Random.Number(VALID_CHARS.Length - 1)])]); + } +} diff --git a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/AddBook/AddBookEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/AddBook/AddBookEndpointTests.cs index 6e2216f1..26a716e6 100644 --- a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/AddBook/AddBookEndpointTests.cs +++ b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/AddBook/AddBookEndpointTests.cs @@ -1,13 +1,24 @@ #region ========================================================================= USING ===================================================================================== using Bogus; +using Lumina.Application.Common.DataAccess.Entities.MediaContributors; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management; +using Lumina.Contracts.Fixtures.Core.DTO.Common; +using Lumina.Contracts.Fixtures.Core.DTO.MediaContributors; +using Lumina.Contracts.Fixtures.Core.DTO.MediaLibrary.WrittenContentLibrary; +using Lumina.Contracts.Fixtures.Core.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary; using Lumina.Contracts.Fixtures.Core.Requests.MediaLibrary.WrittenContentLibrary.BookLibrary.Books; using Lumina.Contracts.Requests.MediaLibrary.WrittenContentLibrary.BookLibrary.Books; +using Lumina.DataAccess.Core.UoW; using Lumina.Domain.Common.Errors; using Lumina.Domain.Core.BoundedContexts.WrittenContentLibraryBoundedContext.BookLibraryAggregate; using Lumina.Domain.SharedKernel.Common.Enums.BookLibrary; +using Lumina.Domain.SharedKernel.Common.Enums.MediaContributors; +using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; using Lumina.Presentation.Api.IntegrationTests.Common.Converters; using Lumina.Presentation.Api.IntegrationTests.Common.Setup; using Microsoft.AspNetCore.Http; +using Microsoft.EntityFrameworkCore; +using Microsoft.Extensions.DependencyInjection; using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; @@ -40,6 +51,16 @@ public class AddBookEndpointTests : IClassFixture } }; private readonly AddBookRequestFixture _requestBookFixture = new(); + private readonly WrittenContentMetadataDtoFixture _writtenContentMetadataDtoFixture = new(); + private readonly ReleaseInfoDtoFixture _releaseInfoDtoFixture = new(); + private readonly GenreDtoFixture _genreDtoFixture = new(); + private readonly TagDtoFixture _tagDtoFixture = new(); + private readonly LanguageInfoDtoFixture _languageInfoDtoFixture = new(); + private readonly IsbnDtoFixture _isbnDtoFixture = new(); + private readonly BookRatingDtoFixture _bookRatingDtoFixture = new(); + private readonly MediaContributorDtoFixture _mediaContributorDtoFixture = new(); + private readonly LibraryEntityFixture _libraryEntityFixture = new(); + private Guid _libraryId; /// /// Initializes a new instance of the class. @@ -52,11 +73,19 @@ public class AddBookEndpointTests : IClassFixture } /// - /// Initializes authenticated API client. + /// Initializes authenticated API client, along with a media library owned by the authenticated user that the added books belong to. /// public async Task InitializeAsync() { _client = await _apiFactory.CreateAuthenticatedClientAsync(); + + // The handler only allows adding books to a library the current user owns, so each test seeds its own owned library. + _libraryId = Guid.NewGuid(); + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + Guid userId = dbContext.Users.Single(user => user.Username == _apiFactory.TestUsername).Id; + dbContext.Libraries.Add(_libraryEntityFixture.Create(id: _libraryId, userId: userId, title: "Test Library", libraryType: LibraryType.EBook, contentLocations: [])); + await dbContext.SaveChangesAsync(); } [Fact] @@ -66,7 +95,7 @@ public class AddBookEndpointTests : IClassFixture AddBookRequest bookRequest = _requestBookFixture.Create(); // Act - HttpResponseMessage response = await _client.PostAsJsonAsync("/api/v1/books", bookRequest); + HttpResponseMessage response = await PostBookAsync(bookRequest); // Assert response.EnsureSuccessStatusCode(); @@ -168,11 +197,10 @@ public class AddBookEndpointTests : IClassFixture public async Task AddBook_WhenCalledWithEmptyTitle_ShouldReturnUnprocessableEntity() { // Arrange - AddBookRequest bookRequest = _requestBookFixture.Create(); - bookRequest = bookRequest with { Metadata = bookRequest.Metadata! with { Title = null! } }; + AddBookRequest bookRequest = _requestBookFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(includeTitle: false)); // Act - HttpResponseMessage response = await _client.PostAsJsonAsync("/api/v1/books", bookRequest); + HttpResponseMessage response = await PostBookAsync(bookRequest); // Assert await AssertUnprocessableEntityWithValidationErrors(response, Errors.Metadata.TitleCannotBeEmpty.Description); @@ -182,11 +210,10 @@ public class AddBookEndpointTests : IClassFixture public async Task AddBook_WhenCalledWithInvalidLengthTitle_ShouldReturnUnprocessableEntity() { // Arrange - AddBookRequest bookRequest = _requestBookFixture.Create(); - bookRequest = bookRequest with { Metadata = bookRequest.Metadata! with { Title = new Faker().Random.String2(300) } }; + AddBookRequest bookRequest = _requestBookFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(title: new Faker().Random.String2(300))); // Act - HttpResponseMessage response = await _client.PostAsJsonAsync("/api/v1/books", bookRequest); + HttpResponseMessage response = await PostBookAsync(bookRequest); // Assert await AssertUnprocessableEntityWithValidationErrors(response, Errors.Metadata.TitleMustBeMaximum255CharactersLong.Description); @@ -196,8 +223,7 @@ public class AddBookEndpointTests : IClassFixture public async Task AddBook_WhenCalledWithEmptyOriginalTitle_ShouldAddBook() { // Arrange - AddBookRequest bookRequest = _requestBookFixture.Create(); - bookRequest = bookRequest with { Metadata = bookRequest.Metadata! with { OriginalTitle = null! } }; + AddBookRequest bookRequest = _requestBookFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(includeOriginalTitle: false)); // Act & Assert await AssertCreated(bookRequest); @@ -207,11 +233,10 @@ public class AddBookEndpointTests : IClassFixture public async Task AddBook_WhenCalledWithInvalidLengthOriginalTitle_ShouldReturnUnprocessableEntity() { // Arrange - AddBookRequest bookRequest = _requestBookFixture.Create(); - bookRequest = bookRequest with { Metadata = bookRequest.Metadata! with { OriginalTitle = new Faker().Random.String2(300) } }; + AddBookRequest bookRequest = _requestBookFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(originalTitle: new Faker().Random.String2(300))); // Act - HttpResponseMessage response = await _client.PostAsJsonAsync("/api/v1/books", bookRequest); + HttpResponseMessage response = await PostBookAsync(bookRequest); // Assert await AssertUnprocessableEntityWithValidationErrors(response, Errors.Metadata.OriginalTitleMustBeMaximum255CharactersLong.Description); @@ -221,8 +246,7 @@ public class AddBookEndpointTests : IClassFixture public async Task AddBook_WhenCalledWithEmptyDescription_ShouldAddBook() { // Arrange - AddBookRequest bookRequest = _requestBookFixture.Create(); - bookRequest = bookRequest with { Metadata = bookRequest.Metadata! with { Description = null! } }; + AddBookRequest bookRequest = _requestBookFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(includeDescription: false)); // Act & Assert await AssertCreated(bookRequest); @@ -232,11 +256,10 @@ public class AddBookEndpointTests : IClassFixture public async Task AddBook_WhenCalledWithInvalidLengthDescription_ShouldReturnUnprocessableEntity() { // Arrange - AddBookRequest bookRequest = _requestBookFixture.Create(); - bookRequest = bookRequest with { Metadata = bookRequest.Metadata! with { Description = new Faker().Random.String2(2001) } }; + AddBookRequest bookRequest = _requestBookFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(description: new Faker().Random.String2(2001))); // Act - HttpResponseMessage response = await _client.PostAsJsonAsync("/api/v1/books", bookRequest); + HttpResponseMessage response = await PostBookAsync(bookRequest); // Assert await AssertUnprocessableEntityWithValidationErrors(response, Errors.Metadata.DescriptionMustBeMaximum2000CharactersLong.Description); @@ -246,11 +269,10 @@ public class AddBookEndpointTests : IClassFixture public async Task AddBook_WhenCalledWithNullReleaseInfo_ShouldReturnUnprocessableEntity() { // Arrange - AddBookRequest bookRequest = _requestBookFixture.Create(); - bookRequest = bookRequest with { Metadata = bookRequest.Metadata! with { ReleaseInfo = null! } }; + AddBookRequest bookRequest = _requestBookFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(includeReleaseInfo: false)); // Act - HttpResponseMessage response = await _client.PostAsJsonAsync("/api/v1/books", bookRequest); + HttpResponseMessage response = await PostBookAsync(bookRequest); // Assert await AssertUnprocessableEntityWithValidationErrors(response, Errors.Metadata.ReleaseInfoCannotBeNull.Description); @@ -260,8 +282,7 @@ public class AddBookEndpointTests : IClassFixture public async Task AddBook_WhenCalledWithEmptyOriginalReleaseYear_ShouldAddBook() { // Arrange - AddBookRequest bookRequest = _requestBookFixture.Create(); - bookRequest = bookRequest with { Metadata = bookRequest.Metadata! with { ReleaseInfo = bookRequest.Metadata.ReleaseInfo! with { OriginalReleaseYear = null! } } }; + AddBookRequest bookRequest = _requestBookFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(includeOriginalReleaseYear: false))); // Act & Assert await AssertCreated(bookRequest); @@ -271,11 +292,10 @@ public class AddBookEndpointTests : IClassFixture public async Task AddBook_WhenCalledWithInvalidValueOriginalReleaseYear_ShouldReturnUnprocessableEntity() { // Arrange - AddBookRequest bookRequest = _requestBookFixture.Create(); - bookRequest = bookRequest with { Metadata = bookRequest.Metadata! with { ReleaseInfo = bookRequest.Metadata.ReleaseInfo! with { OriginalReleaseYear = 10000 } } }; + AddBookRequest bookRequest = _requestBookFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(originalReleaseYear: 10000))); // Act - HttpResponseMessage response = await _client.PostAsJsonAsync("/api/v1/books", bookRequest); + HttpResponseMessage response = await PostBookAsync(bookRequest); // Assert await AssertUnprocessableEntityWithValidationErrors(response, Errors.Metadata.OriginalReleaseYearMustBeBetween1And9999.Description); @@ -285,8 +305,7 @@ public class AddBookEndpointTests : IClassFixture public async Task AddBook_WhenCalledWithEmptyReReleaseYear_ShouldAddBook() { // Arrange - AddBookRequest bookRequest = _requestBookFixture.Create(); - bookRequest = bookRequest with { Metadata = bookRequest.Metadata! with { ReleaseInfo = bookRequest.Metadata.ReleaseInfo! with { ReReleaseYear = null!, ReReleaseDate = null } } }; + AddBookRequest bookRequest = _requestBookFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(includeReReleaseYear: false, includeReReleaseDate: false))); // Act & Assert await AssertCreated(bookRequest); @@ -296,19 +315,10 @@ public class AddBookEndpointTests : IClassFixture public async Task AddBook_WhenCalledWithInvalidValueReReleaseYear_ShouldReturnUnprocessableEntity() { // Arrange - AddBookRequest bookRequest = _requestBookFixture.Create(); - bookRequest = bookRequest with - { - Metadata = bookRequest.Metadata! with - { - ReleaseInfo = bookRequest.Metadata.ReleaseInfo! - with - { ReReleaseYear = 10000 } - } - }; + AddBookRequest bookRequest = _requestBookFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(reReleaseYear: 10000))); // Act - HttpResponseMessage response = await _client.PostAsJsonAsync("/api/v1/books", bookRequest); + HttpResponseMessage response = await PostBookAsync(bookRequest); // Assert await AssertUnprocessableEntityWithValidationErrors(response, Errors.Metadata.ReReleaseYearMustBeBetween1And9999.Description); @@ -318,8 +328,7 @@ public class AddBookEndpointTests : IClassFixture public async Task AddBook_WhenCalledWithEmptyReleaseCountry_ShouldAddBook() { // Arrange - AddBookRequest bookRequest = _requestBookFixture.Create(); - bookRequest = bookRequest with { Metadata = bookRequest.Metadata! with { ReleaseInfo = bookRequest.Metadata.ReleaseInfo! with { ReleaseCountry = null! } } }; + AddBookRequest bookRequest = _requestBookFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(includeReleaseCountry: false))); // Act & Assert await AssertCreated(bookRequest); @@ -329,17 +338,10 @@ public class AddBookEndpointTests : IClassFixture public async Task AddBook_WhenCalledWithInvalidValueReleaseCountry_ShouldReturnUnprocessableEntity() { // Arrange - AddBookRequest bookRequest = _requestBookFixture.Create(); - bookRequest = bookRequest with - { - Metadata = bookRequest.Metadata! with - { - ReleaseInfo = bookRequest.Metadata.ReleaseInfo! with { ReleaseCountry = "test" } - } - }; + AddBookRequest bookRequest = _requestBookFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(releaseCountry: "test"))); // Act - HttpResponseMessage response = await _client.PostAsJsonAsync("/api/v1/books", bookRequest); + HttpResponseMessage response = await PostBookAsync(bookRequest); // Assert await AssertUnprocessableEntityWithValidationErrors(response, Errors.Metadata.CountryCodeMustBe2CharactersLong.Description); @@ -349,8 +351,7 @@ public class AddBookEndpointTests : IClassFixture public async Task AddBook_WhenCalledWithEmptyReleaseVersion_ShouldAddBook() { // Arrange - AddBookRequest bookRequest = _requestBookFixture.Create(); - bookRequest = bookRequest with { Metadata = bookRequest.Metadata! with { ReleaseInfo = bookRequest.Metadata.ReleaseInfo! with { ReleaseVersion = null! } } }; + AddBookRequest bookRequest = _requestBookFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(includeReleaseVersion: false))); // Act & Assert await AssertCreated(bookRequest); @@ -360,17 +361,10 @@ public class AddBookEndpointTests : IClassFixture public async Task AddBook_WhenCalledWithInvalidValueReleasVersion_ShouldReturnUnprocessableEntity() { // Arrange - AddBookRequest bookRequest = _requestBookFixture.Create(); - bookRequest = bookRequest with - { - Metadata = bookRequest.Metadata! with - { - ReleaseInfo = bookRequest.Metadata.ReleaseInfo! with { ReleaseVersion = new Faker().Random.String2(100) } - } - }; + AddBookRequest bookRequest = _requestBookFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(releaseVersion: new Faker().Random.String2(100)))); // Act - HttpResponseMessage response = await _client.PostAsJsonAsync("/api/v1/books", bookRequest); + HttpResponseMessage response = await PostBookAsync(bookRequest); // Assert await AssertUnprocessableEntityWithValidationErrors(response, Errors.Metadata.ReleaseVersionMustBeMaximum50CharactersLong.Description); @@ -380,16 +374,7 @@ public class AddBookEndpointTests : IClassFixture public async Task AddBook_WhenReReleaseYearIsAfterOriginalReleaseYear_ShouldAddBook() { // Arrange - AddBookRequest bookRequest = _requestBookFixture.Create(); - bookRequest = bookRequest with - { - Metadata = bookRequest.Metadata! with - { - ReleaseInfo = bookRequest.Metadata.ReleaseInfo! - with - { OriginalReleaseYear = 2000, OriginalReleaseDate = new DateOnly(2000, 1, 1), ReReleaseYear = 2001, ReReleaseDate = new DateOnly(2001, 1, 1) } - } - }; + AddBookRequest bookRequest = _requestBookFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(originalReleaseDate: new DateOnly(2000, 1, 1), originalReleaseYear: 2000, reReleaseDate: new DateOnly(2001, 1, 1), reReleaseYear: 2001))); // Act & Assert await AssertCreated(bookRequest); @@ -399,19 +384,10 @@ public class AddBookEndpointTests : IClassFixture public async Task AddBook_WhenReReleaseYearIsBeforeReleaseYear_ShouldReturnUnprocessableEntity() { // Arrange - AddBookRequest bookRequest = _requestBookFixture.Create(); - bookRequest = bookRequest with - { - Metadata = bookRequest.Metadata! with - { - ReleaseInfo = bookRequest.Metadata.ReleaseInfo! - with - { OriginalReleaseYear = 2001, OriginalReleaseDate = new DateOnly(2001, 1, 1), ReReleaseYear = 2000, ReReleaseDate = new DateOnly(2000, 1, 1) } - } - }; + AddBookRequest bookRequest = _requestBookFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(originalReleaseDate: new DateOnly(2001, 1, 1), originalReleaseYear: 2001, reReleaseDate: new DateOnly(2000, 1, 1), reReleaseYear: 2000))); // Act - HttpResponseMessage response = await _client.PostAsJsonAsync("/api/v1/books", bookRequest); + HttpResponseMessage response = await PostBookAsync(bookRequest); // Assert await AssertUnprocessableEntityWithValidationErrors(response, Errors.Metadata.ReReleaseYearCannotBeEarlierThanOriginalReleaseYear.Description); @@ -421,16 +397,7 @@ public class AddBookEndpointTests : IClassFixture public async Task AddBook_WhenReReleaseDateIsAfterOriginalReleaseDate_ShouldAddBook() { // Arrange - AddBookRequest bookRequest = _requestBookFixture.Create(); - bookRequest = bookRequest with - { - Metadata = bookRequest.Metadata! with - { - ReleaseInfo = bookRequest.Metadata.ReleaseInfo! - with - { OriginalReleaseYear = 2000, OriginalReleaseDate = new DateOnly(2000, 1, 1), ReReleaseYear = 2001, ReReleaseDate = new DateOnly(2001, 1, 1) } - } - }; + AddBookRequest bookRequest = _requestBookFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(originalReleaseDate: new DateOnly(2000, 1, 1), originalReleaseYear: 2000, reReleaseDate: new DateOnly(2001, 1, 1), reReleaseYear: 2001))); // Act & Assert await AssertCreated(bookRequest); @@ -440,19 +407,10 @@ public class AddBookEndpointTests : IClassFixture public async Task AddBook_WhenReReleaseDateIsBeforeReleaseDate_ShouldReturnUnprocessableEntity() { // Arrange - AddBookRequest bookRequest = _requestBookFixture.Create(); - bookRequest = bookRequest with - { - Metadata = bookRequest.Metadata! with - { - ReleaseInfo = bookRequest.Metadata.ReleaseInfo! - with - { OriginalReleaseYear = 2001, OriginalReleaseDate = new DateOnly(2001, 1, 1), ReReleaseYear = 2000, ReReleaseDate = new DateOnly(2000, 1, 1) } - } - }; + AddBookRequest bookRequest = _requestBookFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(originalReleaseDate: new DateOnly(2001, 1, 1), originalReleaseYear: 2001, reReleaseDate: new DateOnly(2000, 1, 1), reReleaseYear: 2000))); // Act - HttpResponseMessage response = await _client.PostAsJsonAsync("/api/v1/books", bookRequest); + HttpResponseMessage response = await PostBookAsync(bookRequest); // Assert await AssertUnprocessableEntityWithValidationErrors(response, Errors.Metadata.ReReleaseDateCannotBeEarlierThanOriginalReleaseDate.Description); @@ -462,11 +420,10 @@ public class AddBookEndpointTests : IClassFixture public async Task AddBook_WhenCalledWithNullGenres_ShouldReturnUnprocessableEntity() { // Arrange - AddBookRequest bookRequest = _requestBookFixture.Create(); - bookRequest = bookRequest with { Metadata = bookRequest.Metadata! with { Genres = null! } }; + AddBookRequest bookRequest = _requestBookFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(includeGenres: false)); // Act - HttpResponseMessage response = await _client.PostAsJsonAsync("/api/v1/books", bookRequest); + HttpResponseMessage response = await PostBookAsync(bookRequest); // Assert await AssertUnprocessableEntityWithValidationErrors(response, Errors.Metadata.GenresListCannotBeNull.Description); @@ -476,17 +433,10 @@ public class AddBookEndpointTests : IClassFixture public async Task AddBook_WhenCalledWithEmptyGenreName_ShouldReturnUnprocessableEntity() { // Arrange - AddBookRequest bookRequest = _requestBookFixture.Create(); - bookRequest = bookRequest with - { - Metadata = bookRequest.Metadata! with - { - Genres = [.. bookRequest.Metadata.Genres!.Select((genre, index) => index == 0 ? genre with { Name = null } : genre)] - } - }; + AddBookRequest bookRequest = _requestBookFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(genres: [_genreDtoFixture.Create(includeName: false)])); // Act - HttpResponseMessage response = await _client.PostAsJsonAsync("/api/v1/books", bookRequest); + HttpResponseMessage response = await PostBookAsync(bookRequest); // Assert await AssertUnprocessableEntityWithValidationErrors(response, Errors.Metadata.GenreNameCannotBeEmpty.Description); @@ -496,16 +446,9 @@ public class AddBookEndpointTests : IClassFixture public async Task AddBook_WhenCalledWithInvalidLengthGenreName_ShouldReturnUnprocessableEntity() { // Arrange - AddBookRequest bookRequest = _requestBookFixture.Create(); - bookRequest = bookRequest with - { - Metadata = bookRequest.Metadata! with - { - Genres = [.. bookRequest.Metadata.Genres!.Select((genre, index) => index == 0 ? genre with { Name = new Faker().Random.String2(100) } : genre)] - } - }; + AddBookRequest bookRequest = _requestBookFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(genres: [_genreDtoFixture.Create(name: new Faker().Random.String2(100))])); // Act - HttpResponseMessage response = await _client.PostAsJsonAsync("/api/v1/books", bookRequest); + HttpResponseMessage response = await PostBookAsync(bookRequest); // Assert await AssertUnprocessableEntityWithValidationErrors(response, Errors.Metadata.GenreNameMustBeMaximum50CharactersLong.Description); @@ -515,11 +458,10 @@ public class AddBookEndpointTests : IClassFixture public async Task AddBook_WhenCalledWithNullTags_ShouldReturnUnprocessableEntity() { // Arrange - AddBookRequest bookRequest = _requestBookFixture.Create(); - bookRequest = bookRequest with { Metadata = bookRequest.Metadata! with { Tags = null! } }; + AddBookRequest bookRequest = _requestBookFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(includeTags: false)); // Act - HttpResponseMessage response = await _client.PostAsJsonAsync("/api/v1/books", bookRequest); + HttpResponseMessage response = await PostBookAsync(bookRequest); // Assert await AssertUnprocessableEntityWithValidationErrors(response, Errors.Metadata.TagsListCannotBeNull.Description); @@ -529,17 +471,10 @@ public class AddBookEndpointTests : IClassFixture public async Task AddBook_WhenCalledWithEmptyTagName_ShouldReturnUnprocessableEntity() { // Arrange - AddBookRequest bookRequest = _requestBookFixture.Create(); - bookRequest = bookRequest with - { - Metadata = bookRequest.Metadata! with - { - Tags = [.. bookRequest.Metadata.Tags!.Select((tag, index) => index == 0 ? tag with { Name = null } : tag)] - } - }; + AddBookRequest bookRequest = _requestBookFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(tags: [_tagDtoFixture.Create(includeName: false)])); // Act - HttpResponseMessage response = await _client.PostAsJsonAsync("/api/v1/books", bookRequest); + HttpResponseMessage response = await PostBookAsync(bookRequest); // Assert await AssertUnprocessableEntityWithValidationErrors(response, Errors.Metadata.TagNameCannotBeEmpty.Description); @@ -549,16 +484,9 @@ public class AddBookEndpointTests : IClassFixture public async Task AddBook_WhenCalledWithInvalidLengthTagName_ShouldReturnUnprocessableEntity() { // Arrange - AddBookRequest bookRequest = _requestBookFixture.Create(); - bookRequest = bookRequest with - { - Metadata = bookRequest.Metadata! with - { - Tags = [.. bookRequest.Metadata.Tags!.Select((tag, index) => index == 0 ? tag with { Name = new Faker().Random.String2(100) } : tag)] - } - }; + AddBookRequest bookRequest = _requestBookFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(tags: [_tagDtoFixture.Create(name: new Faker().Random.String2(100))])); // Act - HttpResponseMessage response = await _client.PostAsJsonAsync("/api/v1/books", bookRequest); + HttpResponseMessage response = await PostBookAsync(bookRequest); // Assert await AssertUnprocessableEntityWithValidationErrors(response, Errors.Metadata.TagNameMustBeMaximum50CharactersLong.Description); @@ -568,8 +496,7 @@ public class AddBookEndpointTests : IClassFixture public async Task AddBook_WhenCalledWithEmptyLanguage_ShouldAddBook() { // Arrange - AddBookRequest bookRequest = _requestBookFixture.Create(); - bookRequest = bookRequest with { Metadata = bookRequest.Metadata! with { Language = null! } }; + AddBookRequest bookRequest = _requestBookFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(includeLanguage: false)); // Act & Assert await AssertCreated(bookRequest); @@ -579,11 +506,10 @@ public class AddBookEndpointTests : IClassFixture public async Task AddBook_WhenCalledWithEmptyLanguageCode_ShouldReturnUnprocessableEntity() { // Arrange - AddBookRequest bookRequest = _requestBookFixture.Create(); - bookRequest = bookRequest with { Metadata = bookRequest.Metadata! with { Language = bookRequest.Metadata.Language! with { LanguageCode = null } } }; + AddBookRequest bookRequest = _requestBookFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(language: _languageInfoDtoFixture.Create(includeLanguageCode: false))); // Act - HttpResponseMessage response = await _client.PostAsJsonAsync("/api/v1/books", bookRequest); + HttpResponseMessage response = await PostBookAsync(bookRequest); // Assert await AssertUnprocessableEntityWithValidationErrors(response, Errors.Metadata.LanguageCodeCannotBeEmpty.Description); @@ -593,20 +519,10 @@ public class AddBookEndpointTests : IClassFixture public async Task AddBook_WhenCalledWithInvalidLengthLanguageCode_ShouldReturnUnprocessableEntity() { // Arrange - AddBookRequest bookRequest = _requestBookFixture.Create(); - bookRequest = bookRequest with - { - Metadata = bookRequest.Metadata! with - { - Language = bookRequest.Metadata.Language! with - { - LanguageCode = new Faker().Random.String2(10) - } - } - }; + AddBookRequest bookRequest = _requestBookFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(language: _languageInfoDtoFixture.Create(languageCode: new Faker().Random.String2(10)))); // Act - HttpResponseMessage response = await _client.PostAsJsonAsync("/api/v1/books", bookRequest); + HttpResponseMessage response = await PostBookAsync(bookRequest); // Assert await AssertUnprocessableEntityWithValidationErrors(response, Errors.Metadata.LanguageCodeMustBe2CharactersLong.Description); @@ -616,11 +532,10 @@ public class AddBookEndpointTests : IClassFixture public async Task AddBook_WhenCalledWithEmptyLanguageName_ShouldReturnUnprocessableEntity() { // Arrange - AddBookRequest bookRequest = _requestBookFixture.Create(); - bookRequest = bookRequest with { Metadata = bookRequest.Metadata! with { Language = bookRequest.Metadata.Language! with { LanguageName = null } } }; + AddBookRequest bookRequest = _requestBookFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(language: _languageInfoDtoFixture.Create(includeLanguageName: false))); // Act - HttpResponseMessage response = await _client.PostAsJsonAsync("/api/v1/books", bookRequest); + HttpResponseMessage response = await PostBookAsync(bookRequest); // Assert await AssertUnprocessableEntityWithValidationErrors(response, Errors.Metadata.LanguageNameCannotBeEmpty.Description); @@ -630,20 +545,10 @@ public class AddBookEndpointTests : IClassFixture public async Task AddBook_WhenCalledWithInvalidLengthLanguageName_ShouldReturnUnprocessableEntity() { // Arrange - AddBookRequest bookRequest = _requestBookFixture.Create(); - bookRequest = bookRequest with - { - Metadata = bookRequest.Metadata! with - { - Language = bookRequest.Metadata.Language! with - { - LanguageName = new Faker().Random.String2(100) - } - } - }; + AddBookRequest bookRequest = _requestBookFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(language: _languageInfoDtoFixture.Create(languageName: new Faker().Random.String2(100)))); // Act - HttpResponseMessage response = await _client.PostAsJsonAsync("/api/v1/books", bookRequest); + HttpResponseMessage response = await PostBookAsync(bookRequest); // Assert await AssertUnprocessableEntityWithValidationErrors(response, Errors.Metadata.LanguageNameMustBeMaximum50CharactersLong.Description); @@ -653,8 +558,7 @@ public class AddBookEndpointTests : IClassFixture public async Task AddBook_WhenCalledWithEmptyLanguageNativeName_ShouldAddBook() { // Arrange - AddBookRequest bookRequest = _requestBookFixture.Create(); - bookRequest = bookRequest with { Metadata = bookRequest.Metadata! with { Language = bookRequest.Metadata.Language! with { NativeName = null } } }; + AddBookRequest bookRequest = _requestBookFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(language: _languageInfoDtoFixture.Create(includeNativeName: false))); // Act & Assert await AssertCreated(bookRequest); @@ -664,20 +568,10 @@ public class AddBookEndpointTests : IClassFixture public async Task AddBook_WhenCalledWithInvalidLengthNativeLanguageName_ShouldReturnUnprocessableEntity() { // Arrange - AddBookRequest bookRequest = _requestBookFixture.Create(); - bookRequest = bookRequest with - { - Metadata = bookRequest.Metadata! with - { - Language = bookRequest.Metadata.Language! with - { - NativeName = new Faker().Random.String2(100) - } - } - }; + AddBookRequest bookRequest = _requestBookFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(language: _languageInfoDtoFixture.Create(nativeName: new Faker().Random.String2(100)))); // Act - HttpResponseMessage response = await _client.PostAsJsonAsync("/api/v1/books", bookRequest); + HttpResponseMessage response = await PostBookAsync(bookRequest); // Assert await AssertUnprocessableEntityWithValidationErrors(response, Errors.Metadata.LanguageNativeNameMustBeMaximum50CharactersLong.Description); @@ -687,8 +581,7 @@ public class AddBookEndpointTests : IClassFixture public async Task AddBook_WhenCalledWithEmptyOriginalLanguage_ShouldAddBook() { // Arrange - AddBookRequest bookRequest = _requestBookFixture.Create(); - bookRequest = bookRequest with { Metadata = bookRequest.Metadata! with { OriginalLanguage = null! } }; + AddBookRequest bookRequest = _requestBookFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(includeOriginalLanguage: false)); // Act & Assert await AssertCreated(bookRequest); @@ -698,11 +591,10 @@ public class AddBookEndpointTests : IClassFixture public async Task AddBook_WhenCalledWithEmptyOriginalLanguageCode_ShouldReturnUnprocessableEntity() { // Arrange - AddBookRequest bookRequest = _requestBookFixture.Create(); - bookRequest = bookRequest with { Metadata = bookRequest.Metadata! with { OriginalLanguage = bookRequest.Metadata.Language! with { LanguageCode = null } } }; + AddBookRequest bookRequest = _requestBookFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(originalLanguage: _languageInfoDtoFixture.Create(includeLanguageCode: false))); // Act - HttpResponseMessage response = await _client.PostAsJsonAsync("/api/v1/books", bookRequest); + HttpResponseMessage response = await PostBookAsync(bookRequest); // Assert await AssertUnprocessableEntityWithValidationErrors(response, Errors.Metadata.LanguageCodeCannotBeEmpty.Description); @@ -712,20 +604,10 @@ public class AddBookEndpointTests : IClassFixture public async Task AddBook_WhenCalledWithInvalidLengthOriginalLanguageCode_ShouldReturnUnprocessableEntity() { // Arrange - AddBookRequest bookRequest = _requestBookFixture.Create(); - bookRequest = bookRequest with - { - Metadata = bookRequest.Metadata! with - { - OriginalLanguage = bookRequest.Metadata.Language! with - { - LanguageCode = new Faker().Random.String2(10) - } - } - }; + AddBookRequest bookRequest = _requestBookFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(originalLanguage: _languageInfoDtoFixture.Create(languageCode: new Faker().Random.String2(10)))); // Act - HttpResponseMessage response = await _client.PostAsJsonAsync("/api/v1/books", bookRequest); + HttpResponseMessage response = await PostBookAsync(bookRequest); // Assert await AssertUnprocessableEntityWithValidationErrors(response, Errors.Metadata.LanguageCodeMustBe2CharactersLong.Description); @@ -735,11 +617,10 @@ public class AddBookEndpointTests : IClassFixture public async Task AddBook_WhenCalledWithEmptyOriginalLanguageName_ShouldReturnUnprocessableEntity() { // Arrange - AddBookRequest bookRequest = _requestBookFixture.Create(); - bookRequest = bookRequest with { Metadata = bookRequest.Metadata! with { OriginalLanguage = bookRequest.Metadata.Language! with { LanguageName = null } } }; + AddBookRequest bookRequest = _requestBookFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(originalLanguage: _languageInfoDtoFixture.Create(includeLanguageName: false))); // Act - HttpResponseMessage response = await _client.PostAsJsonAsync("/api/v1/books", bookRequest); + HttpResponseMessage response = await PostBookAsync(bookRequest); // Assert await AssertUnprocessableEntityWithValidationErrors(response, Errors.Metadata.LanguageNameCannotBeEmpty.Description); @@ -749,20 +630,10 @@ public class AddBookEndpointTests : IClassFixture public async Task AddBook_WhenCalledWithInvalidLengthOriginalLanguageName_ShouldReturnUnprocessableEntity() { // Arrange - AddBookRequest bookRequest = _requestBookFixture.Create(); - bookRequest = bookRequest with - { - Metadata = bookRequest.Metadata! with - { - OriginalLanguage = bookRequest.Metadata.Language! with - { - LanguageName = new Faker().Random.String2(100) - } - } - }; + AddBookRequest bookRequest = _requestBookFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(originalLanguage: _languageInfoDtoFixture.Create(languageName: new Faker().Random.String2(100)))); // Act - HttpResponseMessage response = await _client.PostAsJsonAsync("/api/v1/books", bookRequest); + HttpResponseMessage response = await PostBookAsync(bookRequest); // Assert await AssertUnprocessableEntityWithValidationErrors(response, Errors.Metadata.LanguageNameMustBeMaximum50CharactersLong.Description); @@ -772,20 +643,10 @@ public class AddBookEndpointTests : IClassFixture public async Task AddBook_WhenCalledWithInvalidLengthOriginalNativeLanguageName_ShouldReturnUnprocessableEntity() { // Arrange - AddBookRequest bookRequest = _requestBookFixture.Create(); - bookRequest = bookRequest with - { - Metadata = bookRequest.Metadata! with - { - OriginalLanguage = bookRequest.Metadata.Language! with - { - NativeName = new Faker().Random.String2(100) - } - } - }; + AddBookRequest bookRequest = _requestBookFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(originalLanguage: _languageInfoDtoFixture.Create(nativeName: new Faker().Random.String2(100)))); // Act - HttpResponseMessage response = await _client.PostAsJsonAsync("/api/v1/books", bookRequest); + HttpResponseMessage response = await PostBookAsync(bookRequest); // Assert await AssertUnprocessableEntityWithValidationErrors(response, Errors.Metadata.LanguageNativeNameMustBeMaximum50CharactersLong.Description); @@ -795,8 +656,7 @@ public class AddBookEndpointTests : IClassFixture public async Task AddBook_WhenCalledWithEmptyOriginalLanguageNativeName_ShouldAddBook() { // Arrange - AddBookRequest bookRequest = _requestBookFixture.Create(); - bookRequest = bookRequest with { Metadata = bookRequest.Metadata! with { OriginalLanguage = bookRequest.Metadata.Language! with { NativeName = null } } }; + AddBookRequest bookRequest = _requestBookFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(originalLanguage: _languageInfoDtoFixture.Create(includeNativeName: false))); // Act & Assert await AssertCreated(bookRequest); @@ -806,8 +666,7 @@ public class AddBookEndpointTests : IClassFixture public async Task AddBook_WhenCalledWithEmptyPublisher_ShouldAddBook() { // Arrange - AddBookRequest bookRequest = _requestBookFixture.Create(); - bookRequest = bookRequest with { Metadata = bookRequest.Metadata! with { Publisher = null } }; + AddBookRequest bookRequest = _requestBookFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(includePublisher: false)); // Act & Assert await AssertCreated(bookRequest); @@ -817,11 +676,10 @@ public class AddBookEndpointTests : IClassFixture public async Task AddBook_WhenCalledWithInvalidLengthPublisher_ShouldReturnUnprocessableEntity() { // Arrange - AddBookRequest bookRequest = _requestBookFixture.Create(); - bookRequest = bookRequest with { Metadata = bookRequest.Metadata! with { Publisher = new Faker().Random.String2(150) } }; + AddBookRequest bookRequest = _requestBookFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(publisher: new Faker().Random.String2(150))); // Act - HttpResponseMessage response = await _client.PostAsJsonAsync("/api/v1/books", bookRequest); + HttpResponseMessage response = await PostBookAsync(bookRequest); // Assert await AssertUnprocessableEntityWithValidationErrors(response, Errors.WrittenContent.PublisherMustBeMaximum100CharactersLong.Description); @@ -831,8 +689,7 @@ public class AddBookEndpointTests : IClassFixture public async Task AddBook_WhenCalledWithEmptyPageCount_ShouldAddBook() { // Arrange - AddBookRequest bookRequest = _requestBookFixture.Create(); - bookRequest = bookRequest with { Metadata = bookRequest.Metadata! with { PageCount = null } }; + AddBookRequest bookRequest = _requestBookFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(includePageCount: false)); // Act & Assert await AssertCreated(bookRequest); @@ -842,11 +699,10 @@ public class AddBookEndpointTests : IClassFixture public async Task AddBook_WhenCalledWithNegativePageCount_ShouldReturnUnprocessableEntity() { // Arrange - AddBookRequest bookRequest = _requestBookFixture.Create(); - bookRequest = bookRequest with { Metadata = bookRequest.Metadata! with { PageCount = -1 } }; + AddBookRequest bookRequest = _requestBookFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(pageCount: -1)); // Act - HttpResponseMessage response = await _client.PostAsJsonAsync("/api/v1/books", bookRequest); + HttpResponseMessage response = await PostBookAsync(bookRequest); // Assert await AssertUnprocessableEntityWithValidationErrors(response, Errors.WrittenContent.PageCountMustBeGreaterThanZero.Description); @@ -856,8 +712,7 @@ public class AddBookEndpointTests : IClassFixture public async Task AddBook_WhenCalledWithEmptyFormat_ShouldAddBook() { // Arrange - AddBookRequest bookRequest = _requestBookFixture.Create(); - bookRequest = bookRequest with { Format = null }; + AddBookRequest bookRequest = _requestBookFixture.Create(isbns: [], contributors: [], ratings: [], includeOptionalProperties: false); // Act & Assert await AssertCreated(bookRequest); @@ -867,11 +722,10 @@ public class AddBookEndpointTests : IClassFixture public async Task AddBook_WhenCalledWithInvalidFormat_ShouldReturnUnprocessableEntity() { // Arrange - AddBookRequest bookRequest = _requestBookFixture.Create(); - bookRequest = bookRequest with { Format = (BookFormat)99 }; + AddBookRequest bookRequest = _requestBookFixture.Create(format: (BookFormat)99); // Act - HttpResponseMessage response = await _client.PostAsJsonAsync("/api/v1/books", bookRequest); + HttpResponseMessage response = await PostBookAsync(bookRequest); // Assert await AssertUnprocessableEntityWithValidationErrors(response, Errors.WrittenContent.UnknownBookFormat.Description); @@ -881,8 +735,7 @@ public class AddBookEndpointTests : IClassFixture public async Task AddBook_WhenCalledWithEmptyEdition_ShouldAddBook() { // Arrange - AddBookRequest bookRequest = _requestBookFixture.Create(); - bookRequest = bookRequest with { Edition = null }; + AddBookRequest bookRequest = _requestBookFixture.Create(isbns: [], contributors: [], ratings: [], includeOptionalProperties: false); // Act & Assert await AssertCreated(bookRequest); @@ -892,11 +745,10 @@ public class AddBookEndpointTests : IClassFixture public async Task AddBook_WhenCalledWithInvalidLengthEdition_ShouldReturnUnprocessableEntity() { // Arrange - AddBookRequest bookRequest = _requestBookFixture.Create(); - bookRequest = bookRequest with { Edition = new Faker().Random.String2(100) }; + AddBookRequest bookRequest = _requestBookFixture.Create(edition: new Faker().Random.String2(100)); // Act - HttpResponseMessage response = await _client.PostAsJsonAsync("/api/v1/books", bookRequest); + HttpResponseMessage response = await PostBookAsync(bookRequest); // Assert await AssertUnprocessableEntityWithValidationErrors(response, Errors.WrittenContent.EditionMustBeMaximum50CharactersLong.Description); @@ -906,8 +758,7 @@ public class AddBookEndpointTests : IClassFixture public async Task AddBook_WhenCalledWithEmptyVolumeNumber_ShouldAddBook() { // Arrange - AddBookRequest bookRequest = _requestBookFixture.Create(); - bookRequest = bookRequest with { VolumeNumber = null }; + AddBookRequest bookRequest = _requestBookFixture.Create(isbns: [], contributors: [], ratings: [], includeOptionalProperties: false); // Act & Assert await AssertCreated(bookRequest); @@ -917,11 +768,10 @@ public class AddBookEndpointTests : IClassFixture public async Task AddBook_WhenCalledWithNegativeVolumeNumber_ShouldReturnUnprocessableEntity() { // Arrange - AddBookRequest bookRequest = _requestBookFixture.Create(); - bookRequest = bookRequest with { VolumeNumber = -1 }; + AddBookRequest bookRequest = _requestBookFixture.Create(volumeNumber: -1); // Act - HttpResponseMessage response = await _client.PostAsJsonAsync("/api/v1/books", bookRequest); + HttpResponseMessage response = await PostBookAsync(bookRequest); // Assert await AssertUnprocessableEntityWithValidationErrors(response, Errors.WrittenContent.VolumeNumberMustBeGreaterThanZero.Description); @@ -932,7 +782,6 @@ public class AddBookEndpointTests : IClassFixture { // Arrange AddBookRequest bookRequest = _requestBookFixture.Create(); - bookRequest = bookRequest with { Series = null }; // Act & Assert await AssertCreated(bookRequest); @@ -973,8 +822,7 @@ public class AddBookEndpointTests : IClassFixture public async Task AddBook_WhenCalledWithEmptyAsin_ShouldAddBook() { // Arrange - AddBookRequest bookRequest = _requestBookFixture.Create(); - bookRequest = bookRequest with { ASIN = null }; + AddBookRequest bookRequest = _requestBookFixture.Create(isbns: [], contributors: [], ratings: [], includeOptionalProperties: false); // Act & Assert await AssertCreated(bookRequest); @@ -984,11 +832,10 @@ public class AddBookEndpointTests : IClassFixture public async Task AddBook_WhenCalledWithInvalidLengthAsin_ShouldReturnUnprocessableEntity() { // Arrange - AddBookRequest bookRequest = _requestBookFixture.Create(); - bookRequest = bookRequest with { ASIN = new Faker().Random.String2(15) }; + AddBookRequest bookRequest = _requestBookFixture.Create(asin: new Faker().Random.String2(15)); // Act - HttpResponseMessage response = await _client.PostAsJsonAsync("/api/v1/books", bookRequest); + HttpResponseMessage response = await PostBookAsync(bookRequest); // Assert await AssertUnprocessableEntityWithValidationErrors(response, Errors.WrittenContent.AsinMustBe10CharactersLong.Description); @@ -998,8 +845,7 @@ public class AddBookEndpointTests : IClassFixture public async Task AddBook_WhenCalledWithEmptyGoodreadsId_ShouldAddBook() { // Arrange - AddBookRequest bookRequest = _requestBookFixture.Create(); - bookRequest = bookRequest with { GoodreadsId = null }; + AddBookRequest bookRequest = _requestBookFixture.Create(isbns: [], contributors: [], ratings: [], includeOptionalProperties: false); // Act & Assert await AssertCreated(bookRequest); @@ -1009,11 +855,10 @@ public class AddBookEndpointTests : IClassFixture public async Task AddBook_WhenCalledWithInvalidGoodreadsId_ShouldReturnUnprocessableEntity() { // Arrange - AddBookRequest bookRequest = _requestBookFixture.Create(); - bookRequest = bookRequest with { GoodreadsId = new Faker().Random.String2(2) }; + AddBookRequest bookRequest = _requestBookFixture.Create(goodreadsId: new Faker().Random.String2(2)); // Act - HttpResponseMessage response = await _client.PostAsJsonAsync("/api/v1/books", bookRequest); + HttpResponseMessage response = await PostBookAsync(bookRequest); // Assert await AssertUnprocessableEntityWithValidationErrors(response, Errors.WrittenContent.GoodreadsIdMustBeNumeric.Description); @@ -1023,8 +868,7 @@ public class AddBookEndpointTests : IClassFixture public async Task AddBook_WhenCalledWithEmptyLccn_ShouldAddBook() { // Arrange - AddBookRequest bookRequest = _requestBookFixture.Create(); - bookRequest = bookRequest with { LCCN = null }; + AddBookRequest bookRequest = _requestBookFixture.Create(isbns: [], contributors: [], ratings: [], includeOptionalProperties: false); // Act & Assert await AssertCreated(bookRequest); @@ -1034,11 +878,10 @@ public class AddBookEndpointTests : IClassFixture public async Task AddBook_WhenCalledWithInvalidLccn_ShouldReturnUnprocessableEntity() { // Arrange - AddBookRequest bookRequest = _requestBookFixture.Create(); - bookRequest = bookRequest with { LCCN = new Faker().Random.String2(200) }; + AddBookRequest bookRequest = _requestBookFixture.Create(lccn: new Faker().Random.String2(200)); // Act - HttpResponseMessage response = await _client.PostAsJsonAsync("/api/v1/books", bookRequest); + HttpResponseMessage response = await PostBookAsync(bookRequest); // Assert await AssertUnprocessableEntityWithValidationErrors(response, Errors.WrittenContent.InvalidLccnFormat.Description); @@ -1048,8 +891,7 @@ public class AddBookEndpointTests : IClassFixture public async Task AddBook_WhenCalledWithEmptyOclcNumber_ShouldAddBook() { // Arrange - AddBookRequest bookRequest = _requestBookFixture.Create(); - bookRequest = bookRequest with { OCLCNumber = null }; + AddBookRequest bookRequest = _requestBookFixture.Create(isbns: [], contributors: [], ratings: [], includeOptionalProperties: false); // Act & Assert await AssertCreated(bookRequest); @@ -1059,11 +901,10 @@ public class AddBookEndpointTests : IClassFixture public async Task AddBook_WhenCalledWithInvalidOclcNumber_ShouldReturnUnprocessableEntity() { // Arrange - AddBookRequest bookRequest = _requestBookFixture.Create(); - bookRequest = bookRequest with { OCLCNumber = new Faker().Random.String2(200) }; + AddBookRequest bookRequest = _requestBookFixture.Create(oclcNumber: new Faker().Random.String2(200)); // Act - HttpResponseMessage response = await _client.PostAsJsonAsync("/api/v1/books", bookRequest); + HttpResponseMessage response = await PostBookAsync(bookRequest); // Assert await AssertUnprocessableEntityWithValidationErrors(response, Errors.WrittenContent.InvalidOclcFormat.Description); @@ -1073,8 +914,7 @@ public class AddBookEndpointTests : IClassFixture public async Task AddBook_WhenCalledWithEmptyOpenLibraryId_ShouldAddBook() { // Arrange - AddBookRequest bookRequest = _requestBookFixture.Create(); - bookRequest = bookRequest with { OpenLibraryId = null }; + AddBookRequest bookRequest = _requestBookFixture.Create(isbns: [], contributors: [], ratings: [], includeOptionalProperties: false); // Act & Assert await AssertCreated(bookRequest); @@ -1084,11 +924,10 @@ public class AddBookEndpointTests : IClassFixture public async Task AddBook_WhenCalledWithInvalidOpenLibraryId_ShouldReturnUnprocessableEntity() { // Arrange - AddBookRequest bookRequest = _requestBookFixture.Create(); - bookRequest = bookRequest with { OpenLibraryId = new Faker().Random.String2(200) }; + AddBookRequest bookRequest = _requestBookFixture.Create(openLibraryId: new Faker().Random.String2(200)); // Act - HttpResponseMessage response = await _client.PostAsJsonAsync("/api/v1/books", bookRequest); + HttpResponseMessage response = await PostBookAsync(bookRequest); // Assert await AssertUnprocessableEntityWithValidationErrors(response, Errors.WrittenContent.InvalidOpenLibraryId.Description); @@ -1098,8 +937,7 @@ public class AddBookEndpointTests : IClassFixture public async Task AddBook_WhenCalledWithEmptyLibraryThingId_ShouldAddBook() { // Arrange - AddBookRequest bookRequest = _requestBookFixture.Create(); - bookRequest = bookRequest with { LibraryThingId = null }; + AddBookRequest bookRequest = _requestBookFixture.Create(isbns: [], contributors: [], ratings: [], includeOptionalProperties: false); // Act & Assert await AssertCreated(bookRequest); @@ -1109,11 +947,10 @@ public class AddBookEndpointTests : IClassFixture public async Task AddBook_WhenCalledWithInvalidLengthLibraryThingId_ShouldReturnUnprocessableEntity() { // Arrange - AddBookRequest bookRequest = _requestBookFixture.Create(); - bookRequest = bookRequest with { LibraryThingId = new Faker().Random.String2(200) }; + AddBookRequest bookRequest = _requestBookFixture.Create(libraryThingId: new Faker().Random.String2(200)); // Act - HttpResponseMessage response = await _client.PostAsJsonAsync("/api/v1/books", bookRequest); + HttpResponseMessage response = await PostBookAsync(bookRequest); // Assert await AssertUnprocessableEntityWithValidationErrors(response, Errors.WrittenContent.LibraryThingIdMustBeMaximum50CharactersLong.Description); @@ -1123,8 +960,7 @@ public class AddBookEndpointTests : IClassFixture public async Task AddBook_WhenCalledWithEmptyGoogleBooksId_ShouldAddBook() { // Arrange - AddBookRequest bookRequest = _requestBookFixture.Create(); - bookRequest = bookRequest with { GoogleBooksId = null }; + AddBookRequest bookRequest = _requestBookFixture.Create(isbns: [], contributors: [], ratings: [], includeOptionalProperties: false); // Act & Assert await AssertCreated(bookRequest); @@ -1134,11 +970,10 @@ public class AddBookEndpointTests : IClassFixture public async Task AddBook_WhenCalledWithInvalidLengthGoogleBooksId_ShouldReturnUnprocessableEntity() { // Arrange - AddBookRequest bookRequest = _requestBookFixture.Create(); - bookRequest = bookRequest with { GoogleBooksId = new Faker().Random.String2(20) }; + AddBookRequest bookRequest = _requestBookFixture.Create(googleBooksId: new Faker().Random.String2(20)); // Act - HttpResponseMessage response = await _client.PostAsJsonAsync("/api/v1/books", bookRequest); + HttpResponseMessage response = await PostBookAsync(bookRequest); // Assert await AssertUnprocessableEntityWithValidationErrors(response, Errors.WrittenContent.GoogleBooksIdMustBe12CharactersLong.Description); @@ -1148,11 +983,10 @@ public class AddBookEndpointTests : IClassFixture public async Task AddBook_WhenCalledWithInvalidGoogleBooksId_ShouldReturnUnprocessableEntity() { // Arrange - AddBookRequest bookRequest = _requestBookFixture.Create(); - bookRequest = bookRequest with { GoogleBooksId = new Faker().Random.String2(11) + " " }; + AddBookRequest bookRequest = _requestBookFixture.Create(googleBooksId: new Faker().Random.String2(11) + " "); // Act - HttpResponseMessage response = await _client.PostAsJsonAsync("/api/v1/books", bookRequest); + HttpResponseMessage response = await PostBookAsync(bookRequest); // Assert await AssertUnprocessableEntityWithValidationErrors(response, Errors.WrittenContent.InvalidGoogleBooksIdFormat.Description); @@ -1162,8 +996,7 @@ public class AddBookEndpointTests : IClassFixture public async Task AddBook_WhenCalledWithEmptyBarnesAndNobleId_ShouldAddBook() { // Arrange - AddBookRequest bookRequest = _requestBookFixture.Create(); - bookRequest = bookRequest with { BarnesAndNobleId = null }; + AddBookRequest bookRequest = _requestBookFixture.Create(isbns: [], contributors: [], ratings: [], includeOptionalProperties: false); // Act & Assert await AssertCreated(bookRequest); @@ -1173,11 +1006,10 @@ public class AddBookEndpointTests : IClassFixture public async Task AddBook_WhenCalledWithInvalidLengthBarnesAndNobleId_ShouldReturnUnprocessableEntity() { // Arrange - AddBookRequest bookRequest = _requestBookFixture.Create(); - bookRequest = bookRequest with { BarnesAndNobleId = new Faker().Random.String2(20) }; + AddBookRequest bookRequest = _requestBookFixture.Create(barnesAndNobleId: new Faker().Random.String2(20)); // Act - HttpResponseMessage response = await _client.PostAsJsonAsync("/api/v1/books", bookRequest); + HttpResponseMessage response = await PostBookAsync(bookRequest); // Assert await AssertUnprocessableEntityWithValidationErrors(response, Errors.WrittenContent.BarnesAndNoblesIdMustBe10CharactersLong.Description); @@ -1187,11 +1019,10 @@ public class AddBookEndpointTests : IClassFixture public async Task AddBook_WhenCalledWithInvalidBarnesAndNobleId_ShouldReturnUnprocessableEntity() { // Arrange - AddBookRequest bookRequest = _requestBookFixture.Create(); - bookRequest = bookRequest with { BarnesAndNobleId = new Faker().Random.String2(10) }; + AddBookRequest bookRequest = _requestBookFixture.Create(barnesAndNobleId: new Faker().Random.String2(10)); // Act - HttpResponseMessage response = await _client.PostAsJsonAsync("/api/v1/books", bookRequest); + HttpResponseMessage response = await PostBookAsync(bookRequest); // Assert await AssertUnprocessableEntityWithValidationErrors(response, Errors.WrittenContent.InvalidBarnesAndNoblesIdFormat.Description); @@ -1201,8 +1032,7 @@ public class AddBookEndpointTests : IClassFixture public async Task AddBook_WhenCalledWithEmptyAppleBooksId_ShouldAddBook() { // Arrange - AddBookRequest bookRequest = _requestBookFixture.Create(); - bookRequest = bookRequest with { AppleBooksId = null }; + AddBookRequest bookRequest = _requestBookFixture.Create(isbns: [], contributors: [], ratings: [], includeOptionalProperties: false); // Act & Assert await AssertCreated(bookRequest); @@ -1212,11 +1042,10 @@ public class AddBookEndpointTests : IClassFixture public async Task AddBook_WhenCalledWithInvalidAppleBooksId_ShouldReturnUnprocessableEntity() { // Arrange - AddBookRequest bookRequest = _requestBookFixture.Create(); - bookRequest = bookRequest with { AppleBooksId = new Faker().Random.String2(10) }; + AddBookRequest bookRequest = _requestBookFixture.Create(appleBooksId: new Faker().Random.String2(10)); // Act - HttpResponseMessage response = await _client.PostAsJsonAsync("/api/v1/books", bookRequest); + HttpResponseMessage response = await PostBookAsync(bookRequest); // Assert await AssertUnprocessableEntityWithValidationErrors(response, Errors.WrittenContent.InvalidAppleBooksIdFormat.Description); @@ -1226,11 +1055,10 @@ public class AddBookEndpointTests : IClassFixture public async Task AddBook_WhenCalledWithNullIsbns_ShouldReturnUnprocessableEntity() { // Arrange - AddBookRequest bookRequest = _requestBookFixture.Create(); - bookRequest = bookRequest with { ISBNs = null! }; + AddBookRequest bookRequest = _requestBookFixture.Create(includeOptionalProperties: false); // Act - HttpResponseMessage response = await _client.PostAsJsonAsync("/api/v1/books", bookRequest); + HttpResponseMessage response = await PostBookAsync(bookRequest); // Assert await AssertUnprocessableEntityWithValidationErrors(response, Errors.WrittenContent.IsbnListCannotBeNull.Description); @@ -1240,14 +1068,10 @@ public class AddBookEndpointTests : IClassFixture public async Task AddBook_WhenCalledWithEmptyIsbnValue_ShouldReturnUnprocessableEntity() { // Arrange - AddBookRequest bookRequest = _requestBookFixture.Create(); - bookRequest = bookRequest with - { - ISBNs = [.. bookRequest.ISBNs!.Select((isbn, index) => index == 0 ? isbn with { Value = null } : isbn)] - }; + AddBookRequest bookRequest = _requestBookFixture.Create(isbns: [_isbnDtoFixture.Create(value: string.Empty)]); // Act - HttpResponseMessage response = await _client.PostAsJsonAsync("/api/v1/books", bookRequest); + HttpResponseMessage response = await PostBookAsync(bookRequest); // Assert await AssertUnprocessableEntityWithValidationErrors(response, Errors.WrittenContent.IsbnValueCannotBeEmpty.Description); @@ -1257,14 +1081,10 @@ public class AddBookEndpointTests : IClassFixture public async Task AddBook_WhenCalledWithInvalidIsbn10Value_ShouldReturnUnprocessableEntity() { // Arrange - AddBookRequest bookRequest = _requestBookFixture.Create(); - bookRequest = bookRequest with - { - ISBNs = [.. bookRequest.ISBNs!.Select((isbn, index) => index == 0 ? isbn with { Value = new Faker().Random.String2(5), Format = IsbnFormat.Isbn10 } : isbn)] - }; + AddBookRequest bookRequest = _requestBookFixture.Create(isbns: [_isbnDtoFixture.Create(value: new Faker().Random.String2(5), format: IsbnFormat.Isbn10)]); // Act - HttpResponseMessage response = await _client.PostAsJsonAsync("/api/v1/books", bookRequest); + HttpResponseMessage response = await PostBookAsync(bookRequest); // Assert await AssertUnprocessableEntityWithValidationErrors(response, Errors.WrittenContent.InvalidIsbn10Format.Description); @@ -1274,14 +1094,10 @@ public class AddBookEndpointTests : IClassFixture public async Task AddBook_WhenCalledWithInvalidIsbn13Value_ShouldReturnUnprocessableEntity() { // Arrange - AddBookRequest bookRequest = _requestBookFixture.Create(); - bookRequest = bookRequest with - { - ISBNs = [.. bookRequest.ISBNs!.Select((isbn, index) => index == 0 ? isbn with { Value = new Faker().Random.String2(5), Format = IsbnFormat.Isbn13 } : isbn)] - }; + AddBookRequest bookRequest = _requestBookFixture.Create(isbns: [_isbnDtoFixture.Create(value: new Faker().Random.String2(5), format: IsbnFormat.Isbn13)]); // Act - HttpResponseMessage response = await _client.PostAsJsonAsync("/api/v1/books", bookRequest); + HttpResponseMessage response = await PostBookAsync(bookRequest); // Assert await AssertUnprocessableEntityWithValidationErrors(response, Errors.WrittenContent.InvalidIsbn13Format.Description); @@ -1291,13 +1107,9 @@ public class AddBookEndpointTests : IClassFixture public async Task AddBook_WhenCalledWithInvalidIsbnFormat_ShouldReturnUnprocessableEntity() { // Arrange - AddBookRequest bookRequest = _requestBookFixture.Create(); - bookRequest = bookRequest with - { - ISBNs = [.. bookRequest.ISBNs!.Select((isbn, index) => index == 0 ? isbn with { Format = (IsbnFormat)99 } : isbn)] - }; + AddBookRequest bookRequest = _requestBookFixture.Create(isbns: [_isbnDtoFixture.Create(format: (IsbnFormat)99)]); // Act - HttpResponseMessage response = await _client.PostAsJsonAsync("/api/v1/books", bookRequest); + HttpResponseMessage response = await PostBookAsync(bookRequest); // Assert await AssertUnprocessableEntityWithValidationErrors(response, Errors.WrittenContent.UnknownIsbnFormat.Description); @@ -1307,11 +1119,10 @@ public class AddBookEndpointTests : IClassFixture public async Task AddBook_WhenCalledWithNullContributors_ShouldReturnUnprocessableEntity() { // Arrange - AddBookRequest bookRequest = _requestBookFixture.Create(); - bookRequest = bookRequest with { Contributors = null! }; + AddBookRequest bookRequest = _requestBookFixture.Create(includeOptionalProperties: false); // Act - HttpResponseMessage response = await _client.PostAsJsonAsync("/api/v1/books", bookRequest); + HttpResponseMessage response = await PostBookAsync(bookRequest); // Assert await AssertUnprocessableEntityWithValidationErrors(response, Errors.MediaContributor.ContributorsListCannotBeNull.Description); @@ -1321,14 +1132,10 @@ public class AddBookEndpointTests : IClassFixture public async Task AddBook_WhenCalledWithNullContributorName_ShouldReturnUnprocessableEntity() { // Arrange - AddBookRequest bookRequest = _requestBookFixture.Create(); - bookRequest = bookRequest with - { - Contributors = [.. bookRequest.Contributors!.Select((contributor, index) => index == 0 ? contributor with { Name = null! } : contributor)] - }; + AddBookRequest bookRequest = _requestBookFixture.Create(contributors: [_mediaContributorDtoFixture.Create(roleName: "author", roleCategory: MediaContributorRoleCategory.Author, includeName: false)]); // Act - HttpResponseMessage response = await _client.PostAsJsonAsync("/api/v1/books", bookRequest); + HttpResponseMessage response = await PostBookAsync(bookRequest); // Assert await AssertUnprocessableEntityWithValidationErrors(response, Errors.MediaContributor.ContributorNameCannotBeEmpty.Description); @@ -1338,14 +1145,10 @@ public class AddBookEndpointTests : IClassFixture public async Task AddBook_WhenCalledWithEmptyContributorDisplayName_ShouldReturnUnprocessableEntity() { // Arrange - AddBookRequest bookRequest = _requestBookFixture.Create(); - bookRequest = bookRequest with - { - Contributors = [.. bookRequest.Contributors!.Select((contributor, index) => index == 0 ? contributor with { Name = contributor.Name! with { DisplayName = string.Empty } } : contributor)] - }; + AddBookRequest bookRequest = _requestBookFixture.Create(contributors: [_mediaContributorDtoFixture.Create(displayName: string.Empty)]); // Act - HttpResponseMessage response = await _client.PostAsJsonAsync("/api/v1/books", bookRequest); + HttpResponseMessage response = await PostBookAsync(bookRequest); // Assert await AssertUnprocessableEntityWithValidationErrors(response, Errors.MediaContributor.ContributorDisplayNameCannotBeEmpty.Description); @@ -1355,14 +1158,10 @@ public class AddBookEndpointTests : IClassFixture public async Task AddBook_WhenCalledWithNullContributorDisplayName_ShouldReturnUnprocessableEntity() { // Arrange - AddBookRequest bookRequest = _requestBookFixture.Create(); - bookRequest = bookRequest with - { - Contributors = [.. bookRequest.Contributors!.Select((contributor, index) => index == 0 ? contributor with { Name = contributor.Name! with { DisplayName = null! } } : contributor)] - }; + AddBookRequest bookRequest = _requestBookFixture.Create(contributors: [_mediaContributorDtoFixture.Create(includeDisplayName: false, includeLegalName: false, roleName: "author", roleCategory: MediaContributorRoleCategory.Author)]); // Act - HttpResponseMessage response = await _client.PostAsJsonAsync("/api/v1/books", bookRequest); + HttpResponseMessage response = await PostBookAsync(bookRequest); // Assert await AssertUnprocessableEntityWithValidationErrors(response, Errors.MediaContributor.ContributorDisplayNameCannotBeEmpty.Description); @@ -1372,14 +1171,10 @@ public class AddBookEndpointTests : IClassFixture public async Task AddBook_WhenCalledWithInvalidLengthContributorDisplayName_ShouldReturnUnprocessableEntity() { // Arrange - AddBookRequest bookRequest = _requestBookFixture.Create(); - bookRequest = bookRequest with - { - Contributors = [.. bookRequest.Contributors!.Select((contributor, index) => index == 0 ? contributor with { Name = contributor.Name! with { DisplayName = new Faker().Random.String2(150) } } : contributor)] - }; + AddBookRequest bookRequest = _requestBookFixture.Create(contributors: [_mediaContributorDtoFixture.Create(displayName: new Faker().Random.String2(150))]); // Act - HttpResponseMessage response = await _client.PostAsJsonAsync("/api/v1/books", bookRequest); + HttpResponseMessage response = await PostBookAsync(bookRequest); // Assert await AssertUnprocessableEntityWithValidationErrors(response, Errors.MediaContributor.ContributorDisplayNameMustBeMaximum100CharactersLong.Description); @@ -1389,14 +1184,10 @@ public class AddBookEndpointTests : IClassFixture public async Task AddBook_WhenCalledWithInvalidLengthContributorLegalName_ShouldReturnUnprocessableEntity() { // Arrange - AddBookRequest bookRequest = _requestBookFixture.Create(); - bookRequest = bookRequest with - { - Contributors = [.. bookRequest.Contributors!.Select((contributor, index) => index == 0 ? contributor with { Name = contributor.Name! with { LegalName = new Faker().Random.String2(150) } } : contributor)] - }; + AddBookRequest bookRequest = _requestBookFixture.Create(contributors: [_mediaContributorDtoFixture.Create(displayName: new Faker().Random.String2(50), legalName: new Faker().Random.String2(150), roleName: "author", roleCategory: MediaContributorRoleCategory.Author)]); // Act - HttpResponseMessage response = await _client.PostAsJsonAsync("/api/v1/books", bookRequest); + HttpResponseMessage response = await PostBookAsync(bookRequest); // Assert await AssertUnprocessableEntityWithValidationErrors(response, Errors.MediaContributor.ContributorLegalNameMustBeMaximum100CharactersLong.Description); @@ -1406,14 +1197,10 @@ public class AddBookEndpointTests : IClassFixture public async Task AddBook_WhenCalledWithEmptyContributorRole_ShouldReturnUnprocessableEntity() { // Arrange - AddBookRequest bookRequest = _requestBookFixture.Create(); - bookRequest = bookRequest with - { - Contributors = [.. bookRequest.Contributors!.Select((contributor, index) => index == 0 ? contributor with { Role = null } : contributor)] - }; + AddBookRequest bookRequest = _requestBookFixture.Create(contributors: [_mediaContributorDtoFixture.Create(displayName: new Faker().Random.String2(50), includeRole: false)]); // Act - HttpResponseMessage response = await _client.PostAsJsonAsync("/api/v1/books", bookRequest); + HttpResponseMessage response = await PostBookAsync(bookRequest); // Assert await AssertUnprocessableEntityWithValidationErrors(response, Errors.MediaContributor.ContributorRoleCannotBeNull.Description); @@ -1423,15 +1210,10 @@ public class AddBookEndpointTests : IClassFixture public async Task AddBook_WhenCalledWithEmptyContributorRoleName_ShouldReturnUnprocessableEntity() { // Arrange - AddBookRequest bookRequest = _requestBookFixture.Create(); - bookRequest = bookRequest with - { - Contributors = [.. bookRequest.Contributors!.Select((contributor, index) => index == 0 ? contributor with - { Role = contributor.Role! with { Name = null } } : contributor)] - }; + AddBookRequest bookRequest = _requestBookFixture.Create(contributors: [_mediaContributorDtoFixture.Create(displayName: new Faker().Random.String2(50), includeRoleName: false, roleCategory: MediaContributorRoleCategory.Author)]); // Act - HttpResponseMessage response = await _client.PostAsJsonAsync("/api/v1/books", bookRequest); + HttpResponseMessage response = await PostBookAsync(bookRequest); // Assert await AssertUnprocessableEntityWithValidationErrors(response, Errors.MediaContributor.RoleNameCannotBeEmpty.Description); @@ -1441,15 +1223,10 @@ public class AddBookEndpointTests : IClassFixture public async Task AddBook_WhenCalledWithInvalidLengthContributorRoleName_ShouldReturnUnprocessableEntity() { // Arrange - AddBookRequest bookRequest = _requestBookFixture.Create(); - bookRequest = bookRequest with - { - Contributors = [.. bookRequest.Contributors!.Select((contributor, index) => index == 0 ? contributor with - { Role = contributor.Role! with { Name = new Faker().Random.String2(100) } } : contributor)] - }; + AddBookRequest bookRequest = _requestBookFixture.Create(contributors: [_mediaContributorDtoFixture.Create(displayName: new Faker().Random.String2(50), roleName: new Faker().Random.String2(100), roleCategory: MediaContributorRoleCategory.Author)]); // Act - HttpResponseMessage response = await _client.PostAsJsonAsync("/api/v1/books", bookRequest); + HttpResponseMessage response = await PostBookAsync(bookRequest); // Assert await AssertUnprocessableEntityWithValidationErrors(response, Errors.MediaContributor.RoleNameMustBeMaximum50CharactersLong.Description); @@ -1459,15 +1236,10 @@ public class AddBookEndpointTests : IClassFixture public async Task AddBook_WhenCalledWithEmptyContributorRoleCategory_ShouldReturnUnprocessableEntity() { // Arrange - AddBookRequest bookRequest = _requestBookFixture.Create(); - bookRequest = bookRequest with - { - Contributors = [.. bookRequest.Contributors!.Select((contributor, index) => index == 0 ? contributor with - { Role = contributor.Role! with { Category = null } } : contributor)] - }; + AddBookRequest bookRequest = _requestBookFixture.Create(contributors: [_mediaContributorDtoFixture.Create(displayName: new Faker().Random.String2(50), roleName: "author", includeRoleCategory: false)]); // Act - HttpResponseMessage response = await _client.PostAsJsonAsync("/api/v1/books", bookRequest); + HttpResponseMessage response = await PostBookAsync(bookRequest); // Assert await AssertUnprocessableEntityWithValidationErrors(response, Errors.MediaContributor.RoleCategoryCannotBeEmpty.Description); @@ -1477,11 +1249,10 @@ public class AddBookEndpointTests : IClassFixture public async Task AddBook_WhenCalledWithNullRatings_ShouldReturnUnprocessableEntity() { // Arrange - AddBookRequest bookRequest = _requestBookFixture.Create(); - bookRequest = bookRequest with { Ratings = null! }; + AddBookRequest bookRequest = _requestBookFixture.Create(includeOptionalProperties: false); // Act - HttpResponseMessage response = await _client.PostAsJsonAsync("/api/v1/books", bookRequest); + HttpResponseMessage response = await PostBookAsync(bookRequest); // Assert await AssertUnprocessableEntityWithValidationErrors(response, Errors.Metadata.RatingsListCannotBeNull.Description); @@ -1491,13 +1262,9 @@ public class AddBookEndpointTests : IClassFixture public async Task AddBook_WhenCalledWithNegativeRatingValue_ShouldReturnUnprocessableEntity() { // Arrange - AddBookRequest bookRequest = _requestBookFixture.Create(); - bookRequest = bookRequest with - { - Ratings = [.. bookRequest.Ratings!.Select((rating, index) => index == 0 ? rating with { Value = -3 } : rating)] - }; + AddBookRequest bookRequest = _requestBookFixture.Create(ratings: [_bookRatingDtoFixture.Create(value: -3)]); // Act - HttpResponseMessage response = await _client.PostAsJsonAsync("/api/v1/books", bookRequest); + HttpResponseMessage response = await PostBookAsync(bookRequest); // Assert await AssertUnprocessableEntityWithValidationErrors(response, Errors.Metadata.RatingValueMustBePositive.Description); @@ -1507,13 +1274,9 @@ public class AddBookEndpointTests : IClassFixture public async Task AddBook_WhenCalledWithRatingValueGreaterThanMaxValue_ShouldReturnUnprocessableEntity() { // Arrange - AddBookRequest bookRequest = _requestBookFixture.Create(); - bookRequest = bookRequest with - { - Ratings = [.. bookRequest.Ratings!.Select((rating, index) => index == 0 ? rating with { Value = 3, MaxValue = 2 } : rating)] - }; + AddBookRequest bookRequest = _requestBookFixture.Create(ratings: [_bookRatingDtoFixture.Create(value: 3, maxValue: 2)]); // Act - HttpResponseMessage response = await _client.PostAsJsonAsync("/api/v1/books", bookRequest); + HttpResponseMessage response = await PostBookAsync(bookRequest); // Assert await AssertUnprocessableEntityWithValidationErrors(response, Errors.Metadata.RatingValueCannotBeGreaterThanMaxValue.Description); @@ -1523,13 +1286,9 @@ public class AddBookEndpointTests : IClassFixture public async Task AddBook_WhenCalledWithNegativeMaxRatingValue_ShouldReturnUnprocessableEntity() { // Arrange - AddBookRequest bookRequest = _requestBookFixture.Create(); - bookRequest = bookRequest with - { - Ratings = [.. bookRequest.Ratings!.Select((rating, index) => index == 0 ? rating with { MaxValue = -3 } : rating)] - }; + AddBookRequest bookRequest = _requestBookFixture.Create(ratings: [_bookRatingDtoFixture.Create(maxValue: -3)]); // Act - HttpResponseMessage response = await _client.PostAsJsonAsync("/api/v1/books", bookRequest); + HttpResponseMessage response = await PostBookAsync(bookRequest); // Assert await AssertUnprocessableEntityWithValidationErrors(response, Errors.Metadata.RatingMaxValueMustBePositive.Description); @@ -1539,11 +1298,7 @@ public class AddBookEndpointTests : IClassFixture public async Task AddBook_WhenCalledWithEmptyRatingVoteCount_ShouldAddBook() { // Arrange - AddBookRequest bookRequest = _requestBookFixture.Create(); - bookRequest = bookRequest with - { - Ratings = [.. bookRequest.Ratings!.Select((rating, index) => index == 0 ? rating with { VoteCount = null } : rating)] - }; + AddBookRequest bookRequest = _requestBookFixture.Create(ratings: [_bookRatingDtoFixture.Create(source: BookRatingSource.Goodreads, includeOptionalProperties: false)]); // Act & Assert await AssertCreated(bookRequest); } @@ -1552,18 +1307,56 @@ public class AddBookEndpointTests : IClassFixture public async Task AddBook_WhenCalledWithNegativeVoteCount_ShouldReturnUnprocessableEntity() { // Arrange - AddBookRequest bookRequest = _requestBookFixture.Create(); - bookRequest = bookRequest with - { - Ratings = [.. bookRequest.Ratings!.Select((rating, index) => index == 0 ? rating with { VoteCount = -3 } : rating)] - }; + AddBookRequest bookRequest = _requestBookFixture.Create(ratings: [_bookRatingDtoFixture.Create(voteCount: -3)]); // Act - HttpResponseMessage response = await _client.PostAsJsonAsync("/api/v1/books", bookRequest); + HttpResponseMessage response = await PostBookAsync(bookRequest); // Assert await AssertUnprocessableEntityWithValidationErrors(response, Errors.Metadata.RatingVoteCountMustBePositive.Description); } + [Fact] + public async Task AddBook_WhenTwoContributorsShareTheSameDisplayName_ShouldCreateOneContributorWithTwoBookLinks() + { + // Arrange + AddBookRequest bookRequest = _requestBookFixture.Create(contributors: + [ + _mediaContributorDtoFixture.Create(displayName: "Duplicated Author", legalName: "Duplicated Author Legal", roleName: "author", roleCategory: MediaContributorRoleCategory.Author), + _mediaContributorDtoFixture.Create(displayName: "Duplicated Author", legalName: "Duplicated Author Legal", roleName: "illustrator", roleCategory: MediaContributorRoleCategory.Illustrator) + ]); + + // Act + HttpResponseMessage response = await PostBookAsync(bookRequest); + + // Assert + response.EnsureSuccessStatusCode(); + Assert.Equal(HttpStatusCode.Created, response.StatusCode); + Book? bookResponse = await response.Content.ReadFromJsonAsync(_jsonOptions); + Assert.NotNull(bookResponse); + + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + MediaContributorEntity contributor = dbContext.MediaContributors.Single(mediaContributor => mediaContributor.DisplayName == "Duplicated Author"); + List links = [.. dbContext.Books + .Include(book => book.BookContributors) + .Single(book => book.Id == bookResponse!.Id.Value) + .BookContributors]; + Assert.Equal(2, links.Count); + Assert.All(links, link => Assert.Equal(contributor.Id, link.MediaContributorId)); + Assert.Contains(links, link => link.RoleName == "author"); + Assert.Contains(links, link => link.RoleName == "illustrator"); + } + + /// + /// Posts a request to add a book to the media library owned by the authenticated user of the current test. + /// + /// The request to post. + /// The HTTP response of the POST request. + private Task PostBookAsync(AddBookRequest request) + { + return _client.PostAsJsonAsync("/api/v1/books", request with { LibraryId = _libraryId }); + } + private async Task AssertUnprocessableEntityWithValidationErrors(HttpResponseMessage response, params string[] expectedErrorCodes) { Assert.Equal(HttpStatusCode.UnprocessableContent, response.StatusCode); @@ -1588,7 +1381,7 @@ public class AddBookEndpointTests : IClassFixture private async Task AssertCreated(AddBookRequest bookRequest) { - HttpResponseMessage response = await _client.PostAsJsonAsync("/api/v1/books", bookRequest); + HttpResponseMessage response = await PostBookAsync(bookRequest); response.EnsureSuccessStatusCode(); Book? bookResponse = await response.Content.ReadFromJsonAsync(_jsonOptions); Assert.Equal(HttpStatusCode.Created, response.StatusCode); diff --git a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/GetBook/GetBookEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/GetBook/GetBookEndpointTests.cs index 36a07376..d0f1196e 100644 --- a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/GetBook/GetBookEndpointTests.cs +++ b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/GetBook/GetBookEndpointTests.cs @@ -1,10 +1,25 @@ #region ========================================================================= USING ===================================================================================== +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.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.UsersManagement; +using Lumina.Contracts.Responses.MediaLibrary.WrittenContentLibrary.BookLibrary.Books; +using Lumina.DataAccess.Core.UoW; +using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; using Lumina.Presentation.Api.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.Books.GetBook; using Lumina.Presentation.Api.IntegrationTests.Common.Setup; +using Microsoft.AspNetCore.Http; +using Microsoft.Extensions.DependencyInjection; using System; using System.Diagnostics.CodeAnalysis; +using System.Linq; using System.Net; using System.Net.Http; +using System.Net.Http.Json; +using System.Text.Json; +using System.Text.Json.Serialization; using System.Threading.Tasks; #endregion @@ -18,6 +33,14 @@ public class GetBookEndpointTests : IClassFixture { private HttpClient _client; private readonly AuthenticatedLuminaApiFactory _apiFactory; + private readonly JsonSerializerOptions _jsonOptions = new() + { + PropertyNameCaseInsensitive = true, + Converters = { new JsonStringEnumConverter(JsonNamingPolicy.CamelCase) } + }; + private readonly BookEntityFixture _bookEntityFixture = new(); + private readonly LibraryEntityFixture _libraryEntityFixture = new(); + private readonly UserEntityFixture _userEntityFixture = new(); /// /// Initializes a new instance of the class. @@ -38,16 +61,118 @@ public class GetBookEndpointTests : IClassFixture } [Fact] - public async Task GetBook_WhenCalled_ShouldReturnOk() + public async Task GetBook_WhenBookBelongsToAnOwnedLibrary_ShouldReturnBookDetails() { // Arrange - Guid bookId = Guid.NewGuid(); + Guid userId = GetCurrentUserId(); + (Guid libraryId, Guid bookId) = await SeedLibraryAndBookAsync(userId, "Test Book"); // Act HttpResponseMessage response = await _client.GetAsync($"/api/v1/books/{bookId}"); // Assert Assert.Equal(HttpStatusCode.OK, response.StatusCode); + string content = await response.Content.ReadAsStringAsync(); + BookResponse? book = JsonSerializer.Deserialize(content, _jsonOptions); + Assert.NotNull(book); + Assert.Equal(bookId, book!.Id); + Assert.Equal(libraryId, book.LibraryId); + Assert.Equal("Test Book", book.Metadata!.Title); + Assert.Equal($"/books/{bookId:N}.epub", book.Path); + } + + [Fact] + public async Task GetBook_WhenBookDoesNotExist_ShouldReturnBookNotFoundProblem() + { + // Act + HttpResponseMessage response = await _client.GetAsync($"/api/v1/books/{Guid.NewGuid()}"); + + // Assert + Assert.Equal(HttpStatusCode.NotFound, response.StatusCode); + string content = await response.Content.ReadAsStringAsync(); + Microsoft.AspNetCore.Mvc.ProblemDetails? problemDetails = JsonSerializer.Deserialize(content, _jsonOptions); + Assert.NotNull(problemDetails); + Assert.Equal("General.NotFound", problemDetails!.Title); + Assert.Equal("BookNotFound", problemDetails.Detail); + Assert.DoesNotContain("Exception", content, StringComparison.Ordinal); + } + + [Fact] + public async Task GetBook_WhenBookBelongsToAnotherUserLibrary_ShouldReturnForbiddenProblem() + { + // Arrange + (Guid otherUserId, _) = await SeedOtherUserAsync(); + (_, Guid bookId) = await SeedLibraryAndBookAsync(otherUserId, "Other User Book"); + + // Act + HttpResponseMessage response = await _client.GetAsync($"/api/v1/books/{bookId}"); + + // Assert + Assert.Equal(HttpStatusCode.Forbidden, response.StatusCode); + using JsonDocument problemDetails = JsonDocument.Parse(await response.Content.ReadAsStringAsync()); + Assert.Equal("General.Unauthorized", problemDetails.RootElement.GetProperty("title").GetString()); + Assert.Equal("NotAuthorized", problemDetails.RootElement.GetProperty("detail").GetString()); + Assert.DoesNotContain("Exception", problemDetails.RootElement.GetRawText(), StringComparison.Ordinal); + } + + [Fact] + public async Task GetBook_WhenUnauthorized_ShouldReturnUnauthorizedResult() + { + // Arrange + HttpClient unauthenticatedClient = _apiFactory.CreateClient(); + + // Act + HttpResponseMessage response = await unauthenticatedClient.GetAsync($"/api/v1/books/{Guid.NewGuid()}"); + + // Assert + Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode); + } + + /// + /// Seeds a library owned by and a book belonging to it. + /// + /// The Id of the user that owns the library. + /// The title of the seeded book. + /// The Ids of the seeded library and book. + private async Task<(Guid libraryId, Guid bookId)> SeedLibraryAndBookAsync(Guid userId, string title) + { + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + Guid libraryId = Guid.NewGuid(); + Guid bookId = Guid.NewGuid(); + LibraryEntity library = _libraryEntityFixture.Create(id: libraryId, userId: userId, title: "Test Library", libraryType: LibraryType.EBook, contentLocations: []); + BookEntity book = _bookEntityFixture.Create(id: bookId, libraryId: libraryId, path: $"/books/{bookId:N}.epub", title: title, includeMetadata: false); + dbContext.Libraries.Add(library); + dbContext.Books.Add(book); + await dbContext.SaveChangesAsync(); + return (libraryId, bookId); + } + + /// + /// Seeds a user distinct from the authenticated test user and returns its Id. + /// + /// The Id of the seeded user and its username. + private async Task<(Guid userId, string username)> SeedOtherUserAsync() + { + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + Guid userId = Guid.NewGuid(); + string username = $"otheruser_{Guid.NewGuid()}"; + dbContext.Users.Add(_userEntityFixture.Create(id: userId, username: username, password: "TestPass123!")); + await dbContext.SaveChangesAsync(); + return (userId, username); + } + + /// + /// Gets the Id of the currently authenticated test user. + /// + /// The Id of the authenticated test user. + private Guid GetCurrentUserId() + { + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + UserEntity user = dbContext.Users.First(user => user.Username == _apiFactory.TestUsername); + return user.Id; } /// diff --git a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/Reading/GetReadingAvailability/GetReadingAvailabilityEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/Reading/GetReadingAvailability/GetReadingAvailabilityEndpointTests.cs index 17d95071..82e937fb 100644 --- a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/Reading/GetReadingAvailability/GetReadingAvailabilityEndpointTests.cs +++ b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/Reading/GetReadingAvailability/GetReadingAvailabilityEndpointTests.cs @@ -22,7 +22,7 @@ using System.Threading.Tasks; namespace Lumina.Presentation.Api.IntegrationTests.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.Books.Reading.GetReadingAvailability; /// -/// Contains integration tests for the /books/{bookId}/reading/availability route. +/// Contains integration tests for the class. /// [ExcludeFromCodeCoverage] public class GetReadingAvailabilityEndpointTests : IClassFixture, IAsyncLifetime diff --git a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/Reading/GetReadingManifest/GetReadingManifestEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/Reading/GetReadingManifest/GetReadingManifestEndpointTests.cs index 3a954ded..7fb86434 100644 --- a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/Reading/GetReadingManifest/GetReadingManifestEndpointTests.cs +++ b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/Reading/GetReadingManifest/GetReadingManifestEndpointTests.cs @@ -19,7 +19,7 @@ using System.Threading.Tasks; namespace Lumina.Presentation.Api.IntegrationTests.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.Books.Reading.GetReadingManifest; /// -/// Contains integration tests for the /books/{bookId}/reading/manifest route. +/// Contains integration tests for the class. /// [ExcludeFromCodeCoverage] public class GetReadingManifestEndpointTests : IClassFixture, IAsyncLifetime diff --git a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/Reading/GetReadingResource/GetReadingResourceEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/Reading/GetReadingResource/GetReadingResourceEndpointTests.cs index d2f7a13a..a2db9592 100644 --- a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/Reading/GetReadingResource/GetReadingResourceEndpointTests.cs +++ b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/Reading/GetReadingResource/GetReadingResourceEndpointTests.cs @@ -19,7 +19,7 @@ using System.Threading.Tasks; namespace Lumina.Presentation.Api.IntegrationTests.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.Books.Reading.GetReadingResource; /// -/// Contains integration tests for the /books/{bookId}/reading/resources/{resourceKey} route. +/// Contains integration tests for the class. /// [ExcludeFromCodeCoverage] public class GetReadingResourceEndpointTests : IClassFixture, IAsyncLifetime diff --git a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/Reading/GetReadingSection/GetReadingSectionEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/Reading/GetReadingSection/GetReadingSectionEndpointTests.cs index 888b8e42..209f6ddd 100644 --- a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/Reading/GetReadingSection/GetReadingSectionEndpointTests.cs +++ b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/Reading/GetReadingSection/GetReadingSectionEndpointTests.cs @@ -19,7 +19,7 @@ using System.Threading.Tasks; namespace Lumina.Presentation.Api.IntegrationTests.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.Books.Reading.GetReadingSection; /// -/// Contains integration tests for the /books/{bookId}/reading/sections/{locationRef} route. +/// Contains integration tests for the class. /// [ExcludeFromCodeCoverage] public class GetReadingSectionEndpointTests : IClassFixture, IAsyncLifetime diff --git a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/UpdateBook/UpdateBookEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/UpdateBook/UpdateBookEndpointTests.cs new file mode 100644 index 00000000..a7ae66b2 --- /dev/null +++ b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/UpdateBook/UpdateBookEndpointTests.cs @@ -0,0 +1,298 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Entities.MediaContributors; +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.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.UsersManagement; +using Lumina.Contracts.DTO.MediaContributors; +using Lumina.Contracts.Fixtures.Core.DTO.MediaLibrary.WrittenContentLibrary; +using Lumina.Contracts.Fixtures.Core.Requests.MediaLibrary.WrittenContentLibrary.BookLibrary.Books; +using Lumina.Contracts.Requests.MediaLibrary.WrittenContentLibrary.BookLibrary.Books; +using Lumina.Contracts.Responses.MediaLibrary.WrittenContentLibrary.BookLibrary.Books; +using Lumina.DataAccess.Core.UoW; +using Lumina.Domain.SharedKernel.Common.Enums.MediaContributors; +using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; +using Lumina.Presentation.Api.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.Books.UpdateBook; +using Lumina.Presentation.Api.IntegrationTests.Common.Setup; +using Microsoft.EntityFrameworkCore; +using Microsoft.Extensions.DependencyInjection; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +using System.Net; +using System.Net.Http; +using System.Net.Http.Json; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Api.IntegrationTests.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.Books.UpdateBook; + +/// +/// Contains integration tests for the class. +/// +[ExcludeFromCodeCoverage] +public class UpdateBookEndpointTests : IClassFixture, IAsyncLifetime +{ + private HttpClient _client; + private readonly AuthenticatedLuminaApiFactory _apiFactory; + private readonly JsonSerializerOptions _jsonOptions = new() + { + PropertyNameCaseInsensitive = true, + Converters = { new JsonStringEnumConverter(JsonNamingPolicy.CamelCase) } + }; + private readonly UpdateBookRequestFixture _requestBookFixture = new(); + private readonly WrittenContentMetadataDtoFixture _writtenContentMetadataDtoFixture = new(); + private readonly BookEntityFixture _bookEntityFixture = new(); + private readonly LibraryEntityFixture _libraryEntityFixture = new(); + private readonly UserEntityFixture _userEntityFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + /// Injected in-memory API factory. + public UpdateBookEndpointTests(AuthenticatedLuminaApiFactory apiFactory) + { + _client = apiFactory.CreateClient(); + _apiFactory = apiFactory; + } + + /// + /// Initializes authenticated API client. + /// + public async Task InitializeAsync() + { + _client = await _apiFactory.CreateAuthenticatedClientAsync(); + } + + [Fact] + public async Task UpdateBook_WhenCalledByOwnerWithValidData_ShouldUpdateBookAndPersistChanges() + { + // Arrange + Guid userId = GetCurrentUserId(); + (Guid libraryId, Guid bookId) = await SeedLibraryAndBookAsync(userId, "Original Title"); + UpdateBookRequest request = _requestBookFixture.Create(id: bookId, metadata: _writtenContentMetadataDtoFixture.Create(title: "Updated Title"), isbns: [], contributors: [], ratings: [], includeOptionalProperties: false); + + // Act + HttpResponseMessage response = await _client.PutAsJsonAsync($"/api/v1/books/{bookId}", request); + + // Assert + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + string content = await response.Content.ReadAsStringAsync(); + BookResponse? bookResponse = JsonSerializer.Deserialize(content, _jsonOptions); + Assert.NotNull(bookResponse); + Assert.Equal(bookId, bookResponse!.Id); + Assert.Equal(libraryId, bookResponse.LibraryId); + Assert.Equal("Updated Title", bookResponse.Metadata!.Title); + + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + BookEntity storedBook = dbContext.Books.Single(book => book.Id == bookId); + Assert.Equal("Updated Title", storedBook.Title); + } + + [Fact] + public async Task UpdateBook_WhenTwoContributorsShareTheSameDisplayName_ShouldCreateOneContributorWithTwoBookLinks() + { + // Arrange + Guid userId = GetCurrentUserId(); + (_, Guid bookId) = await SeedLibraryAndBookAsync(userId, "Original Title"); + List duplicatedContributors = + [ + new MediaContributorDto( + new MediaContributorNameDto("Duplicated Author", "Duplicated Author Legal"), + new MediaContributorRoleDto("author", MediaContributorRoleCategory.Author)), + new MediaContributorDto( + new MediaContributorNameDto("Duplicated Author", "Duplicated Author Legal"), + new MediaContributorRoleDto("illustrator", MediaContributorRoleCategory.Illustrator)) + ]; + UpdateBookRequest request = _requestBookFixture.Create(id: bookId, contributors: duplicatedContributors, isbns: [], ratings: [], includeOptionalProperties: false); + + // Act + HttpResponseMessage response = await _client.PutAsJsonAsync($"/api/v1/books/{bookId}", request); + + // Assert + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + MediaContributorEntity contributor = dbContext.MediaContributors.Single(mediaContributor => mediaContributor.DisplayName == "Duplicated Author"); + List links = dbContext.Books + .Include(book => book.BookContributors) + .Single(book => book.Id == bookId) + .BookContributors + .ToList(); + Assert.Equal(2, links.Count); + Assert.All(links, link => Assert.Equal(contributor.Id, link.MediaContributorId)); + Assert.Contains(links, link => link.RoleName == "author"); + Assert.Contains(links, link => link.RoleName == "illustrator"); + } + + [Fact] + public async Task UpdateBook_WhenRouteBookDoesNotExistButBodyIdExists_ShouldNotUpdateTheBodyBook() + { + // Arrange + Guid userId = GetCurrentUserId(); + (Guid libraryId, Guid bodyBookId) = await SeedLibraryAndBookAsync(userId, "Body Book Title"); + Guid routeId = Guid.NewGuid(); + UpdateBookRequest request = _requestBookFixture.Create(id: bodyBookId, metadata: _writtenContentMetadataDtoFixture.Create(title: "Should Not Apply")); + + // Act + HttpResponseMessage response = await _client.PutAsJsonAsync($"/api/v1/books/{routeId}", request); + + // Assert + Assert.Equal(HttpStatusCode.NotFound, response.StatusCode); + string content = await response.Content.ReadAsStringAsync(); + Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase); + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + BookEntity storedBook = dbContext.Books.Single(book => book.Id == bodyBookId); + Assert.Equal("Body Book Title", storedBook.Title); + } + + [Fact] + public async Task UpdateBook_WhenRouteIdIsNotParseable_ShouldReturnUnprocessableEntity() + { + // Arrange + UpdateBookRequest request = _requestBookFixture.Create(); + + // Act + HttpResponseMessage response = await _client.PutAsJsonAsync($"/api/v1/books/not-a-guid", request); + + // Assert + // The route value is kept as a raw string, so the unparseable Id becomes Guid.Empty in the command mapping and the + // command validator reports a clean validation error instead of failing the request binding. + Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode); + string content = await response.Content.ReadAsStringAsync(); + using JsonDocument problemDetails = JsonDocument.Parse(content); + Assert.Equal("General.Validation", problemDetails.RootElement.GetProperty("title").GetString()); + Assert.Contains("BookIdCannotBeEmpty", content, StringComparison.OrdinalIgnoreCase); + } + + [Fact] + public async Task UpdateBook_WhenBookDoesNotExist_ShouldReturnBookNotFoundProblem() + { + // Arrange + UpdateBookRequest request = _requestBookFixture.Create(); + + // Act + HttpResponseMessage response = await _client.PutAsJsonAsync($"/api/v1/books/{Guid.NewGuid()}", request); + + // Assert + Assert.Equal(HttpStatusCode.NotFound, response.StatusCode); + string content = await response.Content.ReadAsStringAsync(); + using JsonDocument problemDetails = JsonDocument.Parse(content); + Assert.Equal("General.NotFound", problemDetails.RootElement.GetProperty("title").GetString()); + Assert.Equal("BookNotFound", problemDetails.RootElement.GetProperty("detail").GetString()); + } + + [Fact] + public async Task UpdateBook_WhenBookBelongsToAnotherUserLibrary_ShouldReturnForbiddenProblem() + { + // Arrange + (Guid otherUserId, _) = await SeedOtherUserAsync(); + (_, Guid bookId) = await SeedLibraryAndBookAsync(otherUserId, "Other User Book"); + UpdateBookRequest request = _requestBookFixture.Create(id: bookId); + + // Act + HttpResponseMessage response = await _client.PutAsJsonAsync($"/api/v1/books/{bookId}", request); + + // Assert + Assert.Equal(HttpStatusCode.Forbidden, response.StatusCode); + string content = await response.Content.ReadAsStringAsync(); + using JsonDocument problemDetails = JsonDocument.Parse(content); + Assert.Equal("General.Unauthorized", problemDetails.RootElement.GetProperty("title").GetString()); + Assert.Equal("NotAuthorized", problemDetails.RootElement.GetProperty("detail").GetString()); + } + + [Fact] + public async Task UpdateBook_WhenCalledWithInvalidBody_ShouldReturnUnprocessableEntity() + { + // Arrange + Guid userId = GetCurrentUserId(); + (_, Guid bookId) = await SeedLibraryAndBookAsync(userId, "Original Title"); + UpdateBookRequest request = _requestBookFixture.Create(id: bookId, metadata: _writtenContentMetadataDtoFixture.Create(includeTitle: false)); + + // Act + HttpResponseMessage response = await _client.PutAsJsonAsync($"/api/v1/books/{bookId}", request); + + // Assert + Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode); + string content = await response.Content.ReadAsStringAsync(); + using JsonDocument problemDetails = JsonDocument.Parse(content); + Assert.Equal("General.Validation", problemDetails.RootElement.GetProperty("title").GetString()); + Assert.Contains("TitleCannotBeEmpty", content, StringComparison.OrdinalIgnoreCase); + } + + [Fact] + public async Task UpdateBook_WhenUnauthorized_ShouldReturnUnauthorizedResult() + { + // Arrange + HttpClient unauthenticatedClient = _apiFactory.CreateClient(); + UpdateBookRequest request = _requestBookFixture.Create(); + + // Act + HttpResponseMessage response = await unauthenticatedClient.PutAsJsonAsync($"/api/v1/books/{Guid.NewGuid()}", request); + + // Assert + Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode); + } + + /// + /// Seeds a library owned by and a book belonging to it. + /// + /// The Id of the user that owns the library. + /// The title of the seeded book. + /// The Ids of the seeded library and book. + private async Task<(Guid libraryId, Guid bookId)> SeedLibraryAndBookAsync(Guid userId, string title) + { + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + Guid libraryId = Guid.NewGuid(); + Guid bookId = Guid.NewGuid(); + LibraryEntity library = _libraryEntityFixture.Create(id: libraryId, userId: userId, title: "Test Library", libraryType: LibraryType.EBook, contentLocations: []); + BookEntity book = _bookEntityFixture.Create(id: bookId, libraryId: libraryId, path: $"/books/{bookId:N}.epub", title: title, includeMetadata: false); + dbContext.Libraries.Add(library); + dbContext.Books.Add(book); + await dbContext.SaveChangesAsync(); + return (libraryId, bookId); + } + + /// + /// Seeds a user distinct from the authenticated test user and returns its Id. + /// + /// The Id of the seeded user and its username. + private async Task<(Guid userId, string username)> SeedOtherUserAsync() + { + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + Guid userId = Guid.NewGuid(); + string username = $"otheruser_{Guid.NewGuid()}"; + dbContext.Users.Add(_userEntityFixture.Create(id: userId, username: username, password: "TestPass123!")); + await dbContext.SaveChangesAsync(); + return (userId, username); + } + + /// + /// Gets the Id of the currently authenticated test user. + /// + /// The Id of the authenticated test user. + private Guid GetCurrentUserId() + { + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + UserEntity user = dbContext.Users.First(user => user.Username == _apiFactory.TestUsername); + return user.Id; + } + + /// + /// Disposes API factory resources. + /// + public async Task DisposeAsync() + { + await _apiFactory.RemoveTestUserAsync(); + } +} diff --git a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/UpdateBookCover/UpdateBookCoverEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/UpdateBookCover/UpdateBookCoverEndpointTests.cs new file mode 100644 index 00000000..793b9e09 --- /dev/null +++ b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/UpdateBookCover/UpdateBookCoverEndpointTests.cs @@ -0,0 +1,266 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Entities.MediaContributors; +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.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.UsersManagement; +using Lumina.DataAccess.Core.UoW; +using Lumina.Domain.SharedKernel.Common.Enums.BookLibrary; +using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; +using Lumina.Presentation.Api.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.Books.UpdateBookCover; +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.Net.Http.Headers; +using System.Text.Json; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Api.IntegrationTests.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.Books.UpdateBookCover; + +/// +/// Contains integration tests for the class. +/// +[ExcludeFromCodeCoverage] +public class UpdateBookCoverEndpointTests : IClassFixture, IAsyncLifetime +{ + private HttpClient _client; + private readonly AuthenticatedLuminaApiFactory _apiFactory; + private readonly BookEntityFixture _bookEntityFixture = new(); + private readonly BookArtworkEntityFixture _bookArtworkEntityFixture = new(); + private readonly LibraryEntityFixture _libraryEntityFixture = new(); + private readonly UserEntityFixture _userEntityFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + /// Injected in-memory API factory. + public UpdateBookCoverEndpointTests(AuthenticatedLuminaApiFactory apiFactory) + { + _client = apiFactory.CreateClient(); + _apiFactory = apiFactory; + } + + /// + /// Initializes authenticated API client. + /// + public async Task InitializeAsync() + { + _client = await _apiFactory.CreateAuthenticatedClientAsync(); + } + + [Fact] + public async Task UpdateBookCover_WhenCalledByOwnerWithValidImage_ShouldReplaceTheStoredCover() + { + // Arrange + Guid userId = GetCurrentUserId(); + (Guid libraryId, Guid bookId) = await SeedLibraryAndBookWithCoverAsync(userId, "/media/books/old-cover.jpg"); + + // Act + HttpResponseMessage response = await _client.PutAsync($"/api/v1/books/{bookId}/cover", CreateCoverForm("cover.png")); + + // Assert + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + string content = await response.Content.ReadAsStringAsync(); + string storedPath = JsonSerializer.Deserialize(content)!; + Assert.False(string.IsNullOrWhiteSpace(storedPath)); + Assert.Contains("cover.png", storedPath, StringComparison.OrdinalIgnoreCase); + + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + BookArtworkEntity coverArtwork = dbContext.Books + .SelectMany(book => book.BookArtwork) + .Single(artwork => artwork.BookId == bookId && artwork.ArtworkType == ArtworkType.Cover); + Assert.Equal(storedPath, coverArtwork.FileName); + Assert.Equal(ArtworkStatus.Enriched, coverArtwork.Status); + } + + [Fact] + public async Task UpdateBookCover_WhenBookHasNoExistingCover_ShouldCreateACoverArtwork() + { + // Arrange + Guid userId = GetCurrentUserId(); + (_, Guid bookId) = await SeedLibraryAndBookAsync(userId); + + // Act + HttpResponseMessage response = await _client.PutAsync($"/api/v1/books/{bookId}/cover", CreateCoverForm("cover.png")); + + // Assert + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + string content = await response.Content.ReadAsStringAsync(); + string storedPath = JsonSerializer.Deserialize(content)!; + Assert.False(string.IsNullOrWhiteSpace(storedPath)); + + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + BookArtworkEntity coverArtwork = dbContext.Books + .SelectMany(book => book.BookArtwork) + .Single(artwork => artwork.BookId == bookId && artwork.ArtworkType == ArtworkType.Cover); + Assert.Equal(storedPath, coverArtwork.FileName); + } + + [Fact] + public async Task UpdateBookCover_WhenBookDoesNotExist_ShouldReturnBookNotFoundProblem() + { + // Act + HttpResponseMessage response = await _client.PutAsync($"/api/v1/books/{Guid.NewGuid()}/cover", CreateCoverForm("cover.png")); + + // Assert + Assert.Equal(HttpStatusCode.NotFound, response.StatusCode); + string content = await response.Content.ReadAsStringAsync(); + using JsonDocument problemDetails = JsonDocument.Parse(content); + Assert.Equal("General.NotFound", problemDetails.RootElement.GetProperty("title").GetString()); + Assert.Equal("BookNotFound", problemDetails.RootElement.GetProperty("detail").GetString()); + } + + [Fact] + public async Task UpdateBookCover_WhenRouteIdIsNotParseable_ShouldReturnUnprocessableEntity() + { + // Act + HttpResponseMessage response = await _client.PutAsync($"/api/v1/books/not-a-guid/cover", CreateCoverForm("cover.png")); + + // Assert + Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode); + string content = await response.Content.ReadAsStringAsync(); + using JsonDocument problemDetails = JsonDocument.Parse(content); + Assert.Equal("General.Validation", problemDetails.RootElement.GetProperty("title").GetString()); + Assert.Contains("BookIdCannotBeEmpty", content, StringComparison.OrdinalIgnoreCase); + } + + [Fact] + public async Task UpdateBookCover_WhenBookBelongsToAnotherUserLibrary_ShouldReturnForbiddenProblem() + { + // Arrange + (Guid otherUserId, _) = await SeedOtherUserAsync(); + (_, Guid bookId) = await SeedLibraryAndBookAsync(otherUserId); + + // Act + HttpResponseMessage response = await _client.PutAsync($"/api/v1/books/{bookId}/cover", CreateCoverForm("cover.png")); + + // Assert + Assert.Equal(HttpStatusCode.Forbidden, response.StatusCode); + string content = await response.Content.ReadAsStringAsync(); + using JsonDocument problemDetails = JsonDocument.Parse(content); + Assert.Equal("General.Unauthorized", problemDetails.RootElement.GetProperty("title").GetString()); + Assert.Equal("NotAuthorized", problemDetails.RootElement.GetProperty("detail").GetString()); + } + + [Fact] + public async Task UpdateBookCover_WhenUnauthorized_ShouldReturnUnauthorizedResult() + { + // Arrange + HttpClient unauthenticatedClient = _apiFactory.CreateClient(); + + // Act + HttpResponseMessage response = await unauthenticatedClient.PutAsync($"/api/v1/books/{Guid.NewGuid()}/cover", CreateCoverForm("cover.png")); + + // Assert + Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode); + } + + /// + /// Creates a multipart form carrying a minimal PNG-like payload. + /// + /// The name of the uploaded file. + /// A configured instance. + private static MultipartFormDataContent CreateCoverForm(string fileName) + { + // The payload only needs to carry the PNG signature in its first bytes and exceed the header detection buffer. + byte[] payload = new byte[100]; + payload[0] = 137; + payload[1] = 80; + payload[2] = 78; + payload[3] = 71; + payload[4] = 13; + payload[5] = 10; + payload[6] = 26; + payload[7] = 10; + MultipartFormDataContent form = []; + ByteArrayContent fileContent = new(payload); + fileContent.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream"); + form.Add(fileContent, "cover", fileName); + return form; + } + + /// + /// Seeds a library owned by and a book with an existing cover belonging to it. + /// + /// The Id of the user that owns the library. + /// The relative path of the existing cover of the book. + /// The Ids of the seeded library and book. + private async Task<(Guid libraryId, Guid bookId)> SeedLibraryAndBookWithCoverAsync(Guid userId, string existingCoverFileName) + { + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + Guid libraryId = Guid.NewGuid(); + Guid bookId = Guid.NewGuid(); + LibraryEntity library = _libraryEntityFixture.Create(id: libraryId, userId: userId, title: "Test Library", libraryType: LibraryType.EBook, contentLocations: []); + BookEntity book = _bookEntityFixture.Create(id: bookId, libraryId: libraryId, path: $"/books/{bookId:N}.epub", title: "Test Book", includeMetadata: false); + BookArtworkEntity existingCover = _bookArtworkEntityFixture.Create(bookId: bookId, artworkType: ArtworkType.Cover, fileName: existingCoverFileName, status: ArtworkStatus.Enriched); + book.BookArtwork.Add(existingCover); + dbContext.Libraries.Add(library); + dbContext.Books.Add(book); + await dbContext.SaveChangesAsync(); + return (libraryId, bookId); + } + + /// + /// Seeds a library owned by and a book belonging to it. + /// + /// The Id of the user that owns the library. + /// The Ids of the seeded library and book. + private async Task<(Guid libraryId, Guid bookId)> SeedLibraryAndBookAsync(Guid userId) + { + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + Guid libraryId = Guid.NewGuid(); + Guid bookId = Guid.NewGuid(); + LibraryEntity library = _libraryEntityFixture.Create(id: libraryId, userId: userId, title: "Test Library", libraryType: LibraryType.EBook, contentLocations: []); + BookEntity book = _bookEntityFixture.Create(id: bookId, libraryId: libraryId, path: $"/books/{bookId:N}.epub", title: "Test Book", includeMetadata: false); + dbContext.Libraries.Add(library); + dbContext.Books.Add(book); + await dbContext.SaveChangesAsync(); + return (libraryId, bookId); + } + + /// + /// Seeds a user distinct from the authenticated test user and returns its Id. + /// + /// The Id of the seeded user and its username. + private async Task<(Guid userId, string username)> SeedOtherUserAsync() + { + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + Guid userId = Guid.NewGuid(); + string username = $"otheruser_{Guid.NewGuid()}"; + dbContext.Users.Add(_userEntityFixture.Create(id: userId, username: username, password: "TestPass123!")); + await dbContext.SaveChangesAsync(); + return (userId, username); + } + + /// + /// Gets the Id of the currently authenticated test user. + /// + /// The Id of the authenticated test user. + private Guid GetCurrentUserId() + { + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + UserEntity user = dbContext.Users.First(user => user.Username == _apiFactory.TestUsername); + return user.Id; + } + + /// + /// Disposes API factory resources. + /// + public async Task DisposeAsync() + { + await _apiFactory.RemoveTestUserAsync(); + } +} diff --git a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Plugins/GetLibraryBookReaders/GetLibraryBookReadersEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Plugins/GetLibraryBookReaders/GetLibraryBookReadersEndpointTests.cs index 3b78fff4..f6c52213 100644 --- a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Plugins/GetLibraryBookReaders/GetLibraryBookReadersEndpointTests.cs +++ b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Plugins/GetLibraryBookReaders/GetLibraryBookReadersEndpointTests.cs @@ -23,7 +23,7 @@ using System.Threading.Tasks; namespace Lumina.Presentation.Api.IntegrationTests.Core.Endpoints.Plugins.GetLibraryBookReaders; /// -/// Contains integration tests for the /libraries/{libraryId}/book-readers route. +/// Contains integration tests for the class. /// [ExcludeFromCodeCoverage] public class GetLibraryBookReadersEndpointTests : IClassFixture, IAsyncLifetime diff --git a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Plugins/SetLibraryBookReaderEnabled/SetLibraryBookReaderEnabledEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Plugins/SetLibraryBookReaderEnabled/SetLibraryBookReaderEnabledEndpointTests.cs index 8003d20f..17dff07f 100644 --- a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Plugins/SetLibraryBookReaderEnabled/SetLibraryBookReaderEnabledEndpointTests.cs +++ b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Plugins/SetLibraryBookReaderEnabled/SetLibraryBookReaderEnabledEndpointTests.cs @@ -23,7 +23,7 @@ using System.Threading.Tasks; namespace Lumina.Presentation.Api.IntegrationTests.Core.Endpoints.Plugins.SetLibraryBookReaderEnabled; /// -/// Contains integration tests for the /libraries/{libraryId}/book-readers/{pluginId}/enabled route. +/// Contains integration tests for the class. /// [ExcludeFromCodeCoverage] public class SetLibraryBookReaderEnabledEndpointTests : IClassFixture, IAsyncLifetime diff --git a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Admin/Authorization/Roles/AddRole/AddRoleEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Admin/Authorization/Roles/AddRole/AddRoleEndpointTests.cs index bc029b1f..b9ac6557 100644 --- a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Admin/Authorization/Roles/AddRole/AddRoleEndpointTests.cs +++ b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Admin/Authorization/Roles/AddRole/AddRoleEndpointTests.cs @@ -19,7 +19,7 @@ using System.Threading.Tasks; namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.Admin.Authorization.Roles.AddRole; /// -/// Contains integration tests for the /{culture}/admin/api-create-role route served by the class. +/// Contains integration tests for the class. /// [ExcludeFromCodeCoverage] public class AddRoleEndpointTests : IClassFixture diff --git a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Admin/Authorization/Roles/DeleteRole/DeleteRoleEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Admin/Authorization/Roles/DeleteRole/DeleteRoleEndpointTests.cs index 963ad8f2..c6c11c9d 100644 --- a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Admin/Authorization/Roles/DeleteRole/DeleteRoleEndpointTests.cs +++ b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Admin/Authorization/Roles/DeleteRole/DeleteRoleEndpointTests.cs @@ -16,7 +16,7 @@ using System.Threading.Tasks; namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.Admin.Authorization.Roles.DeleteRole; /// -/// Contains integration tests for the /{culture}/admin/api-delete-role/{roleId} route served by the class. +/// Contains integration tests for the class. /// [ExcludeFromCodeCoverage] public class DeleteRoleEndpointTests : IClassFixture diff --git a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Admin/Authorization/Roles/GetRolePermissions/GetRolePermissionsEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Admin/Authorization/Roles/GetRolePermissions/GetRolePermissionsEndpointTests.cs index 50c497e1..7b743588 100644 --- a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Admin/Authorization/Roles/GetRolePermissions/GetRolePermissionsEndpointTests.cs +++ b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Admin/Authorization/Roles/GetRolePermissions/GetRolePermissionsEndpointTests.cs @@ -17,7 +17,7 @@ using System.Threading.Tasks; namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.Admin.Authorization.Roles.GetRolePermissions; /// -/// Contains integration tests for the /{culture}/admin/api-get-permissions-by-role-id/{roleId} route served by the class. +/// Contains integration tests for the class. /// [ExcludeFromCodeCoverage] public class GetRolePermissionsEndpointTests : IClassFixture diff --git a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Admin/Authorization/Roles/GetRoles/GetRolesEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Admin/Authorization/Roles/GetRoles/GetRolesEndpointTests.cs index 9a47f7bf..3946e36a 100644 --- a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Admin/Authorization/Roles/GetRoles/GetRolesEndpointTests.cs +++ b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Admin/Authorization/Roles/GetRoles/GetRolesEndpointTests.cs @@ -16,7 +16,7 @@ using System.Threading.Tasks; namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.Admin.Authorization.Roles.GetRoles; /// -/// Contains integration tests for the /{culture}/admin/api-get-roles route served by the class. +/// Contains integration tests for the class. /// [ExcludeFromCodeCoverage] public class GetRolesEndpointTests : IClassFixture diff --git a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Admin/Authorization/Roles/UpdateRole/UpdateRoleEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Admin/Authorization/Roles/UpdateRole/UpdateRoleEndpointTests.cs index 34b80bc2..42cb041f 100644 --- a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Admin/Authorization/Roles/UpdateRole/UpdateRoleEndpointTests.cs +++ b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Admin/Authorization/Roles/UpdateRole/UpdateRoleEndpointTests.cs @@ -19,7 +19,7 @@ using System.Threading.Tasks; namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.Admin.Authorization.Roles.UpdateRole; /// -/// Contains integration tests for the /{culture}/admin/api-update-role route served by the class. +/// Contains integration tests for the class. /// [ExcludeFromCodeCoverage] public class UpdateRoleEndpointTests : IClassFixture diff --git a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Admin/ManagePermissions/ManagePermissionsViewEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Admin/ManagePermissions/ManagePermissionsViewEndpointTests.cs index def9fd02..639bf999 100644 --- a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Admin/ManagePermissions/ManagePermissionsViewEndpointTests.cs +++ b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Admin/ManagePermissions/ManagePermissionsViewEndpointTests.cs @@ -17,7 +17,7 @@ using System.Threading.Tasks; namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.Admin.ManagePermissions; /// -/// Contains integration tests for the /{culture}/admin/manage-permissions route served by the class. +/// Contains integration tests for the class. /// [ExcludeFromCodeCoverage] public class ManagePermissionsViewEndpointTests : IClassFixture diff --git a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Admin/ManageRoles/ManageRolesViewEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Admin/ManageRoles/ManageRolesViewEndpointTests.cs index 53bf006b..b059e5aa 100644 --- a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Admin/ManageRoles/ManageRolesViewEndpointTests.cs +++ b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Admin/ManageRoles/ManageRolesViewEndpointTests.cs @@ -15,7 +15,7 @@ using System.Threading.Tasks; namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.Admin.ManageRoles; /// -/// Contains integration tests for the /{culture}/admin/manage-roles route served by the class. +/// Contains integration tests for the class. /// [ExcludeFromCodeCoverage] public class ManageRolesViewEndpointTests : IClassFixture diff --git a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Admin/Scheduler/AddScheduledJob/AddScheduledJobEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Admin/Scheduler/AddScheduledJob/AddScheduledJobEndpointTests.cs index bef4e989..70f64fe9 100644 --- a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Admin/Scheduler/AddScheduledJob/AddScheduledJobEndpointTests.cs +++ b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Admin/Scheduler/AddScheduledJob/AddScheduledJobEndpointTests.cs @@ -18,7 +18,7 @@ using System.Threading.Tasks; namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.Admin.Scheduler.AddScheduledJob; /// -/// Contains integration tests for the /{culture}/admin/api-scheduled-jobs/add route served by the class. +/// Contains integration tests for the class. /// [ExcludeFromCodeCoverage] public class AddScheduledJobEndpointTests : IClassFixture diff --git a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Admin/Scheduler/FireScheduledJob/FireScheduledJobEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Admin/Scheduler/FireScheduledJob/FireScheduledJobEndpointTests.cs index 5e47ba56..c7938435 100644 --- a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Admin/Scheduler/FireScheduledJob/FireScheduledJobEndpointTests.cs +++ b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Admin/Scheduler/FireScheduledJob/FireScheduledJobEndpointTests.cs @@ -17,7 +17,7 @@ using System.Threading.Tasks; namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.Admin.Scheduler.FireScheduledJob; /// -/// Contains integration tests for the /{culture}/admin/api-scheduled-jobs/{scheduledJobId}/fire route served by the class. +/// Contains integration tests for the class. /// [ExcludeFromCodeCoverage] public class FireScheduledJobEndpointTests : IClassFixture diff --git a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Admin/Scheduler/GetScheduledJobHistory/GetScheduledJobHistoryEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Admin/Scheduler/GetScheduledJobHistory/GetScheduledJobHistoryEndpointTests.cs index 694a0d6b..b4389e6c 100644 --- a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Admin/Scheduler/GetScheduledJobHistory/GetScheduledJobHistoryEndpointTests.cs +++ b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Admin/Scheduler/GetScheduledJobHistory/GetScheduledJobHistoryEndpointTests.cs @@ -15,7 +15,7 @@ using System.Threading.Tasks; namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.Admin.Scheduler.GetScheduledJobHistory; /// -/// Contains integration tests for the /{culture}/admin/api-scheduled-jobs/history route served by the class. +/// Contains integration tests for the class. /// [ExcludeFromCodeCoverage] public class GetScheduledJobHistoryEndpointTests : IClassFixture diff --git a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Admin/Scheduler/GetScheduledJobs/GetScheduledJobsEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Admin/Scheduler/GetScheduledJobs/GetScheduledJobsEndpointTests.cs index 591527c7..58280bc6 100644 --- a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Admin/Scheduler/GetScheduledJobs/GetScheduledJobsEndpointTests.cs +++ b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Admin/Scheduler/GetScheduledJobs/GetScheduledJobsEndpointTests.cs @@ -15,7 +15,7 @@ using System.Threading.Tasks; namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.Admin.Scheduler.GetScheduledJobs; /// -/// Contains integration tests for the /{culture}/admin/api-scheduled-jobs route served by the class. +/// Contains integration tests for the class. /// [ExcludeFromCodeCoverage] public class GetScheduledJobsEndpointTests : IClassFixture diff --git a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Admin/Scheduler/GetSchedulerDisplayPreferences/GetSchedulerDisplayPreferencesEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Admin/Scheduler/GetSchedulerDisplayPreferences/GetSchedulerDisplayPreferencesEndpointTests.cs index eff20ef2..67d32ba4 100644 --- a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Admin/Scheduler/GetSchedulerDisplayPreferences/GetSchedulerDisplayPreferencesEndpointTests.cs +++ b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Admin/Scheduler/GetSchedulerDisplayPreferences/GetSchedulerDisplayPreferencesEndpointTests.cs @@ -15,7 +15,7 @@ using System.Threading.Tasks; namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.Admin.Scheduler.GetSchedulerDisplayPreferences; /// -/// Contains integration tests for the /{culture}/admin/api-scheduled-jobs/display-preferences route served by the class. +/// Contains integration tests for the class. /// [ExcludeFromCodeCoverage] public class GetSchedulerDisplayPreferencesEndpointTests : IClassFixture diff --git a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Admin/Scheduler/RemoveScheduledJob/RemoveScheduledJobEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Admin/Scheduler/RemoveScheduledJob/RemoveScheduledJobEndpointTests.cs index 7a71b990..ad008a21 100644 --- a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Admin/Scheduler/RemoveScheduledJob/RemoveScheduledJobEndpointTests.cs +++ b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Admin/Scheduler/RemoveScheduledJob/RemoveScheduledJobEndpointTests.cs @@ -16,7 +16,7 @@ using System.Threading.Tasks; namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.Admin.Scheduler.RemoveScheduledJob; /// -/// Contains integration tests for the /{culture}/admin/api-scheduled-jobs/{scheduledJobId} route served by the class. +/// Contains integration tests for the class. /// [ExcludeFromCodeCoverage] public class RemoveScheduledJobEndpointTests : IClassFixture diff --git a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Admin/Scheduler/SchedulerIndexViewEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Admin/Scheduler/SchedulerIndexViewEndpointTests.cs index ce0d355c..f6e30b3f 100644 --- a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Admin/Scheduler/SchedulerIndexViewEndpointTests.cs +++ b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Admin/Scheduler/SchedulerIndexViewEndpointTests.cs @@ -13,7 +13,7 @@ using System.Threading.Tasks; namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.Admin.Scheduler; /// -/// Contains integration tests for the /{culture}/admin/scheduled-jobs route served by the class. +/// Contains integration tests for the class. /// [ExcludeFromCodeCoverage] public class SchedulerIndexViewEndpointTests : IClassFixture diff --git a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Admin/Scheduler/StartScheduledJob/StartScheduledJobEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Admin/Scheduler/StartScheduledJob/StartScheduledJobEndpointTests.cs index 1d4da095..2ed51ce3 100644 --- a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Admin/Scheduler/StartScheduledJob/StartScheduledJobEndpointTests.cs +++ b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Admin/Scheduler/StartScheduledJob/StartScheduledJobEndpointTests.cs @@ -16,7 +16,7 @@ using System.Threading.Tasks; namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.Admin.Scheduler.StartScheduledJob; /// -/// Contains integration tests for the /{culture}/admin/api-scheduled-jobs/{scheduledJobId}/start route served by the class. +/// Contains integration tests for the class. /// [ExcludeFromCodeCoverage] public class StartScheduledJobEndpointTests : IClassFixture diff --git a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Admin/Scheduler/StopScheduledJob/StopScheduledJobEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Admin/Scheduler/StopScheduledJob/StopScheduledJobEndpointTests.cs index c8f04969..ab8c19f4 100644 --- a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Admin/Scheduler/StopScheduledJob/StopScheduledJobEndpointTests.cs +++ b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Admin/Scheduler/StopScheduledJob/StopScheduledJobEndpointTests.cs @@ -16,7 +16,7 @@ using System.Threading.Tasks; namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.Admin.Scheduler.StopScheduledJob; /// -/// Contains integration tests for the /{culture}/admin/api-scheduled-jobs/{scheduledJobId}/stop route served by the class. +/// Contains integration tests for the class. /// [ExcludeFromCodeCoverage] public class StopScheduledJobEndpointTests : IClassFixture diff --git a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Admin/Scheduler/UpdateSchedulerDisplayPreferences/UpdateSchedulerDisplayPreferencesEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Admin/Scheduler/UpdateSchedulerDisplayPreferences/UpdateSchedulerDisplayPreferencesEndpointTests.cs index 1e1d5757..942317b2 100644 --- a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Admin/Scheduler/UpdateSchedulerDisplayPreferences/UpdateSchedulerDisplayPreferencesEndpointTests.cs +++ b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Admin/Scheduler/UpdateSchedulerDisplayPreferences/UpdateSchedulerDisplayPreferencesEndpointTests.cs @@ -16,7 +16,7 @@ using System.Threading.Tasks; namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.Admin.Scheduler.UpdateSchedulerDisplayPreferences; /// -/// Contains integration tests for the /{culture}/admin/api-scheduled-jobs/display-preferences route served by the class. +/// Contains integration tests for the class. /// [ExcludeFromCodeCoverage] public class UpdateSchedulerDisplayPreferencesEndpointTests : IClassFixture diff --git a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Admin/Themes/DeleteTheme/DeleteThemeEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Admin/Themes/DeleteTheme/DeleteThemeEndpointTests.cs index 1078a03c..eb726407 100644 --- a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Admin/Themes/DeleteTheme/DeleteThemeEndpointTests.cs +++ b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Admin/Themes/DeleteTheme/DeleteThemeEndpointTests.cs @@ -14,7 +14,7 @@ using System.Threading.Tasks; namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.Admin.Themes.DeleteTheme; /// -/// Contains integration tests for the /{culture}/admin/themes/api-delete-theme/{themeId} route served by the class. +/// Contains integration tests for the class. /// [ExcludeFromCodeCoverage] public class DeleteThemeEndpointTests : IClassFixture diff --git a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Admin/Themes/DownloadTheme/DownloadThemeEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Admin/Themes/DownloadTheme/DownloadThemeEndpointTests.cs index a4f93086..9b4b6025 100644 --- a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Admin/Themes/DownloadTheme/DownloadThemeEndpointTests.cs +++ b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Admin/Themes/DownloadTheme/DownloadThemeEndpointTests.cs @@ -13,7 +13,7 @@ using System.Threading.Tasks; namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.Admin.Themes.DownloadTheme; /// -/// Contains integration tests for the /{culture}/admin/themes/api-download-theme/{themeId} route served by the class. +/// Contains integration tests for the class. /// [ExcludeFromCodeCoverage] public class DownloadThemeEndpointTests : IClassFixture diff --git a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Admin/Themes/GetThemes/GetThemesEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Admin/Themes/GetThemes/GetThemesEndpointTests.cs index 38c8b797..7da44346 100644 --- a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Admin/Themes/GetThemes/GetThemesEndpointTests.cs +++ b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Admin/Themes/GetThemes/GetThemesEndpointTests.cs @@ -16,7 +16,7 @@ using System.Threading.Tasks; namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.Admin.Themes.GetThemes; /// -/// Contains integration tests for the /{culture}/admin/themes/api-get-themes route served by the class. +/// Contains integration tests for the class. /// [ExcludeFromCodeCoverage] public class GetThemesEndpointTests : IClassFixture diff --git a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Admin/Themes/InstallTheme/InstallThemeEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Admin/Themes/InstallTheme/InstallThemeEndpointTests.cs index ea838726..75b39d94 100644 --- a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Admin/Themes/InstallTheme/InstallThemeEndpointTests.cs +++ b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Admin/Themes/InstallTheme/InstallThemeEndpointTests.cs @@ -16,7 +16,7 @@ using System.Threading.Tasks; namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.Admin.Themes.InstallTheme; /// -/// Contains integration tests for the /{culture}/admin/themes/api-install-theme route served by the class. +/// Contains integration tests for the class. /// [ExcludeFromCodeCoverage] public class InstallThemeEndpointTests : IClassFixture diff --git a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Admin/Themes/RestoreTheme/RestoreThemeEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Admin/Themes/RestoreTheme/RestoreThemeEndpointTests.cs index 37b2a082..706407da 100644 --- a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Admin/Themes/RestoreTheme/RestoreThemeEndpointTests.cs +++ b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Admin/Themes/RestoreTheme/RestoreThemeEndpointTests.cs @@ -17,7 +17,7 @@ using System.Threading.Tasks; namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.Admin.Themes.RestoreTheme; /// -/// Contains integration tests for the /{culture}/admin/themes/api-restore-theme/{themeId} route served by the class. +/// Contains integration tests for the class. /// [ExcludeFromCodeCoverage] public class RestoreThemeEndpointTests : IClassFixture diff --git a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Admin/Themes/SetCurrentTheme/SetCurrentThemeEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Admin/Themes/SetCurrentTheme/SetCurrentThemeEndpointTests.cs index ec36ed94..2bf639fd 100644 --- a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Admin/Themes/SetCurrentTheme/SetCurrentThemeEndpointTests.cs +++ b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Admin/Themes/SetCurrentTheme/SetCurrentThemeEndpointTests.cs @@ -18,7 +18,7 @@ using System.Threading.Tasks; namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.Admin.Themes.SetCurrentTheme; /// -/// Contains integration tests for the /{culture}/admin/themes/api-set-current-theme route served by the class. +/// Contains integration tests for the class. /// [ExcludeFromCodeCoverage] public class SetCurrentThemeEndpointTests : IClassFixture diff --git a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Admin/Themes/ThemesIndexViewEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Admin/Themes/ThemesIndexViewEndpointTests.cs index f9ab2759..9e77e2f5 100644 --- a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Admin/Themes/ThemesIndexViewEndpointTests.cs +++ b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Admin/Themes/ThemesIndexViewEndpointTests.cs @@ -13,7 +13,7 @@ using System.Threading.Tasks; namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.Admin.Themes; /// -/// Contains integration tests for the /{culture}/admin/manage-themes route served by the class. +/// Contains integration tests for the class. /// [ExcludeFromCodeCoverage] public class ThemesIndexViewEndpointTests : IClassFixture diff --git a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Admin/UsersManagement/Authorization/GetUserPermissions/GetUserPermissionsEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Admin/UsersManagement/Authorization/GetUserPermissions/GetUserPermissionsEndpointTests.cs index 781e3dd4..15dfefff 100644 --- a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Admin/UsersManagement/Authorization/GetUserPermissions/GetUserPermissionsEndpointTests.cs +++ b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Admin/UsersManagement/Authorization/GetUserPermissions/GetUserPermissionsEndpointTests.cs @@ -17,7 +17,7 @@ using System.Threading.Tasks; namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.Admin.UsersManagement.Authorization.GetUserPermissions; /// -/// Contains integration tests for the /{culture}/admin/api-get-permissions-by-user-id/{userId} route served by the class. +/// Contains integration tests for the class. /// [ExcludeFromCodeCoverage] public class GetUserPermissionsEndpointTests : IClassFixture diff --git a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Admin/UsersManagement/Authorization/GetUserRole/GetUserRoleEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Admin/UsersManagement/Authorization/GetUserRole/GetUserRoleEndpointTests.cs index d2dab495..9f0bca43 100644 --- a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Admin/UsersManagement/Authorization/GetUserRole/GetUserRoleEndpointTests.cs +++ b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Admin/UsersManagement/Authorization/GetUserRole/GetUserRoleEndpointTests.cs @@ -17,7 +17,7 @@ using System.Threading.Tasks; namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.Admin.UsersManagement.Authorization.GetUserRole; /// -/// Contains integration tests for the /{culture}/admin/api-get-role-by-user-id/{userId} route served by the class. +/// Contains integration tests for the class. /// [ExcludeFromCodeCoverage] public class GetUserRoleEndpointTests : IClassFixture diff --git a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Admin/UsersManagement/Authorization/UpdateUserRoleAndPermissions/UpdateUserRoleAndPermissionsEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Admin/UsersManagement/Authorization/UpdateUserRoleAndPermissions/UpdateUserRoleAndPermissionsEndpointTests.cs index 90843ed4..70f13d90 100644 --- a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Admin/UsersManagement/Authorization/UpdateUserRoleAndPermissions/UpdateUserRoleAndPermissionsEndpointTests.cs +++ b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Admin/UsersManagement/Authorization/UpdateUserRoleAndPermissions/UpdateUserRoleAndPermissionsEndpointTests.cs @@ -19,7 +19,7 @@ using System.Threading.Tasks; namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.Admin.UsersManagement.Authorization.UpdateUserRoleAndPermissions; /// -/// Contains integration tests for the /{culture}/admin/api-update-user-authorization route served by the class. +/// Contains integration tests for the class. /// [ExcludeFromCodeCoverage] public class UpdateUserRoleAndPermissionsEndpointTests : IClassFixture diff --git a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/FileSystemManagement/Directories/GetDirectories/GetDirectoriesEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/FileSystemManagement/Directories/GetDirectories/GetDirectoriesEndpointTests.cs index c1ff40b9..543c9b9f 100644 --- a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/FileSystemManagement/Directories/GetDirectories/GetDirectoriesEndpointTests.cs +++ b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/FileSystemManagement/Directories/GetDirectories/GetDirectoriesEndpointTests.cs @@ -16,7 +16,7 @@ using System.Threading.Tasks; namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.FileSystemManagement.Directories.GetDirectories; /// -/// Contains integration tests for the /directories/api-get-directories route served by the class. +/// Contains integration tests for the class. /// [ExcludeFromCodeCoverage] public class GetDirectoriesEndpointTests : IClassFixture diff --git a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/FileSystemManagement/Drives/GetDrives/GetDrivesEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/FileSystemManagement/Drives/GetDrives/GetDrivesEndpointTests.cs index 07c7e66c..f7f4a926 100644 --- a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/FileSystemManagement/Drives/GetDrives/GetDrivesEndpointTests.cs +++ b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/FileSystemManagement/Drives/GetDrives/GetDrivesEndpointTests.cs @@ -15,7 +15,7 @@ using System.Threading.Tasks; namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.FileSystemManagement.Drives.GetDrives; /// -/// Contains integration tests for the /drives/api-get-drives route served by the class. +/// Contains integration tests for the class. /// [ExcludeFromCodeCoverage] public class GetDrivesEndpointTests : IClassFixture diff --git a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/FileSystemManagement/FileSystem/GetType/GetTypeEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/FileSystemManagement/FileSystem/GetType/GetTypeEndpointTests.cs index f2153bc0..1db3b0c2 100644 --- a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/FileSystemManagement/FileSystem/GetType/GetTypeEndpointTests.cs +++ b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/FileSystemManagement/FileSystem/GetType/GetTypeEndpointTests.cs @@ -15,7 +15,7 @@ using System.Threading.Tasks; namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.FileSystemManagement.FileSystem.GetType; /// -/// Contains integration tests for the /file-system/api-get-type route served by the class. +/// Contains integration tests for the class. /// [ExcludeFromCodeCoverage] public class GetTypeEndpointTests : IClassFixture diff --git a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/FileSystemManagement/Files/GetFiles/GetFilesEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/FileSystemManagement/Files/GetFiles/GetFilesEndpointTests.cs index cc2ccee9..bd562e06 100644 --- a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/FileSystemManagement/Files/GetFiles/GetFilesEndpointTests.cs +++ b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/FileSystemManagement/Files/GetFiles/GetFilesEndpointTests.cs @@ -16,7 +16,7 @@ using System.Threading.Tasks; namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.FileSystemManagement.Files.GetFiles; /// -/// Contains integration tests for the /files/api-get-files route served by the class. +/// Contains integration tests for the class. /// [ExcludeFromCodeCoverage] public class GetFilesEndpointTests : IClassFixture diff --git a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/FileSystemManagement/Files/GetTreeFiles/GetTreeFilesEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/FileSystemManagement/Files/GetTreeFiles/GetTreeFilesEndpointTests.cs index b391ad50..1ec83afc 100644 --- a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/FileSystemManagement/Files/GetTreeFiles/GetTreeFilesEndpointTests.cs +++ b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/FileSystemManagement/Files/GetTreeFiles/GetTreeFilesEndpointTests.cs @@ -16,7 +16,7 @@ using System.Threading.Tasks; namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.FileSystemManagement.Files.GetTreeFiles; /// -/// Contains integration tests for the /files/api-get-tree-files route served by the class. +/// Contains integration tests for the class. /// [ExcludeFromCodeCoverage] public class GetTreeFilesEndpointTests : IClassFixture diff --git a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/FileSystemManagement/Path/CheckPathExists/CheckPathExistsEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/FileSystemManagement/Path/CheckPathExists/CheckPathExistsEndpointTests.cs index 835e0471..3e95d5b2 100644 --- a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/FileSystemManagement/Path/CheckPathExists/CheckPathExistsEndpointTests.cs +++ b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/FileSystemManagement/Path/CheckPathExists/CheckPathExistsEndpointTests.cs @@ -15,7 +15,7 @@ using System.Threading.Tasks; namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.FileSystemManagement.Path.CheckPathExists; /// -/// Contains integration tests for the /path/api-check-path-exists route served by the class. +/// Contains integration tests for the class. /// [ExcludeFromCodeCoverage] public class CheckPathExistsEndpointTests : IClassFixture diff --git a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/FileSystemManagement/Path/GetPathParent/GetPathParentEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/FileSystemManagement/Path/GetPathParent/GetPathParentEndpointTests.cs index f3c3d81e..f326b8ca 100644 --- a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/FileSystemManagement/Path/GetPathParent/GetPathParentEndpointTests.cs +++ b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/FileSystemManagement/Path/GetPathParent/GetPathParentEndpointTests.cs @@ -16,7 +16,7 @@ using System.Threading.Tasks; namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.FileSystemManagement.Path.GetPathParent; /// -/// Contains integration tests for the /path/api-get-path-parent route served by the class. +/// Contains integration tests for the class. /// [ExcludeFromCodeCoverage] public class GetPathParentEndpointTests : IClassFixture diff --git a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/FileSystemManagement/Path/GetPathRoot/GetPathRootEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/FileSystemManagement/Path/GetPathRoot/GetPathRootEndpointTests.cs index 5aa67b41..eb485f7e 100644 --- a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/FileSystemManagement/Path/GetPathRoot/GetPathRootEndpointTests.cs +++ b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/FileSystemManagement/Path/GetPathRoot/GetPathRootEndpointTests.cs @@ -15,7 +15,7 @@ using System.Threading.Tasks; namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.FileSystemManagement.Path.GetPathRoot; /// -/// Contains integration tests for the /path/api-get-path-root route served by the class. +/// Contains integration tests for the class. /// [ExcludeFromCodeCoverage] public class GetPathRootEndpointTests : IClassFixture diff --git a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/FileSystemManagement/Path/GetPathSeparator/GetPathSeparatorEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/FileSystemManagement/Path/GetPathSeparator/GetPathSeparatorEndpointTests.cs index c3d971da..f14ce4f0 100644 --- a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/FileSystemManagement/Path/GetPathSeparator/GetPathSeparatorEndpointTests.cs +++ b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/FileSystemManagement/Path/GetPathSeparator/GetPathSeparatorEndpointTests.cs @@ -14,7 +14,7 @@ using System.Threading.Tasks; namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.FileSystemManagement.Path.GetPathSeparator; /// -/// Contains integration tests for the /path/api-get-path-separator route served by the class. +/// Contains integration tests for the class. /// [ExcludeFromCodeCoverage] public class GetPathSeparatorEndpointTests : IClassFixture diff --git a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/FileSystemManagement/Path/SplitPath/SplitPathEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/FileSystemManagement/Path/SplitPath/SplitPathEndpointTests.cs index 9099673a..f6ae9124 100644 --- a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/FileSystemManagement/Path/SplitPath/SplitPathEndpointTests.cs +++ b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/FileSystemManagement/Path/SplitPath/SplitPathEndpointTests.cs @@ -16,7 +16,7 @@ using System.Threading.Tasks; namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.FileSystemManagement.Path.SplitPath; /// -/// Contains integration tests for the /path/api-split route served by the class. +/// Contains integration tests for the class. /// [ExcludeFromCodeCoverage] public class SplitPathEndpointTests : IClassFixture diff --git a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/FileSystemManagement/Path/ValidatePath/ValidatePathEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/FileSystemManagement/Path/ValidatePath/ValidatePathEndpointTests.cs index 01313cdc..0dde4e47 100644 --- a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/FileSystemManagement/Path/ValidatePath/ValidatePathEndpointTests.cs +++ b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/FileSystemManagement/Path/ValidatePath/ValidatePathEndpointTests.cs @@ -15,7 +15,7 @@ using System.Threading.Tasks; namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.FileSystemManagement.Path.ValidatePath; /// -/// Contains integration tests for the /path/api-validate route served by the class. +/// Contains integration tests for the class. /// [ExcludeFromCodeCoverage] public class ValidatePathEndpointTests : IClassFixture diff --git a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Home/HomeErrorEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Home/HomeErrorEndpointTests.cs index 60fab458..5d62be31 100644 --- a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Home/HomeErrorEndpointTests.cs +++ b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Home/HomeErrorEndpointTests.cs @@ -11,7 +11,7 @@ using System.Threading.Tasks; namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.Home; /// -/// Contains integration tests for the /{culture}/error route served by the class. +/// Contains integration tests for the class. /// [ExcludeFromCodeCoverage] public class HomeErrorEndpointTests : IClassFixture diff --git a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Home/HomeIndexEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Home/HomeIndexEndpointTests.cs index 25f1c76d..598e4ccb 100644 --- a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Home/HomeIndexEndpointTests.cs +++ b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Home/HomeIndexEndpointTests.cs @@ -11,7 +11,7 @@ using System.Threading.Tasks; namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.Home; /// -/// Contains integration tests for the /{culture} and / routes served by the class. +/// Contains integration tests for the class. /// [ExcludeFromCodeCoverage] public class HomeIndexEndpointTests : IClassFixture diff --git a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Home/HomeNotFoundViewEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Home/HomeNotFoundViewEndpointTests.cs index 09b1028f..094491a5 100644 --- a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Home/HomeNotFoundViewEndpointTests.cs +++ b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Home/HomeNotFoundViewEndpointTests.cs @@ -11,7 +11,7 @@ using System.Threading.Tasks; namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.Home; /// -/// Contains integration tests for the /{culture}/not-found route served by the class. +/// Contains integration tests for the class. /// [ExcludeFromCodeCoverage] public class HomeNotFoundViewEndpointTests : IClassFixture diff --git a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Home/HomePrivacyEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Home/HomePrivacyEndpointTests.cs index 86ca4fb6..8e46da51 100644 --- a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Home/HomePrivacyEndpointTests.cs +++ b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Home/HomePrivacyEndpointTests.cs @@ -11,7 +11,7 @@ using System.Threading.Tasks; namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.Home; /// -/// Contains integration tests for the /{culture}/privacy route served by the class. +/// Contains integration tests for the class. /// [ExcludeFromCodeCoverage] public class HomePrivacyEndpointTests : IClassFixture diff --git a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/Management/AddLibrary/AddLibraryViewEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/Management/AddLibrary/AddLibraryViewEndpointTests.cs index 63ef8b49..4f706630 100644 --- a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/Management/AddLibrary/AddLibraryViewEndpointTests.cs +++ b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/Management/AddLibrary/AddLibraryViewEndpointTests.cs @@ -11,7 +11,7 @@ using System.Threading.Tasks; namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.Library.Management.AddLibrary; /// -/// Contains integration tests for the /{culture}/libraries/manage/item route served by the class. +/// Contains integration tests for the class. /// [ExcludeFromCodeCoverage] public class AddLibraryViewEndpointTests : IClassFixture diff --git a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/Management/CancelLibrariesScan/CancelLibrariesScanEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/Management/CancelLibrariesScan/CancelLibrariesScanEndpointTests.cs index 7e85cdb0..52c3d142 100644 --- a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/Management/CancelLibrariesScan/CancelLibrariesScanEndpointTests.cs +++ b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/Management/CancelLibrariesScan/CancelLibrariesScanEndpointTests.cs @@ -14,7 +14,7 @@ using System.Threading.Tasks; namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.Library.Management.CancelLibrariesScan; /// -/// Contains integration tests for the /{culture}/libraries/manage/api-cancel-libraries-scan route served by the class. +/// Contains integration tests for the class. /// [ExcludeFromCodeCoverage] public class CancelLibrariesScanEndpointTests : IClassFixture diff --git a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/Management/CancelLibraryScan/CancelLibraryScanEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/Management/CancelLibraryScan/CancelLibraryScanEndpointTests.cs index 93b3b4aa..f5331ad0 100644 --- a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/Management/CancelLibraryScan/CancelLibraryScanEndpointTests.cs +++ b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/Management/CancelLibraryScan/CancelLibraryScanEndpointTests.cs @@ -15,7 +15,7 @@ using System.Threading.Tasks; namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.Library.Management.CancelLibraryScan; /// -/// Contains integration tests for the /{culture}/libraries/manage/{{libraryId}}/api-cancel-library-scan/{{scanId}} route served by the class. +/// Contains integration tests for the class. /// [ExcludeFromCodeCoverage] public class CancelLibraryScanEndpointTests : IClassFixture diff --git a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/Management/DeleteLibrary/DeleteLibraryEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/Management/DeleteLibrary/DeleteLibraryEndpointTests.cs index 16c5b86f..23f206c3 100644 --- a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/Management/DeleteLibrary/DeleteLibraryEndpointTests.cs +++ b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/Management/DeleteLibrary/DeleteLibraryEndpointTests.cs @@ -15,7 +15,7 @@ using System.Threading.Tasks; namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.Library.Management.DeleteLibrary; /// -/// Contains integration tests for the /{culture}/libraries/manage/api-item/{{id}} route served by the class. +/// Contains integration tests for the class. /// [ExcludeFromCodeCoverage] public class DeleteLibraryEndpointTests : IClassFixture diff --git a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/Management/EditLibrary/EditLibraryViewEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/Management/EditLibrary/EditLibraryViewEndpointTests.cs index 456d5e11..08724f1e 100644 --- a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/Management/EditLibrary/EditLibraryViewEndpointTests.cs +++ b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/Management/EditLibrary/EditLibraryViewEndpointTests.cs @@ -17,7 +17,7 @@ using System.Threading.Tasks; namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.Library.Management.EditLibrary; /// -/// Contains integration tests for the /{culture}/libraries/manage/item/{{id}} route served by the class. +/// Contains integration tests for the class. /// [ExcludeFromCodeCoverage] public class EditLibraryViewEndpointTests : IClassFixture diff --git a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/Management/GetArtworkProviders/GetArtworkProvidersEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/Management/GetArtworkProviders/GetArtworkProvidersEndpointTests.cs index 3b87c503..774c4a74 100644 --- a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/Management/GetArtworkProviders/GetArtworkProvidersEndpointTests.cs +++ b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/Management/GetArtworkProviders/GetArtworkProvidersEndpointTests.cs @@ -16,7 +16,7 @@ using System.Threading.Tasks; namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.Library.Management.GetArtworkProviders; /// -/// Contains integration tests for the /{culture}/libraries/manage/api-get-artwork-providers/{{libraryId}} route served by the class. +/// Contains integration tests for the class. /// [ExcludeFromCodeCoverage] public class GetArtworkProvidersEndpointTests : IClassFixture diff --git a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/Management/GetBookReaders/GetBookReadersEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/Management/GetBookReaders/GetBookReadersEndpointTests.cs index d12480e9..5520979d 100644 --- a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/Management/GetBookReaders/GetBookReadersEndpointTests.cs +++ b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/Management/GetBookReaders/GetBookReadersEndpointTests.cs @@ -16,7 +16,7 @@ using System.Threading.Tasks; namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.Library.Management.GetBookReaders; /// -/// Contains integration tests for the /{culture}/libraries/manage/api-get-book-readers/{{libraryId}} route served by the class. +/// Contains integration tests for the class. /// [ExcludeFromCodeCoverage] public class GetBookReadersEndpointTests : IClassFixture diff --git a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/Management/GetEnabledLibraries/GetEnabledLibrariesEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/Management/GetEnabledLibraries/GetEnabledLibrariesEndpointTests.cs index 028e6e65..3521d45a 100644 --- a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/Management/GetEnabledLibraries/GetEnabledLibrariesEndpointTests.cs +++ b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/Management/GetEnabledLibraries/GetEnabledLibrariesEndpointTests.cs @@ -16,7 +16,7 @@ using System.Threading.Tasks; namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.Library.Management.GetEnabledLibraries; /// -/// Contains integration tests for the /{culture}/libraries/manage/api-get-enabled-libraries route served by the class. +/// Contains integration tests for the class. /// [ExcludeFromCodeCoverage] public class GetEnabledLibrariesEndpointTests : IClassFixture diff --git a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/Management/GetLibraries/GetLibrariesEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/Management/GetLibraries/GetLibrariesEndpointTests.cs index d032e6cd..ba171a32 100644 --- a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/Management/GetLibraries/GetLibrariesEndpointTests.cs +++ b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/Management/GetLibraries/GetLibrariesEndpointTests.cs @@ -15,7 +15,7 @@ using System.Threading.Tasks; namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.Library.Management.GetLibraries; /// -/// Contains integration tests for the /{culture}/libraries/manage/api-get-libraries route served by the class. +/// Contains integration tests for the class. /// [ExcludeFromCodeCoverage] public class GetLibrariesEndpointTests : IClassFixture diff --git a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/Management/GetMetadataProviders/GetMetadataProvidersEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/Management/GetMetadataProviders/GetMetadataProvidersEndpointTests.cs index 7ff6e394..c59cc7d7 100644 --- a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/Management/GetMetadataProviders/GetMetadataProvidersEndpointTests.cs +++ b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/Management/GetMetadataProviders/GetMetadataProvidersEndpointTests.cs @@ -16,7 +16,7 @@ using System.Threading.Tasks; namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.Library.Management.GetMetadataProviders; /// -/// Contains integration tests for the /{culture}/libraries/manage/api-get-metadata-providers/{{libraryId}} route served by the class. +/// Contains integration tests for the class. /// [ExcludeFromCodeCoverage] public class GetMetadataProvidersEndpointTests : IClassFixture diff --git a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/Management/GetRunningLibraryScans/GetRunningLibraryScansEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/Management/GetRunningLibraryScans/GetRunningLibraryScansEndpointTests.cs index 4d1fcea0..05c23235 100644 --- a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/Management/GetRunningLibraryScans/GetRunningLibraryScansEndpointTests.cs +++ b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/Management/GetRunningLibraryScans/GetRunningLibraryScansEndpointTests.cs @@ -16,7 +16,7 @@ using System.Threading.Tasks; namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.Library.Management.GetRunningLibraryScans; /// -/// Contains integration tests for the /{culture}/libraries/manage/api-get-running-library-scans route served by the class. +/// Contains integration tests for the class. /// [ExcludeFromCodeCoverage] public class GetRunningLibraryScansEndpointTests : IClassFixture diff --git a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/Management/Index/LibrariesIndexViewEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/Management/Index/LibrariesIndexViewEndpointTests.cs index e36f0c3d..088b0b24 100644 --- a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/Management/Index/LibrariesIndexViewEndpointTests.cs +++ b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/Management/Index/LibrariesIndexViewEndpointTests.cs @@ -11,7 +11,7 @@ using System.Threading.Tasks; namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.Library.Management.Index; /// -/// Contains integration tests for the /{culture}/libraries/manage route served by the class. +/// Contains integration tests for the class. /// [ExcludeFromCodeCoverage] public class LibrariesIndexViewEndpointTests : IClassFixture diff --git a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/Management/ReorderArtworkProviders/ReorderArtworkProvidersEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/Management/ReorderArtworkProviders/ReorderArtworkProvidersEndpointTests.cs index 2a64e24a..940c6cf0 100644 --- a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/Management/ReorderArtworkProviders/ReorderArtworkProvidersEndpointTests.cs +++ b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/Management/ReorderArtworkProviders/ReorderArtworkProvidersEndpointTests.cs @@ -17,7 +17,7 @@ using System.Threading.Tasks; namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.Library.Management.ReorderArtworkProviders; /// -/// Contains integration tests for the /{culture}/libraries/manage/api-reorder-artwork-providers route served by the class. +/// Contains integration tests for the class. /// [ExcludeFromCodeCoverage] public class ReorderArtworkProvidersEndpointTests : IClassFixture diff --git a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/Management/ReorderMetadataProviders/ReorderMetadataProvidersEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/Management/ReorderMetadataProviders/ReorderMetadataProvidersEndpointTests.cs index 6765f340..059ebed5 100644 --- a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/Management/ReorderMetadataProviders/ReorderMetadataProvidersEndpointTests.cs +++ b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/Management/ReorderMetadataProviders/ReorderMetadataProvidersEndpointTests.cs @@ -17,7 +17,7 @@ using System.Threading.Tasks; namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.Library.Management.ReorderMetadataProviders; /// -/// Contains integration tests for the /{culture}/libraries/manage/api-reorder-metadata-providers route served by the class. +/// Contains integration tests for the class. /// [ExcludeFromCodeCoverage] public class ReorderMetadataProvidersEndpointTests : IClassFixture diff --git a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/Management/SaveLibrary/SaveLibraryEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/Management/SaveLibrary/SaveLibraryEndpointTests.cs index 3d8485d6..121701e4 100644 --- a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/Management/SaveLibrary/SaveLibraryEndpointTests.cs +++ b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/Management/SaveLibrary/SaveLibraryEndpointTests.cs @@ -17,7 +17,7 @@ using System.Threading.Tasks; namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.Library.Management.SaveLibrary; /// -/// Contains integration tests for the /{culture}/libraries/manage/api-item route served by the class. +/// Contains integration tests for the class. /// [ExcludeFromCodeCoverage] public class SaveLibraryEndpointTests : IClassFixture diff --git a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/Management/ScanLibraries/ScanLibrariesEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/Management/ScanLibraries/ScanLibrariesEndpointTests.cs index f9dda266..ade53321 100644 --- a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/Management/ScanLibraries/ScanLibrariesEndpointTests.cs +++ b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/Management/ScanLibraries/ScanLibrariesEndpointTests.cs @@ -17,7 +17,7 @@ using System.Threading.Tasks; namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.Library.Management.ScanLibraries; /// -/// Contains integration tests for the /{culture}/libraries/manage/api-scan-libraries route served by the class. +/// Contains integration tests for the class. /// [ExcludeFromCodeCoverage] public class ScanLibrariesEndpointTests : IClassFixture diff --git a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/Management/ScanLibrary/ScanLibraryEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/Management/ScanLibrary/ScanLibraryEndpointTests.cs index e615d08e..9e7d202a 100644 --- a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/Management/ScanLibrary/ScanLibraryEndpointTests.cs +++ b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/Management/ScanLibrary/ScanLibraryEndpointTests.cs @@ -17,7 +17,7 @@ using System.Threading.Tasks; namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.Library.Management.ScanLibrary; /// -/// Contains integration tests for the /{culture}/libraries/manage/api-scan-library/{{id}} route served by the class. +/// Contains integration tests for the class. /// [ExcludeFromCodeCoverage] public class ScanLibraryEndpointTests : IClassFixture diff --git a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/Management/SetArtworkProviderEnabled/SetArtworkProviderEnabledEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/Management/SetArtworkProviderEnabled/SetArtworkProviderEnabledEndpointTests.cs index dcbef9fb..2a2c9995 100644 --- a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/Management/SetArtworkProviderEnabled/SetArtworkProviderEnabledEndpointTests.cs +++ b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/Management/SetArtworkProviderEnabled/SetArtworkProviderEnabledEndpointTests.cs @@ -17,7 +17,7 @@ using System.Threading.Tasks; namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.Library.Management.SetArtworkProviderEnabled; /// -/// Contains integration tests for the /{culture}/libraries/manage/api-set-artwork-provider-enabled route served by the class. +/// Contains integration tests for the class. /// [ExcludeFromCodeCoverage] public class SetArtworkProviderEnabledEndpointTests : IClassFixture diff --git a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/Management/SetBookReaderEnabled/SetBookReaderEnabledEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/Management/SetBookReaderEnabled/SetBookReaderEnabledEndpointTests.cs index e04ba161..25f4a8bb 100644 --- a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/Management/SetBookReaderEnabled/SetBookReaderEnabledEndpointTests.cs +++ b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/Management/SetBookReaderEnabled/SetBookReaderEnabledEndpointTests.cs @@ -18,7 +18,7 @@ using System.Threading.Tasks; namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.Library.Management.SetBookReaderEnabled; /// -/// Contains integration tests for the /{culture}/libraries/manage/api-set-book-reader-enabled route served by the class. +/// Contains integration tests for the class. /// [ExcludeFromCodeCoverage] public class SetBookReaderEnabledEndpointTests : IClassFixture diff --git a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/Management/SetMetadataProviderEnabled/SetMetadataProviderEnabledEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/Management/SetMetadataProviderEnabled/SetMetadataProviderEnabledEndpointTests.cs index 093e89a2..ad6752ac 100644 --- a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/Management/SetMetadataProviderEnabled/SetMetadataProviderEnabledEndpointTests.cs +++ b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/Management/SetMetadataProviderEnabled/SetMetadataProviderEnabledEndpointTests.cs @@ -17,7 +17,7 @@ using System.Threading.Tasks; namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.Library.Management.SetMetadataProviderEnabled; /// -/// Contains integration tests for the /{culture}/libraries/manage/api-set-metadata-provider-enabled route served by the class. +/// Contains integration tests for the class. /// [ExcludeFromCodeCoverage] public class SetMetadataProviderEnabledEndpointTests : IClassFixture diff --git a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/EditBook/EditBookViewEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/EditBook/EditBookViewEndpointTests.cs index 6d694754..30c7fa4e 100644 --- a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/EditBook/EditBookViewEndpointTests.cs +++ b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/EditBook/EditBookViewEndpointTests.cs @@ -1,5 +1,7 @@ #region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Common.DTO.WrittenContentLibrary.BookLibrary; using Lumina.Presentation.Web.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.Books.EditBook; +using Lumina.Presentation.Web.Fixtures.Common.DTO.WrittenContentLibrary.BookLibrary; using Lumina.Presentation.Web.Fixtures.Common.TestHelpers; using Lumina.Presentation.Web.IntegrationTests.Common.Setup; using System; @@ -12,12 +14,13 @@ using System.Threading.Tasks; namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.Books.EditBook; /// -/// Contains integration tests for the /{culture}/library/written-content-library/books-library/books/{{id}} route served by the class. +/// Contains integration tests for the class. /// [ExcludeFromCodeCoverage] public class EditBookViewEndpointTests : IClassFixture { private readonly LuminaWebFactory _apiFactory; + private readonly BookDetailsDtoFixture _bookDetailsDtoFixture = new(); /// /// Initializes a new instance of the class. @@ -33,10 +36,13 @@ public class EditBookViewEndpointTests : IClassFixture { // Arrange _apiFactory.ApiClientStub.Reset(); + BookDetailsDto expectedBook = _bookDetailsDtoFixture.Create(); + expectedBook.Metadata!.Title = "A book"; + _apiFactory.ApiClientStub.RegisterGetResponse($"books/{expectedBook.Id}", expectedBook); AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); // Act - HttpResponseMessage response = await webClient.Client.GetAsync($"/en-us/library/written-content-library/books-library/books/{Guid.NewGuid()}"); + HttpResponseMessage response = await webClient.Client.GetAsync($"/en-us/library/written-content-library/books-library/books/{expectedBook.Id}"); string content = await response.Content.ReadAsStringAsync(); // Assert diff --git a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/GetBookDetails/GetBookDetailsEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/GetBookDetails/GetBookDetailsEndpointTests.cs new file mode 100644 index 00000000..822e2952 --- /dev/null +++ b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/GetBookDetails/GetBookDetailsEndpointTests.cs @@ -0,0 +1,75 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Common.DTO.WrittenContentLibrary.BookLibrary; +using Lumina.Presentation.Web.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.Books.GetBookDetails; +using Lumina.Presentation.Web.Fixtures.Common.DTO.WrittenContentLibrary.BookLibrary; +using Lumina.Presentation.Web.Fixtures.Common.TestHelpers; +using Lumina.Presentation.Web.IntegrationTests.Common.Setup; +using System; +using System.Diagnostics.CodeAnalysis; +using System.Net; +using System.Net.Http; +using System.Net.Http.Headers; +using System.Text.Json; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.Books.GetBookDetails; + +/// +/// Contains integration tests for the class. +/// +[ExcludeFromCodeCoverage] +public class GetBookDetailsEndpointTests : IClassFixture +{ + private readonly LuminaWebFactory _apiFactory; + private readonly BookDetailsDtoFixture _bookDetailsDtoFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + /// Injected Web application factory. + public GetBookDetailsEndpointTests(LuminaWebFactory apiFactory) + { + _apiFactory = apiFactory; + } + + [Fact] + public async Task GetBookDetails_WhenCalledByAuthenticatedUser_ShouldReturnBookDetailsFromApi() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + Guid bookId = Guid.NewGuid(); + BookDetailsDto expectedBook = _bookDetailsDtoFixture.Create(id: bookId); + _apiFactory.ApiClientStub.RegisterGetResponse($"books/{bookId}", expectedBook); + AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); + HttpRequestMessage getRequest = new(HttpMethod.Get, $"/en-us/library/written-content-library/books-library/books/{bookId}/api-get-book"); + getRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); + + // Act + HttpResponseMessage response = await webClient.Client.SendAsync(getRequest); + string content = await response.Content.ReadAsStringAsync(); + + // Assert + response.EnsureSuccessStatusCode(); + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + using JsonDocument json = JsonDocument.Parse(content); + Assert.True(json.RootElement.GetProperty("success").GetBoolean()); + Assert.Equal(bookId, json.RootElement.GetProperty("data").GetProperty("id").GetGuid()); + Assert.Contains($"books/{bookId}", _apiFactory.ApiClientStub.GetEndpointsCalled); + } + + [Fact] + public async Task GetBookDetails_WhenNotAuthenticated_ShouldRedirectToLogin() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + HttpClient anonymousClient = WebTestHelpers.CreateAnonymousClient(_apiFactory); + + // Act + HttpResponseMessage response = await anonymousClient.GetAsync($"/en-us/library/written-content-library/books-library/books/{Guid.NewGuid()}/api-get-book"); + + // Assert + Assert.Equal(HttpStatusCode.Redirect, response.StatusCode); + Assert.DoesNotContain(_apiFactory.ApiClientStub.GetEndpointsCalled, endpoint => endpoint.StartsWith("books/", StringComparison.OrdinalIgnoreCase)); + } +} diff --git a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/GetLibraryItems/GetLibraryItemsEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/GetLibraryItems/GetLibraryItemsEndpointTests.cs index 3e3ac35e..13b87003 100644 --- a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/GetLibraryItems/GetLibraryItemsEndpointTests.cs +++ b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/GetLibraryItems/GetLibraryItemsEndpointTests.cs @@ -16,7 +16,7 @@ using System.Threading.Tasks; namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.Books.GetLibraryItems; /// -/// Contains integration tests for the /{culture}/library/written-content-library/books-library/books/api-get-library-items route served by the class. +/// Contains integration tests for the class. /// [ExcludeFromCodeCoverage] public class GetLibraryItemsEndpointTests : IClassFixture diff --git a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/Index/BooksIndexViewEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/Index/BooksIndexViewEndpointTests.cs index 2661e493..eb02aaee 100644 --- a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/Index/BooksIndexViewEndpointTests.cs +++ b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/Index/BooksIndexViewEndpointTests.cs @@ -14,7 +14,7 @@ using System.Threading.Tasks; namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.Books.Index; /// -/// Contains integration tests for the /{culture}/library/written-content-library/books-library/books route served by the class. +/// Contains integration tests for the class. /// [ExcludeFromCodeCoverage] public class BooksIndexViewEndpointTests : IClassFixture diff --git a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/Reading/GetReadingAvailability/GetReadingAvailabilityEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/Reading/GetReadingAvailability/GetReadingAvailabilityEndpointTests.cs index 1bd01bc6..1501b6c7 100644 --- a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/Reading/GetReadingAvailability/GetReadingAvailabilityEndpointTests.cs +++ b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/Reading/GetReadingAvailability/GetReadingAvailabilityEndpointTests.cs @@ -16,7 +16,7 @@ using System.Threading.Tasks; namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.Books.Reading.GetReadingAvailability; /// -/// Contains integration tests for the /{culture}/library/written-content-library/books-library/books/{bookId}/api-get-reading-availability route served by the class. +/// Contains integration tests for the class. /// [ExcludeFromCodeCoverage] public class GetReadingAvailabilityEndpointTests : IClassFixture diff --git a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/Reading/GetReadingManifest/GetReadingManifestEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/Reading/GetReadingManifest/GetReadingManifestEndpointTests.cs index d1316190..25f8fda3 100644 --- a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/Reading/GetReadingManifest/GetReadingManifestEndpointTests.cs +++ b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/Reading/GetReadingManifest/GetReadingManifestEndpointTests.cs @@ -18,7 +18,7 @@ using System.Threading.Tasks; namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.Books.Reading.GetReadingManifest; /// -/// Contains integration tests for the /{culture}/library/written-content-library/books-library/books/{bookId}/api-get-reading-manifest route served by the class. +/// Contains integration tests for the class. /// [ExcludeFromCodeCoverage] public class GetReadingManifestEndpointTests : IClassFixture diff --git a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/Reading/GetReadingResource/GetReadingResourceEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/Reading/GetReadingResource/GetReadingResourceEndpointTests.cs index d7cdbf10..0ec52239 100644 --- a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/Reading/GetReadingResource/GetReadingResourceEndpointTests.cs +++ b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/Reading/GetReadingResource/GetReadingResourceEndpointTests.cs @@ -15,7 +15,7 @@ using System.Threading.Tasks; namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.Books.Reading.GetReadingResource; /// -/// Contains integration tests for the /{culture}/library/written-content-library/books-library/books/{bookId}/api-get-reading-resource route served by the class. +/// Contains integration tests for the class. /// [ExcludeFromCodeCoverage] public class GetReadingResourceEndpointTests : IClassFixture diff --git a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/Reading/GetReadingSection/GetReadingSectionEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/Reading/GetReadingSection/GetReadingSectionEndpointTests.cs index ed2f600a..5e3bbf4d 100644 --- a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/Reading/GetReadingSection/GetReadingSectionEndpointTests.cs +++ b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/Reading/GetReadingSection/GetReadingSectionEndpointTests.cs @@ -16,7 +16,7 @@ using System.Threading.Tasks; namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.Books.Reading.GetReadingSection; /// -/// Contains integration tests for the /{culture}/library/written-content-library/books-library/books/{bookId}/api-get-reading-section route served by the class. +/// Contains integration tests for the class. /// [ExcludeFromCodeCoverage] public class GetReadingSectionEndpointTests : IClassFixture diff --git a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/Reading/Read/ReadViewEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/Reading/Read/ReadViewEndpointTests.cs index 6a073cd1..d629381e 100644 --- a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/Reading/Read/ReadViewEndpointTests.cs +++ b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/Reading/Read/ReadViewEndpointTests.cs @@ -14,7 +14,7 @@ using System.Threading.Tasks; namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.Books.Reading.Read; /// -/// Contains integration tests for the /{culture}/library/written-content-library/books-library/books/{bookId}/read route served by the class. +/// Contains integration tests for the class. /// [ExcludeFromCodeCoverage] public class ReadViewEndpointTests : IClassFixture diff --git a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/SaveBook/SaveBookEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/SaveBook/SaveBookEndpointTests.cs new file mode 100644 index 00000000..ff9ab793 --- /dev/null +++ b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/SaveBook/SaveBookEndpointTests.cs @@ -0,0 +1,141 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Common.DTO.WrittenContentLibrary.BookLibrary; +using Lumina.Presentation.Web.Common.Requests.Library.WrittenContentLibrary.BookLibrary.Books; +using Lumina.Presentation.Web.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.Books.SaveBook; +using Lumina.Presentation.Web.Fixtures.Common.DTO.WrittenContentLibrary.BookLibrary; +using Lumina.Presentation.Web.Fixtures.Common.Requests.Library.WrittenContentLibrary.BookLibrary.Books; +using Lumina.Presentation.Web.Fixtures.Common.TestHelpers; +using Lumina.Presentation.Web.IntegrationTests.Common.Setup; +using System; +using System.Diagnostics.CodeAnalysis; +using System.Net; +using System.Net.Http; +using System.Net.Http.Headers; +using System.Net.Http.Json; +using System.Text.Json; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.Books.SaveBook; + +/// +/// Contains integration tests for the class. +/// +[ExcludeFromCodeCoverage] +public class SaveBookEndpointTests : IClassFixture +{ + private readonly LuminaWebFactory _apiFactory; + private readonly UpdateBookRequestFixture _updateBookRequestFixture = new(); + private readonly BookDetailsDtoFixture _bookDetailsDtoFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + /// Injected Web application factory. + public SaveBookEndpointTests(LuminaWebFactory apiFactory) + { + _apiFactory = apiFactory; + } + + [Fact] + public async Task SaveBook_WhenCalledByAuthenticatedUserWithAntiforgeryToken_ShouldForwardUpdateAndReturnSuccess() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + Guid bookId = Guid.NewGuid(); + UpdateBookRequest request = _updateBookRequestFixture.Create(id: bookId); + BookDetailsDto expectedBook = _bookDetailsDtoFixture.Create(id: bookId); + _apiFactory.ApiClientStub.RegisterPutResponse($"books/{bookId}", expectedBook); + AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); + HttpRequestMessage saveRequest = CreateSaveRequest(bookId, request); + saveRequest.Headers.Add("RequestVerificationToken", webClient.AntiforgeryToken); + + // Act + HttpResponseMessage response = await webClient.Client.SendAsync(saveRequest); + string content = await response.Content.ReadAsStringAsync(); + + // Assert + response.EnsureSuccessStatusCode(); + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + using JsonDocument json = JsonDocument.Parse(content); + Assert.True(json.RootElement.GetProperty("success").GetBoolean()); + Assert.Equal(bookId, json.RootElement.GetProperty("data").GetProperty("id").GetGuid()); + Assert.Contains(_apiFactory.ApiClientStub.PutRequests, putRequest => putRequest.Endpoint == $"books/{bookId}" && putRequest.Data is UpdateBookRequest forwarded && forwarded.Id == bookId.ToString()); + } + + [Fact] + public async Task SaveBook_WhenRouteIdDiffersFromBodyId_ShouldForwardTheRouteIdToApi() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + Guid routeId = Guid.NewGuid(); + Guid bodyId = Guid.NewGuid(); + UpdateBookRequest request = _updateBookRequestFixture.Create(id: bodyId); + BookDetailsDto expectedBook = _bookDetailsDtoFixture.Create(id: routeId); + _apiFactory.ApiClientStub.RegisterPutResponse($"books/{routeId}", expectedBook); + AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); + HttpRequestMessage saveRequest = CreateSaveRequest(routeId, request); + saveRequest.Headers.Add("RequestVerificationToken", webClient.AntiforgeryToken); + + // Act + HttpResponseMessage response = await webClient.Client.SendAsync(saveRequest); + string content = await response.Content.ReadAsStringAsync(); + + // Assert + response.EnsureSuccessStatusCode(); + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + Assert.Contains(_apiFactory.ApiClientStub.PutRequests, putRequest => putRequest.Endpoint == $"books/{routeId}" && putRequest.Data is UpdateBookRequest forwarded && forwarded.Id == routeId.ToString()); + Assert.DoesNotContain(_apiFactory.ApiClientStub.PutRequests, putRequest => putRequest.Endpoint == $"books/{bodyId}"); + } + + [Fact] + public async Task SaveBook_WhenCalledWithoutAntiforgeryToken_ShouldRejectRequest() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + Guid bookId = Guid.NewGuid(); + UpdateBookRequest request = _updateBookRequestFixture.Create(id: bookId); + AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); + HttpRequestMessage saveRequest = CreateSaveRequest(bookId, request); + + // Act + HttpResponseMessage response = await webClient.Client.SendAsync(saveRequest); + + // Assert + Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode); + Assert.DoesNotContain(_apiFactory.ApiClientStub.PutRequests, putRequest => putRequest.Endpoint == $"books/{bookId}"); + } + + [Fact] + public async Task SaveBook_WhenNotAuthenticated_ShouldRedirectToLogin() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + HttpClient anonymousClient = WebTestHelpers.CreateAnonymousClient(_apiFactory); + HttpRequestMessage saveRequest = CreateSaveRequest(Guid.NewGuid(), _updateBookRequestFixture.Create()); + + // Act + HttpResponseMessage response = await anonymousClient.SendAsync(saveRequest); + + // Assert + Assert.Equal(HttpStatusCode.Redirect, response.StatusCode); + Assert.Empty(_apiFactory.ApiClientStub.PutRequests); + } + + /// + /// Builds the save request that PUTs the given to the book identified by . + /// + /// The route Id of the book to save. + /// The book data to send. + /// The configured save request. + private static HttpRequestMessage CreateSaveRequest(Guid bookId, UpdateBookRequest request) + { + HttpRequestMessage saveRequest = new(HttpMethod.Put, $"/en-us/library/written-content-library/books-library/books/{bookId}/api-save-book") + { + Content = JsonContent.Create(request) + }; + saveRequest.Content!.Headers.ContentType = new MediaTypeHeaderValue("application/json"); + saveRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); + return saveRequest; + } +} diff --git a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/UpdateBookCover/UpdateBookCoverEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/UpdateBookCover/UpdateBookCoverEndpointTests.cs new file mode 100644 index 00000000..b6dd0fce --- /dev/null +++ b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/UpdateBookCover/UpdateBookCoverEndpointTests.cs @@ -0,0 +1,158 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.Books.UpdateBookCover; +using Lumina.Presentation.Web.Fixtures.Common.TestHelpers; +using Lumina.Presentation.Web.IntegrationTests.Common.Setup; +using System; +using System.Diagnostics.CodeAnalysis; +using System.Net; +using System.Net.Http; +using System.Net.Http.Headers; +using System.Text; +using System.Text.Json; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.Books.UpdateBookCover; + +/// +/// Contains integration tests for the class. +/// +[ExcludeFromCodeCoverage] +public class UpdateBookCoverEndpointTests : IClassFixture +{ + private readonly LuminaWebFactory _apiFactory; + + /// + /// Initializes a new instance of the class. + /// + /// Injected Web application factory. + public UpdateBookCoverEndpointTests(LuminaWebFactory apiFactory) + { + _apiFactory = apiFactory; + } + + [Fact] + public async Task UpdateBookCover_WhenCalledByAuthenticatedUserWithAntiforgeryToken_ShouldUploadCoverAndReturnSuccess() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + Guid bookId = Guid.NewGuid(); + string expectedPath = "/media/books/cover.png"; + _apiFactory.ApiClientStub.RegisterPutResponse($"books/{bookId}/cover", expectedPath); + AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); + HttpRequestMessage uploadRequest = CreateUploadRequest(bookId, "cover.png"); + uploadRequest.Headers.Add("RequestVerificationToken", webClient.AntiforgeryToken); + + // Act + HttpResponseMessage response = await webClient.Client.SendAsync(uploadRequest); + string content = await response.Content.ReadAsStringAsync(); + + // Assert + response.EnsureSuccessStatusCode(); + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + using JsonDocument json = JsonDocument.Parse(content); + Assert.True(json.RootElement.GetProperty("success").GetBoolean()); + Assert.Equal(expectedPath, json.RootElement.GetProperty("data").GetString()); + Assert.Contains(_apiFactory.ApiClientStub.PutRequests, putRequest => putRequest.Endpoint == $"books/{bookId}/cover" && putRequest.Data as string == "cover.png"); + } + + [Fact] + public async Task UpdateBookCover_WhenRouteIdDiffersFromFormIdField_ShouldUseTheRouteId() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + Guid routeId = Guid.NewGuid(); + Guid formId = Guid.NewGuid(); + _apiFactory.ApiClientStub.RegisterPutResponse($"books/{routeId}/cover", "/media/books/cover.png"); + AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); + HttpRequestMessage uploadRequest = CreateUploadRequest(routeId, "cover.png"); + uploadRequest.Headers.Add("RequestVerificationToken", webClient.AntiforgeryToken); + MultipartFormDataContent form = (MultipartFormDataContent)uploadRequest.Content!; + form.Add(new StringContent(formId.ToString()), "id"); + + // Act + HttpResponseMessage response = await webClient.Client.SendAsync(uploadRequest); + string content = await response.Content.ReadAsStringAsync(); + + // Assert + response.EnsureSuccessStatusCode(); + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + Assert.Contains(_apiFactory.ApiClientStub.PutRequests, putRequest => putRequest.Endpoint == $"books/{routeId}/cover"); + Assert.DoesNotContain(_apiFactory.ApiClientStub.PutRequests, putRequest => putRequest.Endpoint == $"books/{formId}/cover"); + } + + [Fact] + public async Task UpdateBookCover_WhenCalledWithoutAntiforgeryToken_ShouldRejectRequest() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + Guid bookId = Guid.NewGuid(); + AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); + HttpRequestMessage uploadRequest = CreateUploadRequest(bookId, "cover.png"); + + // Act + HttpResponseMessage response = await webClient.Client.SendAsync(uploadRequest); + + // Assert + Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode); + Assert.DoesNotContain(_apiFactory.ApiClientStub.PutRequests, putRequest => putRequest.Endpoint == $"books/{bookId}/cover"); + } + + [Fact] + public async Task UpdateBookCover_WhenCalledWithoutUploadedFile_ShouldReturnBadRequest() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + Guid bookId = Guid.NewGuid(); + AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); + MultipartFormDataContent noFileForm = []; + noFileForm.Add(new StringContent("unrelated-field")); + HttpRequestMessage uploadRequest = new(HttpMethod.Put, $"/en-us/library/written-content-library/books-library/books/{bookId}/api-update-cover") + { + Content = noFileForm + }; + uploadRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); + uploadRequest.Headers.Add("RequestVerificationToken", webClient.AntiforgeryToken); + + // Act + HttpResponseMessage response = await webClient.Client.SendAsync(uploadRequest); + + // Assert + Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode); + Assert.DoesNotContain(_apiFactory.ApiClientStub.PutRequests, putRequest => putRequest.Endpoint == $"books/{bookId}/cover"); + } + + [Fact] + public async Task UpdateBookCover_WhenNotAuthenticated_ShouldRedirectToLogin() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + HttpClient anonymousClient = WebTestHelpers.CreateAnonymousClient(_apiFactory); + HttpRequestMessage uploadRequest = CreateUploadRequest(Guid.NewGuid(), "cover.png"); + + // Act + HttpResponseMessage response = await anonymousClient.SendAsync(uploadRequest); + + // Assert + Assert.Equal(HttpStatusCode.Redirect, response.StatusCode); + Assert.Empty(_apiFactory.ApiClientStub.PutRequests); + } + + /// + /// Builds the multipart PUT request that uploads a cover to the book identified by . + /// + /// The route Id of the book whose cover is uploaded. + /// The name of the uploaded file. + /// The configured upload request. + private static HttpRequestMessage CreateUploadRequest(Guid bookId, string fileName) + { + MultipartFormDataContent form = []; + ByteArrayContent fileContent = new(Encoding.UTF8.GetBytes("fake cover payload")); + fileContent.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream"); + form.Add(fileContent, "cover", fileName); + return new HttpRequestMessage(HttpMethod.Put, $"/en-us/library/written-content-library/books-library/books/{bookId}/api-update-cover") + { + Content = form + }; + } +} diff --git a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Plugins/GetPluginSettings/GetPluginSettingsEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Plugins/GetPluginSettings/GetPluginSettingsEndpointTests.cs index 65bcc2b6..9e691d36 100644 --- a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Plugins/GetPluginSettings/GetPluginSettingsEndpointTests.cs +++ b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Plugins/GetPluginSettings/GetPluginSettingsEndpointTests.cs @@ -16,7 +16,7 @@ using System.Threading.Tasks; namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.Plugins.GetPluginSettings; /// -/// Contains integration tests for the /{culture}/admin/manage-plugins/api-get-plugin-settings/{pluginId} route served by the class. +/// Contains integration tests for the class. /// [ExcludeFromCodeCoverage] public class GetPluginSettingsEndpointTests : IClassFixture diff --git a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Plugins/GetPlugins/GetPluginsEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Plugins/GetPlugins/GetPluginsEndpointTests.cs index e10a7633..5c1a39f5 100644 --- a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Plugins/GetPlugins/GetPluginsEndpointTests.cs +++ b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Plugins/GetPlugins/GetPluginsEndpointTests.cs @@ -4,7 +4,6 @@ using Lumina.Presentation.Web.Core.Endpoints.Plugins.GetPlugins; using Lumina.Presentation.Web.Fixtures.Common.DTO.Plugins; using Lumina.Presentation.Web.Fixtures.Common.TestHelpers; using Lumina.Presentation.Web.IntegrationTests.Common.Setup; -using System; using System.Diagnostics.CodeAnalysis; using System.Net; using System.Net.Http; @@ -16,7 +15,7 @@ using System.Threading.Tasks; namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.Plugins.GetPlugins; /// -/// Contains integration tests for the /{culture}/admin/manage-plugins/api-get-plugins route served by the class. +/// Contains integration tests for the class. /// [ExcludeFromCodeCoverage] public class GetPluginsEndpointTests : IClassFixture diff --git a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Plugins/Index/PluginsIndexViewEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Plugins/Index/PluginsIndexViewEndpointTests.cs index 01346b29..2e96c4ad 100644 --- a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Plugins/Index/PluginsIndexViewEndpointTests.cs +++ b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Plugins/Index/PluginsIndexViewEndpointTests.cs @@ -13,7 +13,7 @@ using System.Threading.Tasks; namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.Plugins.Index; /// -/// Contains integration tests for the /{culture}/admin/manage-plugins route served by the class. +/// Contains integration tests for the class. /// [ExcludeFromCodeCoverage] public class PluginsIndexViewEndpointTests : IClassFixture diff --git a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Plugins/InstallPlugin/InstallPluginEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Plugins/InstallPlugin/InstallPluginEndpointTests.cs index 373ba328..9741549c 100644 --- a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Plugins/InstallPlugin/InstallPluginEndpointTests.cs +++ b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Plugins/InstallPlugin/InstallPluginEndpointTests.cs @@ -1,10 +1,8 @@ #region ========================================================================= USING ===================================================================================== -using Lumina.Presentation.Web.Common.DTO.Plugins; using Lumina.Presentation.Web.Core.Endpoints.Plugins.InstallPlugin; using Lumina.Presentation.Web.Fixtures.Common.DTO.Plugins; using Lumina.Presentation.Web.Fixtures.Common.TestHelpers; using Lumina.Presentation.Web.IntegrationTests.Common.Setup; -using System; using System.Diagnostics.CodeAnalysis; using System.Net; using System.Net.Http; @@ -16,7 +14,7 @@ using System.Threading.Tasks; namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.Plugins.InstallPlugin; /// -/// Contains integration tests for the /{culture}/admin/manage-plugins/api-install-plugin route served by the class. +/// Contains integration tests for the class. /// [ExcludeFromCodeCoverage] public class InstallPluginEndpointTests : IClassFixture diff --git a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Plugins/UpdatePluginSettings/UpdatePluginSettingsEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Plugins/UpdatePluginSettings/UpdatePluginSettingsEndpointTests.cs index 3ca372ac..41fad1e6 100644 --- a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Plugins/UpdatePluginSettings/UpdatePluginSettingsEndpointTests.cs +++ b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Plugins/UpdatePluginSettings/UpdatePluginSettingsEndpointTests.cs @@ -4,7 +4,6 @@ using Lumina.Presentation.Web.Core.Endpoints.Plugins.UpdatePluginSettings; using Lumina.Presentation.Web.Fixtures.Common.Requests.Plugins; using Lumina.Presentation.Web.Fixtures.Common.TestHelpers; using Lumina.Presentation.Web.IntegrationTests.Common.Setup; -using System; using System.Diagnostics.CodeAnalysis; using System.Net; using System.Net.Http; @@ -17,7 +16,7 @@ using System.Threading.Tasks; namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.Plugins.UpdatePluginSettings; /// -/// Contains integration tests for the /{culture}/admin/manage-plugins/api-update-plugin-settings route served by the class. +/// Contains integration tests for the class. /// [ExcludeFromCodeCoverage] public class UpdatePluginSettingsEndpointTests : IClassFixture diff --git a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Themes/ThemeAssets/ThemeAssetsEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Themes/ThemeAssets/ThemeAssetsEndpointTests.cs index f5801bd9..9ab3d443 100644 --- a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Themes/ThemeAssets/ThemeAssetsEndpointTests.cs +++ b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Themes/ThemeAssets/ThemeAssetsEndpointTests.cs @@ -13,7 +13,7 @@ using System.Threading.Tasks; namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.Themes.ThemeAssets; /// -/// Contains integration tests for the /theme-assets/{themeId}/{path} route served by the class. +/// Contains integration tests for the class. /// [ExcludeFromCodeCoverage] public class ThemeAssetsEndpointTests : IClassFixture diff --git a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Tools/Language/SetLanguage/SetLanguageEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Tools/Language/SetLanguage/SetLanguageEndpointTests.cs index 1fba9da5..ff05e008 100644 --- a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Tools/Language/SetLanguage/SetLanguageEndpointTests.cs +++ b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Tools/Language/SetLanguage/SetLanguageEndpointTests.cs @@ -13,7 +13,7 @@ using System.Threading.Tasks; namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.Tools.Language.SetLanguage; /// -/// Contains integration tests for the /{culture}/tools/language/set-language route served by the class. +/// Contains integration tests for the class. /// [ExcludeFromCodeCoverage] public class SetLanguageEndpointTests : IClassFixture diff --git a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Tools/Settings/GetUserSettings/GetUserSettingsEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Tools/Settings/GetUserSettings/GetUserSettingsEndpointTests.cs index 19fa67c2..436fd2c1 100644 --- a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Tools/Settings/GetUserSettings/GetUserSettingsEndpointTests.cs +++ b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Tools/Settings/GetUserSettings/GetUserSettingsEndpointTests.cs @@ -15,7 +15,7 @@ using System.Threading.Tasks; namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.Tools.Settings.GetUserSettings; /// -/// Contains integration tests for the /{culture}/tools/settings/api-get-user-settings route served by the class. +/// Contains integration tests for the class. /// [ExcludeFromCodeCoverage] public class GetUserSettingsEndpointTests : IClassFixture diff --git a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Tools/Settings/SettingsViewEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Tools/Settings/SettingsViewEndpointTests.cs index d5a1c00b..b37792ab 100644 --- a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Tools/Settings/SettingsViewEndpointTests.cs +++ b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Tools/Settings/SettingsViewEndpointTests.cs @@ -11,7 +11,7 @@ using System.Threading.Tasks; namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.Tools.Settings; /// -/// Contains integration tests for the /{culture}/tools/settings route served by the class. +/// Contains integration tests for the class. /// [ExcludeFromCodeCoverage] public class SettingsViewEndpointTests : IClassFixture diff --git a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Tools/Settings/UpdateUserSettings/UpdateUserSettingsEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Tools/Settings/UpdateUserSettings/UpdateUserSettingsEndpointTests.cs index be26d418..4e362f78 100644 --- a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Tools/Settings/UpdateUserSettings/UpdateUserSettingsEndpointTests.cs +++ b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Tools/Settings/UpdateUserSettings/UpdateUserSettingsEndpointTests.cs @@ -17,7 +17,7 @@ using System.Threading.Tasks; namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.Tools.Settings.UpdateUserSettings; /// -/// Contains integration tests for the /{culture}/tools/settings/api-update-user-settings route served by the class. +/// Contains integration tests for the class. /// [ExcludeFromCodeCoverage] public class UpdateUserSettingsEndpointTests : IClassFixture diff --git a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/UsersManagement/Authentication/AccessDenied/AccessDeniedViewEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/UsersManagement/Authentication/AccessDenied/AccessDeniedViewEndpointTests.cs index 751b5e03..cd82e8a0 100644 --- a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/UsersManagement/Authentication/AccessDenied/AccessDeniedViewEndpointTests.cs +++ b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/UsersManagement/Authentication/AccessDenied/AccessDeniedViewEndpointTests.cs @@ -11,7 +11,7 @@ using System.Threading.Tasks; namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.UsersManagement.Authentication.AccessDenied; /// -/// Contains integration tests for the /{culture}/auth/access-denied route served by the class. +/// Contains integration tests for the class. /// [ExcludeFromCodeCoverage] public class AccessDeniedViewEndpointTests : IClassFixture diff --git a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/UsersManagement/Authentication/ChangePassword/ChangePasswordEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/UsersManagement/Authentication/ChangePassword/ChangePasswordEndpointTests.cs index 88dea4da..7430e978 100644 --- a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/UsersManagement/Authentication/ChangePassword/ChangePasswordEndpointTests.cs +++ b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/UsersManagement/Authentication/ChangePassword/ChangePasswordEndpointTests.cs @@ -19,7 +19,7 @@ using System.Threading.Tasks; namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.UsersManagement.Authentication.ChangePassword; /// -/// Contains integration tests for the /{culture}/auth/api-change-password route served by the class. +/// Contains integration tests for the class. /// [ExcludeFromCodeCoverage] public class ChangePasswordEndpointTests : IClassFixture diff --git a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/UsersManagement/Authentication/ChangePassword/ChangePasswordViewEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/UsersManagement/Authentication/ChangePassword/ChangePasswordViewEndpointTests.cs index c82a4497..e32885f1 100644 --- a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/UsersManagement/Authentication/ChangePassword/ChangePasswordViewEndpointTests.cs +++ b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/UsersManagement/Authentication/ChangePassword/ChangePasswordViewEndpointTests.cs @@ -11,7 +11,7 @@ using System.Threading.Tasks; namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.UsersManagement.Authentication.ChangePassword; /// -/// Contains integration tests for the /{culture}/auth/change-password route served by the class. +/// Contains integration tests for the class. /// [ExcludeFromCodeCoverage] public class ChangePasswordViewEndpointTests : IClassFixture diff --git a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/UsersManagement/Authentication/Login/LoginEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/UsersManagement/Authentication/Login/LoginEndpointTests.cs index 4b522b15..95e74257 100644 --- a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/UsersManagement/Authentication/Login/LoginEndpointTests.cs +++ b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/UsersManagement/Authentication/Login/LoginEndpointTests.cs @@ -21,7 +21,7 @@ using System.Threading.Tasks; namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.UsersManagement.Authentication.Login; /// -/// Contains integration tests for the /{culture}/auth/api-login route served by the class. +/// Contains integration tests for the class. /// [ExcludeFromCodeCoverage] public class LoginEndpointTests : IClassFixture diff --git a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/UsersManagement/Authentication/Login/LoginViewEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/UsersManagement/Authentication/Login/LoginViewEndpointTests.cs index 67cb7f45..e46e90aa 100644 --- a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/UsersManagement/Authentication/Login/LoginViewEndpointTests.cs +++ b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/UsersManagement/Authentication/Login/LoginViewEndpointTests.cs @@ -10,7 +10,7 @@ using System.Threading.Tasks; namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.UsersManagement.Authentication.Login; /// -/// Contains integration tests for the /{culture}/auth/login/{returnUrl?} route served by the class. +/// Contains integration tests for the class. /// [ExcludeFromCodeCoverage] public class LoginViewEndpointTests : IClassFixture diff --git a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/UsersManagement/Authentication/Logout/LogoutEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/UsersManagement/Authentication/Logout/LogoutEndpointTests.cs index b0457f9e..e1c5248f 100644 --- a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/UsersManagement/Authentication/Logout/LogoutEndpointTests.cs +++ b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/UsersManagement/Authentication/Logout/LogoutEndpointTests.cs @@ -11,7 +11,7 @@ using System.Threading.Tasks; namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.UsersManagement.Authentication.Logout; /// -/// Contains integration tests for the /{culture}/auth/logout route served by the class. +/// Contains integration tests for the class. /// [ExcludeFromCodeCoverage] public class LogoutEndpointTests : IClassFixture diff --git a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/UsersManagement/Authentication/RecoverPassword/RecoverPasswordEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/UsersManagement/Authentication/RecoverPassword/RecoverPasswordEndpointTests.cs index dd0909c4..ade89fd0 100644 --- a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/UsersManagement/Authentication/RecoverPassword/RecoverPasswordEndpointTests.cs +++ b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/UsersManagement/Authentication/RecoverPassword/RecoverPasswordEndpointTests.cs @@ -18,7 +18,7 @@ using System.Threading.Tasks; namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.UsersManagement.Authentication.RecoverPassword; /// -/// Contains integration tests for the /{culture}/auth/api-recover-password route served by the class. +/// Contains integration tests for the class. /// [ExcludeFromCodeCoverage] public class RecoverPasswordEndpointTests : IClassFixture diff --git a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/UsersManagement/Authentication/RecoverPassword/RecoverPasswordViewEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/UsersManagement/Authentication/RecoverPassword/RecoverPasswordViewEndpointTests.cs index be8a1c62..3c6a454a 100644 --- a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/UsersManagement/Authentication/RecoverPassword/RecoverPasswordViewEndpointTests.cs +++ b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/UsersManagement/Authentication/RecoverPassword/RecoverPasswordViewEndpointTests.cs @@ -11,7 +11,7 @@ using System.Threading.Tasks; namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.UsersManagement.Authentication.RecoverPassword; /// -/// Contains integration tests for the /{culture}/auth/recover-password route served by the class. +/// Contains integration tests for the class. /// [ExcludeFromCodeCoverage] public class RecoverPasswordViewEndpointTests : IClassFixture diff --git a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/UsersManagement/Authentication/Register/RegisterEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/UsersManagement/Authentication/Register/RegisterEndpointTests.cs index 4a23234f..24658799 100644 --- a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/UsersManagement/Authentication/Register/RegisterEndpointTests.cs +++ b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/UsersManagement/Authentication/Register/RegisterEndpointTests.cs @@ -18,7 +18,7 @@ using System.Threading.Tasks; namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.UsersManagement.Authentication.Register; /// -/// Contains integration tests for the /{culture}/auth/api-register route served by the class. +/// Contains integration tests for the class. /// [ExcludeFromCodeCoverage] public class RegisterEndpointTests : IClassFixture diff --git a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/UsersManagement/Authentication/Register/RegisterViewEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/UsersManagement/Authentication/Register/RegisterViewEndpointTests.cs index ccc43887..4f80b965 100644 --- a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/UsersManagement/Authentication/Register/RegisterViewEndpointTests.cs +++ b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/UsersManagement/Authentication/Register/RegisterViewEndpointTests.cs @@ -11,7 +11,7 @@ using System.Threading.Tasks; namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.UsersManagement.Authentication.Register; /// -/// Contains integration tests for the /{culture}/auth/register route served by the class. +/// Contains integration tests for the class. /// [ExcludeFromCodeCoverage] public class RegisterViewEndpointTests : IClassFixture diff --git a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Admin/Authorization/Permissions/GetPermissionsEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Admin/Authorization/Permissions/GetPermissionsEndpointTests.cs index 049ae901..2f040683 100644 --- a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Admin/Authorization/Permissions/GetPermissionsEndpointTests.cs +++ b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Admin/Authorization/Permissions/GetPermissionsEndpointTests.cs @@ -9,7 +9,7 @@ using System.Text.Json; namespace Lumina.Presentation.Api.SecurityTests.Core.Endpoints.Admin.Authorization.Permissions; /// -/// Contains security tests for the /auth/permissions route. +/// Contains security tests for the class. /// [ExcludeFromCodeCoverage] public class GetPermissionsEndpointTests : IClassFixture diff --git a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Admin/Authorization/Roles/AddRoleEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Admin/Authorization/Roles/AddRoleEndpointTests.cs index 0ddf36fb..a8daf85c 100644 --- a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Admin/Authorization/Roles/AddRoleEndpointTests.cs +++ b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Admin/Authorization/Roles/AddRoleEndpointTests.cs @@ -16,7 +16,7 @@ using System.Text.Json; namespace Lumina.Presentation.Api.SecurityTests.Core.Endpoints.Admin.Authorization.Roles; /// -/// Contains security tests for the /auth/roles route. +/// Contains security tests for the class. /// [ExcludeFromCodeCoverage] public class AddRoleEndpointTests : IClassFixture, IAsyncDisposable diff --git a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Admin/Authorization/Roles/DeleteRoleEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Admin/Authorization/Roles/DeleteRoleEndpointTests.cs index f6550f7a..6279b8ba 100644 --- a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Admin/Authorization/Roles/DeleteRoleEndpointTests.cs +++ b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Admin/Authorization/Roles/DeleteRoleEndpointTests.cs @@ -9,7 +9,7 @@ using System.Text.Json; namespace Lumina.Presentation.Api.SecurityTests.Core.Endpoints.Admin.Authorization.Roles; /// -/// Contains security tests for the /auth/roles/{roleId} route. +/// Contains security tests for the class. /// [ExcludeFromCodeCoverage] public class DeleteRoleEndpointTests : IClassFixture diff --git a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Admin/Authorization/Roles/GetRolePermissionsEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Admin/Authorization/Roles/GetRolePermissionsEndpointTests.cs index 0735a7ba..85c9d027 100644 --- a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Admin/Authorization/Roles/GetRolePermissionsEndpointTests.cs +++ b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Admin/Authorization/Roles/GetRolePermissionsEndpointTests.cs @@ -9,7 +9,7 @@ using System.Text.Json; namespace Lumina.Presentation.Api.SecurityTests.Core.Endpoints.Admin.Authorization.Roles; /// -/// Contains security tests for the /auth/roles/{roleId}/permissions route. +/// Contains security tests for the class. /// [ExcludeFromCodeCoverage] public class GetRolePermissionsEndpointTests : IClassFixture diff --git a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Admin/Authorization/Roles/GetRolesEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Admin/Authorization/Roles/GetRolesEndpointTests.cs index 47aa50f2..d7c1b758 100644 --- a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Admin/Authorization/Roles/GetRolesEndpointTests.cs +++ b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Admin/Authorization/Roles/GetRolesEndpointTests.cs @@ -9,7 +9,7 @@ using System.Text.Json; namespace Lumina.Presentation.Api.SecurityTests.Core.Endpoints.Admin.Authorization.Roles; /// -/// Contains security tests for the /auth/roles route. +/// Contains security tests for the class. /// [ExcludeFromCodeCoverage] public class GetRolesEndpointTests : IClassFixture diff --git a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Admin/Authorization/Roles/UpdateRoleEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Admin/Authorization/Roles/UpdateRoleEndpointTests.cs index e0c082fb..2e999266 100644 --- a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Admin/Authorization/Roles/UpdateRoleEndpointTests.cs +++ b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Admin/Authorization/Roles/UpdateRoleEndpointTests.cs @@ -18,7 +18,7 @@ using System.Text.Json; namespace Lumina.Presentation.Api.SecurityTests.Core.Endpoints.Admin.Authorization.Roles; /// -/// Contains security tests for the /auth/roles route. +/// Contains security tests for the class. /// [ExcludeFromCodeCoverage] public class UpdateRoleEndpointTests : IClassFixture, IAsyncDisposable diff --git a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/FileSystemManagement/Directories/GetDirectoriesEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/FileSystemManagement/Directories/GetDirectoriesEndpointTests.cs index eb1d6ab1..a6e5fd50 100644 --- a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/FileSystemManagement/Directories/GetDirectoriesEndpointTests.cs +++ b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/FileSystemManagement/Directories/GetDirectoriesEndpointTests.cs @@ -9,7 +9,7 @@ using System.Text.Json; namespace Lumina.Presentation.Api.SecurityTests.Core.Endpoints.FileSystemManagement.Directories; /// -/// Contains security tests for the /directories/get-directories route. +/// Contains security tests for the class. /// [ExcludeFromCodeCoverage] public class GetDirectoriesEndpointTests : IClassFixture diff --git a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/FileSystemManagement/Drives/GetDrivesEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/FileSystemManagement/Drives/GetDrivesEndpointTests.cs index 83948cef..8d9748bc 100644 --- a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/FileSystemManagement/Drives/GetDrivesEndpointTests.cs +++ b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/FileSystemManagement/Drives/GetDrivesEndpointTests.cs @@ -9,7 +9,7 @@ using System.Text.Json; namespace Lumina.Presentation.Api.SecurityTests.Core.Endpoints.FileSystemManagement.Drives; /// -/// Contains security tests for the /drives/get-drives route. +/// Contains security tests for the class. /// [ExcludeFromCodeCoverage] public class GetDrivesEndpointTests : IClassFixture diff --git a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/FileSystemManagement/FileSystem/GetTypeEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/FileSystemManagement/FileSystem/GetTypeEndpointTests.cs index efbe2289..271de8e6 100644 --- a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/FileSystemManagement/FileSystem/GetTypeEndpointTests.cs +++ b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/FileSystemManagement/FileSystem/GetTypeEndpointTests.cs @@ -9,7 +9,7 @@ using System.Text.Json; namespace Lumina.Presentation.Api.SecurityTests.Core.Endpoints.FileSystemManagement.FileSystem; /// -/// Contains security tests for the /file-system/get-type route. +/// Contains security tests for the class. /// [ExcludeFromCodeCoverage] public class GetTypeEndpointTests : IClassFixture diff --git a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/FileSystemManagement/Files/GetFilesEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/FileSystemManagement/Files/GetFilesEndpointTests.cs index ba5bfc87..649c6786 100644 --- a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/FileSystemManagement/Files/GetFilesEndpointTests.cs +++ b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/FileSystemManagement/Files/GetFilesEndpointTests.cs @@ -9,7 +9,7 @@ using System.Text.Json; namespace Lumina.Presentation.Api.SecurityTests.Core.Endpoints.FileSystemManagement.Files; /// -/// Contains security tests for the /files/get-files route. +/// Contains security tests for the class. /// [ExcludeFromCodeCoverage] public class GetFilesEndpointTests : IClassFixture diff --git a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/FileSystemManagement/Files/GetTreeFilesEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/FileSystemManagement/Files/GetTreeFilesEndpointTests.cs index cff25ace..697f4e2e 100644 --- a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/FileSystemManagement/Files/GetTreeFilesEndpointTests.cs +++ b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/FileSystemManagement/Files/GetTreeFilesEndpointTests.cs @@ -9,7 +9,7 @@ using System.Text.Json; namespace Lumina.Presentation.Api.SecurityTests.Core.Endpoints.FileSystemManagement.Files; /// -/// Contains security tests for the /files/get-tree-files route. +/// Contains security tests for the class. /// [ExcludeFromCodeCoverage] public class GetTreeFilesEndpointTests : IClassFixture diff --git a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/FileSystemManagement/Path/CheckPathExistsEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/FileSystemManagement/Path/CheckPathExistsEndpointTests.cs index 9a5229e4..e4b97187 100644 --- a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/FileSystemManagement/Path/CheckPathExistsEndpointTests.cs +++ b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/FileSystemManagement/Path/CheckPathExistsEndpointTests.cs @@ -9,7 +9,7 @@ using System.Text.Json; namespace Lumina.Presentation.Api.SecurityTests.Core.Endpoints.FileSystemManagement.Path; /// -/// Contains security tests for the /path/check-path-exists route. +/// Contains security tests for the class. /// [ExcludeFromCodeCoverage] public class CheckPathExistsEndpointTests : IClassFixture diff --git a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/FileSystemManagement/Path/CombinePathEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/FileSystemManagement/Path/CombinePathEndpointTests.cs index 6c6ca236..ce7d37f0 100644 --- a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/FileSystemManagement/Path/CombinePathEndpointTests.cs +++ b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/FileSystemManagement/Path/CombinePathEndpointTests.cs @@ -9,7 +9,7 @@ using System.Text.Json; namespace Lumina.Presentation.Api.SecurityTests.Core.Endpoints.FileSystemManagement.Path; /// -/// Contains security tests for the /path/combine route. +/// Contains security tests for the class. /// [ExcludeFromCodeCoverage] public class CombinePathEndpointTests : IClassFixture diff --git a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/FileSystemManagement/Path/GetPathParentEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/FileSystemManagement/Path/GetPathParentEndpointTests.cs index ca67e30b..c51d38cd 100644 --- a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/FileSystemManagement/Path/GetPathParentEndpointTests.cs +++ b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/FileSystemManagement/Path/GetPathParentEndpointTests.cs @@ -9,7 +9,7 @@ using System.Text.Json; namespace Lumina.Presentation.Api.SecurityTests.Core.Endpoints.FileSystemManagement.Path; /// -/// Contains security tests for the /path/get-path-parent route. +/// Contains security tests for the class. /// [ExcludeFromCodeCoverage] public class GetPathParentEndpointTests : IClassFixture diff --git a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/FileSystemManagement/Path/GetPathRootEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/FileSystemManagement/Path/GetPathRootEndpointTests.cs index 080b3139..4632c94d 100644 --- a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/FileSystemManagement/Path/GetPathRootEndpointTests.cs +++ b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/FileSystemManagement/Path/GetPathRootEndpointTests.cs @@ -9,7 +9,7 @@ using System.Text.Json; namespace Lumina.Presentation.Api.SecurityTests.Core.Endpoints.FileSystemManagement.Path; /// -/// Contains security tests for the /path/get-path-root route. +/// Contains security tests for the class. /// [ExcludeFromCodeCoverage] public class GetPathRootEndpointTests : IClassFixture diff --git a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/FileSystemManagement/Path/GetPathSeparatorEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/FileSystemManagement/Path/GetPathSeparatorEndpointTests.cs index c0089b97..90db779b 100644 --- a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/FileSystemManagement/Path/GetPathSeparatorEndpointTests.cs +++ b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/FileSystemManagement/Path/GetPathSeparatorEndpointTests.cs @@ -9,7 +9,7 @@ using System.Text.Json; namespace Lumina.Presentation.Api.SecurityTests.Core.Endpoints.FileSystemManagement.Path; /// -/// Contains security tests for the /path/get-path-separator route. +/// Contains security tests for the class. /// [ExcludeFromCodeCoverage] public class GetPathSeparatorEndpointTests : IClassFixture diff --git a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/FileSystemManagement/Path/SplitPathEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/FileSystemManagement/Path/SplitPathEndpointTests.cs index 8acf47a8..f7fa2dd5 100644 --- a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/FileSystemManagement/Path/SplitPathEndpointTests.cs +++ b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/FileSystemManagement/Path/SplitPathEndpointTests.cs @@ -9,7 +9,7 @@ using System.Text.Json; namespace Lumina.Presentation.Api.SecurityTests.Core.Endpoints.FileSystemManagement.Path; /// -/// Contains security tests for the /path/split route. +/// Contains security tests for the class. /// [ExcludeFromCodeCoverage] public class SplitPathEndpointTests : IClassFixture diff --git a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/FileSystemManagement/Path/ValidatePathEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/FileSystemManagement/Path/ValidatePathEndpointTests.cs index 4de7b1d1..d6bcd2a9 100644 --- a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/FileSystemManagement/Path/ValidatePathEndpointTests.cs +++ b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/FileSystemManagement/Path/ValidatePathEndpointTests.cs @@ -9,7 +9,7 @@ using System.Text.Json; namespace Lumina.Presentation.Api.SecurityTests.Core.Endpoints.FileSystemManagement.Path; /// -/// Contains security tests for the /path/validate route. +/// Contains security tests for the class. /// [ExcludeFromCodeCoverage] public class ValidatePathEndpointTests : IClassFixture diff --git a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/FileSystemManagement/Thumbnails/GetThumbnailEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/FileSystemManagement/Thumbnails/GetThumbnailEndpointTests.cs index eea1acc6..6d060d6e 100644 --- a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/FileSystemManagement/Thumbnails/GetThumbnailEndpointTests.cs +++ b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/FileSystemManagement/Thumbnails/GetThumbnailEndpointTests.cs @@ -9,7 +9,7 @@ using System.Text.Json; namespace Lumina.Presentation.Api.SecurityTests.Core.Endpoints.FileSystemManagement.Thumbnails; /// -/// Contains security tests for the /thumbnails/get-thumbnail route. +/// Contains security tests for the class. /// [ExcludeFromCodeCoverage] public class GetThumbnailEndpointTests : IClassFixture diff --git a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Library/Management/AddLibrary/AddLibraryEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Library/Management/AddLibrary/AddLibraryEndpointTests.cs index 238c06f5..7795cae6 100644 --- a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Library/Management/AddLibrary/AddLibraryEndpointTests.cs +++ b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Library/Management/AddLibrary/AddLibraryEndpointTests.cs @@ -16,7 +16,7 @@ using System.Text.Json; namespace Lumina.Presentation.Api.SecurityTests.Core.Endpoints.Library.Management.AddLibrary; /// -/// Contains security tests for the /libraries route. +/// Contains security tests for the class. /// [ExcludeFromCodeCoverage] public class AddLibraryEndpointTests : IClassFixture diff --git a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Library/Management/CancelLibrariesScan/CancelLibrariesScanEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Library/Management/CancelLibrariesScan/CancelLibrariesScanEndpointTests.cs index 1f9ff1fc..5e6c3745 100644 --- a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Library/Management/CancelLibrariesScan/CancelLibrariesScanEndpointTests.cs +++ b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Library/Management/CancelLibrariesScan/CancelLibrariesScanEndpointTests.cs @@ -18,7 +18,7 @@ using System.Text.Json; namespace Lumina.Presentation.Api.SecurityTests.Core.Endpoints.Library.Management.CancelLibrariesScan; /// -/// Contains security tests for the /libraries/scans/cancel route. +/// Contains security tests for the class. /// [ExcludeFromCodeCoverage] public class CancelLibrariesScanEndpointTests : IClassFixture diff --git a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Library/Management/CancelLibraryScan/CancelLibraryScanEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Library/Management/CancelLibraryScan/CancelLibraryScanEndpointTests.cs index bfb988e1..a22fed58 100644 --- a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Library/Management/CancelLibraryScan/CancelLibraryScanEndpointTests.cs +++ b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Library/Management/CancelLibraryScan/CancelLibraryScanEndpointTests.cs @@ -14,7 +14,7 @@ using System.Text.Json; namespace Lumina.Presentation.Api.SecurityTests.Core.Endpoints.Library.Management.CancelLibraryScan; /// -/// Contains security tests for the /libraries/{libraryId}/scans/{scanId}/cancel route. +/// Contains security tests for the class. /// [ExcludeFromCodeCoverage] public class CancelLibraryScanEndpointTests : IClassFixture diff --git a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Library/Management/DeleteLibrary/DeleteLibraryEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Library/Management/DeleteLibrary/DeleteLibraryEndpointTests.cs index ee2af717..a400aa53 100644 --- a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Library/Management/DeleteLibrary/DeleteLibraryEndpointTests.cs +++ b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Library/Management/DeleteLibrary/DeleteLibraryEndpointTests.cs @@ -13,7 +13,7 @@ using System.Text.Json; namespace Lumina.Presentation.Api.SecurityTests.Core.Endpoints.Library.Management.DeleteLibrary; /// -/// Contains security tests for the /libraries/{id} route. +/// Contains security tests for the class. /// [ExcludeFromCodeCoverage] public class DeleteLibraryEndpointTests : IClassFixture diff --git a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Library/Management/GetEnabledLibraries/GetEnabledLibrariesEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Library/Management/GetEnabledLibraries/GetEnabledLibrariesEndpointTests.cs index dd622751..e0d6a5c1 100644 --- a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Library/Management/GetEnabledLibraries/GetEnabledLibrariesEndpointTests.cs +++ b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Library/Management/GetEnabledLibraries/GetEnabledLibrariesEndpointTests.cs @@ -18,7 +18,7 @@ using System.Text.Json; namespace Lumina.Presentation.Api.SecurityTests.Core.Endpoints.Library.Management.GetEnabledLibraries; /// -/// Contains security tests for the /libraries/enabled route. +/// Contains security tests for the class. /// [ExcludeFromCodeCoverage] public class GetEnabledLibrariesEndpointTests : IClassFixture diff --git a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Library/Management/GetLibraries/GetLibrariesEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Library/Management/GetLibraries/GetLibrariesEndpointTests.cs index c433756b..a28cd713 100644 --- a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Library/Management/GetLibraries/GetLibrariesEndpointTests.cs +++ b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Library/Management/GetLibraries/GetLibrariesEndpointTests.cs @@ -18,7 +18,7 @@ using System.Text.Json; namespace Lumina.Presentation.Api.SecurityTests.Core.Endpoints.Library.Management.GetLibraries; /// -/// Contains security tests for the /libraries route. +/// Contains security tests for the class. /// [ExcludeFromCodeCoverage] public class GetLibrariesEndpointTests : IClassFixture diff --git a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Library/Management/GetLibrary/GetLibraryEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Library/Management/GetLibrary/GetLibraryEndpointTests.cs index d9dc96f4..569ef2d2 100644 --- a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Library/Management/GetLibrary/GetLibraryEndpointTests.cs +++ b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Library/Management/GetLibrary/GetLibraryEndpointTests.cs @@ -20,7 +20,7 @@ using System.Text.Json; namespace Lumina.Presentation.Api.SecurityTests.Core.Endpoints.Library.Management.GetLibrary; /// -/// Contains security tests for the /libraries/{id} route. +/// Contains security tests for the class. /// [ExcludeFromCodeCoverage] public class GetLibraryEndpointTests : IClassFixture diff --git a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Library/Management/GetLibraryScanProgress/GetLibraryScanProgressEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Library/Management/GetLibraryScanProgress/GetLibraryScanProgressEndpointTests.cs index c38d991d..de45001e 100644 --- a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Library/Management/GetLibraryScanProgress/GetLibraryScanProgressEndpointTests.cs +++ b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Library/Management/GetLibraryScanProgress/GetLibraryScanProgressEndpointTests.cs @@ -13,7 +13,7 @@ using System.Text.Json; namespace Lumina.Presentation.Api.SecurityTests.Core.Endpoints.Library.Management.GetLibraryScanProgress; /// -/// Contains security tests for the /libraries/{libraryId}/scans/{scanId}/progress route. +/// Contains security tests for the class. /// [ExcludeFromCodeCoverage] public class GetLibraryScanProgressEndpointTests : IClassFixture diff --git a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Library/Management/GetRunningLibraryScans/GetRunningLibraryScansEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Library/Management/GetRunningLibraryScans/GetRunningLibraryScansEndpointTests.cs index c7f82d86..d4c3aa6a 100644 --- a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Library/Management/GetRunningLibraryScans/GetRunningLibraryScansEndpointTests.cs +++ b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Library/Management/GetRunningLibraryScans/GetRunningLibraryScansEndpointTests.cs @@ -18,7 +18,7 @@ using System.Text.Json; namespace Lumina.Presentation.Api.SecurityTests.Core.Endpoints.Library.Management.GetRunningLibraryScans; /// -/// Contains security tests for the /libraries/scans/running route. +/// Contains security tests for the class. /// [ExcludeFromCodeCoverage] public class GetRunningLibraryScansEndpointTests : IClassFixture diff --git a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Library/Management/ScanLibraries/ScanLibrariesEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Library/Management/ScanLibraries/ScanLibrariesEndpointTests.cs index 8bcd3d50..cc825e90 100644 --- a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Library/Management/ScanLibraries/ScanLibrariesEndpointTests.cs +++ b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Library/Management/ScanLibraries/ScanLibrariesEndpointTests.cs @@ -18,7 +18,7 @@ using System.Text.Json; namespace Lumina.Presentation.Api.SecurityTests.Core.Endpoints.Library.Management.ScanLibraries; /// -/// Contains security tests for the /libraries/scans route. +/// Contains security tests for the class. /// [ExcludeFromCodeCoverage] public class ScanLibrariesEndpointTests : IClassFixture diff --git a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Library/Management/ScanLibrary/ScanLibraryEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Library/Management/ScanLibrary/ScanLibraryEndpointTests.cs index 20bf16d3..6332695e 100644 --- a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Library/Management/ScanLibrary/ScanLibraryEndpointTests.cs +++ b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Library/Management/ScanLibrary/ScanLibraryEndpointTests.cs @@ -14,7 +14,7 @@ using System.Text.Json; namespace Lumina.Presentation.Api.SecurityTests.Core.Endpoints.Library.Management.ScanLibrary; /// -/// Contains security tests for the /libraries/{id}/scans route. +/// Contains security tests for the class. /// [ExcludeFromCodeCoverage] public class ScanLibraryEndpointTests : IClassFixture diff --git a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Library/Management/UpdateLibrary/UpdateLibraryEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Library/Management/UpdateLibrary/UpdateLibraryEndpointTests.cs index 50a59428..a5e9a231 100644 --- a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Library/Management/UpdateLibrary/UpdateLibraryEndpointTests.cs +++ b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Library/Management/UpdateLibrary/UpdateLibraryEndpointTests.cs @@ -18,7 +18,7 @@ using System.Text.Json; namespace Lumina.Presentation.Api.SecurityTests.Core.Endpoints.Library.Management.UpdateLibrary; /// -/// Contains security tests for the /libraries/{id} route. +/// Contains security tests for the class. /// [ExcludeFromCodeCoverage] public class UpdateLibraryEndpointTests : IClassFixture diff --git a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/AddBook/AddBookEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/AddBook/AddBookEndpointTests.cs index 436a84ff..5f8031dc 100644 --- a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/AddBook/AddBookEndpointTests.cs +++ b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/AddBook/AddBookEndpointTests.cs @@ -20,7 +20,7 @@ using System.Threading.Tasks; namespace Lumina.Presentation.Api.SecurityTests.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.Books.AddBook; /// -/// Contains security tests for the /books route. +/// Contains security tests for the class. /// [ExcludeFromCodeCoverage] public class AddBookEndpointTests : IClassFixture, IDisposable @@ -51,7 +51,7 @@ public class AddBookEndpointTests : IClassFixture, IDisposable (Guid userId, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(client); Guid libraryId = Guid.NewGuid(); await _apiFactory.SeedLibraryAsync(libraryId, userId); - AddBookRequest request = _addBookRequestFixture.Create() with { LibraryId = libraryId, Path = maliciousPath }; + AddBookRequest request = _addBookRequestFixture.Create(libraryId: libraryId, path: maliciousPath); // Act HttpResponseMessage response = await client.PostAsJsonAsync("/api/v1/books", request); diff --git a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/GetBook/GetBookEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/GetBook/GetBookEndpointTests.cs index 3e64f24e..4088d216 100644 --- a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/GetBook/GetBookEndpointTests.cs +++ b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/GetBook/GetBookEndpointTests.cs @@ -1,20 +1,23 @@ #region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Api.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.Books.GetBook; using Lumina.Presentation.Api.SecurityTests.Common.Setup; +using System; using System.Diagnostics.CodeAnalysis; using System.Net; using System.Net.Http; +using System.Text.Json; using System.Threading.Tasks; #endregion namespace Lumina.Presentation.Api.SecurityTests.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.Books.GetBook; /// -/// Contains security tests for the /books/{id} route. +/// Contains security tests for the class. /// [ExcludeFromCodeCoverage] public class GetBookEndpointTests : IClassFixture { - private readonly HttpClient _client; + private readonly LuminaApiFactory _apiFactory; /// /// Initializes a new instance of the class. @@ -22,46 +25,46 @@ public class GetBookEndpointTests : IClassFixture /// Injected in-memory API factory. public GetBookEndpointTests(LuminaApiFactory apiFactory) { - _client = apiFactory.CreateClient(); + _apiFactory = apiFactory; } [Fact] - public async Task GetBook_WhenCalledWithoutAuthentication_ShouldBeAccessible() + public async Task GetBook_WhenCalledWithoutAuthentication_ShouldReturnUnauthorized() { // Arrange - Guid bookId = Guid.NewGuid(); + HttpClient client = _apiFactory.CreateClient(); // Act - HttpResponseMessage response = await _client.GetAsync($"/api/v1/books/{bookId}"); + HttpResponseMessage response = await client.GetAsync($"/api/v1/books/{Guid.NewGuid()}"); // Assert - Assert.Equal(HttpStatusCode.OK, response.StatusCode); + Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode); string content = await response.Content.ReadAsStringAsync(); - Assert.DoesNotContain("password", content, StringComparison.OrdinalIgnoreCase); - Assert.DoesNotContain("hash", content, StringComparison.OrdinalIgnoreCase); - Assert.DoesNotContain("salt", content, StringComparison.OrdinalIgnoreCase); Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase); } [Theory] - [InlineData("' OR '1'='1")] // basic SQL injection - [InlineData("'; DROP TABLE Books--")] // destructive injection - public async Task GetBook_WithSQLInjectionInBookId_ShouldNotLeakOrError(string maliciousBookId) + [InlineData("'; DROP TABLE Books; --")] // destructive injection + [InlineData("' OR '1'='1")] // boolean-based injection + public async Task GetBook_WithSQLInjectionInBookId_ShouldNotCorruptOrLeakData(string maliciousBookId) { // Arrange - // the {id} route parameter is string-typed, so the malicious value binds and reaches the anonymous endpoint handler + HttpClient client = _apiFactory.CreateClient(); + (_, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(client); // Act - HttpResponseMessage response = await _client.GetAsync($"/api/v1/books/{Uri.EscapeDataString(maliciousBookId)}"); - string content = await response.Content.ReadAsStringAsync(); + HttpResponseMessage response = await client.GetAsync($"/api/v1/books/{Uri.EscapeDataString(maliciousBookId)}"); // Assert - // the endpoint processes the value without querying the persistence medium and without leaking it - Assert.Equal(HttpStatusCode.OK, response.StatusCode); + // The unparseable route value becomes an empty book Id, which the query validator reports as a missing book Id. + Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode); + string content = await response.Content.ReadAsStringAsync(); Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("SQL", content, StringComparison.OrdinalIgnoreCase); Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase); - Assert.DoesNotContain("password", content, StringComparison.OrdinalIgnoreCase); - Assert.DoesNotContain("hash", content, StringComparison.OrdinalIgnoreCase); - Assert.DoesNotContain("salt", content, StringComparison.OrdinalIgnoreCase); + using JsonDocument problemDetails = JsonDocument.Parse(content); + Assert.Equal("General.Validation", problemDetails.RootElement.GetProperty("title").GetString()); + + await _apiFactory.RemoveTestUserAsync(username); } } diff --git a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/GetBooks/GetBooksEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/GetBooks/GetBooksEndpointTests.cs index 98f13088..6e3132d7 100644 --- a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/GetBooks/GetBooksEndpointTests.cs +++ b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/GetBooks/GetBooksEndpointTests.cs @@ -14,7 +14,7 @@ using System.Threading.Tasks; namespace Lumina.Presentation.Api.SecurityTests.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.Books.GetBooks; /// -/// Contains security tests for the /books route. +/// Contains security tests for the class. /// [ExcludeFromCodeCoverage] public class GetBooksEndpointTests : IClassFixture, IDisposable diff --git a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/GetBooksLite/GetBooksLiteEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/GetBooksLite/GetBooksLiteEndpointTests.cs index fb62b38f..bf387226 100644 --- a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/GetBooksLite/GetBooksLiteEndpointTests.cs +++ b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/GetBooksLite/GetBooksLiteEndpointTests.cs @@ -15,7 +15,7 @@ using System.Threading.Tasks; namespace Lumina.Presentation.Api.SecurityTests.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.Books.GetBooksLite; /// -/// Contains security tests for the /books/lite route. +/// Contains security tests for the class. /// [ExcludeFromCodeCoverage] public class GetBooksLiteEndpointTests : IClassFixture, IDisposable diff --git a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/Reading/GetReadingAvailability/GetReadingAvailabilityEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/Reading/GetReadingAvailability/GetReadingAvailabilityEndpointTests.cs index 52de5fd7..f0d2cab7 100644 --- a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/Reading/GetReadingAvailability/GetReadingAvailabilityEndpointTests.cs +++ b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/Reading/GetReadingAvailability/GetReadingAvailabilityEndpointTests.cs @@ -9,7 +9,7 @@ using System.Text.Json; namespace Lumina.Presentation.Api.SecurityTests.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.Books.Reading.GetReadingAvailability; /// -/// Contains security tests for the /books/{bookId}/reading/availability route. +/// Contains security tests for the class. /// [ExcludeFromCodeCoverage] public class GetReadingAvailabilityEndpointTests : IClassFixture diff --git a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/Reading/GetReadingManifest/GetReadingManifestEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/Reading/GetReadingManifest/GetReadingManifestEndpointTests.cs index bf528b9b..e4841be8 100644 --- a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/Reading/GetReadingManifest/GetReadingManifestEndpointTests.cs +++ b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/Reading/GetReadingManifest/GetReadingManifestEndpointTests.cs @@ -13,7 +13,7 @@ using System.Threading.Tasks; namespace Lumina.Presentation.Api.SecurityTests.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.Books.Reading.GetReadingManifest; /// -/// Contains security tests for the /books/{bookId}/reading/manifest route. +/// Contains security tests for the class. /// [ExcludeFromCodeCoverage] public class GetReadingManifestEndpointTests : IClassFixture diff --git a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/Reading/GetReadingResource/GetReadingResourceEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/Reading/GetReadingResource/GetReadingResourceEndpointTests.cs index 4e6021f3..d1e2ba8f 100644 --- a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/Reading/GetReadingResource/GetReadingResourceEndpointTests.cs +++ b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/Reading/GetReadingResource/GetReadingResourceEndpointTests.cs @@ -13,7 +13,7 @@ using System.Threading.Tasks; namespace Lumina.Presentation.Api.SecurityTests.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.Books.Reading.GetReadingResource; /// -/// Contains security tests for the /books/{bookId}/reading/resources/{resourceKey} route. +/// Contains security tests for the class. /// [ExcludeFromCodeCoverage] public class GetReadingResourceEndpointTests : IClassFixture diff --git a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/Reading/GetReadingSection/GetReadingSectionEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/Reading/GetReadingSection/GetReadingSectionEndpointTests.cs index d946c69d..89b8842f 100644 --- a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/Reading/GetReadingSection/GetReadingSectionEndpointTests.cs +++ b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/Reading/GetReadingSection/GetReadingSectionEndpointTests.cs @@ -13,7 +13,7 @@ using System.Threading.Tasks; namespace Lumina.Presentation.Api.SecurityTests.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.Books.Reading.GetReadingSection; /// -/// Contains security tests for the /books/{bookId}/reading/sections/{locationRef} route. +/// Contains security tests for the class. /// [ExcludeFromCodeCoverage] public class GetReadingSectionEndpointTests : IClassFixture diff --git a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/UpdateBook/UpdateBookEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/UpdateBook/UpdateBookEndpointTests.cs new file mode 100644 index 00000000..3864d177 --- /dev/null +++ b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/UpdateBook/UpdateBookEndpointTests.cs @@ -0,0 +1,130 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Contracts.Fixtures.Core.DTO.MediaLibrary.WrittenContentLibrary; +using Lumina.Contracts.Fixtures.Core.Requests.MediaLibrary.WrittenContentLibrary.BookLibrary.Books; +using Lumina.Contracts.Requests.MediaLibrary.WrittenContentLibrary.BookLibrary.Books; +using Lumina.Presentation.Api.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.Books.UpdateBook; +using Lumina.Presentation.Api.SecurityTests.Common.Setup; +using System; +using System.Diagnostics.CodeAnalysis; +using System.Net; +using System.Net.Http; +using System.Net.Http.Json; +using System.Text.Json; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Api.SecurityTests.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.Books.UpdateBook; + +/// +/// Contains security tests for the class. +/// +[ExcludeFromCodeCoverage] +public class UpdateBookEndpointTests : IClassFixture +{ + private readonly LuminaApiFactory _apiFactory; + private readonly UpdateBookRequestFixture _updateBookRequestFixture = new(); + private readonly WrittenContentMetadataDtoFixture _writtenContentMetadataDtoFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + /// Injected in-memory API factory. + public UpdateBookEndpointTests(LuminaApiFactory apiFactory) + { + _apiFactory = apiFactory; + } + + [Fact] + public async Task UpdateBook_WhenCalledWithoutAuthentication_ShouldReturnUnauthorized() + { + // Arrange + HttpClient client = _apiFactory.CreateClient(); + UpdateBookRequest request = _updateBookRequestFixture.Create(); + + // Act + HttpResponseMessage response = await client.PutAsJsonAsync($"/api/v1/books/{request.Id}", request); + + // Assert + Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode); + string content = await response.Content.ReadAsStringAsync(); + Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase); + } + + [Theory] + [InlineData("'; DROP TABLE Books; --")] // destructive injection + [InlineData("' OR '1'='1")] // boolean-based injection + public async Task UpdateBook_WithSQLInjectionInBody_ShouldNotCorruptOrLeakData(string maliciousTitle) + { + // Arrange + HttpClient client = _apiFactory.CreateClient(); + (_, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(client); + UpdateBookRequest request = _updateBookRequestFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(title: maliciousTitle)); + + // Act + HttpResponseMessage response = await client.PutAsJsonAsync($"/api/v1/books/{request.Id}", request); + + // Assert + // The injected title is validated and handled by the parameterized update flow: the route book does not exist, + // so the request fails with a clean not found response and the injected payload is never executed as SQL. + Assert.Equal(HttpStatusCode.NotFound, response.StatusCode); + string content = await response.Content.ReadAsStringAsync(); + Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain(maliciousTitle, content, StringComparison.Ordinal); + + await _apiFactory.RemoveTestUserAsync(username); + } + + [Theory] + [InlineData("'; DROP TABLE Books; --")] // destructive injection + [InlineData("' OR '1'='1")] // boolean-based injection + public async Task UpdateBook_WithSQLInjectionInRouteId_ShouldNeverCorruptOrLeakData(string maliciousBookId) + { + // Arrange + HttpClient client = _apiFactory.CreateClient(); + (_, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(client); + UpdateBookRequest request = _updateBookRequestFixture.Create(); + + // Act + HttpResponseMessage response = await client.PutAsJsonAsync($"/api/v1/books/{Uri.EscapeDataString(maliciousBookId)}", request); + + // Assert + // The route is authoritative and its raw value is kept as a string, so an unparseable route Id reaches the command + // mapping and becomes Guid.Empty, which the command validator reports as a clean validation error. The response must + // not leak stack traces, database details, or the injected payload, and the body Id never redirects the update. + Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode); + string content = await response.Content.ReadAsStringAsync(); + Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain(maliciousBookId, content, StringComparison.Ordinal); + using JsonDocument problemDetails = JsonDocument.Parse(content); + Assert.Equal("General.Validation", problemDetails.RootElement.GetProperty("title").GetString()); + Assert.Contains("BookIdCannotBeEmpty", content, StringComparison.OrdinalIgnoreCase); + + await _apiFactory.RemoveTestUserAsync(username); + } + + [Fact] + public async Task UpdateBook_WhenRouteBookDoesNotExistEvenIfBodyIdDiffers_ShouldReturnNotFound() + { + // Arrange + HttpClient client = _apiFactory.CreateClient(); + (_, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(client); + Guid routeId = Guid.NewGuid(); + UpdateBookRequest request = _updateBookRequestFixture.Create(); + + // Act + HttpResponseMessage response = await client.PutAsJsonAsync($"/api/v1/books/{routeId}", request); + + // Assert + Assert.Equal(HttpStatusCode.NotFound, response.StatusCode); + string content = await response.Content.ReadAsStringAsync(); + Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase); + using JsonDocument problemDetails = JsonDocument.Parse(content); + Assert.Equal("General.NotFound", problemDetails.RootElement.GetProperty("title").GetString()); + Assert.Equal("BookNotFound", problemDetails.RootElement.GetProperty("detail").GetString()); + + await _apiFactory.RemoveTestUserAsync(username); + } +} diff --git a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/UpdateBookCover/UpdateBookCoverEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/UpdateBookCover/UpdateBookCoverEndpointTests.cs new file mode 100644 index 00000000..a2d91107 --- /dev/null +++ b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/UpdateBookCover/UpdateBookCoverEndpointTests.cs @@ -0,0 +1,109 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Api.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.Books.UpdateBookCover; +using Lumina.Presentation.Api.SecurityTests.Common.Setup; +using System; +using System.Diagnostics.CodeAnalysis; +using System.Net; +using System.Net.Http; +using System.Net.Http.Headers; +using System.Text; +using System.Text.Json; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Api.SecurityTests.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.Books.UpdateBookCover; + +/// +/// Contains security tests for the class. +/// +[ExcludeFromCodeCoverage] +public class UpdateBookCoverEndpointTests : IClassFixture +{ + private readonly LuminaApiFactory _apiFactory; + + /// + /// Initializes a new instance of the class. + /// + /// Injected in-memory API factory. + public UpdateBookCoverEndpointTests(LuminaApiFactory apiFactory) + { + _apiFactory = apiFactory; + } + + [Fact] + public async Task UpdateBookCover_WhenCalledWithoutAuthentication_ShouldReturnUnauthorized() + { + // Arrange + HttpClient client = _apiFactory.CreateClient(); + MultipartFormDataContent form = CreateCoverForm("cover.jpg"); + + // Act + HttpResponseMessage response = await client.PutAsync($"/api/v1/books/{Guid.NewGuid()}/cover", form); + + // Assert + Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode); + string content = await response.Content.ReadAsStringAsync(); + Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase); + } + + [Theory] + [InlineData("'; DROP TABLE Books; --")] // destructive injection + [InlineData("' OR '1'='1")] // boolean-based injection + public async Task UpdateBookCover_WithSQLInjectionInRouteId_ShouldNotCorruptOrLeakData(string maliciousBookId) + { + // Arrange + HttpClient client = _apiFactory.CreateClient(); + (_, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(client); + MultipartFormDataContent form = CreateCoverForm("cover.jpg"); + + // Act + HttpResponseMessage response = await client.PutAsync($"/api/v1/books/{Uri.EscapeDataString(maliciousBookId)}/cover", form); + + // Assert + // The unparseable route value becomes an empty book Id, which the command validator reports as a missing book Id. + Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode); + string content = await response.Content.ReadAsStringAsync(); + Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("SQL", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase); + using JsonDocument problemDetails = JsonDocument.Parse(content); + Assert.Equal("General.Validation", problemDetails.RootElement.GetProperty("title").GetString()); + + await _apiFactory.RemoveTestUserAsync(username); + } + + [Fact] + public async Task UpdateBookCover_WithMaliciousFileName_ShouldNotCorruptOrLeakData() + { + // Arrange + HttpClient client = _apiFactory.CreateClient(); + (_, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(client); + MultipartFormDataContent form = CreateCoverForm("..\\..\\evil.jpg"); + + // Act + HttpResponseMessage response = await client.PutAsync($"/api/v1/books/{Guid.NewGuid()}/cover", form); + + // Assert + // The book does not exist, so the handler returns a clean not found response before the uploaded file name is used. + Assert.Equal(HttpStatusCode.NotFound, response.StatusCode); + string content = await response.Content.ReadAsStringAsync(); + Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase); + + await _apiFactory.RemoveTestUserAsync(username); + } + + /// + /// Creates a multipart form carrying a minimal cover payload with the specified file name. + /// + /// The name of the uploaded file. + /// A configured instance. + private static MultipartFormDataContent CreateCoverForm(string fileName) + { + MultipartFormDataContent form = []; + ByteArrayContent fileContent = new(Encoding.UTF8.GetBytes("fake cover payload")); + fileContent.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream"); + form.Add(fileContent, "cover", fileName); + return form; + } +} diff --git a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Maintenance/ApplicationSetup/CheckInitializationEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Maintenance/ApplicationSetup/CheckInitializationEndpointTests.cs index a60be659..5a6daf05 100644 --- a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Maintenance/ApplicationSetup/CheckInitializationEndpointTests.cs +++ b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Maintenance/ApplicationSetup/CheckInitializationEndpointTests.cs @@ -7,7 +7,7 @@ using System.Net; namespace Lumina.Presentation.Api.SecurityTests.Core.Endpoints.Maintenance.ApplicationSetup; /// -/// Contains security tests for the /initialization route. +/// Contains security tests for the class. /// [ExcludeFromCodeCoverage] public class CheckInitializationEndpointTests : IClassFixture diff --git a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Maintenance/ApplicationSetup/SetupApplicationEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Maintenance/ApplicationSetup/SetupApplicationEndpointTests.cs index c6235d7d..6e3dd3eb 100644 --- a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Maintenance/ApplicationSetup/SetupApplicationEndpointTests.cs +++ b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Maintenance/ApplicationSetup/SetupApplicationEndpointTests.cs @@ -10,7 +10,7 @@ using System.Net.Http.Json; namespace Lumina.Presentation.Api.SecurityTests.Core.Endpoints.Maintenance.ApplicationSetup; /// -/// Contains security tests for the /initialization route. +/// Contains security tests for the class. /// [ExcludeFromCodeCoverage] public class SetupApplicationEndpointTests : IClassFixture diff --git a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Maintenance/CheckHealthEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Maintenance/CheckHealthEndpointTests.cs index adce30ab..695e54df 100644 --- a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Maintenance/CheckHealthEndpointTests.cs +++ b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Maintenance/CheckHealthEndpointTests.cs @@ -2,14 +2,12 @@ using Lumina.Presentation.Api.SecurityTests.Common.Setup; using System.Diagnostics.CodeAnalysis; using System.Net; -using System.Net.Http; -using System.Threading.Tasks; #endregion namespace Lumina.Presentation.Api.SecurityTests.Core.Endpoints.Maintenance; /// -/// Contains security tests for the /check-health route. +/// Contains security tests for the class. /// [ExcludeFromCodeCoverage] public class CheckHealthEndpointTests : IClassFixture diff --git a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Plugins/GetLibraryArtworkProviders/GetLibraryArtworkProvidersEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Plugins/GetLibraryArtworkProviders/GetLibraryArtworkProvidersEndpointTests.cs index 4e6d5c9f..43eb2eae 100644 --- a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Plugins/GetLibraryArtworkProviders/GetLibraryArtworkProvidersEndpointTests.cs +++ b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Plugins/GetLibraryArtworkProviders/GetLibraryArtworkProvidersEndpointTests.cs @@ -14,7 +14,7 @@ using System.Text.Json; namespace Lumina.Presentation.Api.SecurityTests.Core.Endpoints.Plugins.GetLibraryArtworkProviders; /// -/// Contains security tests for the /libraries/{libraryId}/artwork-providers route. +/// Contains security tests for the class. /// [ExcludeFromCodeCoverage] public class GetLibraryArtworkProvidersEndpointTests : IClassFixture diff --git a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Plugins/GetLibraryBookReaders/GetLibraryBookReadersEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Plugins/GetLibraryBookReaders/GetLibraryBookReadersEndpointTests.cs index c685f32f..199ad2f2 100644 --- a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Plugins/GetLibraryBookReaders/GetLibraryBookReadersEndpointTests.cs +++ b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Plugins/GetLibraryBookReaders/GetLibraryBookReadersEndpointTests.cs @@ -13,7 +13,7 @@ using System.Threading.Tasks; namespace Lumina.Presentation.Api.SecurityTests.Core.Endpoints.Plugins.GetLibraryBookReaders; /// -/// Contains security tests for the /libraries/{libraryId}/book-readers route. +/// Contains security tests for the class. /// [ExcludeFromCodeCoverage] public class GetLibraryBookReadersEndpointTests : IClassFixture diff --git a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Plugins/GetLibraryMetadataProviders/GetLibraryMetadataProvidersEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Plugins/GetLibraryMetadataProviders/GetLibraryMetadataProvidersEndpointTests.cs index f8467d7e..0c928291 100644 --- a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Plugins/GetLibraryMetadataProviders/GetLibraryMetadataProvidersEndpointTests.cs +++ b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Plugins/GetLibraryMetadataProviders/GetLibraryMetadataProvidersEndpointTests.cs @@ -14,7 +14,7 @@ using System.Text.Json; namespace Lumina.Presentation.Api.SecurityTests.Core.Endpoints.Plugins.GetLibraryMetadataProviders; /// -/// Contains security tests for the /libraries/{libraryId}/metadata-providers route. +/// Contains security tests for the class. /// [ExcludeFromCodeCoverage] public class GetLibraryMetadataProvidersEndpointTests : IClassFixture diff --git a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Plugins/GetPluginSettings/GetPluginSettingsEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Plugins/GetPluginSettings/GetPluginSettingsEndpointTests.cs index a6f962e6..f60c55fb 100644 --- a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Plugins/GetPluginSettings/GetPluginSettingsEndpointTests.cs +++ b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Plugins/GetPluginSettings/GetPluginSettingsEndpointTests.cs @@ -13,7 +13,7 @@ using System.Text.Json; namespace Lumina.Presentation.Api.SecurityTests.Core.Endpoints.Plugins.GetPluginSettings; /// -/// Contains security tests for the /plugins/{pluginId}/settings route. +/// Contains security tests for the class. /// [ExcludeFromCodeCoverage] public class GetPluginSettingsEndpointTests : IClassFixture diff --git a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Plugins/GetPlugins/GetPluginsEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Plugins/GetPlugins/GetPluginsEndpointTests.cs index 7464eb31..0c39c0ce 100644 --- a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Plugins/GetPlugins/GetPluginsEndpointTests.cs +++ b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Plugins/GetPlugins/GetPluginsEndpointTests.cs @@ -11,7 +11,7 @@ using System.Threading.Tasks; namespace Lumina.Presentation.Api.SecurityTests.Core.Endpoints.Plugins.GetPlugins; /// -/// Contains security tests for the /plugins route. +/// Contains security tests for the class. /// [ExcludeFromCodeCoverage] public class GetPluginsEndpointTests : IClassFixture diff --git a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Plugins/InstallPlugin/InstallPluginEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Plugins/InstallPlugin/InstallPluginEndpointTests.cs index 47e855b9..97330c60 100644 --- a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Plugins/InstallPlugin/InstallPluginEndpointTests.cs +++ b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Plugins/InstallPlugin/InstallPluginEndpointTests.cs @@ -16,7 +16,7 @@ using System.Text.Json; namespace Lumina.Presentation.Api.SecurityTests.Core.Endpoints.Plugins.InstallPlugin; /// -/// Contains security tests for the POST /api/v1/plugins route. +/// Contains security tests for the class. /// [ExcludeFromCodeCoverage] public class InstallPluginEndpointTests : IClassFixture, IDisposable @@ -37,7 +37,7 @@ public class InstallPluginEndpointTests : IClassFixture, IDisp { _apiFactory = apiFactory; _client = apiFactory.CreateClient(); - // a unique X-Forwarded-For isolates rate limiting state per test + // A unique X-Forwarded-For isolates rate limiting state per test. _client.DefaultRequestHeaders.Add("X-Forwarded-For", LuminaApiFactory.GetUniqueTestIp()); } diff --git a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Plugins/ReorderLibraryArtworkProviders/ReorderLibraryArtworkProvidersEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Plugins/ReorderLibraryArtworkProviders/ReorderLibraryArtworkProvidersEndpointTests.cs index 9749c528..ac511655 100644 --- a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Plugins/ReorderLibraryArtworkProviders/ReorderLibraryArtworkProvidersEndpointTests.cs +++ b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Plugins/ReorderLibraryArtworkProviders/ReorderLibraryArtworkProvidersEndpointTests.cs @@ -17,7 +17,7 @@ using System.Text.Json; namespace Lumina.Presentation.Api.SecurityTests.Core.Endpoints.Plugins.ReorderLibraryArtworkProviders; /// -/// Contains security tests for the /libraries/{libraryId}/artwork-providers/reorder route. +/// Contains security tests for the class. /// [ExcludeFromCodeCoverage] public class ReorderLibraryArtworkProvidersEndpointTests : IClassFixture diff --git a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Plugins/ReorderLibraryMetadataProviders/ReorderLibraryMetadataProvidersEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Plugins/ReorderLibraryMetadataProviders/ReorderLibraryMetadataProvidersEndpointTests.cs index aa6a983e..d7604735 100644 --- a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Plugins/ReorderLibraryMetadataProviders/ReorderLibraryMetadataProvidersEndpointTests.cs +++ b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Plugins/ReorderLibraryMetadataProviders/ReorderLibraryMetadataProvidersEndpointTests.cs @@ -17,7 +17,7 @@ using System.Text.Json; namespace Lumina.Presentation.Api.SecurityTests.Core.Endpoints.Plugins.ReorderLibraryMetadataProviders; /// -/// Contains security tests for the /libraries/{libraryId}/metadata-providers/reorder route. +/// Contains security tests for the class. /// [ExcludeFromCodeCoverage] public class ReorderLibraryMetadataProvidersEndpointTests : IClassFixture diff --git a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Plugins/SetLibraryArtworkProviderEnabled/SetLibraryArtworkProviderEnabledEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Plugins/SetLibraryArtworkProviderEnabled/SetLibraryArtworkProviderEnabledEndpointTests.cs index 72501673..ad92bf3c 100644 --- a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Plugins/SetLibraryArtworkProviderEnabled/SetLibraryArtworkProviderEnabledEndpointTests.cs +++ b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Plugins/SetLibraryArtworkProviderEnabled/SetLibraryArtworkProviderEnabledEndpointTests.cs @@ -17,7 +17,7 @@ using System.Text.Json; namespace Lumina.Presentation.Api.SecurityTests.Core.Endpoints.Plugins.SetLibraryArtworkProviderEnabled; /// -/// Contains security tests for the /libraries/{libraryId}/artwork-providers/{pluginId}/enabled route. +/// Contains security tests for the class. /// [ExcludeFromCodeCoverage] public class SetLibraryArtworkProviderEnabledEndpointTests : IClassFixture diff --git a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Plugins/SetLibraryBookReaderEnabled/SetLibraryBookReaderEnabledEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Plugins/SetLibraryBookReaderEnabled/SetLibraryBookReaderEnabledEndpointTests.cs index 16bca2d9..45e65524 100644 --- a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Plugins/SetLibraryBookReaderEnabled/SetLibraryBookReaderEnabledEndpointTests.cs +++ b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Plugins/SetLibraryBookReaderEnabled/SetLibraryBookReaderEnabledEndpointTests.cs @@ -12,7 +12,7 @@ using System.Text.Json; namespace Lumina.Presentation.Api.SecurityTests.Core.Endpoints.Plugins.SetLibraryBookReaderEnabled; /// -/// Contains security tests for the /libraries/{libraryId}/book-readers/{pluginId}/enabled route. +/// Contains security tests for the class. /// [ExcludeFromCodeCoverage] public class SetLibraryBookReaderEnabledEndpointTests : IClassFixture diff --git a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Plugins/SetLibraryMetadataProviderEnabled/SetLibraryMetadataProviderEnabledEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Plugins/SetLibraryMetadataProviderEnabled/SetLibraryMetadataProviderEnabledEndpointTests.cs index 62ba2bcc..29fe12c0 100644 --- a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Plugins/SetLibraryMetadataProviderEnabled/SetLibraryMetadataProviderEnabledEndpointTests.cs +++ b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Plugins/SetLibraryMetadataProviderEnabled/SetLibraryMetadataProviderEnabledEndpointTests.cs @@ -17,7 +17,7 @@ using System.Text.Json; namespace Lumina.Presentation.Api.SecurityTests.Core.Endpoints.Plugins.SetLibraryMetadataProviderEnabled; /// -/// Contains security tests for the /libraries/{libraryId}/metadata-providers/{pluginId}/enabled route. +/// Contains security tests for the class. /// [ExcludeFromCodeCoverage] public class SetLibraryMetadataProviderEnabledEndpointTests : IClassFixture diff --git a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Plugins/UpdatePluginSettings/UpdatePluginSettingsEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Plugins/UpdatePluginSettings/UpdatePluginSettingsEndpointTests.cs index e0b4ebd4..6b507f75 100644 --- a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Plugins/UpdatePluginSettings/UpdatePluginSettingsEndpointTests.cs +++ b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Plugins/UpdatePluginSettings/UpdatePluginSettingsEndpointTests.cs @@ -18,7 +18,7 @@ using System.Text.Json; namespace Lumina.Presentation.Api.SecurityTests.Core.Endpoints.Plugins.UpdatePluginSettings; /// -/// Contains security tests for the /plugins/{pluginId}/settings route. +/// Contains security tests for the class. /// [ExcludeFromCodeCoverage] public class UpdatePluginSettingsEndpointTests : IClassFixture diff --git a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Scheduling/AddScheduledJob/AddScheduledJobEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Scheduling/AddScheduledJob/AddScheduledJobEndpointTests.cs index 910ed7f2..8b024531 100644 --- a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Scheduling/AddScheduledJob/AddScheduledJobEndpointTests.cs +++ b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Scheduling/AddScheduledJob/AddScheduledJobEndpointTests.cs @@ -21,7 +21,7 @@ using System.Threading.Tasks; namespace Lumina.Presentation.Api.SecurityTests.Core.Endpoints.Scheduling.AddScheduledJob; /// -/// Contains security tests for the /api/v1/scheduled-jobs route. +/// Contains security tests for the class. /// [ExcludeFromCodeCoverage] public class AddScheduledJobEndpointTests : IClassFixture, IAsyncDisposable diff --git a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Themes/Management/DeleteTheme/DeleteThemeEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Themes/Management/DeleteTheme/DeleteThemeEndpointTests.cs index 48fdcb60..951fdf0d 100644 --- a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Themes/Management/DeleteTheme/DeleteThemeEndpointTests.cs +++ b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Themes/Management/DeleteTheme/DeleteThemeEndpointTests.cs @@ -11,7 +11,7 @@ using System.Threading.Tasks; namespace Lumina.Presentation.Api.SecurityTests.Core.Endpoints.Themes.Management.DeleteTheme; /// -/// Contains security tests for the DELETE /api/v1/themes/{themeId} route. +/// Contains security tests for the class. /// [ExcludeFromCodeCoverage] public class DeleteThemeEndpointTests : IClassFixture, IDisposable @@ -31,7 +31,7 @@ public class DeleteThemeEndpointTests : IClassFixture, IDispos { _apiFactory = apiFactory; _client = apiFactory.CreateClient(); - // a unique X-Forwarded-For isolates rate limiting state per test + // A unique X-Forwarded-For isolates rate limiting state per test. _client.DefaultRequestHeaders.Add("X-Forwarded-For", LuminaApiFactory.GetUniqueTestIp()); } diff --git a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Themes/Management/InstallTheme/InstallThemeEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Themes/Management/InstallTheme/InstallThemeEndpointTests.cs index b93999b5..1d30aa15 100644 --- a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Themes/Management/InstallTheme/InstallThemeEndpointTests.cs +++ b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Themes/Management/InstallTheme/InstallThemeEndpointTests.cs @@ -13,7 +13,7 @@ using System.Text.Json; namespace Lumina.Presentation.Api.SecurityTests.Core.Endpoints.Themes.Management.InstallTheme; /// -/// Contains security tests for the POST /api/v1/themes route. +/// Contains security tests for the class. /// [ExcludeFromCodeCoverage] public class InstallThemeEndpointTests : IClassFixture, IDisposable @@ -48,7 +48,7 @@ public class InstallThemeEndpointTests : IClassFixture, IDispo { _apiFactory = apiFactory; _client = apiFactory.CreateClient(); - // a unique X-Forwarded-For isolates rate limiting state per test + // A unique X-Forwarded-For isolates rate limiting state per test. _client.DefaultRequestHeaders.Add("X-Forwarded-For", LuminaApiFactory.GetUniqueTestIp()); } diff --git a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Themes/Management/RestoreTheme/RestoreThemeEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Themes/Management/RestoreTheme/RestoreThemeEndpointTests.cs index 8cf6dff8..ffce1d33 100644 --- a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Themes/Management/RestoreTheme/RestoreThemeEndpointTests.cs +++ b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Themes/Management/RestoreTheme/RestoreThemeEndpointTests.cs @@ -4,22 +4,17 @@ using Lumina.Application.Fixtures.Common.DataAccess.Entities.Themes; using Lumina.DataAccess.Core.UoW; using Lumina.Presentation.Api.SecurityTests.Common.Setup; using Microsoft.AspNetCore.Http; -using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.DependencyInjection; -using System; -using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Net; -using System.Net.Http; using System.Net.Http.Json; using System.Text.Json; -using System.Threading.Tasks; #endregion namespace Lumina.Presentation.Api.SecurityTests.Core.Endpoints.Themes.Management.RestoreTheme; /// -/// Contains security tests for the POST /api/v1/themes/{themeId}/restore route. +/// Contains security tests for the class. /// [ExcludeFromCodeCoverage] public class RestoreThemeEndpointTests : IClassFixture, IDisposable @@ -41,7 +36,7 @@ public class RestoreThemeEndpointTests : IClassFixture, IDispo { _apiFactory = apiFactory; _client = apiFactory.CreateClient(); - // a unique X-Forwarded-For isolates rate limiting state per test + // A unique X-Forwarded-For isolates rate limiting state per test. _client.DefaultRequestHeaders.Add("X-Forwarded-For", LuminaApiFactory.GetUniqueTestIp()); _themeId = $"testtheme{Guid.NewGuid():N}"; } diff --git a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Themes/Management/SetCurrentTheme/SetCurrentThemeEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Themes/Management/SetCurrentTheme/SetCurrentThemeEndpointTests.cs index 9f550895..8d7f5181 100644 --- a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Themes/Management/SetCurrentTheme/SetCurrentThemeEndpointTests.cs +++ b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Themes/Management/SetCurrentTheme/SetCurrentThemeEndpointTests.cs @@ -4,16 +4,14 @@ using Lumina.Presentation.Api.SecurityTests.Common.Setup; using Microsoft.AspNetCore.Http; using System.Diagnostics.CodeAnalysis; using System.Net; -using System.Net.Http; using System.Net.Http.Json; using System.Text.Json; -using System.Threading.Tasks; #endregion namespace Lumina.Presentation.Api.SecurityTests.Core.Endpoints.Themes.Management.SetCurrentTheme; /// -/// Contains security tests for the PUT /api/v1/themes/current route. +/// Contains security tests for the class. /// [ExcludeFromCodeCoverage] public class SetCurrentThemeEndpointTests : IClassFixture, IDisposable @@ -33,7 +31,7 @@ public class SetCurrentThemeEndpointTests : IClassFixture, IDi { _apiFactory = apiFactory; _client = apiFactory.CreateClient(); - // a unique X-Forwarded-For isolates rate limiting state per test + // A unique X-Forwarded-For isolates rate limiting state per test. _client.DefaultRequestHeaders.Add("X-Forwarded-For", LuminaApiFactory.GetUniqueTestIp()); } diff --git a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Themes/Queries/GetCurrentTheme/GetCurrentThemeEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Themes/Queries/GetCurrentTheme/GetCurrentThemeEndpointTests.cs index 2eee95fb..9f7f3cf1 100644 --- a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Themes/Queries/GetCurrentTheme/GetCurrentThemeEndpointTests.cs +++ b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Themes/Queries/GetCurrentTheme/GetCurrentThemeEndpointTests.cs @@ -3,15 +3,13 @@ using Lumina.Presentation.Api.SecurityTests.Common.Setup; using Microsoft.AspNetCore.Http; using System.Diagnostics.CodeAnalysis; using System.Net; -using System.Net.Http; using System.Text.Json; -using System.Threading.Tasks; #endregion namespace Lumina.Presentation.Api.SecurityTests.Core.Endpoints.Themes.Queries.GetCurrentTheme; /// -/// Contains security tests for the /api/v1/themes/current route. +/// Contains security tests for the class. /// [ExcludeFromCodeCoverage] public class GetCurrentThemeEndpointTests : IClassFixture, IDisposable @@ -29,7 +27,7 @@ public class GetCurrentThemeEndpointTests : IClassFixture, IDi public GetCurrentThemeEndpointTests(LuminaApiFactory apiFactory) { _client = apiFactory.CreateClient(); - // a unique X-Forwarded-For isolates rate limiting state per test + // A unique X-Forwarded-For isolates rate limiting state per test. _client.DefaultRequestHeaders.Add("X-Forwarded-For", LuminaApiFactory.GetUniqueTestIp()); } @@ -42,7 +40,7 @@ public class GetCurrentThemeEndpointTests : IClassFixture, IDi string content = await response.Content.ReadAsStringAsync(); // Assert - // the route is AllowAnonymous, so anonymous callers must never be challenged for credentials + // The route is AllowAnonymous, so anonymous callers must never be challenged for credentials. Assert.NotEqual(HttpStatusCode.Unauthorized, response.StatusCode); Assert.NotEqual(HttpStatusCode.InternalServerError, response.StatusCode); @@ -54,7 +52,7 @@ public class GetCurrentThemeEndpointTests : IClassFixture, IDi Assert.DoesNotContain("salt", content, StringComparison.OrdinalIgnoreCase); Assert.DoesNotContain(AppContext.BaseDirectory, content, StringComparison.OrdinalIgnoreCase); - // when no active theme exists yet, the failure must be a clean, generic 404 that discloses nothing internal + // When no active theme exists yet, the failure must be a clean, generic 404 that discloses nothing internal. if (response.StatusCode == HttpStatusCode.NotFound) { Dictionary? problemDetails = JsonSerializer.Deserialize>(content, _jsonOptions); diff --git a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Themes/Queries/GetThemeArchive/GetThemeArchiveEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Themes/Queries/GetThemeArchive/GetThemeArchiveEndpointTests.cs index 4228c897..5b283904 100644 --- a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Themes/Queries/GetThemeArchive/GetThemeArchiveEndpointTests.cs +++ b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Themes/Queries/GetThemeArchive/GetThemeArchiveEndpointTests.cs @@ -11,7 +11,7 @@ using System.Threading.Tasks; namespace Lumina.Presentation.Api.SecurityTests.Core.Endpoints.Themes.Queries.GetThemeArchive; /// -/// Contains security tests for the /api/v1/themes/{themeId}/archive route. +/// Contains security tests for the class. /// [ExcludeFromCodeCoverage] public class GetThemeArchiveEndpointTests : IClassFixture, IDisposable @@ -31,7 +31,7 @@ public class GetThemeArchiveEndpointTests : IClassFixture, IDi { _apiFactory = apiFactory; _client = apiFactory.CreateClient(); - // a unique X-Forwarded-For isolates rate limiting state per test + // A unique X-Forwarded-For isolates rate limiting state per test. _client.DefaultRequestHeaders.Add("X-Forwarded-For", LuminaApiFactory.GetUniqueTestIp()); } @@ -81,8 +81,8 @@ public class GetThemeArchiveEndpointTests : IClassFixture, IDi Assert.DoesNotContain("stack trace", content, StringComparison.OrdinalIgnoreCase); Assert.DoesNotContain(AppContext.BaseDirectory, content, StringComparison.OrdinalIgnoreCase); - // note: some payloads are normalized away by the server before routing, producing an empty-body 404; - // when the value reaches the handler, the failure must still be the generic theme-not-found problem + // Note: some payloads are normalized away by the server before routing, producing an empty-body 404; + // when the value reaches the handler, the failure must still be the generic theme-not-found problem. if (!string.IsNullOrWhiteSpace(content)) { Dictionary? problemDetails = JsonSerializer.Deserialize>(content, _jsonOptions); diff --git a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Themes/Queries/GetThemeAsset/GetThemeAssetEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Themes/Queries/GetThemeAsset/GetThemeAssetEndpointTests.cs index 0a3eadf2..9d14af12 100644 --- a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Themes/Queries/GetThemeAsset/GetThemeAssetEndpointTests.cs +++ b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Themes/Queries/GetThemeAsset/GetThemeAssetEndpointTests.cs @@ -17,7 +17,7 @@ using System.Threading.Tasks; namespace Lumina.Presentation.Api.SecurityTests.Core.Endpoints.Themes.Queries.GetThemeAsset; /// -/// Contains security tests for the /api/v1/themes/{themeId}/assets/{*assetPath} route. +/// Contains security tests for the class. /// [ExcludeFromCodeCoverage] public class GetThemeAssetEndpointTests : IClassFixture, IDisposable @@ -42,7 +42,7 @@ public class GetThemeAssetEndpointTests : IClassFixture, IDisp { _apiFactory = apiFactory; _client = apiFactory.CreateClient(); - // a unique X-Forwarded-For isolates rate limiting state per test + // A unique X-Forwarded-For isolates rate limiting state per test. _client.DefaultRequestHeaders.Add("X-Forwarded-For", LuminaApiFactory.GetUniqueTestIp()); _themeId = $"testtheme{Guid.NewGuid():N}"; } @@ -93,8 +93,8 @@ public class GetThemeAssetEndpointTests : IClassFixture, IDisp string content = await response.Content.ReadAsStringAsync(); // Assert - // the encoded traversal is rejected either by the server before it reaches the handler (403) or by the theme service validation (422); - // in both cases it must be a clean client error that never serves or leaks the decoy + // The encoded traversal is rejected either by the server before it reaches the handler (403) or by the theme service validation (422); + // in both cases it must be a clean client error that never serves or leaks the decoy. Assert.True(response.StatusCode >= HttpStatusCode.BadRequest && response.StatusCode < HttpStatusCode.InternalServerError, $"Unexpected status code {response.StatusCode}."); Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase); Assert.DoesNotContain("SQL", content, StringComparison.OrdinalIgnoreCase); @@ -112,7 +112,7 @@ public class GetThemeAssetEndpointTests : IClassFixture, IDisp EnsureDecoyFileOnDisk(); // Act - // note: Kestrel normalizes literal dot-segments out of the raw path, so the request is re-routed or rejected before the handler + // Note: Kestrel normalizes literal dot-segments out of the raw path, so the request is re-routed or rejected before the handler. HttpResponseMessage response = await _client.GetAsync($"/api/v1/themes/{_themeId}/assets/../evil.txt"); string content = await response.Content.ReadAsStringAsync(); @@ -146,8 +146,8 @@ public class GetThemeAssetEndpointTests : IClassFixture, IDisp Assert.DoesNotContain("stack trace", content, StringComparison.OrdinalIgnoreCase); Assert.DoesNotContain(AppContext.BaseDirectory, content, StringComparison.OrdinalIgnoreCase); - // note: some payloads are normalized away by the server before routing, producing an empty-body 404; - // when the value reaches the handler, the failure must still be the generic theme-not-found problem + // Note: some payloads are normalized away by the server before routing, producing an empty-body 404; + // when the value reaches the handler, the failure must still be the generic theme-not-found problem. if (!string.IsNullOrWhiteSpace(content)) { Dictionary? problemDetails = JsonSerializer.Deserialize>(content, _jsonOptions); diff --git a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Themes/Queries/GetThemeSettings/GetThemeSettingsEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Themes/Queries/GetThemeSettings/GetThemeSettingsEndpointTests.cs index 93c44b12..b50dbc55 100644 --- a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Themes/Queries/GetThemeSettings/GetThemeSettingsEndpointTests.cs +++ b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Themes/Queries/GetThemeSettings/GetThemeSettingsEndpointTests.cs @@ -2,14 +2,12 @@ using Lumina.Presentation.Api.SecurityTests.Common.Setup; using System.Diagnostics.CodeAnalysis; using System.Net; -using System.Net.Http; -using System.Threading.Tasks; #endregion namespace Lumina.Presentation.Api.SecurityTests.Core.Endpoints.Themes.Queries.GetThemeSettings; /// -/// Contains security tests for the /api/v1/themes/settings route. +/// Contains security tests for the class. /// [ExcludeFromCodeCoverage] public class GetThemeSettingsEndpointTests : IClassFixture, IDisposable @@ -23,7 +21,7 @@ public class GetThemeSettingsEndpointTests : IClassFixture, ID public GetThemeSettingsEndpointTests(LuminaApiFactory apiFactory) { _client = apiFactory.CreateClient(); - // a unique X-Forwarded-For isolates rate limiting state per test + // A unique X-Forwarded-For isolates rate limiting state per test. _client.DefaultRequestHeaders.Add("X-Forwarded-For", LuminaApiFactory.GetUniqueTestIp()); } @@ -35,7 +33,7 @@ public class GetThemeSettingsEndpointTests : IClassFixture, ID HttpResponseMessage response = await _client.GetAsync("/api/v1/themes/settings"); // Assert - // the route is AllowAnonymous, so anonymous callers must never be challenged for credentials + // The route is AllowAnonymous, so anonymous callers must never be challenged for credentials. Assert.Equal(HttpStatusCode.OK, response.StatusCode); } diff --git a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Themes/Queries/GetThemeTemplate/GetThemeTemplateEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Themes/Queries/GetThemeTemplate/GetThemeTemplateEndpointTests.cs index cafced8f..06d6dd6b 100644 --- a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Themes/Queries/GetThemeTemplate/GetThemeTemplateEndpointTests.cs +++ b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Themes/Queries/GetThemeTemplate/GetThemeTemplateEndpointTests.cs @@ -4,20 +4,16 @@ using Lumina.Application.Fixtures.Common.DataAccess.Entities.Themes; using Lumina.DataAccess.Core.UoW; using Lumina.Presentation.Api.SecurityTests.Common.Setup; using Microsoft.AspNetCore.Http; -using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.DependencyInjection; using System.Diagnostics.CodeAnalysis; -using System.IO; using System.Net; -using System.Net.Http; using System.Text.Json; -using System.Threading.Tasks; #endregion namespace Lumina.Presentation.Api.SecurityTests.Core.Endpoints.Themes.Queries.GetThemeTemplate; /// -/// Contains security tests for the /api/v1/themes/{themeId}/templates/{*pageKey} route. +/// Contains security tests for the class. /// [ExcludeFromCodeCoverage] public class GetThemeTemplateEndpointTests : IClassFixture, IDisposable @@ -42,7 +38,7 @@ public class GetThemeTemplateEndpointTests : IClassFixture, ID { _apiFactory = apiFactory; _client = apiFactory.CreateClient(); - // a unique X-Forwarded-For isolates rate limiting state per test + // A unique X-Forwarded-For isolates rate limiting state per test. _client.DefaultRequestHeaders.Add("X-Forwarded-For", LuminaApiFactory.GetUniqueTestIp()); _themeId = $"testtheme{Guid.NewGuid():N}"; } @@ -99,7 +95,7 @@ public class GetThemeTemplateEndpointTests : IClassFixture, ID Assert.DoesNotContain(DECOY_CONTENT, content, StringComparison.OrdinalIgnoreCase); Assert.DoesNotContain(AppContext.BaseDirectory, content, StringComparison.OrdinalIgnoreCase); - // a successful render must only ever come from a template inside the theme pack + // A successful render must only ever come from a template inside the theme pack. if (response.StatusCode == HttpStatusCode.OK) Assert.Contains("default-template", content, StringComparison.OrdinalIgnoreCase); } @@ -113,7 +109,7 @@ public class GetThemeTemplateEndpointTests : IClassFixture, ID EnsureDecoyFileOnDisk(); // Act - // note: Kestrel normalizes literal dot-segments out of the raw path, so the request is re-routed or rejected before the handler + // Note: Kestrel normalizes literal dot-segments out of the raw path, so the request is re-routed or rejected before the handler. HttpResponseMessage response = await _client.GetAsync($"/api/v1/themes/{_themeId}/templates/../evil.html"); string content = await response.Content.ReadAsStringAsync(); @@ -147,8 +143,8 @@ public class GetThemeTemplateEndpointTests : IClassFixture, ID Assert.DoesNotContain("stack trace", content, StringComparison.OrdinalIgnoreCase); Assert.DoesNotContain(AppContext.BaseDirectory, content, StringComparison.OrdinalIgnoreCase); - // note: some payloads are normalized away by the server before routing, producing an empty-body 404; - // when the value reaches the handler, the failure must still be the generic theme-not-found problem + // Note: some payloads are normalized away by the server before routing, producing an empty-body 404; + // when the value reaches the handler, the failure must still be the generic theme-not-found problem. if (!string.IsNullOrWhiteSpace(content)) { Dictionary? problemDetails = JsonSerializer.Deserialize>(content, _jsonOptions); diff --git a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Themes/Queries/GetThemes/GetThemesEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Themes/Queries/GetThemes/GetThemesEndpointTests.cs index 77dfddc4..cba2f4a0 100644 --- a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Themes/Queries/GetThemes/GetThemesEndpointTests.cs +++ b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Themes/Queries/GetThemes/GetThemesEndpointTests.cs @@ -11,7 +11,7 @@ using System.Threading.Tasks; namespace Lumina.Presentation.Api.SecurityTests.Core.Endpoints.Themes.Queries.GetThemes; /// -/// Contains security tests for the /api/v1/themes route. +/// Contains security tests for the class. /// [ExcludeFromCodeCoverage] public class GetThemesEndpointTests : IClassFixture, IDisposable @@ -31,7 +31,7 @@ public class GetThemesEndpointTests : IClassFixture, IDisposab { _apiFactory = apiFactory; _client = apiFactory.CreateClient(); - // a unique X-Forwarded-For isolates rate limiting state per test + // A unique X-Forwarded-For isolates rate limiting state per test. _client.DefaultRequestHeaders.Add("X-Forwarded-For", LuminaApiFactory.GetUniqueTestIp()); } diff --git a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/UsersManagement/Authentication/ChangePasswordEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/UsersManagement/Authentication/ChangePasswordEndpointTests.cs index 6432c0c0..10880ed1 100644 --- a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/UsersManagement/Authentication/ChangePasswordEndpointTests.cs +++ b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/UsersManagement/Authentication/ChangePasswordEndpointTests.cs @@ -20,7 +20,7 @@ using System.Text.Json; namespace Lumina.Presentation.Api.SecurityTests.Core.Endpoints.UsersManagement.Authentication; /// -/// Contains security tests for the /auth/change-password route. +/// Contains security tests for the class. /// [ExcludeFromCodeCoverage] public class ChangePasswordEndpointTests : IClassFixture, IDisposable @@ -121,9 +121,9 @@ public class ChangePasswordEndpointTests : IClassFixture, IDis HttpResponseMessage response = await _client.PostAsJsonAsync("/api/v1/auth/change-password", request); // Assert - // the malicious username is queried by GetByUsernameAsync, so it must never be executed against the database; + // The malicious username is queried by GetByUsernameAsync, so it must never be executed against the database; // if a boolean-injection regression returned the only user in the database, the current password would match and - // the password would change, so the response must be a failure and the stored password hash must be unchanged + // the password would change, so the response must be a failure and the stored password hash must be unchanged. Assert.NotEqual(HttpStatusCode.OK, response.StatusCode); Assert.DoesNotContain("SqliteException", await response.Content.ReadAsStringAsync(), StringComparison.OrdinalIgnoreCase); @@ -157,14 +157,14 @@ public class ChangePasswordEndpointTests : IClassFixture, IDis using IServiceScope scope = _apiFactory.Services.CreateScope(); LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); - // create test user + // Create test user. UserEntity user = _userEntityFixture.Create(username: _testUsername, password: _hashService.HashString("TestPass123!")); user.TotpSecret = null; dbContext.Users.Add(user); await dbContext.SaveChangesAsync(); - // authenticate user + // Authenticate user. LoginRequest loginRequest = new( Username: user.Username, Password: "TestPass123!" @@ -174,7 +174,7 @@ public class ChangePasswordEndpointTests : IClassFixture, IDis string content = await loginResponse.Content.ReadAsStringAsync(); LoginResponse? result = JsonSerializer.Deserialize(content, _jsonOptions); - // set auth header for subsequent requests + // Set auth header for subsequent requests. _client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", result!.Token); return user; diff --git a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/UsersManagement/Authentication/GetUsersEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/UsersManagement/Authentication/GetUsersEndpointTests.cs index 11b81e89..ca5f1f13 100644 --- a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/UsersManagement/Authentication/GetUsersEndpointTests.cs +++ b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/UsersManagement/Authentication/GetUsersEndpointTests.cs @@ -9,7 +9,7 @@ using System.Text.Json; namespace Lumina.Presentation.Api.SecurityTests.Core.Endpoints.UsersManagement.Authentication; /// -/// Contains security tests for the /auth/users route. +/// Contains security tests for the class. /// [ExcludeFromCodeCoverage] public class GetUsersEndpointTests : IClassFixture diff --git a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/UsersManagement/Authentication/LoginEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/UsersManagement/Authentication/LoginEndpointTests.cs index b83cf2bc..7544cfa9 100644 --- a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/UsersManagement/Authentication/LoginEndpointTests.cs +++ b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/UsersManagement/Authentication/LoginEndpointTests.cs @@ -23,7 +23,7 @@ using System.Text.Json.Serialization; namespace Lumina.Presentation.Api.SecurityTests.Core.Endpoints.UsersManagement.Authentication; /// -/// Contains security tests for the /auth/login route. +/// Contains security tests for the class. /// [ExcludeFromCodeCoverage] public class LoginEndpointTests : IClassFixture, IDisposable @@ -50,7 +50,7 @@ public class LoginEndpointTests : IClassFixture, IDisposable { _apiFactory = apiFactory; _client = apiFactory.CreateClient(); - // set a fake IP for this test instance + // Set a fake IP for this test instance. _client.DefaultRequestHeaders.Clear(); _client.DefaultRequestHeaders.Add("X-Forwarded-For", $"192.168.1.1"); _testUsername = $"testuser_{Guid.NewGuid()}"; @@ -85,7 +85,7 @@ public class LoginEndpointTests : IClassFixture, IDisposable 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) + // 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); @@ -146,7 +146,7 @@ public class LoginEndpointTests : IClassFixture, IDisposable public async Task Login_WhenRateLimitExceeded_ShouldReturnTooManyRequests() { // Arrange - // set a fake IP for this test instance + // Set a fake IP for this test instance. _client.DefaultRequestHeaders.Clear(); _client.DefaultRequestHeaders.Add("X-Forwarded-For", $"192.168.1.3"); LoginRequest request = _loginRequestFixture.Create( @@ -156,7 +156,7 @@ public class LoginEndpointTests : IClassFixture, IDisposable // Act List responses = []; - for (int i = 0; i < 11; i++) // exceed the 10 request limit + for (int i = 0; i < 11; i++) // Exceed the 10 request limit. responses.Add(await _client.PostAsJsonAsync("/api/v1/auth/login", request)); // Assert @@ -200,10 +200,10 @@ public class LoginEndpointTests : IClassFixture, IDisposable Assert.Equal(HttpStatusCode.Forbidden, response.StatusCode); Assert.DoesNotContain("SQL", content); Assert.DoesNotContain("Exception", content); - Assert.DoesNotContain(legitimateUser.Username, content); // shouldn't expose other usernames - Assert.DoesNotContain(legitimateUser.Password, content); // shouldn't expose password hashes + Assert.DoesNotContain(legitimateUser.Username, content); // Shouldn't expose other usernames. + Assert.DoesNotContain(legitimateUser.Password, content); // Shouldn't expose password hashes. - // the injected statement must never be executed: the Users table and the seeded user must still be there + // The injected statement must never be executed: the Users table and the seeded user must still be there. using IServiceScope scope = _apiFactory.Services.CreateScope(); LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); Assert.NotNull(await dbContext.Users.FirstOrDefaultAsync(user => user.Id == legitimateUser.Id)); diff --git a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/UsersManagement/Authentication/RecoverPasswordEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/UsersManagement/Authentication/RecoverPasswordEndpointTests.cs index b2425704..0da62077 100644 --- a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/UsersManagement/Authentication/RecoverPasswordEndpointTests.cs +++ b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/UsersManagement/Authentication/RecoverPasswordEndpointTests.cs @@ -23,7 +23,7 @@ using System.Threading.Tasks; namespace Lumina.Presentation.Api.SecurityTests.Core.Endpoints.UsersManagement.Authentication; /// -/// Contains security tests for the /auth/recover-password route. +/// Contains security tests for the class. /// [ExcludeFromCodeCoverage] public class RecoverPasswordEndpointTests : IClassFixture, IDisposable @@ -47,7 +47,7 @@ public class RecoverPasswordEndpointTests : IClassFixture, IDi { _apiFactory = apiFactory; _client = apiFactory.CreateClient(); - // set a fake IP for this test instance + // 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()}"; @@ -64,7 +64,7 @@ public class RecoverPasswordEndpointTests : IClassFixture, IDi // Act List responses = []; - for (int i = 0; i < 11; i++) // exceed the 10 request limit + for (int i = 0; i < 11; i++) // Exceed the 10 request limit. responses.Add(await _client.PostAsJsonAsync("/api/v1/auth/recover-password", request)); // Assert @@ -91,8 +91,8 @@ public class RecoverPasswordEndpointTests : IClassFixture, IDi public async Task RecoverPassword_WithSQLInjectionInUsername_ShouldNotCorruptOrDeleteData(string maliciousUsername) { // Arrange - // use a dedicated unique IP, so the rate-limit test (which exhausts the 10-permit window on its own IP) - // cannot run first and 429 this test; the NotEqual(TooManyRequests) assertion below guards against any collision + // Use a dedicated unique IP, so the rate-limit test (which exhausts the 10-permit window on its own IP) + // cannot run first and 429 this test; the NotEqual(TooManyRequests) assertion below guards against any collision. HttpClient client = _apiFactory.CreateClient(); client.DefaultRequestHeaders.Clear(); client.DefaultRequestHeaders.Add("X-Forwarded-For", LuminaApiFactory.GetUniqueTestIp()); @@ -106,7 +106,7 @@ public class RecoverPasswordEndpointTests : IClassFixture, IDi HttpResponseMessage response = await client.PostAsJsonAsync("/api/v1/auth/recover-password", request); // Assert - // the malicious username queries for a user, so it must never be executed against the database + // The malicious username queries for a user, so it must never be executed against the database. Assert.NotEqual(HttpStatusCode.TooManyRequests, response.StatusCode); Assert.DoesNotContain("SqliteException", await response.Content.ReadAsStringAsync(), StringComparison.OrdinalIgnoreCase); diff --git a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/UsersManagement/Authentication/RegisterEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/UsersManagement/Authentication/RegisterEndpointTests.cs index 21bc9e5c..447cf96e 100644 --- a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/UsersManagement/Authentication/RegisterEndpointTests.cs +++ b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/UsersManagement/Authentication/RegisterEndpointTests.cs @@ -18,7 +18,7 @@ using System.Text.Json.Serialization; namespace Lumina.Presentation.Api.SecurityTests.Core.Endpoints.UsersManagement.Authentication; /// -/// Contains security tests for the /auth/register route. +/// Contains security tests for the class. /// [ExcludeFromCodeCoverage] public class RegisterEndpointTests : IClassFixture, IDisposable @@ -114,8 +114,8 @@ public class RegisterEndpointTests : IClassFixture, IDisposabl public async Task Register_WithSQLInjectionAttempt_ShouldRemainSecure(string maliciousUsername) { // Arrange - // note: the register validator rejects these usernames (invalid username format) with 422 before any DB access, - // so the malicious username never reaches a query; the 422 assertion below is the security guarantee + // Note: the register validator rejects these usernames (invalid username format) with 422 before any DB access, + // so the malicious username never reaches a query; the 422 assertion below is the security guarantee. RegistrationRequest request = _registrationRequestFixture.Create( username: maliciousUsername, password: "TestPass123!", diff --git a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/UsersManagement/Authorization/GetAuthorizationEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/UsersManagement/Authorization/GetAuthorizationEndpointTests.cs index 82791c34..2ff7218f 100644 --- a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/UsersManagement/Authorization/GetAuthorizationEndpointTests.cs +++ b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/UsersManagement/Authorization/GetAuthorizationEndpointTests.cs @@ -9,7 +9,7 @@ using System.Text.Json; namespace Lumina.Presentation.Api.SecurityTests.Core.Endpoints.UsersManagement.Authorization; /// -/// Contains security tests for the /auth/get-authorization route. +/// Contains security tests for the class. /// [ExcludeFromCodeCoverage] public class GetAuthorizationEndpointTests : IClassFixture diff --git a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/UsersManagement/Authorization/GetUserPermissionsEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/UsersManagement/Authorization/GetUserPermissionsEndpointTests.cs index d40a017c..22ad25b4 100644 --- a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/UsersManagement/Authorization/GetUserPermissionsEndpointTests.cs +++ b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/UsersManagement/Authorization/GetUserPermissionsEndpointTests.cs @@ -9,7 +9,7 @@ using System.Text.Json; namespace Lumina.Presentation.Api.SecurityTests.Core.Endpoints.UsersManagement.Authorization; /// -/// Contains security tests for the /auth/users/{userId}/permissions route. +/// Contains security tests for the class. /// [ExcludeFromCodeCoverage] public class GetUserPermissionsEndpointTests : IClassFixture diff --git a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/UsersManagement/Authorization/GetUserRoleEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/UsersManagement/Authorization/GetUserRoleEndpointTests.cs index c1d3526e..c6e25f7d 100644 --- a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/UsersManagement/Authorization/GetUserRoleEndpointTests.cs +++ b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/UsersManagement/Authorization/GetUserRoleEndpointTests.cs @@ -9,7 +9,7 @@ using System.Text.Json; namespace Lumina.Presentation.Api.SecurityTests.Core.Endpoints.UsersManagement.Authorization; /// -/// Contains security tests for the /auth/users/{userId}/role route. +/// Contains security tests for the class. /// [ExcludeFromCodeCoverage] public class GetUserRoleEndpointTests : IClassFixture diff --git a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/UsersManagement/Authorization/UpdateUserRoleAndPermissionsEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/UsersManagement/Authorization/UpdateUserRoleAndPermissionsEndpointTests.cs index 8434b4fa..89ecad1e 100644 --- a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/UsersManagement/Authorization/UpdateUserRoleAndPermissionsEndpointTests.cs +++ b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/UsersManagement/Authorization/UpdateUserRoleAndPermissionsEndpointTests.cs @@ -10,7 +10,7 @@ using System.Text.Json; namespace Lumina.Presentation.Api.SecurityTests.Core.Endpoints.UsersManagement.Authorization; /// -/// Contains security tests for the /auth/users/{userId}/role-and-permissions route. +/// Contains security tests for the class. /// [ExcludeFromCodeCoverage] public class UpdateUserRoleAndPermissionsEndpointTests : IClassFixture diff --git a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/UsersManagement/Settings/GetUserSettings/GetUserSettingsEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/UsersManagement/Settings/GetUserSettings/GetUserSettingsEndpointTests.cs index 8055436e..fcf7cccf 100644 --- a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/UsersManagement/Settings/GetUserSettings/GetUserSettingsEndpointTests.cs +++ b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/UsersManagement/Settings/GetUserSettings/GetUserSettingsEndpointTests.cs @@ -18,7 +18,7 @@ using System.Text.Json; namespace Lumina.Presentation.Api.SecurityTests.Core.Endpoints.UsersManagement.Settings.GetUserSettings; /// -/// Contains security tests for the /users/me/settings route. +/// Contains security tests for the class. /// [ExcludeFromCodeCoverage] public class GetUserSettingsEndpointTests : IClassFixture diff --git a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/UsersManagement/Settings/UpdateUserSettings/UpdateUserSettingsEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/UsersManagement/Settings/UpdateUserSettings/UpdateUserSettingsEndpointTests.cs index b2dcba4a..81cae5ec 100644 --- a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/UsersManagement/Settings/UpdateUserSettings/UpdateUserSettingsEndpointTests.cs +++ b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/UsersManagement/Settings/UpdateUserSettings/UpdateUserSettingsEndpointTests.cs @@ -20,7 +20,7 @@ using System.Text.Json; namespace Lumina.Presentation.Api.SecurityTests.Core.Endpoints.UsersManagement.Settings.UpdateUserSettings; /// -/// Contains security tests for the /users/me/settings route. +/// Contains security tests for the class. /// [ExcludeFromCodeCoverage] public class UpdateUserSettingsEndpointTests : IClassFixture diff --git a/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Admin/Authorization/Roles/AddRole/AddRoleEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Admin/Authorization/Roles/AddRole/AddRoleEndpointTests.cs index 6de8855b..27fc9d15 100644 --- a/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Admin/Authorization/Roles/AddRole/AddRoleEndpointTests.cs +++ b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Admin/Authorization/Roles/AddRole/AddRoleEndpointTests.cs @@ -15,7 +15,7 @@ using System.Net.Http.Json; namespace Lumina.Presentation.Web.SecurityTests.Core.Endpoints.Admin.Authorization.Roles.AddRole; /// -/// Contains security tests for the /{culture}/admin/api-create-role route served by the class. +/// Contains security tests for the class. /// [ExcludeFromCodeCoverage] public class AddRoleEndpointTests : IClassFixture diff --git a/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Admin/Authorization/Roles/DeleteRole/DeleteRoleEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Admin/Authorization/Roles/DeleteRole/DeleteRoleEndpointTests.cs index fb2ed8cf..37c26421 100644 --- a/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Admin/Authorization/Roles/DeleteRole/DeleteRoleEndpointTests.cs +++ b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Admin/Authorization/Roles/DeleteRole/DeleteRoleEndpointTests.cs @@ -12,7 +12,7 @@ using System.Text; namespace Lumina.Presentation.Web.SecurityTests.Core.Endpoints.Admin.Authorization.Roles.DeleteRole; /// -/// Contains security tests for the /{culture}/admin/api-delete-role/{roleId} route served by the class. +/// Contains security tests for the class. /// [ExcludeFromCodeCoverage] public class DeleteRoleEndpointTests : IClassFixture diff --git a/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Admin/Authorization/Roles/GetRolePermissions/GetRolePermissionsEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Admin/Authorization/Roles/GetRolePermissions/GetRolePermissionsEndpointTests.cs index 9da9e71a..f8a04c97 100644 --- a/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Admin/Authorization/Roles/GetRolePermissions/GetRolePermissionsEndpointTests.cs +++ b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Admin/Authorization/Roles/GetRolePermissions/GetRolePermissionsEndpointTests.cs @@ -11,7 +11,7 @@ using System.Net; namespace Lumina.Presentation.Web.SecurityTests.Core.Endpoints.Admin.Authorization.Roles.GetRolePermissions; /// -/// Contains security tests for the /{culture}/admin/api-get-permissions-by-role-id/{roleId} route served by the class. +/// Contains security tests for the class. /// [ExcludeFromCodeCoverage] public class GetRolePermissionsEndpointTests : IClassFixture diff --git a/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Admin/Authorization/Roles/GetRoles/GetRolesEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Admin/Authorization/Roles/GetRoles/GetRolesEndpointTests.cs index c3519440..13157dfd 100644 --- a/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Admin/Authorization/Roles/GetRoles/GetRolesEndpointTests.cs +++ b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Admin/Authorization/Roles/GetRoles/GetRolesEndpointTests.cs @@ -12,7 +12,7 @@ using System.Net; namespace Lumina.Presentation.Web.SecurityTests.Core.Endpoints.Admin.Authorization.Roles.GetRoles; /// -/// Contains security tests for the /{culture}/admin/api-get-roles route served by the class. +/// Contains security tests for the class. /// [ExcludeFromCodeCoverage] public class GetRolesEndpointTests : IClassFixture diff --git a/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Admin/Authorization/Roles/UpdateRole/UpdateRoleEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Admin/Authorization/Roles/UpdateRole/UpdateRoleEndpointTests.cs index 1cd600ba..79f2e41a 100644 --- a/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Admin/Authorization/Roles/UpdateRole/UpdateRoleEndpointTests.cs +++ b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Admin/Authorization/Roles/UpdateRole/UpdateRoleEndpointTests.cs @@ -15,7 +15,7 @@ using System.Net.Http.Json; namespace Lumina.Presentation.Web.SecurityTests.Core.Endpoints.Admin.Authorization.Roles.UpdateRole; /// -/// Contains security tests for the /{culture}/admin/api-update-role route served by the class. +/// Contains security tests for the class. /// [ExcludeFromCodeCoverage] public class UpdateRoleEndpointTests : IClassFixture diff --git a/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Admin/ManagePermissions/ManagePermissionsViewEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Admin/ManagePermissions/ManagePermissionsViewEndpointTests.cs index 2730d614..f2e02196 100644 --- a/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Admin/ManagePermissions/ManagePermissionsViewEndpointTests.cs +++ b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Admin/ManagePermissions/ManagePermissionsViewEndpointTests.cs @@ -14,7 +14,7 @@ using System.Net; namespace Lumina.Presentation.Web.SecurityTests.Core.Endpoints.Admin.ManagePermissions; /// -/// Contains security tests for the /{culture}/admin/manage-permissions route served by the class. +/// Contains security tests for the class. /// [ExcludeFromCodeCoverage] public class ManagePermissionsViewEndpointTests : IClassFixture diff --git a/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Admin/ManageRoles/ManageRolesViewEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Admin/ManageRoles/ManageRolesViewEndpointTests.cs index 9e28575c..11d82278 100644 --- a/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Admin/ManageRoles/ManageRolesViewEndpointTests.cs +++ b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Admin/ManageRoles/ManageRolesViewEndpointTests.cs @@ -12,7 +12,7 @@ using System.Net; namespace Lumina.Presentation.Web.SecurityTests.Core.Endpoints.Admin.ManageRoles; /// -/// Contains security tests for the /{culture}/admin/manage-roles route served by the class. +/// Contains security tests for the class. /// [ExcludeFromCodeCoverage] public class ManageRolesViewEndpointTests : IClassFixture diff --git a/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Admin/Scheduler/AddScheduledJob/AddScheduledJobEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Admin/Scheduler/AddScheduledJob/AddScheduledJobEndpointTests.cs index 1cc4b2f0..78f16dea 100644 --- a/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Admin/Scheduler/AddScheduledJob/AddScheduledJobEndpointTests.cs +++ b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Admin/Scheduler/AddScheduledJob/AddScheduledJobEndpointTests.cs @@ -13,7 +13,7 @@ using System.Threading.Tasks; namespace Lumina.Presentation.Web.SecurityTests.Core.Endpoints.Admin.Scheduler.AddScheduledJob; /// -/// Contains security tests for the /{culture}/admin/api-scheduled-jobs/add route served by the class. +/// Contains security tests for the class. /// [ExcludeFromCodeCoverage] public class AddScheduledJobEndpointTests : IClassFixture diff --git a/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Admin/Scheduler/FireScheduledJob/FireScheduledJobEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Admin/Scheduler/FireScheduledJob/FireScheduledJobEndpointTests.cs index 9a81a979..4164d109 100644 --- a/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Admin/Scheduler/FireScheduledJob/FireScheduledJobEndpointTests.cs +++ b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Admin/Scheduler/FireScheduledJob/FireScheduledJobEndpointTests.cs @@ -13,7 +13,7 @@ using System.Threading.Tasks; namespace Lumina.Presentation.Web.SecurityTests.Core.Endpoints.Admin.Scheduler.FireScheduledJob; /// -/// Contains security tests for the /{culture}/admin/api-scheduled-jobs/{scheduledJobId}/fire route served by the class. +/// Contains security tests for the class. /// [ExcludeFromCodeCoverage] public class FireScheduledJobEndpointTests : IClassFixture diff --git a/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Admin/Scheduler/GetScheduledJobHistory/GetScheduledJobHistoryEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Admin/Scheduler/GetScheduledJobHistory/GetScheduledJobHistoryEndpointTests.cs index 8c543f07..73175386 100644 --- a/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Admin/Scheduler/GetScheduledJobHistory/GetScheduledJobHistoryEndpointTests.cs +++ b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Admin/Scheduler/GetScheduledJobHistory/GetScheduledJobHistoryEndpointTests.cs @@ -16,7 +16,7 @@ using System.Threading.Tasks; namespace Lumina.Presentation.Web.SecurityTests.Core.Endpoints.Admin.Scheduler.GetScheduledJobHistory; /// -/// Contains security tests for the /{culture}/admin/api-scheduled-jobs/history route served by the class. +/// Contains security tests for the class. /// [ExcludeFromCodeCoverage] public class GetScheduledJobHistoryEndpointTests : IClassFixture diff --git a/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Admin/Scheduler/GetScheduledJobs/GetScheduledJobsEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Admin/Scheduler/GetScheduledJobs/GetScheduledJobsEndpointTests.cs index 3dcb9a45..854cdebc 100644 --- a/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Admin/Scheduler/GetScheduledJobs/GetScheduledJobsEndpointTests.cs +++ b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Admin/Scheduler/GetScheduledJobs/GetScheduledJobsEndpointTests.cs @@ -16,7 +16,7 @@ using System.Threading.Tasks; namespace Lumina.Presentation.Web.SecurityTests.Core.Endpoints.Admin.Scheduler.GetScheduledJobs; /// -/// Contains security tests for the /{culture}/admin/api-scheduled-jobs route served by the class. +/// Contains security tests for the class. /// [ExcludeFromCodeCoverage] public class GetScheduledJobsEndpointTests : IClassFixture diff --git a/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Admin/Scheduler/GetSchedulerDisplayPreferences/GetSchedulerDisplayPreferencesEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Admin/Scheduler/GetSchedulerDisplayPreferences/GetSchedulerDisplayPreferencesEndpointTests.cs index 79a4fc7e..5cb3e105 100644 --- a/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Admin/Scheduler/GetSchedulerDisplayPreferences/GetSchedulerDisplayPreferencesEndpointTests.cs +++ b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Admin/Scheduler/GetSchedulerDisplayPreferences/GetSchedulerDisplayPreferencesEndpointTests.cs @@ -16,7 +16,7 @@ using System.Threading.Tasks; namespace Lumina.Presentation.Web.SecurityTests.Core.Endpoints.Admin.Scheduler.GetSchedulerDisplayPreferences; /// -/// Contains security tests for the /{culture}/admin/api-scheduled-jobs/display-preferences route served by the class. +/// Contains security tests for the class. /// [ExcludeFromCodeCoverage] public class GetSchedulerDisplayPreferencesEndpointTests : IClassFixture diff --git a/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Admin/Scheduler/RemoveScheduledJob/RemoveScheduledJobEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Admin/Scheduler/RemoveScheduledJob/RemoveScheduledJobEndpointTests.cs index 576f7881..9f56564f 100644 --- a/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Admin/Scheduler/RemoveScheduledJob/RemoveScheduledJobEndpointTests.cs +++ b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Admin/Scheduler/RemoveScheduledJob/RemoveScheduledJobEndpointTests.cs @@ -13,7 +13,7 @@ using System.Threading.Tasks; namespace Lumina.Presentation.Web.SecurityTests.Core.Endpoints.Admin.Scheduler.RemoveScheduledJob; /// -/// Contains security tests for the /{culture}/admin/api-scheduled-jobs/{scheduledJobId} route served by the class. +/// Contains security tests for the class. /// [ExcludeFromCodeCoverage] public class RemoveScheduledJobEndpointTests : IClassFixture diff --git a/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Admin/Scheduler/SchedulerIndexViewEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Admin/Scheduler/SchedulerIndexViewEndpointTests.cs index be0107a6..ebca80a0 100644 --- a/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Admin/Scheduler/SchedulerIndexViewEndpointTests.cs +++ b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Admin/Scheduler/SchedulerIndexViewEndpointTests.cs @@ -3,17 +3,14 @@ using Lumina.Presentation.Web.Core.Endpoints.Admin.Scheduler; using Lumina.Presentation.Web.Fixtures.Common.Responses.Authorization; using Lumina.Presentation.Web.Fixtures.Common.TestHelpers; using Lumina.Presentation.Web.SecurityTests.Common.Setup; -using System; using System.Diagnostics.CodeAnalysis; using System.Net; -using System.Net.Http; -using System.Threading.Tasks; #endregion namespace Lumina.Presentation.Web.SecurityTests.Core.Endpoints.Admin.Scheduler; /// -/// Contains security tests for the /{culture}/admin/scheduled-jobs route served by the class. +/// Contains security tests for the class. /// [ExcludeFromCodeCoverage] public class SchedulerIndexViewEndpointTests : IClassFixture diff --git a/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Admin/Scheduler/StartScheduledJob/StartScheduledJobEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Admin/Scheduler/StartScheduledJob/StartScheduledJobEndpointTests.cs index 99bdf02f..d139c495 100644 --- a/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Admin/Scheduler/StartScheduledJob/StartScheduledJobEndpointTests.cs +++ b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Admin/Scheduler/StartScheduledJob/StartScheduledJobEndpointTests.cs @@ -13,7 +13,7 @@ using System.Threading.Tasks; namespace Lumina.Presentation.Web.SecurityTests.Core.Endpoints.Admin.Scheduler.StartScheduledJob; /// -/// Contains security tests for the /{culture}/admin/api-scheduled-jobs/{scheduledJobId}/start route served by the class. +/// Contains security tests for the class. /// [ExcludeFromCodeCoverage] public class StartScheduledJobEndpointTests : IClassFixture diff --git a/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Admin/Scheduler/StopScheduledJob/StopScheduledJobEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Admin/Scheduler/StopScheduledJob/StopScheduledJobEndpointTests.cs index 1a26764f..8fbe91dd 100644 --- a/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Admin/Scheduler/StopScheduledJob/StopScheduledJobEndpointTests.cs +++ b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Admin/Scheduler/StopScheduledJob/StopScheduledJobEndpointTests.cs @@ -13,7 +13,7 @@ using System.Threading.Tasks; namespace Lumina.Presentation.Web.SecurityTests.Core.Endpoints.Admin.Scheduler.StopScheduledJob; /// -/// Contains security tests for the /{culture}/admin/api-scheduled-jobs/{scheduledJobId}/stop route served by the class. +/// Contains security tests for the class. /// [ExcludeFromCodeCoverage] public class StopScheduledJobEndpointTests : IClassFixture diff --git a/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Admin/Scheduler/UpdateSchedulerDisplayPreferences/UpdateSchedulerDisplayPreferencesEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Admin/Scheduler/UpdateSchedulerDisplayPreferences/UpdateSchedulerDisplayPreferencesEndpointTests.cs index b8b8dfaa..73342dfd 100644 --- a/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Admin/Scheduler/UpdateSchedulerDisplayPreferences/UpdateSchedulerDisplayPreferencesEndpointTests.cs +++ b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Admin/Scheduler/UpdateSchedulerDisplayPreferences/UpdateSchedulerDisplayPreferencesEndpointTests.cs @@ -1,19 +1,16 @@ #region ========================================================================= USING ===================================================================================== using Lumina.Presentation.Web.Fixtures.Common.TestHelpers; using Lumina.Presentation.Web.SecurityTests.Common.Setup; -using System; using System.Diagnostics.CodeAnalysis; using System.Net; -using System.Net.Http; using System.Net.Http.Headers; using System.Text; -using System.Threading.Tasks; #endregion namespace Lumina.Presentation.Web.SecurityTests.Core.Endpoints.Admin.Scheduler.UpdateSchedulerDisplayPreferences; /// -/// Contains security tests for the /{culture}/admin/api-scheduled-jobs/display-preferences route served by the class. +/// Contains security tests for the class. /// [ExcludeFromCodeCoverage] public class UpdateSchedulerDisplayPreferencesEndpointTests : IClassFixture @@ -82,4 +79,4 @@ public class UpdateSchedulerDisplayPreferencesEndpointTests : IClassFixture -/// Contains security tests for the /{culture}/admin/themes/api-delete-theme/{themeId} route served by the class. +/// Contains security tests for the class. /// [ExcludeFromCodeCoverage] public class DeleteThemeEndpointTests : IClassFixture diff --git a/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Admin/Themes/DownloadTheme/DownloadThemeEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Admin/Themes/DownloadTheme/DownloadThemeEndpointTests.cs index 846c8c05..04f7baed 100644 --- a/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Admin/Themes/DownloadTheme/DownloadThemeEndpointTests.cs +++ b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Admin/Themes/DownloadTheme/DownloadThemeEndpointTests.cs @@ -10,7 +10,7 @@ using System.Net.Http.Headers; namespace Lumina.Presentation.Web.SecurityTests.Core.Endpoints.Admin.Themes.DownloadTheme; /// -/// Contains security tests for the /{culture}/admin/themes/api-download-theme/{themeId} route served by the class. +/// Contains security tests for the class. /// [ExcludeFromCodeCoverage] public class DownloadThemeEndpointTests : IClassFixture diff --git a/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Admin/Themes/GetThemes/GetThemesEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Admin/Themes/GetThemes/GetThemesEndpointTests.cs index b50c4f80..7bdae1b1 100644 --- a/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Admin/Themes/GetThemes/GetThemesEndpointTests.cs +++ b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Admin/Themes/GetThemes/GetThemesEndpointTests.cs @@ -10,7 +10,7 @@ using System.Net.Http.Headers; namespace Lumina.Presentation.Web.SecurityTests.Core.Endpoints.Admin.Themes.GetThemes; /// -/// Contains security tests for the /{culture}/admin/themes/api-get-themes route served by the class. +/// Contains security tests for the class. /// [ExcludeFromCodeCoverage] public class GetThemesEndpointTests : IClassFixture diff --git a/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Admin/Themes/InstallTheme/InstallThemeEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Admin/Themes/InstallTheme/InstallThemeEndpointTests.cs index 7e232089..5e1702fc 100644 --- a/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Admin/Themes/InstallTheme/InstallThemeEndpointTests.cs +++ b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Admin/Themes/InstallTheme/InstallThemeEndpointTests.cs @@ -10,7 +10,7 @@ using System.Net.Http.Headers; namespace Lumina.Presentation.Web.SecurityTests.Core.Endpoints.Admin.Themes.InstallTheme; /// -/// Contains security tests for the /{culture}/admin/themes/api-install-theme route served by the class. +/// Contains security tests for the class. /// [ExcludeFromCodeCoverage] public class InstallThemeEndpointTests : IClassFixture diff --git a/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Admin/Themes/RestoreTheme/RestoreThemeEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Admin/Themes/RestoreTheme/RestoreThemeEndpointTests.cs index 93238c02..50472628 100644 --- a/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Admin/Themes/RestoreTheme/RestoreThemeEndpointTests.cs +++ b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Admin/Themes/RestoreTheme/RestoreThemeEndpointTests.cs @@ -11,7 +11,7 @@ using System.Text; namespace Lumina.Presentation.Web.SecurityTests.Core.Endpoints.Admin.Themes.RestoreTheme; /// -/// Contains security tests for the /{culture}/admin/themes/api-restore-theme/{themeId} route served by the class. +/// Contains security tests for the class. /// [ExcludeFromCodeCoverage] public class RestoreThemeEndpointTests : IClassFixture diff --git a/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Admin/Themes/SetCurrentTheme/SetCurrentThemeEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Admin/Themes/SetCurrentTheme/SetCurrentThemeEndpointTests.cs index 6d790938..81821d49 100644 --- a/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Admin/Themes/SetCurrentTheme/SetCurrentThemeEndpointTests.cs +++ b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Admin/Themes/SetCurrentTheme/SetCurrentThemeEndpointTests.cs @@ -12,7 +12,7 @@ using System.Net.Http.Json; namespace Lumina.Presentation.Web.SecurityTests.Core.Endpoints.Admin.Themes.SetCurrentTheme; /// -/// Contains security tests for the /{culture}/admin/themes/api-set-current-theme route served by the class. +/// Contains security tests for the class. /// [ExcludeFromCodeCoverage] public class SetCurrentThemeEndpointTests : IClassFixture diff --git a/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Admin/Themes/ThemesIndexViewEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Admin/Themes/ThemesIndexViewEndpointTests.cs index bf2c0de5..abd54250 100644 --- a/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Admin/Themes/ThemesIndexViewEndpointTests.cs +++ b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Admin/Themes/ThemesIndexViewEndpointTests.cs @@ -9,7 +9,7 @@ using System.Net; namespace Lumina.Presentation.Web.SecurityTests.Core.Endpoints.Admin.Themes; /// -/// Contains security tests for the /{culture}/admin/manage-themes route served by the class. +/// Contains security tests for the class. /// [ExcludeFromCodeCoverage] public class ThemesIndexViewEndpointTests : IClassFixture diff --git a/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Admin/UsersManagement/Authorization/GetUserPermissions/GetUserPermissionsEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Admin/UsersManagement/Authorization/GetUserPermissions/GetUserPermissionsEndpointTests.cs index 4463b697..0c384ca5 100644 --- a/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Admin/UsersManagement/Authorization/GetUserPermissions/GetUserPermissionsEndpointTests.cs +++ b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Admin/UsersManagement/Authorization/GetUserPermissions/GetUserPermissionsEndpointTests.cs @@ -12,7 +12,7 @@ using System.Net; namespace Lumina.Presentation.Web.SecurityTests.Core.Endpoints.Admin.UsersManagement.Authorization.GetUserPermissions; /// -/// Contains security tests for the /{culture}/admin/api-get-permissions-by-user-id/{userId} route served by the class. +/// Contains security tests for the class. /// [ExcludeFromCodeCoverage] public class GetUserPermissionsEndpointTests : IClassFixture diff --git a/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Admin/UsersManagement/Authorization/GetUserRole/GetUserRoleEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Admin/UsersManagement/Authorization/GetUserRole/GetUserRoleEndpointTests.cs index ac609df2..cba08d57 100644 --- a/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Admin/UsersManagement/Authorization/GetUserRole/GetUserRoleEndpointTests.cs +++ b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Admin/UsersManagement/Authorization/GetUserRole/GetUserRoleEndpointTests.cs @@ -11,7 +11,7 @@ using System.Net; namespace Lumina.Presentation.Web.SecurityTests.Core.Endpoints.Admin.UsersManagement.Authorization.GetUserRole; /// -/// Contains security tests for the /{culture}/admin/api-get-role-by-user-id/{userId} route served by the class. +/// Contains security tests for the class. /// [ExcludeFromCodeCoverage] public class GetUserRoleEndpointTests : IClassFixture diff --git a/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Admin/UsersManagement/Authorization/UpdateUserRoleAndPermissions/UpdateUserRoleAndPermissionsEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Admin/UsersManagement/Authorization/UpdateUserRoleAndPermissions/UpdateUserRoleAndPermissionsEndpointTests.cs index befdd67e..7e5a6314 100644 --- a/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Admin/UsersManagement/Authorization/UpdateUserRoleAndPermissions/UpdateUserRoleAndPermissionsEndpointTests.cs +++ b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Admin/UsersManagement/Authorization/UpdateUserRoleAndPermissions/UpdateUserRoleAndPermissionsEndpointTests.cs @@ -14,7 +14,7 @@ using System.Text; namespace Lumina.Presentation.Web.SecurityTests.Core.Endpoints.Admin.UsersManagement.Authorization.UpdateUserRoleAndPermissions; /// -/// Contains security tests for the /{culture}/admin/api-update-user-authorization route served by the class. +/// Contains security tests for the class. /// [ExcludeFromCodeCoverage] public class UpdateUserRoleAndPermissionsEndpointTests : IClassFixture diff --git a/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/FileSystemManagement/Directories/GetDirectories/GetDirectoriesEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/FileSystemManagement/Directories/GetDirectories/GetDirectoriesEndpointTests.cs index 789cf711..0ac6b729 100644 --- a/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/FileSystemManagement/Directories/GetDirectories/GetDirectoriesEndpointTests.cs +++ b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/FileSystemManagement/Directories/GetDirectories/GetDirectoriesEndpointTests.cs @@ -11,7 +11,7 @@ using System.Net.Http.Headers; namespace Lumina.Presentation.Web.SecurityTests.Core.Endpoints.FileSystemManagement.Directories.GetDirectories; /// -/// Contains security tests for the /directories/api-get-directories route served by the class. +/// Contains security tests for the class. /// [ExcludeFromCodeCoverage] public class GetDirectoriesEndpointTests : IClassFixture diff --git a/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/FileSystemManagement/Drives/GetDrives/GetDrivesEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/FileSystemManagement/Drives/GetDrives/GetDrivesEndpointTests.cs index 3f8b7848..b5dc661d 100644 --- a/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/FileSystemManagement/Drives/GetDrives/GetDrivesEndpointTests.cs +++ b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/FileSystemManagement/Drives/GetDrives/GetDrivesEndpointTests.cs @@ -9,7 +9,7 @@ using System.Net; namespace Lumina.Presentation.Web.SecurityTests.Core.Endpoints.FileSystemManagement.Drives.GetDrives; /// -/// Contains security tests for the /drives/api-get-drives route served by the class. +/// Contains security tests for the class. /// [ExcludeFromCodeCoverage] public class GetDrivesEndpointTests : IClassFixture diff --git a/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/FileSystemManagement/FileSystem/GetType/GetTypeEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/FileSystemManagement/FileSystem/GetType/GetTypeEndpointTests.cs index 3974eea3..0e171046 100644 --- a/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/FileSystemManagement/FileSystem/GetType/GetTypeEndpointTests.cs +++ b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/FileSystemManagement/FileSystem/GetType/GetTypeEndpointTests.cs @@ -9,7 +9,7 @@ using System.Net; namespace Lumina.Presentation.Web.SecurityTests.Core.Endpoints.FileSystemManagement.FileSystem.GetType; /// -/// Contains security tests for the /file-system/api-get-type route served by the class. +/// Contains security tests for the class. /// [ExcludeFromCodeCoverage] public class GetTypeEndpointTests : IClassFixture diff --git a/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/FileSystemManagement/Files/GetFiles/GetFilesEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/FileSystemManagement/Files/GetFiles/GetFilesEndpointTests.cs index 82d98650..c34cfae1 100644 --- a/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/FileSystemManagement/Files/GetFiles/GetFilesEndpointTests.cs +++ b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/FileSystemManagement/Files/GetFiles/GetFilesEndpointTests.cs @@ -11,7 +11,7 @@ using System.Net.Http.Headers; namespace Lumina.Presentation.Web.SecurityTests.Core.Endpoints.FileSystemManagement.Files.GetFiles; /// -/// Contains security tests for the /files/api-get-files route served by the class. +/// Contains security tests for the class. /// [ExcludeFromCodeCoverage] public class GetFilesEndpointTests : IClassFixture diff --git a/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/FileSystemManagement/Files/GetTreeFiles/GetTreeFilesEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/FileSystemManagement/Files/GetTreeFiles/GetTreeFilesEndpointTests.cs index fb4dbeaf..95057afb 100644 --- a/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/FileSystemManagement/Files/GetTreeFiles/GetTreeFilesEndpointTests.cs +++ b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/FileSystemManagement/Files/GetTreeFiles/GetTreeFilesEndpointTests.cs @@ -9,7 +9,7 @@ using System.Net; namespace Lumina.Presentation.Web.SecurityTests.Core.Endpoints.FileSystemManagement.Files.GetTreeFiles; /// -/// Contains security tests for the /files/api-get-tree-files route served by the class. +/// Contains security tests for the class. /// [ExcludeFromCodeCoverage] public class GetTreeFilesEndpointTests : IClassFixture diff --git a/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/FileSystemManagement/Path/CheckPathExists/CheckPathExistsEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/FileSystemManagement/Path/CheckPathExists/CheckPathExistsEndpointTests.cs index a4d3b46a..c24e173c 100644 --- a/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/FileSystemManagement/Path/CheckPathExists/CheckPathExistsEndpointTests.cs +++ b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/FileSystemManagement/Path/CheckPathExists/CheckPathExistsEndpointTests.cs @@ -11,7 +11,7 @@ using System.Net.Http.Headers; namespace Lumina.Presentation.Web.SecurityTests.Core.Endpoints.FileSystemManagement.Path.CheckPathExists; /// -/// Contains security tests for the /path/api-check-path-exists route served by the class. +/// Contains security tests for the class. /// [ExcludeFromCodeCoverage] public class CheckPathExistsEndpointTests : IClassFixture diff --git a/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/FileSystemManagement/Path/GetPathParent/GetPathParentEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/FileSystemManagement/Path/GetPathParent/GetPathParentEndpointTests.cs index 9b24a184..216c82ab 100644 --- a/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/FileSystemManagement/Path/GetPathParent/GetPathParentEndpointTests.cs +++ b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/FileSystemManagement/Path/GetPathParent/GetPathParentEndpointTests.cs @@ -11,7 +11,7 @@ using System.Net.Http.Headers; namespace Lumina.Presentation.Web.SecurityTests.Core.Endpoints.FileSystemManagement.Path.GetPathParent; /// -/// Contains security tests for the /path/api-get-path-parent route served by the class. +/// Contains security tests for the class. /// [ExcludeFromCodeCoverage] public class GetPathParentEndpointTests : IClassFixture diff --git a/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/FileSystemManagement/Path/GetPathRoot/GetPathRootEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/FileSystemManagement/Path/GetPathRoot/GetPathRootEndpointTests.cs index d088e589..a979740d 100644 --- a/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/FileSystemManagement/Path/GetPathRoot/GetPathRootEndpointTests.cs +++ b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/FileSystemManagement/Path/GetPathRoot/GetPathRootEndpointTests.cs @@ -11,7 +11,7 @@ using System.Net.Http.Headers; namespace Lumina.Presentation.Web.SecurityTests.Core.Endpoints.FileSystemManagement.Path.GetPathRoot; /// -/// Contains security tests for the /path/api-get-path-root route served by the class. +/// Contains security tests for the class. /// [ExcludeFromCodeCoverage] public class GetPathRootEndpointTests : IClassFixture diff --git a/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/FileSystemManagement/Path/GetPathSeparator/GetPathSeparatorEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/FileSystemManagement/Path/GetPathSeparator/GetPathSeparatorEndpointTests.cs index 6a7666c1..17c649ee 100644 --- a/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/FileSystemManagement/Path/GetPathSeparator/GetPathSeparatorEndpointTests.cs +++ b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/FileSystemManagement/Path/GetPathSeparator/GetPathSeparatorEndpointTests.cs @@ -9,7 +9,7 @@ using System.Net; namespace Lumina.Presentation.Web.SecurityTests.Core.Endpoints.FileSystemManagement.Path.GetPathSeparator; /// -/// Contains security tests for the /path/api-get-path-separator route served by the class. +/// Contains security tests for the class. /// [ExcludeFromCodeCoverage] public class GetPathSeparatorEndpointTests : IClassFixture diff --git a/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/FileSystemManagement/Path/SplitPath/SplitPathEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/FileSystemManagement/Path/SplitPath/SplitPathEndpointTests.cs index cd358c66..cc85ac29 100644 --- a/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/FileSystemManagement/Path/SplitPath/SplitPathEndpointTests.cs +++ b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/FileSystemManagement/Path/SplitPath/SplitPathEndpointTests.cs @@ -11,7 +11,7 @@ using System.Net.Http.Headers; namespace Lumina.Presentation.Web.SecurityTests.Core.Endpoints.FileSystemManagement.Path.SplitPath; /// -/// Contains security tests for the /path/api-split route served by the class. +/// Contains security tests for the class. /// [ExcludeFromCodeCoverage] public class SplitPathEndpointTests : IClassFixture diff --git a/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/FileSystemManagement/Path/ValidatePath/ValidatePathEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/FileSystemManagement/Path/ValidatePath/ValidatePathEndpointTests.cs index 19a5fb43..6b60b2e0 100644 --- a/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/FileSystemManagement/Path/ValidatePath/ValidatePathEndpointTests.cs +++ b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/FileSystemManagement/Path/ValidatePath/ValidatePathEndpointTests.cs @@ -11,7 +11,7 @@ using System.Net.Http.Headers; namespace Lumina.Presentation.Web.SecurityTests.Core.Endpoints.FileSystemManagement.Path.ValidatePath; /// -/// Contains security tests for the /path/api-validate route served by the class. +/// Contains security tests for the class. /// [ExcludeFromCodeCoverage] public class ValidatePathEndpointTests : IClassFixture diff --git a/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/FileSystemManagement/Thumbnails/GetThumbnail/GetThumbnailEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/FileSystemManagement/Thumbnails/GetThumbnail/GetThumbnailEndpointTests.cs index d053ef48..2d598b8e 100644 --- a/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/FileSystemManagement/Thumbnails/GetThumbnail/GetThumbnailEndpointTests.cs +++ b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/FileSystemManagement/Thumbnails/GetThumbnail/GetThumbnailEndpointTests.cs @@ -13,7 +13,7 @@ using System.Threading.Tasks; namespace Lumina.Presentation.Web.SecurityTests.Core.Endpoints.FileSystemManagement.Thumbnails.GetThumbnail; /// -/// Contains security tests for the /thumbnails/api-get-thumbnail route served by the class. +/// Contains security tests for the class. /// [ExcludeFromCodeCoverage] public class GetThumbnailEndpointTests : IClassFixture diff --git a/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Home/HomeErrorEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Home/HomeErrorEndpointTests.cs index c26abcbd..fd82bc2e 100644 --- a/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Home/HomeErrorEndpointTests.cs +++ b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Home/HomeErrorEndpointTests.cs @@ -9,7 +9,7 @@ using System.Net; namespace Lumina.Presentation.Web.SecurityTests.Core.Endpoints.Home; /// -/// Contains security tests for the /{culture}/error route served by the class. +/// Contains security tests for the class. /// [ExcludeFromCodeCoverage] public class HomeErrorEndpointTests : IClassFixture diff --git a/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Home/HomeIndexEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Home/HomeIndexEndpointTests.cs index c5e19386..93cb33b9 100644 --- a/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Home/HomeIndexEndpointTests.cs +++ b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Home/HomeIndexEndpointTests.cs @@ -9,7 +9,7 @@ using System.Net; namespace Lumina.Presentation.Web.SecurityTests.Core.Endpoints.Home; /// -/// Contains security tests for the /{culture} and / routes served by the class. +/// Contains security tests for the class. /// [ExcludeFromCodeCoverage] public class HomeIndexEndpointTests : IClassFixture @@ -35,7 +35,7 @@ public class HomeIndexEndpointTests : IClassFixture HttpResponseMessage response = await client.GetAsync("/en-us"); // Assert - // the home page requires authentication, so an anonymous request must be redirected to the login page + // The home page requires authentication, so an anonymous request must be redirected to the login page. Assert.Equal(HttpStatusCode.Redirect, response.StatusCode); Assert.Equal("http://localhost/en-us/auth/login", response.Headers.Location!.ToString()); string content = await response.Content.ReadAsStringAsync(); @@ -52,7 +52,7 @@ public class HomeIndexEndpointTests : IClassFixture HttpResponseMessage response = await client.GetAsync("/"); // Assert - // the culture-less root must never demand authentication or leak internals, only redirect to the default culture + // The culture-less root must never demand authentication or leak internals, only redirect to the default culture. Assert.Equal(HttpStatusCode.Redirect, response.StatusCode); Assert.Equal("/en-us/", response.Headers.Location!.ToString()); string content = await response.Content.ReadAsStringAsync(); diff --git a/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Home/HomeNotFoundViewEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Home/HomeNotFoundViewEndpointTests.cs index 53c25060..0384ad4b 100644 --- a/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Home/HomeNotFoundViewEndpointTests.cs +++ b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Home/HomeNotFoundViewEndpointTests.cs @@ -9,7 +9,7 @@ using System.Net; namespace Lumina.Presentation.Web.SecurityTests.Core.Endpoints.Home; /// -/// Contains security tests for the /{culture}/not-found route served by the class. +/// Contains security tests for the class. /// [ExcludeFromCodeCoverage] public class HomeNotFoundViewEndpointTests : IClassFixture diff --git a/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Home/HomePrivacyEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Home/HomePrivacyEndpointTests.cs index 46954637..347209aa 100644 --- a/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Home/HomePrivacyEndpointTests.cs +++ b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Home/HomePrivacyEndpointTests.cs @@ -9,7 +9,7 @@ using System.Net; namespace Lumina.Presentation.Web.SecurityTests.Core.Endpoints.Home; /// -/// Contains security tests for the /{culture}/privacy route served by the class. +/// Contains security tests for the class. /// [ExcludeFromCodeCoverage] public class HomePrivacyEndpointTests : IClassFixture diff --git a/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Library/Management/AddLibrary/AddLibraryViewEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Library/Management/AddLibrary/AddLibraryViewEndpointTests.cs index 2779c0fd..90e1620e 100644 --- a/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Library/Management/AddLibrary/AddLibraryViewEndpointTests.cs +++ b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Library/Management/AddLibrary/AddLibraryViewEndpointTests.cs @@ -9,7 +9,7 @@ using System.Net; namespace Lumina.Presentation.Web.SecurityTests.Core.Endpoints.Library.Management.AddLibrary; /// -/// Contains security tests for the /{culture}/libraries/manage/item route served by the class. +/// Contains security tests for the class. /// [ExcludeFromCodeCoverage] public class AddLibraryViewEndpointTests : IClassFixture diff --git a/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Library/Management/CancelLibrariesScan/CancelLibrariesScanEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Library/Management/CancelLibrariesScan/CancelLibrariesScanEndpointTests.cs index 15f4ce80..9f6237c9 100644 --- a/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Library/Management/CancelLibrariesScan/CancelLibrariesScanEndpointTests.cs +++ b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Library/Management/CancelLibrariesScan/CancelLibrariesScanEndpointTests.cs @@ -11,7 +11,7 @@ using System.Text; namespace Lumina.Presentation.Web.SecurityTests.Core.Endpoints.Library.Management.CancelLibrariesScan; /// -/// Contains security tests for the /{culture}/libraries/manage/api-cancel-libraries-scan route served by the class. +/// Contains security tests for the class. /// [ExcludeFromCodeCoverage] public class CancelLibrariesScanEndpointTests : IClassFixture diff --git a/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Library/Management/CancelLibraryScan/CancelLibraryScanEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Library/Management/CancelLibraryScan/CancelLibraryScanEndpointTests.cs index 41ee3f42..fc1fdd81 100644 --- a/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Library/Management/CancelLibraryScan/CancelLibraryScanEndpointTests.cs +++ b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Library/Management/CancelLibraryScan/CancelLibraryScanEndpointTests.cs @@ -11,7 +11,7 @@ using System.Text; namespace Lumina.Presentation.Web.SecurityTests.Core.Endpoints.Library.Management.CancelLibraryScan; /// -/// Contains security tests for the /{culture}/libraries/manage/{{libraryId}}/api-cancel-library-scan/{{scanId}} route served by the class. +/// Contains security tests for the class. /// [ExcludeFromCodeCoverage] public class CancelLibraryScanEndpointTests : IClassFixture diff --git a/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Library/Management/DeleteLibrary/DeleteLibraryEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Library/Management/DeleteLibrary/DeleteLibraryEndpointTests.cs index daa20b3e..410bf983 100644 --- a/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Library/Management/DeleteLibrary/DeleteLibraryEndpointTests.cs +++ b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Library/Management/DeleteLibrary/DeleteLibraryEndpointTests.cs @@ -11,7 +11,7 @@ using System.Text; namespace Lumina.Presentation.Web.SecurityTests.Core.Endpoints.Library.Management.DeleteLibrary; /// -/// Contains security tests for the /{culture}/libraries/manage/api-item/{{id}} route served by the class. +/// Contains security tests for the class. /// [ExcludeFromCodeCoverage] public class DeleteLibraryEndpointTests : IClassFixture diff --git a/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Library/Management/EditLibrary/EditLibraryViewEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Library/Management/EditLibrary/EditLibraryViewEndpointTests.cs index 7222c593..6d9e3879 100644 --- a/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Library/Management/EditLibrary/EditLibraryViewEndpointTests.cs +++ b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Library/Management/EditLibrary/EditLibraryViewEndpointTests.cs @@ -9,7 +9,7 @@ using System.Net; namespace Lumina.Presentation.Web.SecurityTests.Core.Endpoints.Library.Management.EditLibrary; /// -/// Contains security tests for the /{culture}/libraries/manage/item/{{id}} route served by the class. +/// Contains security tests for the class. /// [ExcludeFromCodeCoverage] public class EditLibraryViewEndpointTests : IClassFixture diff --git a/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Library/Management/GetBookReaders/GetBookReadersEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Library/Management/GetBookReaders/GetBookReadersEndpointTests.cs index 5e6211cc..8858a385 100644 --- a/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Library/Management/GetBookReaders/GetBookReadersEndpointTests.cs +++ b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Library/Management/GetBookReaders/GetBookReadersEndpointTests.cs @@ -10,7 +10,7 @@ using System.Net; namespace Lumina.Presentation.Web.SecurityTests.Core.Endpoints.Library.Management.GetBookReaders; /// -/// Contains security tests for the /{culture}/libraries/manage/api-get-book-readers/{{libraryId}} route served by the class. +/// Contains security tests for the class. /// [ExcludeFromCodeCoverage] public class GetBookReadersEndpointTests : IClassFixture diff --git a/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Library/Management/GetEnabledLibraries/GetEnabledLibrariesEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Library/Management/GetEnabledLibraries/GetEnabledLibrariesEndpointTests.cs index 5fbcb785..60290f79 100644 --- a/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Library/Management/GetEnabledLibraries/GetEnabledLibrariesEndpointTests.cs +++ b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Library/Management/GetEnabledLibraries/GetEnabledLibrariesEndpointTests.cs @@ -10,7 +10,7 @@ using System.Net.Http.Headers; namespace Lumina.Presentation.Web.SecurityTests.Core.Endpoints.Library.Management.GetEnabledLibraries; /// -/// Contains security tests for the /{culture}/libraries/manage/api-get-enabled-libraries route served by the class. +/// Contains security tests for the class. /// [ExcludeFromCodeCoverage] public class GetEnabledLibrariesEndpointTests : IClassFixture diff --git a/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Library/Management/GetLibraries/GetLibrariesEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Library/Management/GetLibraries/GetLibrariesEndpointTests.cs index e79104e2..94b10640 100644 --- a/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Library/Management/GetLibraries/GetLibrariesEndpointTests.cs +++ b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Library/Management/GetLibraries/GetLibrariesEndpointTests.cs @@ -10,7 +10,7 @@ using System.Net.Http.Headers; namespace Lumina.Presentation.Web.SecurityTests.Core.Endpoints.Library.Management.GetLibraries; /// -/// Contains security tests for the /{culture}/libraries/manage/api-get-libraries route served by the class. +/// Contains security tests for the class. /// [ExcludeFromCodeCoverage] public class GetLibrariesEndpointTests : IClassFixture diff --git a/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Library/Management/GetMetadataProviders/GetMetadataProvidersEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Library/Management/GetMetadataProviders/GetMetadataProvidersEndpointTests.cs index 3092267b..dc444fdb 100644 --- a/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Library/Management/GetMetadataProviders/GetMetadataProvidersEndpointTests.cs +++ b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Library/Management/GetMetadataProviders/GetMetadataProvidersEndpointTests.cs @@ -10,7 +10,7 @@ using System.Net.Http.Headers; namespace Lumina.Presentation.Web.SecurityTests.Core.Endpoints.Library.Management.GetMetadataProviders; /// -/// Contains security tests for the /{culture}/libraries/manage/api-get-metadata-providers/{{libraryId}} route served by the class. +/// Contains security tests for the class. /// [ExcludeFromCodeCoverage] public class GetMetadataProvidersEndpointTests : IClassFixture diff --git a/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Library/Management/GetRunningLibraryScans/GetRunningLibraryScansEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Library/Management/GetRunningLibraryScans/GetRunningLibraryScansEndpointTests.cs index 06a1dc01..3798d4dd 100644 --- a/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Library/Management/GetRunningLibraryScans/GetRunningLibraryScansEndpointTests.cs +++ b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Library/Management/GetRunningLibraryScans/GetRunningLibraryScansEndpointTests.cs @@ -10,7 +10,7 @@ using System.Net.Http.Headers; namespace Lumina.Presentation.Web.SecurityTests.Core.Endpoints.Library.Management.GetRunningLibraryScans; /// -/// Contains security tests for the /{culture}/libraries/manage/api-get-running-library-scans route served by the class. +/// Contains security tests for the class. /// [ExcludeFromCodeCoverage] public class GetRunningLibraryScansEndpointTests : IClassFixture diff --git a/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Library/Management/Index/LibrariesIndexViewEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Library/Management/Index/LibrariesIndexViewEndpointTests.cs index c176096d..4ee889f7 100644 --- a/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Library/Management/Index/LibrariesIndexViewEndpointTests.cs +++ b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Library/Management/Index/LibrariesIndexViewEndpointTests.cs @@ -9,7 +9,7 @@ using System.Net; namespace Lumina.Presentation.Web.SecurityTests.Core.Endpoints.Library.Management.Index; /// -/// Contains security tests for the /{culture}/libraries/manage route served by the class. +/// Contains security tests for the class. /// [ExcludeFromCodeCoverage] public class LibrariesIndexViewEndpointTests : IClassFixture diff --git a/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Library/Management/ReorderMetadataProviders/ReorderMetadataProvidersEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Library/Management/ReorderMetadataProviders/ReorderMetadataProvidersEndpointTests.cs index c4f3a860..2fc62af3 100644 --- a/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Library/Management/ReorderMetadataProviders/ReorderMetadataProvidersEndpointTests.cs +++ b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Library/Management/ReorderMetadataProviders/ReorderMetadataProvidersEndpointTests.cs @@ -13,7 +13,7 @@ using System.Net.Http.Json; namespace Lumina.Presentation.Web.SecurityTests.Core.Endpoints.Library.Management.ReorderMetadataProviders; /// -/// Contains security tests for the /{culture}/libraries/manage/api-reorder-metadata-providers route served by the class. +/// Contains security tests for the class. /// [ExcludeFromCodeCoverage] public class ReorderMetadataProvidersEndpointTests : IClassFixture diff --git a/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Library/Management/SaveLibrary/SaveLibraryEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Library/Management/SaveLibrary/SaveLibraryEndpointTests.cs index 22913584..165a1d40 100644 --- a/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Library/Management/SaveLibrary/SaveLibraryEndpointTests.cs +++ b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Library/Management/SaveLibrary/SaveLibraryEndpointTests.cs @@ -13,7 +13,7 @@ using System.Net.Http.Json; namespace Lumina.Presentation.Web.SecurityTests.Core.Endpoints.Library.Management.SaveLibrary; /// -/// Contains security tests for the /{culture}/libraries/manage/api-item route served by the class. +/// Contains security tests for the class. /// [ExcludeFromCodeCoverage] public class SaveLibraryEndpointTests : IClassFixture diff --git a/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Library/Management/ScanLibraries/ScanLibrariesEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Library/Management/ScanLibraries/ScanLibrariesEndpointTests.cs index f2704f51..64422453 100644 --- a/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Library/Management/ScanLibraries/ScanLibrariesEndpointTests.cs +++ b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Library/Management/ScanLibraries/ScanLibrariesEndpointTests.cs @@ -11,7 +11,7 @@ using System.Text; namespace Lumina.Presentation.Web.SecurityTests.Core.Endpoints.Library.Management.ScanLibraries; /// -/// Contains security tests for the /{culture}/libraries/manage/api-scan-libraries route served by the class. +/// Contains security tests for the class. /// [ExcludeFromCodeCoverage] public class ScanLibrariesEndpointTests : IClassFixture diff --git a/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Library/Management/ScanLibrary/ScanLibraryEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Library/Management/ScanLibrary/ScanLibraryEndpointTests.cs index 5bbbfeb5..c0a7a2da 100644 --- a/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Library/Management/ScanLibrary/ScanLibraryEndpointTests.cs +++ b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Library/Management/ScanLibrary/ScanLibraryEndpointTests.cs @@ -12,7 +12,7 @@ using System.Text.Json; namespace Lumina.Presentation.Web.SecurityTests.Core.Endpoints.Library.Management.ScanLibrary; /// -/// Contains security tests for the /{culture}/libraries/manage/api-scan-library/{{id}} route served by the class. +/// Contains security tests for the class. /// [ExcludeFromCodeCoverage] public class ScanLibraryEndpointTests : IClassFixture diff --git a/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Library/Management/SetBookReaderEnabled/SetBookReaderEnabledEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Library/Management/SetBookReaderEnabled/SetBookReaderEnabledEndpointTests.cs index 8d679cd2..77943547 100644 --- a/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Library/Management/SetBookReaderEnabled/SetBookReaderEnabledEndpointTests.cs +++ b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Library/Management/SetBookReaderEnabled/SetBookReaderEnabledEndpointTests.cs @@ -16,7 +16,7 @@ using System.Threading.Tasks; namespace Lumina.Presentation.Web.SecurityTests.Core.Endpoints.Library.Management.SetBookReaderEnabled; /// -/// Contains security tests for the /{culture}/libraries/manage/api-set-book-reader-enabled route served by the class. +/// Contains security tests for the class. /// [ExcludeFromCodeCoverage] public class SetBookReaderEnabledEndpointTests : IClassFixture diff --git a/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Library/Management/SetMetadataProviderEnabled/SetMetadataProviderEnabledEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Library/Management/SetMetadataProviderEnabled/SetMetadataProviderEnabledEndpointTests.cs index a328ed61..fb13897e 100644 --- a/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Library/Management/SetMetadataProviderEnabled/SetMetadataProviderEnabledEndpointTests.cs +++ b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Library/Management/SetMetadataProviderEnabled/SetMetadataProviderEnabledEndpointTests.cs @@ -13,7 +13,7 @@ using System.Net.Http.Json; namespace Lumina.Presentation.Web.SecurityTests.Core.Endpoints.Library.Management.SetMetadataProviderEnabled; /// -/// Contains security tests for the /{culture}/libraries/manage/api-set-metadata-provider-enabled route served by the class. +/// Contains security tests for the class. /// [ExcludeFromCodeCoverage] public class SetMetadataProviderEnabledEndpointTests : IClassFixture diff --git a/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/EditBook/EditBookViewEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/EditBook/EditBookViewEndpointTests.cs index 333c37f5..7ae99999 100644 --- a/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/EditBook/EditBookViewEndpointTests.cs +++ b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/EditBook/EditBookViewEndpointTests.cs @@ -9,7 +9,7 @@ using System.Net; namespace Lumina.Presentation.Web.SecurityTests.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.Books.EditBook; /// -/// Contains security tests for the /{culture}/library/written-content-library/books-library/books/{{id}} route served by the class. +/// Contains security tests for the class. /// [ExcludeFromCodeCoverage] public class EditBookViewEndpointTests : IClassFixture diff --git a/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/GetBookDetails/GetBookDetailsEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/GetBookDetails/GetBookDetailsEndpointTests.cs new file mode 100644 index 00000000..8f7d8083 --- /dev/null +++ b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/GetBookDetails/GetBookDetailsEndpointTests.cs @@ -0,0 +1,78 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Common.DTO.WrittenContentLibrary.BookLibrary; +using Lumina.Presentation.Web.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.Books.GetBookDetails; +using Lumina.Presentation.Web.Fixtures.Common.DTO.WrittenContentLibrary.BookLibrary; +using Lumina.Presentation.Web.Fixtures.Common.TestHelpers; +using Lumina.Presentation.Web.SecurityTests.Common.Setup; +using System; +using System.Diagnostics.CodeAnalysis; +using System.Net; +using System.Net.Http; +using System.Text.Json; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.SecurityTests.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.Books.GetBookDetails; + +/// +/// Contains security tests for the class. +/// +[ExcludeFromCodeCoverage] +public class GetBookDetailsEndpointTests : IClassFixture +{ + private readonly LuminaWebFactory _apiFactory; + private readonly BookDetailsDtoFixture _bookDetailsDtoFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + /// Injected Web application factory. + public GetBookDetailsEndpointTests(LuminaWebFactory apiFactory) + { + _apiFactory = apiFactory; + } + + [Fact] + public async Task GetBookDetails_WhenCalledWithoutAuthentication_ShouldRedirectToLoginWithoutCallingApi() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + HttpClient anonymousClient = WebTestHelpers.CreateAnonymousClient(_apiFactory); + + // Act + HttpResponseMessage response = await anonymousClient.GetAsync($"/en-us/library/written-content-library/books-library/books/{Guid.NewGuid()}/api-get-book"); + + // Assert + Assert.Equal(HttpStatusCode.Redirect, response.StatusCode); + Assert.DoesNotContain(_apiFactory.ApiClientStub.GetEndpointsCalled, endpoint => endpoint.StartsWith("books/", StringComparison.OrdinalIgnoreCase)); + } + + [Theory] + [InlineData("'; DROP TABLE Books; --")] // destructive injection + [InlineData("' OR '1'='1")] // boolean-based injection + public async Task GetBookDetails_WithSQLInjectionInBookId_ShouldNormalizeTheIdWithoutLeakingData(string maliciousBookId) + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + string normalizedBookId = Guid.Empty.ToString(); + BookDetailsDto expectedBook = _bookDetailsDtoFixture.Create(); + _apiFactory.ApiClientStub.RegisterGetResponse($"books/{normalizedBookId}", expectedBook); + AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); + + // Act + HttpResponseMessage response = await webClient.Client.GetAsync($"/en-us/library/written-content-library/books-library/books/{Uri.EscapeDataString(maliciousBookId)}/api-get-book"); + string content = await response.Content.ReadAsStringAsync(); + + // Assert + // The route Id is normalized to a Guid before it is substituted into the upstream URL, so a crafted route value can never escape + // its URL segment or reach a different book lookup; the unparseable value is reported by the API as a missing book Id, and the + // Web layer must not fail local binding, leak stack traces or database details. + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + using (JsonDocument json = JsonDocument.Parse(content)) + Assert.True(json.RootElement.GetProperty("success").GetBoolean()); + Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("at Lumina", content, StringComparison.OrdinalIgnoreCase); + Assert.Contains(_apiFactory.ApiClientStub.GetEndpointsCalled, endpoint => endpoint == $"books/{normalizedBookId}"); + } +} diff --git a/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/GetLibraryItems/GetLibraryItemsEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/GetLibraryItems/GetLibraryItemsEndpointTests.cs index 762ab1e0..ec70b8fe 100644 --- a/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/GetLibraryItems/GetLibraryItemsEndpointTests.cs +++ b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/GetLibraryItems/GetLibraryItemsEndpointTests.cs @@ -11,7 +11,7 @@ using System.Net.Http.Headers; namespace Lumina.Presentation.Web.SecurityTests.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.Books.GetLibraryItems; /// -/// Contains security tests for the /{culture}/library/written-content-library/books-library/books/api-get-library-items route served by the class. +/// Contains security tests for the class. /// [ExcludeFromCodeCoverage] public class GetLibraryItemsEndpointTests : IClassFixture diff --git a/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/Index/BooksIndexViewEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/Index/BooksIndexViewEndpointTests.cs index 4784adfb..1bb168f1 100644 --- a/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/Index/BooksIndexViewEndpointTests.cs +++ b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/Index/BooksIndexViewEndpointTests.cs @@ -9,7 +9,7 @@ using System.Net; namespace Lumina.Presentation.Web.SecurityTests.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.Books.Index; /// -/// Contains security tests for the /{culture}/library/written-content-library/books-library/books route served by the class. +/// Contains security tests for the class. /// [ExcludeFromCodeCoverage] public class BooksIndexViewEndpointTests : IClassFixture diff --git a/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/Reading/GetReadingAvailability/GetReadingAvailabilityEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/Reading/GetReadingAvailability/GetReadingAvailabilityEndpointTests.cs index 6f39bd58..cb91a049 100644 --- a/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/Reading/GetReadingAvailability/GetReadingAvailabilityEndpointTests.cs +++ b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/Reading/GetReadingAvailability/GetReadingAvailabilityEndpointTests.cs @@ -15,7 +15,7 @@ using System.Threading.Tasks; namespace Lumina.Presentation.Web.SecurityTests.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.Books.Reading.GetReadingAvailability; /// -/// Contains security tests for the /{culture}/library/written-content-library/books-library/books/{bookId}/api-get-reading-availability route served by the class. +/// Contains security tests for the class. /// [ExcludeFromCodeCoverage] public class GetReadingAvailabilityEndpointTests : IClassFixture diff --git a/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/Reading/GetReadingManifest/GetReadingManifestEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/Reading/GetReadingManifest/GetReadingManifestEndpointTests.cs index 5c2593da..07c5e170 100644 --- a/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/Reading/GetReadingManifest/GetReadingManifestEndpointTests.cs +++ b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/Reading/GetReadingManifest/GetReadingManifestEndpointTests.cs @@ -15,7 +15,7 @@ using System.Threading.Tasks; namespace Lumina.Presentation.Web.SecurityTests.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.Books.Reading.GetReadingManifest; /// -/// Contains security tests for the /{culture}/library/written-content-library/books-library/books/{bookId}/api-get-reading-manifest route served by the class. +/// Contains security tests for the class. /// [ExcludeFromCodeCoverage] public class GetReadingManifestEndpointTests : IClassFixture diff --git a/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/Reading/GetReadingResource/GetReadingResourceEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/Reading/GetReadingResource/GetReadingResourceEndpointTests.cs index 8016ad62..696e9977 100644 --- a/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/Reading/GetReadingResource/GetReadingResourceEndpointTests.cs +++ b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/Reading/GetReadingResource/GetReadingResourceEndpointTests.cs @@ -14,7 +14,7 @@ using System.Threading.Tasks; namespace Lumina.Presentation.Web.SecurityTests.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.Books.Reading.GetReadingResource; /// -/// Contains security tests for the /{culture}/library/written-content-library/books-library/books/{bookId}/api-get-reading-resource route served by the class. +/// Contains security tests for the class. /// [ExcludeFromCodeCoverage] public class GetReadingResourceEndpointTests : IClassFixture diff --git a/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/Reading/GetReadingSection/GetReadingSectionEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/Reading/GetReadingSection/GetReadingSectionEndpointTests.cs index fc1c79bc..1a4f88bf 100644 --- a/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/Reading/GetReadingSection/GetReadingSectionEndpointTests.cs +++ b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/Reading/GetReadingSection/GetReadingSectionEndpointTests.cs @@ -15,7 +15,7 @@ using System.Threading.Tasks; namespace Lumina.Presentation.Web.SecurityTests.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.Books.Reading.GetReadingSection; /// -/// Contains security tests for the /{culture}/library/written-content-library/books-library/books/{bookId}/api-get-reading-section route served by the class. +/// Contains security tests for the class. /// [ExcludeFromCodeCoverage] public class GetReadingSectionEndpointTests : IClassFixture diff --git a/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/Reading/Read/ReadViewEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/Reading/Read/ReadViewEndpointTests.cs index 24983be2..41803eb1 100644 --- a/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/Reading/Read/ReadViewEndpointTests.cs +++ b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/Reading/Read/ReadViewEndpointTests.cs @@ -12,7 +12,7 @@ using System.Threading.Tasks; namespace Lumina.Presentation.Web.SecurityTests.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.Books.Reading.Read; /// -/// Contains security tests for the /{culture}/library/written-content-library/books-library/books/{bookId}/read route served by the class. +/// Contains security tests for the class. /// [ExcludeFromCodeCoverage] public class ReadViewEndpointTests : IClassFixture diff --git a/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/SaveBook/SaveBookEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/SaveBook/SaveBookEndpointTests.cs new file mode 100644 index 00000000..75fa6a13 --- /dev/null +++ b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/SaveBook/SaveBookEndpointTests.cs @@ -0,0 +1,131 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Common.DTO.WrittenContentLibrary.BookLibrary; +using Lumina.Presentation.Web.Common.Requests.Library.WrittenContentLibrary.BookLibrary.Books; +using Lumina.Presentation.Web.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.Books.SaveBook; +using Lumina.Presentation.Web.Fixtures.Common.DTO.WrittenContentLibrary.BookLibrary; +using Lumina.Presentation.Web.Fixtures.Common.Requests.Library.WrittenContentLibrary.BookLibrary.Books; +using Lumina.Presentation.Web.Fixtures.Common.TestHelpers; +using Lumina.Presentation.Web.SecurityTests.Common.Setup; +using System; +using System.Diagnostics.CodeAnalysis; +using System.Net; +using System.Net.Http; +using System.Net.Http.Headers; +using System.Net.Http.Json; +using System.Text.Json; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.SecurityTests.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.Books.SaveBook; + +/// +/// Contains security tests for the class. +/// +[ExcludeFromCodeCoverage] +public class SaveBookEndpointTests : IClassFixture +{ + private readonly LuminaWebFactory _apiFactory; + private readonly UpdateBookRequestFixture _updateBookRequestFixture = new(); + private readonly BookDetailsDtoFixture _bookDetailsDtoFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + /// Injected Web application factory. + public SaveBookEndpointTests(LuminaWebFactory apiFactory) + { + _apiFactory = apiFactory; + } + + [Theory] + [InlineData("'; DROP TABLE Books; --")] // destructive injection + [InlineData("' OR '1'='1")] // boolean-based injection + public async Task SaveBook_WithSQLInjectionInRouteId_ShouldNormalizeTheIdAndNeverCallTheBodyBookEndpoint(string maliciousBookId) + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + Guid bodyId = Guid.NewGuid(); + string normalizedBookId = Guid.Empty.ToString(); + _apiFactory.ApiClientStub.RegisterPutResponse($"books/{normalizedBookId}", _bookDetailsDtoFixture.Create()); + AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); + HttpRequestMessage saveRequest = CreateSaveRequest(maliciousBookId, _updateBookRequestFixture.Create(id: bodyId)); + saveRequest.Headers.Add("RequestVerificationToken", webClient.AntiforgeryToken); + + // Act + HttpResponseMessage response = await webClient.Client.SendAsync(saveRequest); + string content = await response.Content.ReadAsStringAsync(); + + // Assert + // The route is authoritative and its value is normalized to a Guid before it is substituted into the upstream URL, so a crafted + // route value can never escape its URL segment or redirect the update to the book carried in the body, and the response must not + // leak stack traces or database details. + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("at Lumina", content, StringComparison.OrdinalIgnoreCase); + Assert.Contains(_apiFactory.ApiClientStub.PutRequests, putRequest => putRequest.Endpoint == $"books/{normalizedBookId}" && putRequest.Data is UpdateBookRequest forwarded && forwarded.Id == normalizedBookId); + Assert.DoesNotContain(_apiFactory.ApiClientStub.PutRequests, putRequest => putRequest.Endpoint == $"books/{bodyId}"); + } + + [Theory] + [InlineData("'; DROP TABLE Books; --")] // destructive injection + [InlineData("' OR '1'='1")] // boolean-based injection + public async Task SaveBook_WithSQLInjectionInPostedTitle_ShouldNotLeakOrExecuteIt(string maliciousTitle) + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + Guid bookId = Guid.NewGuid(); + UpdateBookRequest request = _updateBookRequestFixture.Create(id: bookId); + request.Metadata!.Title = maliciousTitle; + BookDetailsDto expectedBook = _bookDetailsDtoFixture.Create(id: bookId); + expectedBook.Metadata!.Title = maliciousTitle; + _apiFactory.ApiClientStub.RegisterPutResponse($"books/{bookId}", expectedBook); + AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); + HttpRequestMessage saveRequest = CreateSaveRequest(bookId.ToString(), request); + saveRequest.Headers.Add("RequestVerificationToken", webClient.AntiforgeryToken); + + // Act + HttpResponseMessage response = await webClient.Client.SendAsync(saveRequest); + string content = await response.Content.ReadAsStringAsync(); + + // Assert + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + Assert.DoesNotContain("SQL", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase); + Assert.Contains(_apiFactory.ApiClientStub.PutRequests, putRequest => putRequest.Endpoint == $"books/{bookId}" && putRequest.Data is UpdateBookRequest forwarded && forwarded.Metadata!.Title == maliciousTitle); + } + + [Fact] + public async Task SaveBook_WhenCalledWithoutAuthentication_ShouldRedirectToLogin() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + HttpClient anonymousClient = WebTestHelpers.CreateAnonymousClient(_apiFactory); + HttpRequestMessage saveRequest = CreateSaveRequest(Guid.NewGuid().ToString(), _updateBookRequestFixture.Create()); + + // Act + HttpResponseMessage response = await anonymousClient.SendAsync(saveRequest); + + // Assert + Assert.Equal(HttpStatusCode.Redirect, response.StatusCode); + Assert.Empty(_apiFactory.ApiClientStub.PutRequests); + } + + /// + /// Builds the save request that PUTs the given to the book identified by . + /// + /// The route Id of the book to save. + /// The book data to send. + /// The configured save request. + private static HttpRequestMessage CreateSaveRequest(string bookId, UpdateBookRequest request) + { + HttpRequestMessage saveRequest = new(HttpMethod.Put, $"/en-us/library/written-content-library/books-library/books/{Uri.EscapeDataString(bookId)}/api-save-book") + { + Content = JsonContent.Create(request) + }; + saveRequest.Content!.Headers.ContentType = new MediaTypeHeaderValue("application/json"); + saveRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); + return saveRequest; + } +} diff --git a/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/UpdateBookCover/UpdateBookCoverEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/UpdateBookCover/UpdateBookCoverEndpointTests.cs new file mode 100644 index 00000000..bf3de484 --- /dev/null +++ b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/UpdateBookCover/UpdateBookCoverEndpointTests.cs @@ -0,0 +1,110 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.Books.UpdateBookCover; +using Lumina.Presentation.Web.Fixtures.Common.TestHelpers; +using Lumina.Presentation.Web.SecurityTests.Common.Setup; +using System; +using System.Diagnostics.CodeAnalysis; +using System.Net; +using System.Net.Http; +using System.Net.Http.Headers; +using System.Text; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.SecurityTests.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.Books.UpdateBookCover; + +/// +/// Contains security tests for the class. +/// +[ExcludeFromCodeCoverage] +public class UpdateBookCoverEndpointTests : IClassFixture +{ + private readonly LuminaWebFactory _apiFactory; + + /// + /// Initializes a new instance of the class. + /// + /// Injected Web application factory. + public UpdateBookCoverEndpointTests(LuminaWebFactory apiFactory) + { + _apiFactory = apiFactory; + } + + [Theory] + [InlineData("'; DROP TABLE Books; --")] // destructive injection + [InlineData("' OR '1'='1")] // boolean-based injection + public async Task UpdateBookCover_WithSQLInjectionInRouteId_ShouldNeverReachABookOrLeakData(string maliciousBookId) + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + _apiFactory.ApiClientStub.RegisterPutResponse($"books/{Guid.Empty}/cover", "/media/books/cover.png"); + AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); + HttpRequestMessage uploadRequest = CreateUploadRequest(maliciousBookId, "cover.png"); + uploadRequest.Headers.Add("RequestVerificationToken", webClient.AntiforgeryToken); + + // Act + HttpResponseMessage response = await webClient.Client.SendAsync(uploadRequest); + string content = await response.Content.ReadAsStringAsync(); + + // Assert + // The route is authoritative: an unparseable route value becomes an empty book Id, so the upload can never reach a real book. + Assert.DoesNotContain("SQL", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase); + Assert.Contains(_apiFactory.ApiClientStub.PutRequests, putRequest => putRequest.Endpoint == $"books/{Guid.Empty}/cover"); + } + + [Fact] + public async Task UpdateBookCover_WithPathTraversalFileName_ShouldNotLeakData() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + _apiFactory.ApiClientStub.RegisterPutResponse($"books/{Guid.NewGuid()}/cover", "/media/books/cover.png"); + AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); + HttpRequestMessage uploadRequest = CreateUploadRequest(Guid.NewGuid().ToString(), "..\\..\\evil.png"); + uploadRequest.Headers.Add("RequestVerificationToken", webClient.AntiforgeryToken); + + // Act + HttpResponseMessage response = await webClient.Client.SendAsync(uploadRequest); + string content = await response.Content.ReadAsStringAsync(); + + // Assert + Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("..\\", content, StringComparison.Ordinal); + } + + [Fact] + public async Task UpdateBookCover_WhenCalledWithoutAuthentication_ShouldRedirectToLogin() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + HttpClient anonymousClient = WebTestHelpers.CreateAnonymousClient(_apiFactory); + HttpRequestMessage uploadRequest = CreateUploadRequest(Guid.NewGuid().ToString(), "cover.png"); + + // Act + HttpResponseMessage response = await anonymousClient.SendAsync(uploadRequest); + + // Assert + Assert.Equal(HttpStatusCode.Redirect, response.StatusCode); + Assert.Empty(_apiFactory.ApiClientStub.PutRequests); + } + + /// + /// Builds the multipart PUT request that uploads a cover to the book identified by . + /// + /// The route Id of the book whose cover is uploaded. + /// The name of the uploaded file. + /// The configured upload request. + private static HttpRequestMessage CreateUploadRequest(string bookId, string fileName) + { + MultipartFormDataContent form = []; + ByteArrayContent fileContent = new(Encoding.UTF8.GetBytes("fake cover payload")); + fileContent.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream"); + form.Add(fileContent, "cover", fileName); + return new HttpRequestMessage(HttpMethod.Put, $"/en-us/library/written-content-library/books-library/books/{Uri.EscapeDataString(bookId)}/api-update-cover") + { + Content = form + }; + } +} diff --git a/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Plugins/GetPluginSettings/GetPluginSettingsEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Plugins/GetPluginSettings/GetPluginSettingsEndpointTests.cs index e2e0c6d1..ce4f7f13 100644 --- a/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Plugins/GetPluginSettings/GetPluginSettingsEndpointTests.cs +++ b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Plugins/GetPluginSettings/GetPluginSettingsEndpointTests.cs @@ -11,7 +11,7 @@ using System.Text.Json; namespace Lumina.Presentation.Web.SecurityTests.Core.Endpoints.Plugins.GetPluginSettings; /// -/// Contains security tests for the /{culture}/admin/manage-plugins/api-get-plugin-settings/{pluginId} route served by the class. +/// Contains security tests for the class. /// [ExcludeFromCodeCoverage] public class GetPluginSettingsEndpointTests : IClassFixture diff --git a/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Plugins/GetPlugins/GetPluginsEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Plugins/GetPlugins/GetPluginsEndpointTests.cs index 392ac0b6..a6d2fa9f 100644 --- a/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Plugins/GetPlugins/GetPluginsEndpointTests.cs +++ b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Plugins/GetPlugins/GetPluginsEndpointTests.cs @@ -12,7 +12,7 @@ using System.Net.Http.Headers; namespace Lumina.Presentation.Web.SecurityTests.Core.Endpoints.Plugins.GetPlugins; /// -/// Contains security tests for the /{culture}/admin/manage-plugins/api-get-plugins route served by the class. +/// Contains security tests for the class. /// [ExcludeFromCodeCoverage] public class GetPluginsEndpointTests : IClassFixture diff --git a/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Plugins/Index/PluginsIndexViewEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Plugins/Index/PluginsIndexViewEndpointTests.cs index bd107f1b..e463e1f5 100644 --- a/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Plugins/Index/PluginsIndexViewEndpointTests.cs +++ b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Plugins/Index/PluginsIndexViewEndpointTests.cs @@ -9,7 +9,7 @@ using System.Net; namespace Lumina.Presentation.Web.SecurityTests.Core.Endpoints.Plugins.Index; /// -/// Contains security tests for the /{culture}/admin/manage-plugins route served by the class. +/// Contains security tests for the class. /// [ExcludeFromCodeCoverage] public class PluginsIndexViewEndpointTests : IClassFixture diff --git a/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Plugins/InstallPlugin/InstallPluginEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Plugins/InstallPlugin/InstallPluginEndpointTests.cs index a3003933..d9fb64fc 100644 --- a/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Plugins/InstallPlugin/InstallPluginEndpointTests.cs +++ b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Plugins/InstallPlugin/InstallPluginEndpointTests.cs @@ -13,7 +13,7 @@ using System.Text.Json; namespace Lumina.Presentation.Web.SecurityTests.Core.Endpoints.Plugins.InstallPlugin; /// -/// Contains security tests for the /{culture}/admin/manage-plugins/api-install-plugin route served by the class. +/// Contains security tests for the class. /// [ExcludeFromCodeCoverage] public class InstallPluginEndpointTests : IClassFixture diff --git a/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Plugins/UpdatePluginSettings/UpdatePluginSettingsEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Plugins/UpdatePluginSettings/UpdatePluginSettingsEndpointTests.cs index 868af133..0dc9f4e9 100644 --- a/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Plugins/UpdatePluginSettings/UpdatePluginSettingsEndpointTests.cs +++ b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Plugins/UpdatePluginSettings/UpdatePluginSettingsEndpointTests.cs @@ -15,7 +15,7 @@ using System.Net.Http.Json; namespace Lumina.Presentation.Web.SecurityTests.Core.Endpoints.Plugins.UpdatePluginSettings; /// -/// Contains security tests for the /{culture}/admin/manage-plugins/api-update-plugin-settings route served by the class. +/// Contains security tests for the class. /// [ExcludeFromCodeCoverage] public class UpdatePluginSettingsEndpointTests : IClassFixture diff --git a/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Themes/ThemeAssets/ThemeAssetsEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Themes/ThemeAssets/ThemeAssetsEndpointTests.cs index c79c35ba..07a135d5 100644 --- a/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Themes/ThemeAssets/ThemeAssetsEndpointTests.cs +++ b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Themes/ThemeAssets/ThemeAssetsEndpointTests.cs @@ -10,7 +10,7 @@ using System.Net; namespace Lumina.Presentation.Web.SecurityTests.Core.Endpoints.Themes.ThemeAssets; /// -/// Contains security tests for the /theme-assets/{themeId}/{path} route served by the class. +/// Contains security tests for the class. /// [ExcludeFromCodeCoverage] public class ThemeAssetsEndpointTests : IClassFixture diff --git a/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Tools/Language/SetLanguage/SetLanguageEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Tools/Language/SetLanguage/SetLanguageEndpointTests.cs index 00d4459d..20e59b6a 100644 --- a/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Tools/Language/SetLanguage/SetLanguageEndpointTests.cs +++ b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Tools/Language/SetLanguage/SetLanguageEndpointTests.cs @@ -9,7 +9,7 @@ using System.Net; namespace Lumina.Presentation.Web.SecurityTests.Core.Endpoints.Tools.Language.SetLanguage; /// -/// Contains security tests for the /{culture}/tools/language/set-language route served by the class. +/// Contains security tests for the class. /// [ExcludeFromCodeCoverage] public class SetLanguageEndpointTests : IClassFixture diff --git a/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Tools/Settings/GetUserSettings/GetUserSettingsEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Tools/Settings/GetUserSettings/GetUserSettingsEndpointTests.cs index 191e3e59..0dce7839 100644 --- a/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Tools/Settings/GetUserSettings/GetUserSettingsEndpointTests.cs +++ b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Tools/Settings/GetUserSettings/GetUserSettingsEndpointTests.cs @@ -10,7 +10,7 @@ using System.Net.Http.Headers; namespace Lumina.Presentation.Web.SecurityTests.Core.Endpoints.Tools.Settings.GetUserSettings; /// -/// Contains security tests for the /{culture}/tools/settings/api-get-user-settings route served by the class. +/// Contains security tests for the class. /// [ExcludeFromCodeCoverage] public class GetUserSettingsEndpointTests : IClassFixture diff --git a/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Tools/Settings/SettingsViewEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Tools/Settings/SettingsViewEndpointTests.cs index 2f45ecdf..9141eb0b 100644 --- a/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Tools/Settings/SettingsViewEndpointTests.cs +++ b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Tools/Settings/SettingsViewEndpointTests.cs @@ -9,7 +9,7 @@ using System.Net; namespace Lumina.Presentation.Web.SecurityTests.Core.Endpoints.Tools.Settings; /// -/// Contains security tests for the /{culture}/tools/settings route served by the class. +/// Contains security tests for the class. /// [ExcludeFromCodeCoverage] public class SettingsViewEndpointTests : IClassFixture diff --git a/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Tools/Settings/UpdateUserSettings/UpdateUserSettingsEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Tools/Settings/UpdateUserSettings/UpdateUserSettingsEndpointTests.cs index 897dc53a..2fa25f2c 100644 --- a/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Tools/Settings/UpdateUserSettings/UpdateUserSettingsEndpointTests.cs +++ b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Tools/Settings/UpdateUserSettings/UpdateUserSettingsEndpointTests.cs @@ -12,7 +12,7 @@ using System.Net.Http.Json; namespace Lumina.Presentation.Web.SecurityTests.Core.Endpoints.Tools.Settings.UpdateUserSettings; /// -/// Contains security tests for the /{culture}/tools/settings/api-update-user-settings route served by the class. +/// Contains security tests for the class. /// [ExcludeFromCodeCoverage] public class UpdateUserSettingsEndpointTests : IClassFixture diff --git a/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/UsersManagement/Authentication/AccessDenied/AccessDeniedViewEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/UsersManagement/Authentication/AccessDenied/AccessDeniedViewEndpointTests.cs index 7947bd26..d516d981 100644 --- a/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/UsersManagement/Authentication/AccessDenied/AccessDeniedViewEndpointTests.cs +++ b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/UsersManagement/Authentication/AccessDenied/AccessDeniedViewEndpointTests.cs @@ -9,7 +9,7 @@ using System.Net; namespace Lumina.Presentation.Web.SecurityTests.Core.Endpoints.UsersManagement.Authentication.AccessDenied; /// -/// Contains security tests for the /{culture}/auth/access-denied route served by the class. +/// Contains security tests for the class. /// [ExcludeFromCodeCoverage] public class AccessDeniedViewEndpointTests : IClassFixture diff --git a/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/UsersManagement/Authentication/ChangePassword/ChangePasswordEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/UsersManagement/Authentication/ChangePassword/ChangePasswordEndpointTests.cs index 40e78d53..feac478f 100644 --- a/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/UsersManagement/Authentication/ChangePassword/ChangePasswordEndpointTests.cs +++ b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/UsersManagement/Authentication/ChangePassword/ChangePasswordEndpointTests.cs @@ -16,7 +16,7 @@ using System.Text.Json; namespace Lumina.Presentation.Web.SecurityTests.Core.Endpoints.UsersManagement.Authentication.ChangePassword; /// -/// Contains security tests for the /{culture}/auth/api-change-password route served by the class. +/// Contains security tests for the class. /// [ExcludeFromCodeCoverage] public class ChangePasswordEndpointTests : IClassFixture diff --git a/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/UsersManagement/Authentication/ChangePassword/ChangePasswordViewEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/UsersManagement/Authentication/ChangePassword/ChangePasswordViewEndpointTests.cs index 23bd174c..99a16e8c 100644 --- a/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/UsersManagement/Authentication/ChangePassword/ChangePasswordViewEndpointTests.cs +++ b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/UsersManagement/Authentication/ChangePassword/ChangePasswordViewEndpointTests.cs @@ -9,7 +9,7 @@ using System.Net; namespace Lumina.Presentation.Web.SecurityTests.Core.Endpoints.UsersManagement.Authentication.ChangePassword; /// -/// Contains security tests for the /{culture}/auth/change-password route served by the class. +/// Contains security tests for the class. /// [ExcludeFromCodeCoverage] public class ChangePasswordViewEndpointTests : IClassFixture diff --git a/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/UsersManagement/Authentication/Login/LoginEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/UsersManagement/Authentication/Login/LoginEndpointTests.cs index 253f76ed..884e414c 100644 --- a/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/UsersManagement/Authentication/Login/LoginEndpointTests.cs +++ b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/UsersManagement/Authentication/Login/LoginEndpointTests.cs @@ -16,7 +16,7 @@ using System.Text.Json; namespace Lumina.Presentation.Web.SecurityTests.Core.Endpoints.UsersManagement.Authentication.Login; /// -/// Contains security tests for the /{culture}/auth/api-login route served by the class. +/// Contains security tests for the class. /// [ExcludeFromCodeCoverage] public class LoginEndpointTests : IClassFixture diff --git a/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/UsersManagement/Authentication/Login/LoginViewEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/UsersManagement/Authentication/Login/LoginViewEndpointTests.cs index 300c5e01..2ca1fba2 100644 --- a/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/UsersManagement/Authentication/Login/LoginViewEndpointTests.cs +++ b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/UsersManagement/Authentication/Login/LoginViewEndpointTests.cs @@ -9,7 +9,7 @@ using System.Net; namespace Lumina.Presentation.Web.SecurityTests.Core.Endpoints.UsersManagement.Authentication.Login; /// -/// Contains security tests for the /{culture}/auth/login/{returnUrl?} route served by the class. +/// Contains security tests for the class. /// [ExcludeFromCodeCoverage] public class LoginViewEndpointTests : IClassFixture diff --git a/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/UsersManagement/Authentication/Logout/LogoutEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/UsersManagement/Authentication/Logout/LogoutEndpointTests.cs index 7e0374f8..e29f25d3 100644 --- a/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/UsersManagement/Authentication/Logout/LogoutEndpointTests.cs +++ b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/UsersManagement/Authentication/Logout/LogoutEndpointTests.cs @@ -9,7 +9,7 @@ using System.Net; namespace Lumina.Presentation.Web.SecurityTests.Core.Endpoints.UsersManagement.Authentication.Logout; /// -/// Contains security tests for the /{culture}/auth/logout route served by the class. +/// Contains security tests for the class. /// [ExcludeFromCodeCoverage] public class LogoutEndpointTests : IClassFixture diff --git a/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/UsersManagement/Authentication/RecoverPassword/RecoverPasswordEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/UsersManagement/Authentication/RecoverPassword/RecoverPasswordEndpointTests.cs index 4a26f5b3..4090af5e 100644 --- a/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/UsersManagement/Authentication/RecoverPassword/RecoverPasswordEndpointTests.cs +++ b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/UsersManagement/Authentication/RecoverPassword/RecoverPasswordEndpointTests.cs @@ -16,7 +16,7 @@ using System.Text.Json; namespace Lumina.Presentation.Web.SecurityTests.Core.Endpoints.UsersManagement.Authentication.RecoverPassword; /// -/// Contains security tests for the /{culture}/auth/api-recover-password route served by the class. +/// Contains security tests for the class. /// [ExcludeFromCodeCoverage] public class RecoverPasswordEndpointTests : IClassFixture diff --git a/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/UsersManagement/Authentication/RecoverPassword/RecoverPasswordViewEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/UsersManagement/Authentication/RecoverPassword/RecoverPasswordViewEndpointTests.cs index 8f2cbdd7..82d52eb9 100644 --- a/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/UsersManagement/Authentication/RecoverPassword/RecoverPasswordViewEndpointTests.cs +++ b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/UsersManagement/Authentication/RecoverPassword/RecoverPasswordViewEndpointTests.cs @@ -9,7 +9,7 @@ using System.Net; namespace Lumina.Presentation.Web.SecurityTests.Core.Endpoints.UsersManagement.Authentication.RecoverPassword; /// -/// Contains security tests for the /{culture}/auth/recover-password route served by the class. +/// Contains security tests for the class. /// [ExcludeFromCodeCoverage] public class RecoverPasswordViewEndpointTests : IClassFixture diff --git a/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/UsersManagement/Authentication/Register/RegisterEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/UsersManagement/Authentication/Register/RegisterEndpointTests.cs index 85a1546a..bd03b5f2 100644 --- a/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/UsersManagement/Authentication/Register/RegisterEndpointTests.cs +++ b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/UsersManagement/Authentication/Register/RegisterEndpointTests.cs @@ -16,7 +16,7 @@ using System.Text.Json; namespace Lumina.Presentation.Web.SecurityTests.Core.Endpoints.UsersManagement.Authentication.Register; /// -/// Contains security tests for the /{culture}/auth/api-register route served by the class. +/// Contains security tests for the class. /// [ExcludeFromCodeCoverage] public class RegisterEndpointTests : IClassFixture diff --git a/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/UsersManagement/Authentication/Register/RegisterViewEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/UsersManagement/Authentication/Register/RegisterViewEndpointTests.cs index 6f18a19f..dd66a864 100644 --- a/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/UsersManagement/Authentication/Register/RegisterViewEndpointTests.cs +++ b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/UsersManagement/Authentication/Register/RegisterViewEndpointTests.cs @@ -9,7 +9,7 @@ using System.Net; namespace Lumina.Presentation.Web.SecurityTests.Core.Endpoints.UsersManagement.Authentication.Register; /// -/// Contains security tests for the /{culture}/auth/register route served by the class. +/// Contains security tests for the class. /// [ExcludeFromCodeCoverage] public class RegisterViewEndpointTests : IClassFixture diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/BookMetadataDtoMappingTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/BookMetadataDtoMappingTests.cs index 5dcf533a..3c6fd887 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/BookMetadataDtoMappingTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/BookMetadataDtoMappingTests.cs @@ -57,10 +57,8 @@ public class BookMetadataDtoMappingTests Book book = _bookFixture.Create(); BookMetadataDto metadata = _bookMetadataDtoFixture.Create( title: "The Fellowship of the Ring", - goodreadsId: "3") with - { - Genres = [_genreDtoFixture.Create(name: "")] - }; + goodreadsId: "3", + genres: [_genreDtoFixture.Create(name: "")]); // Act Result result = book.ApplyMetadata(metadata); diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/GetBookRequestMappingTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/GetBookRequestMappingTests.cs new file mode 100644 index 00000000..4c3dbcab --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/GetBookRequestMappingTests.cs @@ -0,0 +1,46 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.Mapping.MediaLibrary.WrittenContentLibrary.BookLibrary.Books; +using Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Queries.GetBook; +using Lumina.Contracts.Fixtures.Core.Requests.MediaLibrary.WrittenContentLibrary.BookLibrary.Books; +using Lumina.Contracts.Requests.MediaLibrary.WrittenContentLibrary.BookLibrary.Books; +using System; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Application.UnitTests.Common.Mapping.MediaLibrary.WrittenContentLibrary.BookLibrary.Books; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class GetBookRequestMappingTests +{ + private readonly GetBookRequestFixture _requestFixture = new(); + + [Fact] + public void ToQuery_WhenMappingRequestWithValidId_ShouldMapIdCorrectly() + { + // Arrange + Guid bookId = Guid.NewGuid(); + GetBookRequest request = _requestFixture.Create(id: bookId.ToString()); + + // Act + GetBookQuery result = request.ToQuery(); + + // Assert + Assert.Equal(bookId, result.Id); + } + + [Fact] + public void ToQuery_WhenMappingRequestWithInvalidId_ShouldMapEmptyGuid() + { + // Arrange + GetBookRequest request = _requestFixture.Create(id: "not-a-guid"); + + // Act + GetBookQuery result = request.ToQuery(); + + // Assert + Assert.Equal(Guid.Empty, result.Id); + } +} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/GetBooksLiteRequestMappingTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/GetBooksLiteRequestMappingTests.cs index 24ac76d0..9a603ef4 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/GetBooksLiteRequestMappingTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/GetBooksLiteRequestMappingTests.cs @@ -40,8 +40,7 @@ public class GetBooksLiteRequestMappingTests public void ToQuery_WhenNoPaginationProvided_ShouldNotBuildPaginationData() { // Arrange - GetBooksLiteRequest request = _getBooksLiteRequestFixture.Create(); - request = request with { CurrentPage = null, PerPage = null }; + GetBooksLiteRequest request = _getBooksLiteRequestFixture.Create(includeCurrentPage: false, includePerPage: false); // Act GetBooksLiteQuery result = request.ToQuery(); @@ -56,8 +55,7 @@ public class GetBooksLiteRequestMappingTests public void ToQuery_WhenOnlyPerPageProvided_ShouldDefaultCurrentPageToOne() { // Arrange - GetBooksLiteRequest request = _getBooksLiteRequestFixture.Create(); - request = request with { CurrentPage = null, PerPage = 25 }; + GetBooksLiteRequest request = _getBooksLiteRequestFixture.Create(perPage: 25, includeCurrentPage: false); // Act GetBooksLiteQuery result = request.ToQuery(); @@ -72,8 +70,7 @@ public class GetBooksLiteRequestMappingTests public void ToQuery_WhenOnlyCurrentPageProvided_ShouldDefaultPerPageToTwoHundred() { // Arrange - GetBooksLiteRequest request = _getBooksLiteRequestFixture.Create(); - request = request with { CurrentPage = 3, PerPage = null }; + GetBooksLiteRequest request = _getBooksLiteRequestFixture.Create(currentPage: 3, includePerPage: false); // Act GetBooksLiteQuery result = request.ToQuery(); diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/GetBooksRequestMappingTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/GetBooksRequestMappingTests.cs index 962a647f..fffc881b 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/GetBooksRequestMappingTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/GetBooksRequestMappingTests.cs @@ -40,8 +40,7 @@ public class GetBooksRequestMappingTests public void ToQuery_WhenNoPaginationProvided_ShouldNotBuildPaginationData() { // Arrange - GetBooksRequest request = _getBooksRequestFixture.Create(); - request = request with { CurrentPage = null, PerPage = null }; + GetBooksRequest request = _getBooksRequestFixture.Create(includeCurrentPage: false, includePerPage: false); // Act GetBooksQuery result = request.ToQuery(); @@ -56,8 +55,7 @@ public class GetBooksRequestMappingTests public void ToQuery_WhenOnlyPerPageProvided_ShouldDefaultCurrentPageToOne() { // Arrange - GetBooksRequest request = _getBooksRequestFixture.Create(); - request = request with { CurrentPage = null, PerPage = 25 }; + GetBooksRequest request = _getBooksRequestFixture.Create(perPage: 25, includeCurrentPage: false); // Act GetBooksQuery result = request.ToQuery(); @@ -72,8 +70,7 @@ public class GetBooksRequestMappingTests public void ToQuery_WhenOnlyCurrentPageProvided_ShouldDefaultPerPageToTwoHundred() { // Arrange - GetBooksRequest request = _getBooksRequestFixture.Create(); - request = request with { CurrentPage = 3, PerPage = null }; + GetBooksRequest request = _getBooksRequestFixture.Create(currentPage: 3, includePerPage: false); // Act GetBooksQuery result = request.ToQuery(); diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/UpdateBookCommandMappingTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/UpdateBookCommandMappingTests.cs new file mode 100644 index 00000000..f913bdd4 --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/UpdateBookCommandMappingTests.cs @@ -0,0 +1,58 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.Mapping.MediaLibrary.WrittenContentLibrary.BookLibrary.Books; +using Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Commands.UpdateBook; +using Lumina.Application.Fixtures.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Commands.UpdateBook; +using Lumina.Contracts.DTO.MediaLibrary.WrittenContentLibrary.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 UpdateBookCommandMappingTests +{ + private readonly UpdateBookCommandFixture _commandFixture = new(); + + [Fact] + public void ToBookMetadataDto_WhenMappingCompleteCommand_ShouldMapAllPropertiesCorrectly() + { + // Arrange + UpdateBookCommand command = _commandFixture.Create(); + + // Act + BookMetadataDto result = command.ToBookMetadataDto(); + + // Assert + Assert.NotNull(result); + Assert.Equal(command.Metadata!.Title, result.Title); + Assert.Equal(command.Metadata.OriginalTitle, result.OriginalTitle); + Assert.Equal(command.Metadata.Description, result.Description); + Assert.Equal(command.Metadata.ReleaseInfo, result.ReleaseInfo); + Assert.Equal(command.Metadata.Genres, result.Genres); + Assert.Equal(command.Metadata.Tags, result.Tags); + Assert.Equal(command.Metadata.Language, result.Language); + Assert.Equal(command.Metadata.OriginalLanguage, result.OriginalLanguage); + Assert.Equal(command.Metadata.Publisher, result.Publisher); + Assert.Equal(command.Metadata.PageCount, result.PageCount); + Assert.Equal(command.Format, result.Format); + Assert.Equal(command.Edition, result.Edition); + Assert.Equal(command.VolumeNumber, result.VolumeNumber); + Assert.Equal(command.Series, result.Series); + Assert.Equal(command.ASIN, result.ASIN); + Assert.Equal(command.GoodreadsId, result.GoodreadsId); + Assert.Equal(command.LCCN, result.LCCN); + Assert.Equal(command.OCLCNumber, result.OCLCNumber); + Assert.Equal(command.OpenLibraryId, result.OpenLibraryId); + Assert.Equal(command.LibraryThingId, result.LibraryThingId); + Assert.Equal(command.GoogleBooksId, result.GoogleBooksId); + Assert.Equal(command.BarnesAndNobleId, result.BarnesAndNobleId); + Assert.Equal(command.AppleBooksId, result.AppleBooksId); + Assert.Equal(command.ISBNs, result.Isbns); + Assert.Equal(command.Contributors, result.Contributors); + Assert.Equal(command.Ratings, result.Ratings); + Assert.Null(result.CoverImagePath); + } +} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/UpdateBookRequestMappingTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/UpdateBookRequestMappingTests.cs new file mode 100644 index 00000000..20937a11 --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/UpdateBookRequestMappingTests.cs @@ -0,0 +1,152 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.Mapping.MediaLibrary.WrittenContentLibrary.BookLibrary.Books; +using Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Commands.UpdateBook; +using Lumina.Contracts.Fixtures.Core.Requests.MediaLibrary.WrittenContentLibrary.BookLibrary.Books; +using Lumina.Contracts.Requests.MediaLibrary.WrittenContentLibrary.BookLibrary.Books; +using Lumina.Domain.SharedKernel.Common.Enums.BookLibrary; +using Lumina.Domain.SharedKernel.Common.Enums.MediaContributors; +using System; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Application.UnitTests.Common.Mapping.MediaLibrary.WrittenContentLibrary.BookLibrary.Books; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class UpdateBookRequestMappingTests +{ + private readonly UpdateBookRequestFixture _requestFixture = new(); + + [Fact] + public void ToCommand_WhenMappingCompleteRequest_ShouldMapAllPropertiesCorrectly() + { + // Arrange + Guid bookId = Guid.NewGuid(); + UpdateBookRequest request = _requestFixture.Create(id: bookId); + + // Act + UpdateBookCommand result = request.ToCommand(); + + // Assert + Assert.NotNull(result); + Assert.Equal(bookId, result.Id); + Assert.Equal(request.Metadata, result.Metadata); + Assert.Equal(request.Format, result.Format); + Assert.Equal(request.Edition, result.Edition); + Assert.Equal(request.VolumeNumber, result.VolumeNumber); + Assert.Equal(request.Series, result.Series); + Assert.Equal(request.ASIN, result.ASIN); + Assert.Equal(request.GoodreadsId, result.GoodreadsId); + Assert.Equal(request.LCCN, result.LCCN); + Assert.Equal(request.OCLCNumber, result.OCLCNumber); + Assert.Equal(request.OpenLibraryId, result.OpenLibraryId); + Assert.Equal(request.LibraryThingId, result.LibraryThingId); + Assert.Equal(request.GoogleBooksId, result.GoogleBooksId); + Assert.Equal(request.BarnesAndNobleId, result.BarnesAndNobleId); + Assert.Equal(request.AppleBooksId, result.AppleBooksId); + Assert.Equal(request.ISBNs, result.ISBNs); + Assert.Equal(request.Contributors, result.Contributors); + Assert.Equal(request.Ratings, result.Ratings); + } + + [Fact] + public void ToCommand_WhenMappingMinimalRequest_ShouldMapCorrectly() + { + // Arrange + Guid bookId = Guid.NewGuid(); + UpdateBookRequest request = _requestFixture.Create(id: bookId, includeOptionalProperties: false); + + // Act + UpdateBookCommand result = request.ToCommand(); + + // Assert + Assert.NotNull(result); + Assert.Equal(bookId, result.Id); + Assert.NotNull(result.Metadata); + Assert.Equal(request.Metadata, result.Metadata); + Assert.Null(result.Format); + Assert.Null(result.Edition); + Assert.Null(result.VolumeNumber); + Assert.Null(result.Series); + Assert.Null(result.ASIN); + Assert.Null(result.GoodreadsId); + Assert.Null(result.LCCN); + Assert.Null(result.OCLCNumber); + Assert.Null(result.OpenLibraryId); + Assert.Null(result.LibraryThingId); + Assert.Null(result.GoogleBooksId); + Assert.Null(result.BarnesAndNobleId); + Assert.Null(result.AppleBooksId); + Assert.Null(result.ISBNs); + Assert.Null(result.Contributors); + Assert.Null(result.Ratings); + } + + [Fact] + public void ToCommand_WhenMappingRequestWithCollections_ShouldMapCollectionsCorrectly() + { + // Arrange + UpdateBookRequest request = _requestFixture.Create( + isbns: [new("978-0-123456-78-9", IsbnFormat.Isbn13)], + contributors: + [ + new( + new("John Doe", "John Smith Doe"), + new("Author", MediaContributorRoleCategory.Author) + ) + ], + ratings: [new(4.5m, 5m, BookRatingSource.Goodreads, 1000)], + includeOptionalProperties: false + ); + + // Act + UpdateBookCommand result = request.ToCommand(); + + // Assert + Assert.NotNull(result); + Assert.Equal(request.ISBNs, result.ISBNs); + Assert.Equal(request.Contributors, result.Contributors); + Assert.Equal(request.Ratings, result.Ratings); + } + + [Fact] + public void ToCommand_WhenMappingRequestWithNullId_ShouldMapEmptyGuid() + { + // Arrange + UpdateBookRequest request = _requestFixture.Create(includeId: false); + + // Act + UpdateBookCommand result = request.ToCommand(); + + // Assert + Assert.Equal(Guid.Empty, result.Id); + } + + [Fact] + public void ToCommand_WhenMappingRequestWithEmptyId_ShouldMapEmptyGuid() + { + // Arrange + UpdateBookRequest request = _requestFixture.Create(rawId: string.Empty); + + // Act + UpdateBookCommand result = request.ToCommand(); + + // Assert + Assert.Equal(Guid.Empty, result.Id); + } + + [Fact] + public void ToCommand_WhenMappingRequestWithUnparseableId_ShouldMapEmptyGuid() + { + // Arrange + UpdateBookRequest request = _requestFixture.Create(rawId: "not-a-guid"); + + // Act + UpdateBookCommand result = request.ToCommand(); + + // Assert + Assert.Equal(Guid.Empty, result.Id); + } +} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Commands/AddBook/AddBookCommandHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Commands/AddBook/AddBookCommandHandlerTests.cs index dc92eb45..6575ebc0 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Commands/AddBook/AddBookCommandHandlerTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Commands/AddBook/AddBookCommandHandlerTests.cs @@ -1,24 +1,34 @@ #region ========================================================================= USING ===================================================================================== using AutoFixture; using AutoFixture.AutoNSubstitute; +using Lumina.Application.Common.DataAccess.Entities.MediaContributors; using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary; using Lumina.Application.Common.DataAccess.Repositories.Books; +using Lumina.Application.Common.DataAccess.Repositories.MediaContributors; using Lumina.Application.Common.DataAccess.UoW; +using Lumina.Application.Common.Infrastructure.Authentication; +using Lumina.Application.Common.Infrastructure.Authorization; +using Lumina.Application.Common.Infrastructure.Authorization.Policies.LibraryOwnership; using Lumina.Application.Common.Infrastructure.Validation; using Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Commands.AddBook; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaContributors; using Lumina.Application.Fixtures.Common.Setup; using Lumina.Application.Fixtures.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Commands.AddBook; using Lumina.Contracts.Fixtures.Core.DTO.Common; +using Lumina.Contracts.Fixtures.Core.DTO.MediaContributors; +using Lumina.Contracts.Fixtures.Core.DTO.MediaLibrary.WrittenContentLibrary; using Lumina.Contracts.Fixtures.Core.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary; using Lumina.Contracts.Responses.MediaLibrary.WrittenContentLibrary.BookLibrary.Books; using Lumina.Domain.Common.Errors; using Lumina.Domain.Common.Primitives; using Lumina.Domain.SharedKernel.Common.Enums.BookLibrary; +using Lumina.Domain.SharedKernel.Common.Enums.MediaContributors; using NSubstitute; using System; using System.Diagnostics.CodeAnalysis; using System.Threading; using System.Threading.Tasks; +using ApplicationErrors = Lumina.Application.Common.Errors.Errors; #endregion namespace Lumina.Application.UnitTests.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Commands.AddBook; @@ -32,6 +42,10 @@ public class AddBookCommandHandlerTests private readonly IFixture _fixture; private readonly IUnitOfWork _mockUnitOfWork; private readonly IBookRepository _mockBookRepository; + private readonly IMediaContributorRepository _mockMediaContributorRepository; + private readonly IAuthorizationService _mockAuthorizationService; + private readonly ICurrentUserService _mockCurrentUserService; + private readonly Guid _userId; private readonly AddBookCommandHandler _sut; private readonly AddBookCommandFixture _commandBookFixture = new(); private readonly IsbnDtoFixture _isbnDtoFixture = new(); @@ -40,6 +54,9 @@ public class AddBookCommandHandlerTests private readonly TagDtoFixture _tagDtoFixture = new(); private readonly ReleaseInfoDtoFixture _releaseInfoDtoFixture = new(); private readonly LanguageInfoDtoFixture _languageInfoDtoFixture = new(); + private readonly WrittenContentMetadataDtoFixture _writtenContentMetadataDtoFixture = new(); + private readonly MediaContributorDtoFixture _mediaContributorDtoFixture = new(); + private readonly MediaContributorEntityFixture _mediaContributorEntityFixture = new(); /// /// Initializes a new instance of the class. @@ -52,13 +69,24 @@ public class AddBookCommandHandlerTests _mockUnitOfWork = Substitute.For(); _mockBookRepository = Substitute.For(); + _mockMediaContributorRepository = Substitute.For(); + _mockAuthorizationService = Substitute.For(); + _mockCurrentUserService = Substitute.For(); + _userId = Guid.NewGuid(); _mockUnitOfWork.BookRepository.Returns(_mockBookRepository); + _mockUnitOfWork.MediaContributorRepository.Returns(_mockMediaContributorRepository); + _mockMediaContributorRepository.FindOrCreateByDisplayNameAsync(Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(Result.From(_mediaContributorEntityFixture.Create())); + // Default stubs: the current user is authenticated and the library ownership policy allows access. + _mockCurrentUserService.UserId.Returns(_userId); + _mockAuthorizationService.EvaluatePolicyAsync(_userId, Arg.Any(), Arg.Any()) + .Returns(true); IValidator mockValidator = Substitute.For>(); mockValidator.Validate(Arg.Any()) .Returns([]); - _sut = new AddBookCommandHandler(_mockUnitOfWork, mockValidator); + _sut = new AddBookCommandHandler(_mockUnitOfWork, _mockAuthorizationService, _mockCurrentUserService, mockValidator); } [Fact] @@ -103,8 +131,7 @@ public class AddBookCommandHandlerTests public async Task HandleAsync_WhenCalledWithInvalidISBN_ShouldReturnFailureResult() { // Arrange - AddBookCommand bookCommand = _commandBookFixture.Create(); - bookCommand = bookCommand with { ISBNs = [_isbnDtoFixture.Create(value: "invalid", format: IsbnFormat.Isbn13)] }; + AddBookCommand bookCommand = _commandBookFixture.Create(isbns: [_isbnDtoFixture.Create(value: "invalid", format: IsbnFormat.Isbn13)]); // Act Result result = await _sut.HandleAsync(bookCommand, CancellationToken.None); @@ -113,6 +140,7 @@ public class AddBookCommandHandlerTests Assert.True(result.IsFailure); Assert.Contains(result.Errors, e => e.Description == Errors.WrittenContent.InvalidIsbn13Format.Description); await _mockBookRepository.DidNotReceive().InsertAsync(Arg.Any(), Arg.Any()); + await _mockMediaContributorRepository.DidNotReceive().FindOrCreateByDisplayNameAsync(Arg.Any(), Arg.Any(), Arg.Any()); await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); } @@ -120,8 +148,7 @@ public class AddBookCommandHandlerTests public async Task HandleAsync_WhenCalledWithInvalidRating_ShouldReturnFailureResult() { // Arrange - AddBookCommand bookCommand = _commandBookFixture.Create(); - bookCommand = bookCommand with { Ratings = [_bookRatingDtoFixture.Create(value: -1, maxValue: 5, includeOptionalProperties: false)] }; + AddBookCommand bookCommand = _commandBookFixture.Create(ratings: [_bookRatingDtoFixture.Create(value: -1, maxValue: 5, includeOptionalProperties: false)]); // Act Result result = await _sut.HandleAsync(bookCommand, CancellationToken.None); @@ -130,6 +157,7 @@ public class AddBookCommandHandlerTests Assert.True(result.IsFailure); Assert.Contains(result.Errors, e => e.Description == Errors.Metadata.RatingValueMustBePositive.Description); await _mockBookRepository.DidNotReceive().InsertAsync(Arg.Any(), Arg.Any()); + await _mockMediaContributorRepository.DidNotReceive().FindOrCreateByDisplayNameAsync(Arg.Any(), Arg.Any(), Arg.Any()); await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); } @@ -137,14 +165,7 @@ public class AddBookCommandHandlerTests public async Task HandleAsync_WhenGenreCreationFails_ShouldReturnFailureResult() { // Arrange - AddBookCommand bookCommand = _commandBookFixture.Create(); - bookCommand = bookCommand with - { - Metadata = bookCommand.Metadata! with - { - Genres = [_genreDtoFixture.Create(name: "")] - } - }; + AddBookCommand bookCommand = _commandBookFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(genres: [_genreDtoFixture.Create(name: "")])); // Act Result result = await _sut.HandleAsync(bookCommand, CancellationToken.None); @@ -153,6 +174,7 @@ public class AddBookCommandHandlerTests Assert.True(result.IsFailure); Assert.Contains(result.Errors, e => e.Description == Errors.Metadata.GenreNameCannotBeEmpty.Description); await _mockBookRepository.DidNotReceive().InsertAsync(Arg.Any(), Arg.Any()); + await _mockMediaContributorRepository.DidNotReceive().FindOrCreateByDisplayNameAsync(Arg.Any(), Arg.Any(), Arg.Any()); await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); } @@ -160,14 +182,7 @@ public class AddBookCommandHandlerTests public async Task HandleAsync_WhenTagCreationFails_ShouldReturnFailureResult() { // Arrange - AddBookCommand bookCommand = _commandBookFixture.Create(); - bookCommand = bookCommand with - { - Metadata = bookCommand.Metadata! with - { - Tags = [_tagDtoFixture.Create(name: "")] - } - }; + AddBookCommand bookCommand = _commandBookFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(tags: [_tagDtoFixture.Create(name: "")])); // Act Result result = await _sut.HandleAsync(bookCommand, CancellationToken.None); @@ -176,6 +191,7 @@ public class AddBookCommandHandlerTests Assert.True(result.IsFailure); Assert.Contains(result.Errors, e => e.Description == Errors.Metadata.TagNameCannotBeEmpty.Description); await _mockBookRepository.DidNotReceive().InsertAsync(Arg.Any(), Arg.Any()); + await _mockMediaContributorRepository.DidNotReceive().FindOrCreateByDisplayNameAsync(Arg.Any(), Arg.Any(), Arg.Any()); await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); } @@ -183,16 +199,11 @@ public class AddBookCommandHandlerTests public async Task HandleAsync_WhenReleaseInfoCreationFails_ShouldReturnFailureResult() { // Arrange - AddBookCommand bookCommand = _commandBookFixture.Create(); - bookCommand = bookCommand with - { - Metadata = bookCommand.Metadata! with - { - ReleaseInfo = _releaseInfoDtoFixture.Create( + AddBookCommand bookCommand = _commandBookFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create( originalReleaseDate: new DateOnly(2025, 1, 1), - reReleaseDate: new DateOnly(2024, 1, 1)) - } - }; + originalReleaseYear: 2025, + reReleaseDate: new DateOnly(2024, 1, 1), + reReleaseYear: 2024))); // Act Result result = await _sut.HandleAsync(bookCommand, CancellationToken.None); @@ -201,6 +212,7 @@ public class AddBookCommandHandlerTests Assert.True(result.IsFailure); Assert.Contains(result.Errors, e => e.Description == Errors.Metadata.ReReleaseDateCannotBeEarlierThanOriginalReleaseDate.Description); await _mockBookRepository.DidNotReceive().InsertAsync(Arg.Any(), Arg.Any()); + await _mockMediaContributorRepository.DidNotReceive().FindOrCreateByDisplayNameAsync(Arg.Any(), Arg.Any(), Arg.Any()); await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); } @@ -208,14 +220,7 @@ public class AddBookCommandHandlerTests public async Task HandleAsync_WhenLanguageInfoCreationFails_ShouldReturnFailureResult() { // Arrange - AddBookCommand bookCommand = _commandBookFixture.Create(); - bookCommand = bookCommand with - { - Metadata = bookCommand.Metadata! with - { - Language = _languageInfoDtoFixture.Create(languageCode: "", languageName: "English") - } - }; + AddBookCommand bookCommand = _commandBookFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(language: _languageInfoDtoFixture.Create(languageCode: "", languageName: "English"))); // Act Result result = await _sut.HandleAsync(bookCommand, CancellationToken.None); @@ -224,6 +229,7 @@ public class AddBookCommandHandlerTests Assert.True(result.IsFailure); Assert.Contains(result.Errors, e => e.Description == Errors.Metadata.LanguageCodeCannotBeEmpty.Description); await _mockBookRepository.DidNotReceive().InsertAsync(Arg.Any(), Arg.Any()); + await _mockMediaContributorRepository.DidNotReceive().FindOrCreateByDisplayNameAsync(Arg.Any(), Arg.Any(), Arg.Any()); await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); } @@ -231,14 +237,7 @@ public class AddBookCommandHandlerTests public async Task HandleAsync_WhenOriginalLanguageInfoCreationFails_ShouldReturnFailureResult() { // Arrange - AddBookCommand bookCommand = _commandBookFixture.Create(); - bookCommand = bookCommand with - { - Metadata = bookCommand.Metadata! with - { - OriginalLanguage = _languageInfoDtoFixture.Create(languageCode: "", languageName: "English") - } - }; + AddBookCommand bookCommand = _commandBookFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(originalLanguage: _languageInfoDtoFixture.Create(languageCode: "", languageName: "English"))); // Act Result result = await _sut.HandleAsync(bookCommand, CancellationToken.None); @@ -247,6 +246,194 @@ public class AddBookCommandHandlerTests Assert.True(result.IsFailure); Assert.Contains(result.Errors, e => e.Description == Errors.Metadata.LanguageCodeCannotBeEmpty.Description); await _mockBookRepository.DidNotReceive().InsertAsync(Arg.Any(), Arg.Any()); + await _mockMediaContributorRepository.DidNotReceive().FindOrCreateByDisplayNameAsync(Arg.Any(), Arg.Any(), Arg.Any()); await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); } + + [Fact] + public async Task HandleAsync_WhenContributorsAreLinked_ShouldAttachBookContributorRowsAndReturnThemInTheResponse() + { + // Arrange + AddBookCommand bookCommand = _commandBookFixture.Create(contributors: + [ + _mediaContributorDtoFixture.Create(displayName: "Author One", legalName: "Author One Legal", roleName: "author", roleCategory: MediaContributorRoleCategory.Author), + _mediaContributorDtoFixture.Create(displayName: "Author Two", legalName: "Author Two Legal", roleName: "illustrator", roleCategory: MediaContributorRoleCategory.Illustrator) + ]); + MediaContributorEntity firstContributor = _mediaContributorEntityFixture.Create(); + MediaContributorEntity secondContributor = _mediaContributorEntityFixture.Create(); + _mockMediaContributorRepository.FindOrCreateByDisplayNameAsync(Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(callInfo => Result.From(callInfo.ArgAt(0) == "Author One" ? firstContributor : secondContributor)); + BookEntity? insertedEntity = null; + _mockBookRepository.InsertAsync(Arg.Any(), Arg.Any()) + .Returns(callInfo => + { + insertedEntity = callInfo.Arg(); + return Result.Created; + }); + + // Act + Result result = await _sut.HandleAsync(bookCommand, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal(bookCommand.Contributors, result.Value.Contributors); + Assert.NotNull(insertedEntity); + Assert.Equal(2, insertedEntity!.BookContributors.Count); + Assert.Equal(firstContributor.Id, insertedEntity.BookContributors[0].MediaContributorId); + Assert.Equal("author", insertedEntity.BookContributors[0].RoleName); + Assert.Equal(MediaContributorRoleCategory.Author, insertedEntity.BookContributors[0].RoleCategory); + Assert.Equal(secondContributor.Id, insertedEntity.BookContributors[1].MediaContributorId); + Assert.Equal("illustrator", insertedEntity.BookContributors[1].RoleName); + Assert.Equal(MediaContributorRoleCategory.Illustrator, insertedEntity.BookContributors[1].RoleCategory); + await _mockBookRepository.Received(1).InsertAsync(Arg.Any(), Arg.Any()); + await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenContributorsShareTheSameDisplayName_ShouldResolveContributorOnceAndLinkEveryRole() + { + // Arrange + AddBookCommand bookCommand = _commandBookFixture.Create(contributors: + [ + _mediaContributorDtoFixture.Create(displayName: "John Doe", legalName: "John Smith Doe", roleName: "author", roleCategory: MediaContributorRoleCategory.Author), + _mediaContributorDtoFixture.Create(displayName: "John Doe", legalName: "John Smith Doe", roleName: "illustrator", roleCategory: MediaContributorRoleCategory.Illustrator) + ]); + MediaContributorEntity contributor = _mediaContributorEntityFixture.Create(); + _mockMediaContributorRepository.FindOrCreateByDisplayNameAsync(Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(Result.From(contributor)); + BookEntity? insertedEntity = null; + _mockBookRepository.InsertAsync(Arg.Any(), Arg.Any()) + .Returns(callInfo => + { + insertedEntity = callInfo.Arg(); + return Result.Created; + }); + + // Act + Result result = await _sut.HandleAsync(bookCommand, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + await _mockMediaContributorRepository.Received(1).FindOrCreateByDisplayNameAsync( + "John Doe", "John Smith Doe", Arg.Any()); + Assert.NotNull(insertedEntity); + Assert.Equal(2, insertedEntity!.BookContributors.Count); + Assert.All(insertedEntity.BookContributors, linkedContributor => Assert.Equal(contributor.Id, linkedContributor.MediaContributorId)); + Assert.Contains(insertedEntity.BookContributors, linkedContributor => linkedContributor.RoleName == "author"); + Assert.Contains(insertedEntity.BookContributors, linkedContributor => linkedContributor.RoleName == "illustrator"); + await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenContributorHasNullDisplayName_ShouldSkipIt() + { + // Arrange + AddBookCommand bookCommand = _commandBookFixture.Create(contributors: + [ + _mediaContributorDtoFixture.Create(displayName: "John Doe", legalName: "John Smith Doe", roleName: "author", roleCategory: MediaContributorRoleCategory.Author), + _mediaContributorDtoFixture.Create(includeName: false, roleName: "unknown", roleCategory: MediaContributorRoleCategory.Other) + ]); + MediaContributorEntity contributor = _mediaContributorEntityFixture.Create(); + _mockMediaContributorRepository.FindOrCreateByDisplayNameAsync(Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(Result.From(contributor)); + BookEntity? insertedEntity = null; + _mockBookRepository.InsertAsync(Arg.Any(), Arg.Any()) + .Returns(callInfo => + { + insertedEntity = callInfo.Arg(); + return Result.Created; + }); + + // Act + Result result = await _sut.HandleAsync(bookCommand, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + await _mockMediaContributorRepository.Received(1).FindOrCreateByDisplayNameAsync( + "John Doe", "John Smith Doe", Arg.Any()); + Assert.NotNull(insertedEntity); + Assert.Single(insertedEntity!.BookContributors); + Assert.Equal(contributor.Id, insertedEntity.BookContributors[0].MediaContributorId); + } + + [Fact] + public async Task HandleAsync_WhenContributorFindOrCreateFails_ShouldReturnFailureResultWithoutInserting() + { + // Arrange + AddBookCommand bookCommand = _commandBookFixture.Create(); + Error findOrCreateError = Error.Validation("MediaContributor.FindOrCreate", "Could not find or create the media contributor."); + _mockMediaContributorRepository.FindOrCreateByDisplayNameAsync(Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(findOrCreateError); + + // Act + Result result = await _sut.HandleAsync(bookCommand, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(findOrCreateError, result.FirstError); + await _mockBookRepository.DidNotReceive().InsertAsync(Arg.Any(), Arg.Any()); + await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenUserIsNotAuthenticated_ShouldReturnNotAuthorizedError() + { + // Arrange + AddBookCommand bookCommand = _commandBookFixture.Create(); + _mockCurrentUserService.UserId.Returns((Guid?)null); + + // Act + Result result = await _sut.HandleAsync(bookCommand, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(ApplicationErrors.Authorization.NotAuthorized, result.FirstError); + await _mockBookRepository.DidNotReceive().InsertAsync(Arg.Any(), Arg.Any()); + await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenUserDoesNotOwnTheLibrary_ShouldReturnNotAuthorizedError() + { + // Arrange + AddBookCommand bookCommand = _commandBookFixture.Create(); + _mockAuthorizationService.EvaluatePolicyAsync(_userId, Arg.Any(), Arg.Any()) + .Returns(false); + + // Act + Result result = await _sut.HandleAsync(bookCommand, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(ApplicationErrors.Authorization.NotAuthorized, result.FirstError); + await _mockAuthorizationService.Received(1).EvaluatePolicyAsync( + _userId, Arg.Is(context => context.LibraryId == bookCommand.LibraryId), Arg.Any()); + await _mockBookRepository.DidNotReceive().InsertAsync(Arg.Any(), Arg.Any()); + await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenCalledWithValidCommand_ShouldStampTheCurrentUserAsTheAuditActor() + { + // Arrange + AddBookCommand bookCommand = _commandBookFixture.Create(contributors: [_mediaContributorDtoFixture.Create()]); + BookEntity? insertedEntity = null; + _mockBookRepository.InsertAsync(Arg.Any(), Arg.Any()) + .Returns(callInfo => + { + insertedEntity = callInfo.Arg(); + return Result.Created; + }); + + // Act + Result result = await _sut.HandleAsync(bookCommand, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + Assert.NotNull(insertedEntity); + Assert.Equal(_userId, insertedEntity!.CreatedBy); + Assert.NotEmpty(insertedEntity.BookContributors); + Assert.All(insertedEntity.BookContributors, contributor => Assert.Equal(_userId, contributor.CreatedBy)); + await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any()); + } } diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Commands/AddBook/AddBookCommandValidatorTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Commands/AddBook/AddBookCommandValidatorTests.cs index ae80f5f8..ed69ce73 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Commands/AddBook/AddBookCommandValidatorTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Commands/AddBook/AddBookCommandValidatorTests.cs @@ -3,13 +3,19 @@ using Bogus; using Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Commands.AddBook; using Lumina.Application.Fixtures.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Commands.AddBook; using Lumina.Application.UnitTests.Common.Setup; +using Lumina.Contracts.DTO.Common; +using Lumina.Contracts.DTO.MediaContributors; +using Lumina.Contracts.Fixtures.Core.DTO.Common; +using Lumina.Contracts.Fixtures.Core.DTO.MediaContributors; +using Lumina.Contracts.Fixtures.Core.DTO.MediaLibrary.WrittenContentLibrary; +using Lumina.Contracts.Fixtures.Core.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary; using Lumina.Domain.Common.Errors; using Lumina.Domain.Common.Primitives; using Lumina.Domain.SharedKernel.Common.Enums.BookLibrary; +using Lumina.Domain.SharedKernel.Common.Enums.MediaContributors; using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; -using System.Linq; #endregion namespace Lumina.Application.UnitTests.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Commands.AddBook; @@ -22,13 +28,20 @@ public class AddBookCommandValidatorTests { private readonly AddBookCommandFixture _commandBookFixture = new(); private readonly AddBookCommandValidator _validator = new(); + private readonly WrittenContentMetadataDtoFixture _writtenContentMetadataDtoFixture = new(); + private readonly ReleaseInfoDtoFixture _releaseInfoDtoFixture = new(); + private readonly GenreDtoFixture _genreDtoFixture = new(); + private readonly TagDtoFixture _tagDtoFixture = new(); + private readonly LanguageInfoDtoFixture _languageInfoDtoFixture = new(); + private readonly IsbnDtoFixture _isbnDtoFixture = new(); + private readonly BookRatingDtoFixture _bookRatingDtoFixture = new(); + private readonly MediaContributorDtoFixture _mediaContributorDtoFixture = new(); [Fact] public void Validate_WhenTitleIsNull_ShouldHaveValidationError() { // Arrange - AddBookCommand bookCommand = _commandBookFixture.Create(); - bookCommand = bookCommand with { Metadata = bookCommand.Metadata! with { Title = null! } }; + AddBookCommand bookCommand = _commandBookFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(includeTitle: false)); // Act List result = _validator.TestValidate(bookCommand); @@ -41,8 +54,7 @@ public class AddBookCommandValidatorTests public void Validate_WhenTitleExceeds255Characters_ShouldHaveValidationError() { // Arrange - AddBookCommand bookCommand = _commandBookFixture.Create(); - bookCommand = bookCommand with { Metadata = bookCommand.Metadata! with { Title = new Faker().Random.String2(300) } }; + AddBookCommand bookCommand = _commandBookFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(title: new Faker().Random.String2(300))); // Act List result = _validator.TestValidate(bookCommand); @@ -55,8 +67,7 @@ public class AddBookCommandValidatorTests public void Validate_WhenTitleIsValid_ShouldNotHaveValidationError() { // Arrange - AddBookCommand bookCommand = _commandBookFixture.Create(); - bookCommand = bookCommand with { Metadata = bookCommand.Metadata! with { Title = new Faker().Random.String2(200) } }; + AddBookCommand bookCommand = _commandBookFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(title: new Faker().Random.String2(200))); // Act List result = _validator.TestValidate(bookCommand); @@ -69,8 +80,7 @@ public class AddBookCommandValidatorTests public void Validate_WhenOriginalTitleExceeds255Characters_ShouldHaveValidationError() { // Arrange - AddBookCommand bookCommand = _commandBookFixture.Create(); - bookCommand = bookCommand with { Metadata = bookCommand.Metadata! with { OriginalTitle = new Faker().Random.String2(300) } }; + AddBookCommand bookCommand = _commandBookFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(originalTitle: new Faker().Random.String2(300))); // Act List result = _validator.TestValidate(bookCommand); @@ -83,8 +93,7 @@ public class AddBookCommandValidatorTests public void Validate_WhenOriginalTitleIsValid_ShouldNotHaveValidationError() { // Arrange - AddBookCommand bookCommand = _commandBookFixture.Create(); - bookCommand = bookCommand with { Metadata = bookCommand.Metadata! with { OriginalTitle = new Faker().Random.String2(200) } }; + AddBookCommand bookCommand = _commandBookFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(originalTitle: new Faker().Random.String2(200))); // Act List result = _validator.TestValidate(bookCommand); @@ -97,8 +106,7 @@ public class AddBookCommandValidatorTests public void Validate_WhenOriginalTitleIsNull_ShouldNotHaveValidationError() { // Arrange - AddBookCommand bookCommand = _commandBookFixture.Create(); - bookCommand = bookCommand with { Metadata = bookCommand.Metadata! with { OriginalTitle = null! } }; + AddBookCommand bookCommand = _commandBookFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(includeOriginalTitle: false)); // Act List result = _validator.TestValidate(bookCommand); @@ -111,8 +119,7 @@ public class AddBookCommandValidatorTests public void Validate_WhenDescriptionExceeds2000Characters_ShouldHaveValidationError() { // Arrange - AddBookCommand bookCommand = _commandBookFixture.Create(); - bookCommand = bookCommand with { Metadata = bookCommand.Metadata! with { Description = new Faker().Random.String2(2001) } }; + AddBookCommand bookCommand = _commandBookFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(description: new Faker().Random.String2(2001))); // Act List result = _validator.TestValidate(bookCommand); @@ -125,8 +132,7 @@ public class AddBookCommandValidatorTests public void Validate_WhenDescriptionIsValid_ShouldNotHaveValidationError() { // Arrange - AddBookCommand bookCommand = _commandBookFixture.Create(); - bookCommand = bookCommand with { Metadata = bookCommand.Metadata! with { Description = new Faker().Random.String2(1500) } }; + AddBookCommand bookCommand = _commandBookFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(description: new Faker().Random.String2(1500))); // Act List result = _validator.TestValidate(bookCommand); @@ -139,8 +145,7 @@ public class AddBookCommandValidatorTests public void Validate_WhenDescriptionIsNull_ShouldNotHaveValidationError() { // Arrange - AddBookCommand bookCommand = _commandBookFixture.Create(); - bookCommand = bookCommand with { Metadata = bookCommand.Metadata! with { Description = null! } }; + AddBookCommand bookCommand = _commandBookFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(includeDescription: false)); // Act List result = _validator.TestValidate(bookCommand); @@ -153,8 +158,7 @@ public class AddBookCommandValidatorTests public void Validate_WhenDescriptionIsEmpty_ShouldNotHaveValidationError() { // Arrange - AddBookCommand bookCommand = _commandBookFixture.Create(); - bookCommand = bookCommand with { Metadata = bookCommand.Metadata! with { Description = string.Empty } }; + AddBookCommand bookCommand = _commandBookFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(description: string.Empty)); // Act List result = _validator.TestValidate(bookCommand); @@ -167,8 +171,7 @@ public class AddBookCommandValidatorTests public void Validate_WhenReleaseInfoIsNull_ShouldHaveValidationError() { // Arrange - AddBookCommand bookCommand = _commandBookFixture.Create(); - bookCommand = bookCommand with { Metadata = bookCommand.Metadata! with { ReleaseInfo = null! } }; + AddBookCommand bookCommand = _commandBookFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(includeReleaseInfo: false)); // Act List result = _validator.TestValidate(bookCommand); @@ -181,8 +184,7 @@ public class AddBookCommandValidatorTests public void Validate_WhenOriginalReleaseYearIsValid_ShouldNotHaveValidationError() { // Arrange - AddBookCommand bookCommand = _commandBookFixture.Create(); - 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! } } }; + AddBookCommand bookCommand = _commandBookFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(includeOriginalReleaseDate: false, originalReleaseYear: new Faker().Random.Int(2000, 2005), reReleaseYear: new Faker().Random.Int(2005, 2010), includeReReleaseDate: false))); // Act List result = _validator.TestValidate(bookCommand); @@ -195,8 +197,7 @@ public class AddBookCommandValidatorTests public void Validate_WhenOriginalReleaseYearIsLessThan1_ShouldHaveValidationError() { // Arrange - AddBookCommand bookCommand = _commandBookFixture.Create(); - bookCommand = bookCommand with { Metadata = bookCommand.Metadata! with { ReleaseInfo = bookCommand.Metadata.ReleaseInfo! with { OriginalReleaseYear = 0 } } }; + AddBookCommand bookCommand = _commandBookFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(releaseInfo: new ReleaseInfoDto(null, 0, null, null, null, null))); // Act List result = _validator.TestValidate(bookCommand); @@ -209,8 +210,7 @@ public class AddBookCommandValidatorTests public void Validate_WhenOriginalReleaseYearIsGreaterThan9999_ShouldHaveValidationError() { // Arrange - AddBookCommand bookCommand = _commandBookFixture.Create(); - bookCommand = bookCommand with { Metadata = bookCommand.Metadata! with { ReleaseInfo = bookCommand.Metadata.ReleaseInfo! with { OriginalReleaseYear = 10000 } } }; + AddBookCommand bookCommand = _commandBookFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(releaseInfo: new ReleaseInfoDto(null, 10000, null, null, null, null))); // Act List result = _validator.TestValidate(bookCommand); @@ -223,16 +223,7 @@ public class AddBookCommandValidatorTests public void Validate_WhenReReleaseYearIsValid_ShouldNotHaveValidationError() { // Arrange - AddBookCommand bookCommand = _commandBookFixture.Create(); - 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), ReReleaseDate = null! } - } - }; + AddBookCommand bookCommand = _commandBookFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(originalReleaseYear: new Faker().Random.Int(2000, 2005), reReleaseYear: new Faker().Random.Int(2005, 2010), includeReReleaseDate: false))); // Act List result = _validator.TestValidate(bookCommand); @@ -245,8 +236,7 @@ public class AddBookCommandValidatorTests public void Validate_WhenReReleaseYearIsLessThan1_ShouldHaveValidationError() { // Arrange - AddBookCommand bookCommand = _commandBookFixture.Create(); - bookCommand = bookCommand with { Metadata = bookCommand.Metadata! with { ReleaseInfo = bookCommand.Metadata.ReleaseInfo! with { ReReleaseYear = 0 } } }; + AddBookCommand bookCommand = _commandBookFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(releaseInfo: new ReleaseInfoDto(null, null, null, 0, null, null))); // Act List result = _validator.TestValidate(bookCommand); @@ -259,8 +249,7 @@ public class AddBookCommandValidatorTests public void Validate_WhenReReleaseYearIsGreaterThan9999_ShouldHaveValidationError() { // Arrange - AddBookCommand bookCommand = _commandBookFixture.Create(); - bookCommand = bookCommand with { Metadata = bookCommand.Metadata! with { ReleaseInfo = bookCommand.Metadata.ReleaseInfo! with { ReReleaseYear = 10000 } } }; + AddBookCommand bookCommand = _commandBookFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(releaseInfo: new ReleaseInfoDto(null, null, null, 10000, null, null))); // Act List result = _validator.TestValidate(bookCommand); @@ -273,8 +262,7 @@ public class AddBookCommandValidatorTests public void Validate_WhenReleaseCountryIsValid_ShouldNotHaveValidationError() { // Arrange - AddBookCommand bookCommand = _commandBookFixture.Create(); - bookCommand = bookCommand with { Metadata = bookCommand.Metadata! with { ReleaseInfo = bookCommand.Metadata.ReleaseInfo! with { ReleaseCountry = new Faker().Random.String2(2).ToUpper() } } }; + AddBookCommand bookCommand = _commandBookFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(releaseCountry: new Faker().Random.String2(2).ToUpper()))); // Act List result = _validator.TestValidate(bookCommand); @@ -287,8 +275,7 @@ public class AddBookCommandValidatorTests public void Validate_WhenReleaseCountryIsInvalid_ShouldHaveValidationError() { // Arrange - AddBookCommand bookCommand = _commandBookFixture.Create(); - bookCommand = bookCommand with { Metadata = bookCommand.Metadata! with { ReleaseInfo = bookCommand.Metadata.ReleaseInfo! with { ReleaseCountry = new Faker().Random.String2(3) } } }; + AddBookCommand bookCommand = _commandBookFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(releaseCountry: new Faker().Random.String2(3)))); // Act List result = _validator.TestValidate(bookCommand); @@ -301,8 +288,7 @@ public class AddBookCommandValidatorTests public void Validate_WhenReleaseVersionIsValid_ShouldNotHaveValidationError() { // Arrange - AddBookCommand bookCommand = _commandBookFixture.Create(); - bookCommand = bookCommand with { Metadata = bookCommand.Metadata! with { ReleaseInfo = bookCommand.Metadata.ReleaseInfo! with { ReleaseVersion = new Faker().Random.String2(50) } } }; + AddBookCommand bookCommand = _commandBookFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(releaseVersion: new Faker().Random.String2(50)))); // Act List result = _validator.TestValidate(bookCommand); @@ -315,8 +301,7 @@ public class AddBookCommandValidatorTests public void Validate_WhenReleaseVersionExceeds50Characters_ShouldHaveValidationError() { // Arrange - AddBookCommand bookCommand = _commandBookFixture.Create(); - bookCommand = bookCommand with { Metadata = bookCommand.Metadata! with { ReleaseInfo = bookCommand.Metadata.ReleaseInfo! with { ReleaseVersion = new Faker().Random.String2(51) } } }; + AddBookCommand bookCommand = _commandBookFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(releaseVersion: new Faker().Random.String2(51)))); // Act List result = _validator.TestValidate(bookCommand); @@ -329,8 +314,7 @@ public class AddBookCommandValidatorTests public void Validate_WhenReReleaseYearIsAfterOriginalReleaseYear_ShouldNotHaveValidationError() { // Arrange - AddBookCommand bookCommand = _commandBookFixture.Create(); - bookCommand = bookCommand with { Metadata = bookCommand.Metadata! with { ReleaseInfo = bookCommand.Metadata.ReleaseInfo! with { OriginalReleaseYear = 2000, ReReleaseYear = 2001, ReReleaseDate = null! } } }; + AddBookCommand bookCommand = _commandBookFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(originalReleaseYear: 2000, reReleaseYear: 2001, includeReReleaseDate: false))); // Act List result = _validator.TestValidate(bookCommand); @@ -343,8 +327,7 @@ public class AddBookCommandValidatorTests public void Validate_WhenReReleaseYearIsBeforeOriginalReleaseYear_ShouldHaveValidationError() { // Arrange - AddBookCommand bookCommand = _commandBookFixture.Create(); - bookCommand = bookCommand with { Metadata = bookCommand.Metadata! with { ReleaseInfo = bookCommand.Metadata.ReleaseInfo! with { OriginalReleaseYear = 2001, ReReleaseYear = 2000, ReReleaseDate = null! } } }; + AddBookCommand bookCommand = _commandBookFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(originalReleaseYear: 2001, reReleaseYear: 2000, includeReReleaseDate: false))); // Act List result = _validator.TestValidate(bookCommand); @@ -357,8 +340,7 @@ public class AddBookCommandValidatorTests public void Validate_WhenReReleaseDateIsAfterOriginalReleaseDate_ShouldNotHaveValidationError() { // Arrange - AddBookCommand bookCommand = _commandBookFixture.Create(); - bookCommand = bookCommand with { Metadata = bookCommand.Metadata! with { ReleaseInfo = bookCommand.Metadata.ReleaseInfo! with { OriginalReleaseDate = new DateOnly(2000, 1, 1), ReReleaseDate = new DateOnly(2001, 1, 1) } } }; + AddBookCommand bookCommand = _commandBookFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(originalReleaseDate: new DateOnly(2000, 1, 1), reReleaseDate: new DateOnly(2001, 1, 1)))); // Act List result = _validator.TestValidate(bookCommand); @@ -371,8 +353,7 @@ public class AddBookCommandValidatorTests public void Validate_WhenReReleaseDateIsBeforeOriginalReleaseDate_ShouldHaveValidationError() { // Arrange - AddBookCommand bookCommand = _commandBookFixture.Create(); - bookCommand = bookCommand with { Metadata = bookCommand.Metadata! with { ReleaseInfo = bookCommand.Metadata.ReleaseInfo! with { OriginalReleaseDate = new DateOnly(2001, 1, 1), ReReleaseDate = new DateOnly(2000, 1, 1) } } }; + AddBookCommand bookCommand = _commandBookFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(originalReleaseDate: new DateOnly(2001, 1, 1), reReleaseDate: new DateOnly(2000, 1, 1)))); // Act List result = _validator.TestValidate(bookCommand); @@ -385,8 +366,7 @@ public class AddBookCommandValidatorTests public void Validate_WhenGenresIsNull_ShouldHaveValidationError() { // Arrange - AddBookCommand bookCommand = _commandBookFixture.Create(); - bookCommand = bookCommand with { Metadata = bookCommand.Metadata! with { Genres = null! } }; + AddBookCommand bookCommand = _commandBookFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(includeGenres: false)); // Act List result = _validator.TestValidate(bookCommand); @@ -399,8 +379,7 @@ public class AddBookCommandValidatorTests public void Validate_WhenGenreNameIsEmpty_ShouldHaveValidationError() { // Arrange - AddBookCommand bookCommand = _commandBookFixture.Create(); - bookCommand = bookCommand with { Metadata = bookCommand.Metadata! with { Genres = [.. bookCommand.Metadata.Genres!.Select((genre, index) => index == 0 ? genre with { Name = string.Empty } : genre)] } }; + AddBookCommand bookCommand = _commandBookFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(genres: [_genreDtoFixture.Create(name: string.Empty)])); // Act List result = _validator.TestValidate(bookCommand); @@ -413,8 +392,7 @@ public class AddBookCommandValidatorTests public void Validate_WhenGenreNameExceeds50Characters_ShouldHaveValidationError() { // Arrange - AddBookCommand bookCommand = _commandBookFixture.Create(); - bookCommand = bookCommand with { Metadata = bookCommand.Metadata! with { Genres = [.. bookCommand.Metadata.Genres!.Select((genre, index) => index == 0 ? genre with { Name = new Faker().Random.String2(51) } : genre)] } }; + AddBookCommand bookCommand = _commandBookFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(genres: [_genreDtoFixture.Create(name: new Faker().Random.String2(51))])); // Act List result = _validator.TestValidate(bookCommand); @@ -427,14 +405,7 @@ public class AddBookCommandValidatorTests public void Validate_WhenGenresAreValid_ShouldNotHaveValidationError() { // Arrange - AddBookCommand bookCommand = _commandBookFixture.Create(); - bookCommand = bookCommand with - { - Metadata = bookCommand.Metadata! with - { - Genres = [.. bookCommand.Metadata.Genres!.Select((genre, index) => index == 0 ? genre with { Name = new Faker().Random.String2(50) } : genre)] - } - }; + AddBookCommand bookCommand = _commandBookFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(genres: [_genreDtoFixture.Create(name: new Faker().Random.String2(50))])); // Act List result = _validator.TestValidate(bookCommand); @@ -447,8 +418,7 @@ public class AddBookCommandValidatorTests public void Validate_WhenTagsIsNull_ShouldHaveValidationError() { // Arrange - AddBookCommand bookCommand = _commandBookFixture.Create(); - bookCommand = bookCommand with { Metadata = bookCommand.Metadata! with { Tags = null! } }; + AddBookCommand bookCommand = _commandBookFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(includeTags: false)); // Act List result = _validator.TestValidate(bookCommand); @@ -461,8 +431,7 @@ public class AddBookCommandValidatorTests public void Validate_WhenTagNameIsEmpty_ShouldHaveValidationError() { // Arrange - AddBookCommand bookCommand = _commandBookFixture.Create(); - bookCommand = bookCommand with { Metadata = bookCommand.Metadata! with { Tags = [.. bookCommand.Metadata.Tags!.Select((tag, index) => index == 0 ? tag with { Name = string.Empty } : tag)] } }; + AddBookCommand bookCommand = _commandBookFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(tags: [_tagDtoFixture.Create(name: string.Empty)])); // Act List result = _validator.TestValidate(bookCommand); @@ -475,8 +444,7 @@ public class AddBookCommandValidatorTests public void Validate_WhenTagNameExceeds50Characters_ShouldHaveValidationError() { // Arrange - AddBookCommand bookCommand = _commandBookFixture.Create(); - bookCommand = bookCommand with { Metadata = bookCommand.Metadata! with { Tags = [.. bookCommand.Metadata.Tags!.Select((tag, index) => index == 0 ? tag with { Name = new Faker().Random.String2(51) } : tag)] } }; + AddBookCommand bookCommand = _commandBookFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(tags: [_tagDtoFixture.Create(name: new Faker().Random.String2(51))])); // Act List result = _validator.TestValidate(bookCommand); @@ -489,14 +457,7 @@ public class AddBookCommandValidatorTests public void Validate_WhenTagsAreValid_ShouldNotHaveValidationError() { // Arrange - AddBookCommand bookCommand = _commandBookFixture.Create(); - bookCommand = bookCommand with - { - Metadata = bookCommand.Metadata! with - { - Tags = [.. bookCommand.Metadata.Tags!.Select((tag, index) => index == 0 ? tag with { Name = new Faker().Random.String2(50) } : tag)] - } - }; + AddBookCommand bookCommand = _commandBookFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(tags: [_tagDtoFixture.Create(name: new Faker().Random.String2(50))])); // Act List result = _validator.TestValidate(bookCommand); @@ -509,8 +470,7 @@ public class AddBookCommandValidatorTests public void Validate_WhenLanguageIsNull_ShouldNotHaveValidationError() { // Arrange - AddBookCommand bookCommand = _commandBookFixture.Create(); - bookCommand = bookCommand with { Metadata = bookCommand.Metadata! with { Language = null! } }; + AddBookCommand bookCommand = _commandBookFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(includeLanguage: false)); // Act List result = _validator.TestValidate(bookCommand); @@ -523,8 +483,7 @@ public class AddBookCommandValidatorTests public void Validate_WhenLanguageCodeIsEmpty_ShouldHaveValidationError() { // Arrange - AddBookCommand bookCommand = _commandBookFixture.Create(); - bookCommand = bookCommand with { Metadata = bookCommand.Metadata! with { Language = bookCommand.Metadata.Language! with { LanguageCode = string.Empty } } }; + AddBookCommand bookCommand = _commandBookFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(language: _languageInfoDtoFixture.Create(languageCode: string.Empty))); // Act List result = _validator.TestValidate(bookCommand); @@ -537,8 +496,7 @@ public class AddBookCommandValidatorTests public void Validate_WhenLanguageCodeExceeds2Characters_ShouldHaveValidationError() { // Arrange - AddBookCommand bookCommand = _commandBookFixture.Create(); - bookCommand = bookCommand with { Metadata = bookCommand.Metadata! with { Language = bookCommand.Metadata.Language! with { LanguageCode = new Faker().Random.String2(3) } } }; + AddBookCommand bookCommand = _commandBookFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(language: _languageInfoDtoFixture.Create(languageCode: new Faker().Random.String2(3)))); // Act List result = _validator.TestValidate(bookCommand); @@ -551,8 +509,7 @@ public class AddBookCommandValidatorTests public void Validate_WhenLanguageNameIsEmpty_ShouldHaveValidationError() { // Arrange - AddBookCommand bookCommand = _commandBookFixture.Create(); - bookCommand = bookCommand with { Metadata = bookCommand.Metadata! with { Language = bookCommand.Metadata.Language! with { LanguageName = string.Empty } } }; + AddBookCommand bookCommand = _commandBookFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(language: _languageInfoDtoFixture.Create(languageName: string.Empty))); // Act List result = _validator.TestValidate(bookCommand); @@ -565,8 +522,7 @@ public class AddBookCommandValidatorTests public void Validate_WhenLanguageNameExceeds50Characters_ShouldHaveValidationError() { // Arrange - AddBookCommand bookCommand = _commandBookFixture.Create(); - bookCommand = bookCommand with { Metadata = bookCommand.Metadata! with { Language = bookCommand.Metadata.Language! with { LanguageName = new Faker().Random.String2(51) } } }; + AddBookCommand bookCommand = _commandBookFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(language: _languageInfoDtoFixture.Create(languageName: new Faker().Random.String2(51)))); // Act List result = _validator.TestValidate(bookCommand); @@ -579,8 +535,7 @@ public class AddBookCommandValidatorTests public void Validate_WhenLanguageNativeNameIsNull_ShouldNotHaveValidationError() { // Arrange - AddBookCommand bookCommand = _commandBookFixture.Create(); - bookCommand = bookCommand with { Metadata = bookCommand.Metadata! with { Language = bookCommand.Metadata.Language! with { NativeName = null! } } }; + AddBookCommand bookCommand = _commandBookFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(language: _languageInfoDtoFixture.Create(includeNativeName: false))); // Act List result = _validator.TestValidate(bookCommand); @@ -593,8 +548,7 @@ public class AddBookCommandValidatorTests public void Validate_WhenLanguageNativeNameExceeds50Characters_ShouldHaveValidationError() { // Arrange - AddBookCommand bookCommand = _commandBookFixture.Create(); - bookCommand = bookCommand with { Metadata = bookCommand.Metadata! with { Language = bookCommand.Metadata.Language! with { NativeName = new Faker().Random.String2(51) } } }; + AddBookCommand bookCommand = _commandBookFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(language: _languageInfoDtoFixture.Create(nativeName: new Faker().Random.String2(51)))); // Act List result = _validator.TestValidate(bookCommand); @@ -607,8 +561,7 @@ public class AddBookCommandValidatorTests public void Validate_WhenOriginalLanguageIsNull_ShouldNotHaveValidationError() { // Arrange - AddBookCommand bookCommand = _commandBookFixture.Create(); - bookCommand = bookCommand with { Metadata = bookCommand.Metadata! with { OriginalLanguage = null! } }; + AddBookCommand bookCommand = _commandBookFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(includeOriginalLanguage: false)); // Act List result = _validator.TestValidate(bookCommand); @@ -621,8 +574,7 @@ public class AddBookCommandValidatorTests public void Validate_WhenOriginalLanguageCodeIsEmpty_ShouldHaveValidationError() { // Arrange - AddBookCommand bookCommand = _commandBookFixture.Create(); - bookCommand = bookCommand with { Metadata = bookCommand.Metadata! with { OriginalLanguage = bookCommand.Metadata.OriginalLanguage! with { LanguageCode = string.Empty } } }; + AddBookCommand bookCommand = _commandBookFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(originalLanguage: _languageInfoDtoFixture.Create(languageCode: string.Empty))); // Act List result = _validator.TestValidate(bookCommand); @@ -635,8 +587,7 @@ public class AddBookCommandValidatorTests public void Validate_WhenOriginalLanguageCodeExceeds2Characters_ShouldHaveValidationError() { // Arrange - AddBookCommand bookCommand = _commandBookFixture.Create(); - bookCommand = bookCommand with { Metadata = bookCommand.Metadata! with { OriginalLanguage = bookCommand.Metadata.OriginalLanguage! with { LanguageCode = new Faker().Random.String2(3) } } }; + AddBookCommand bookCommand = _commandBookFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(originalLanguage: _languageInfoDtoFixture.Create(languageCode: new Faker().Random.String2(3)))); // Act List result = _validator.TestValidate(bookCommand); @@ -649,8 +600,7 @@ public class AddBookCommandValidatorTests public void Validate_WhenOriginalLanguageNameIsEmpty_ShouldHaveValidationError() { // Arrange - AddBookCommand bookCommand = _commandBookFixture.Create(); - bookCommand = bookCommand with { Metadata = bookCommand.Metadata! with { OriginalLanguage = bookCommand.Metadata.OriginalLanguage! with { LanguageName = string.Empty } } }; + AddBookCommand bookCommand = _commandBookFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(originalLanguage: _languageInfoDtoFixture.Create(languageName: string.Empty))); // Act List result = _validator.TestValidate(bookCommand); @@ -663,8 +613,7 @@ public class AddBookCommandValidatorTests public void Validate_WhenOriginalLanguageNameExceeds50Characters_ShouldHaveValidationError() { // Arrange - AddBookCommand bookCommand = _commandBookFixture.Create(); - bookCommand = bookCommand with { Metadata = bookCommand.Metadata! with { OriginalLanguage = bookCommand.Metadata.OriginalLanguage! with { LanguageName = new Faker().Random.String2(51) } } }; + AddBookCommand bookCommand = _commandBookFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(originalLanguage: _languageInfoDtoFixture.Create(languageName: new Faker().Random.String2(51)))); // Act List result = _validator.TestValidate(bookCommand); @@ -677,8 +626,7 @@ public class AddBookCommandValidatorTests public void Validate_WhenOriginalLanguageNativeNameIsNull_ShouldNotHaveValidationError() { // Arrange - AddBookCommand bookCommand = _commandBookFixture.Create(); - bookCommand = bookCommand with { Metadata = bookCommand.Metadata! with { OriginalLanguage = bookCommand.Metadata.OriginalLanguage! with { NativeName = null! } } }; + AddBookCommand bookCommand = _commandBookFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(originalLanguage: _languageInfoDtoFixture.Create(includeNativeName: false))); // Act List result = _validator.TestValidate(bookCommand); @@ -691,8 +639,7 @@ public class AddBookCommandValidatorTests public void Validate_WhenOriginalLanguageNativeNameExceeds50Characters_ShouldHaveValidationError() { // Arrange - AddBookCommand bookCommand = _commandBookFixture.Create(); - bookCommand = bookCommand with { Metadata = bookCommand.Metadata! with { OriginalLanguage = bookCommand.Metadata.OriginalLanguage! with { NativeName = new Faker().Random.String2(51) } } }; + AddBookCommand bookCommand = _commandBookFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(originalLanguage: _languageInfoDtoFixture.Create(nativeName: new Faker().Random.String2(51)))); // Act List result = _validator.TestValidate(bookCommand); @@ -705,8 +652,7 @@ public class AddBookCommandValidatorTests public void Validate_WhenCalledWithEmptyPublisher_ShouldNotHaveValidationError() { // Arrange - AddBookCommand bookCommand = _commandBookFixture.Create(); - bookCommand = bookCommand with { Metadata = bookCommand.Metadata! with { Publisher = null! } }; + AddBookCommand bookCommand = _commandBookFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(includePublisher: false)); // Act List result = _validator.TestValidate(bookCommand); @@ -719,8 +665,7 @@ public class AddBookCommandValidatorTests public void Validate_WhenCalledWithValidPublisher_ShouldNotHaveValidationError() { // Arrange - AddBookCommand bookCommand = _commandBookFixture.Create(); - bookCommand = bookCommand with { Metadata = bookCommand.Metadata! with { Publisher = new Faker().Random.String2(100) } }; + AddBookCommand bookCommand = _commandBookFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(publisher: new Faker().Random.String2(100))); // Act List result = _validator.TestValidate(bookCommand); @@ -733,8 +678,7 @@ public class AddBookCommandValidatorTests public void Validate_WhenCalledWithInvalidLengthPublisher_ShouldHaveValidationError() { // Arrange - AddBookCommand bookCommand = _commandBookFixture.Create(); - bookCommand = bookCommand with { Metadata = bookCommand.Metadata! with { Publisher = new Faker().Random.String2(101) } }; + AddBookCommand bookCommand = _commandBookFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(publisher: new Faker().Random.String2(101))); // Act List result = _validator.TestValidate(bookCommand); @@ -747,8 +691,7 @@ public class AddBookCommandValidatorTests public void Validate_WhenPageCountIsNull_ShouldNotHaveValidationError() { // Arrange - AddBookCommand bookCommand = _commandBookFixture.Create(); - bookCommand = bookCommand with { Metadata = bookCommand.Metadata! with { PageCount = null } }; + AddBookCommand bookCommand = _commandBookFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(includePageCount: false)); // Act List result = _validator.TestValidate(bookCommand); @@ -761,8 +704,7 @@ public class AddBookCommandValidatorTests public void Validate_WhenPageCountIsZero_ShouldHaveValidationError() { // Arrange - AddBookCommand bookCommand = _commandBookFixture.Create(); - bookCommand = bookCommand with { Metadata = bookCommand.Metadata! with { PageCount = 0 } }; + AddBookCommand bookCommand = _commandBookFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(pageCount: 0)); // Act List result = _validator.TestValidate(bookCommand); @@ -775,8 +717,7 @@ public class AddBookCommandValidatorTests public void Validate_WhenPageCountIsNegative_ShouldHaveValidationError() { // Arrange - AddBookCommand bookCommand = _commandBookFixture.Create(); - bookCommand = bookCommand with { Metadata = bookCommand.Metadata! with { PageCount = -1 } }; + AddBookCommand bookCommand = _commandBookFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(pageCount: -1)); // Act List result = _validator.TestValidate(bookCommand); @@ -789,8 +730,7 @@ public class AddBookCommandValidatorTests public void Validate_WhenPageCountIsPositive_ShouldNotHaveValidationError() { // Arrange - AddBookCommand bookCommand = _commandBookFixture.Create(); - bookCommand = bookCommand with { Metadata = bookCommand.Metadata! with { PageCount = 100 } }; + AddBookCommand bookCommand = _commandBookFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(pageCount: 100)); // Act List result = _validator.TestValidate(bookCommand); @@ -803,8 +743,7 @@ public class AddBookCommandValidatorTests public void Validate_WhenFormatIsNull_ShouldNotHaveValidationError() { // Arrange - AddBookCommand bookCommand = _commandBookFixture.Create(); - bookCommand = bookCommand with { Format = null }; + AddBookCommand bookCommand = _commandBookFixture.Create(includeOptionalProperties: false); // Act List result = _validator.TestValidate(bookCommand); @@ -817,8 +756,7 @@ public class AddBookCommandValidatorTests public void Validate_WhenFormatIsValid_ShouldNotHaveValidationError() { // Arrange - AddBookCommand bookCommand = _commandBookFixture.Create(); - bookCommand = bookCommand with { Format = BookFormat.Hardcover }; + AddBookCommand bookCommand = _commandBookFixture.Create(format: BookFormat.Hardcover); // Act List result = _validator.TestValidate(bookCommand); @@ -831,8 +769,7 @@ public class AddBookCommandValidatorTests public void Validate_WhenFormatIsInvalid_ShouldHaveValidationError() { // Arrange - AddBookCommand bookCommand = _commandBookFixture.Create(); - bookCommand = bookCommand with { Format = (BookFormat)99 }; + AddBookCommand bookCommand = _commandBookFixture.Create(format: (BookFormat)99); // Act List result = _validator.TestValidate(bookCommand); @@ -845,8 +782,7 @@ public class AddBookCommandValidatorTests public void Validate_WhenEditionIsNull_ShouldNotHaveValidationError() { // Arrange - AddBookCommand bookCommand = _commandBookFixture.Create(); - bookCommand = bookCommand with { Edition = null }; + AddBookCommand bookCommand = _commandBookFixture.Create(includeOptionalProperties: false); // Act List result = _validator.TestValidate(bookCommand); @@ -859,8 +795,7 @@ public class AddBookCommandValidatorTests public void Validate_WhenEditionIsValid_ShouldNotHaveValidationError() { // Arrange - AddBookCommand bookCommand = _commandBookFixture.Create(); - bookCommand = bookCommand with { Edition = new Faker().Random.String2(50) }; + AddBookCommand bookCommand = _commandBookFixture.Create(edition: new Faker().Random.String2(50)); // Act List result = _validator.TestValidate(bookCommand); @@ -873,8 +808,7 @@ public class AddBookCommandValidatorTests public void Validate_WhenEditionExceeds50Characters_ShouldHaveValidationError() { // Arrange - AddBookCommand bookCommand = _commandBookFixture.Create(); - bookCommand = bookCommand with { Edition = new Faker().Random.String2(51) }; + AddBookCommand bookCommand = _commandBookFixture.Create(edition: new Faker().Random.String2(51)); // Act List result = _validator.TestValidate(bookCommand); @@ -887,8 +821,7 @@ public class AddBookCommandValidatorTests public void Validate_WhenVolumeNumberIsNull_ShouldNotHaveValidationError() { // Arrange - AddBookCommand bookCommand = _commandBookFixture.Create(); - bookCommand = bookCommand with { VolumeNumber = null }; + AddBookCommand bookCommand = _commandBookFixture.Create(includeOptionalProperties: false); // Act List result = _validator.TestValidate(bookCommand); @@ -901,8 +834,7 @@ public class AddBookCommandValidatorTests public void Validate_WhenVolumeNumberIsZero_ShouldHaveValidationError() { // Arrange - AddBookCommand bookCommand = _commandBookFixture.Create(); - bookCommand = bookCommand with { VolumeNumber = 0 }; + AddBookCommand bookCommand = _commandBookFixture.Create(volumeNumber: 0); // Act List result = _validator.TestValidate(bookCommand); @@ -915,8 +847,7 @@ public class AddBookCommandValidatorTests public void Validate_WhenVolumeNumberIsNegative_ShouldHaveValidationError() { // Arrange - AddBookCommand bookCommand = _commandBookFixture.Create(); - bookCommand = bookCommand with { VolumeNumber = -1 }; + AddBookCommand bookCommand = _commandBookFixture.Create(volumeNumber: -1); // Act List result = _validator.TestValidate(bookCommand); @@ -929,8 +860,7 @@ public class AddBookCommandValidatorTests public void Validate_WhenVolumeNumberIsPositive_ShouldNotHaveValidationError() { // Arrange - AddBookCommand bookCommand = _commandBookFixture.Create(); - bookCommand = bookCommand with { VolumeNumber = 1 }; + AddBookCommand bookCommand = _commandBookFixture.Create(volumeNumber: 1); // Act List result = _validator.TestValidate(bookCommand); @@ -944,7 +874,6 @@ public class AddBookCommandValidatorTests { // Arrange AddBookCommand bookCommand = _commandBookFixture.Create(); - bookCommand = bookCommand with { Series = null }; // Act List result = _validator.TestValidate(bookCommand); @@ -999,8 +928,7 @@ public class AddBookCommandValidatorTests public void Validate_WhenAsinIsValid_ShouldNotHaveValidationError() { // Arrange - AddBookCommand bookCommand = _commandBookFixture.Create(); - bookCommand = bookCommand with { ASIN = new Faker().Random.String2(10) }; + AddBookCommand bookCommand = _commandBookFixture.Create(asin: new Faker().Random.String2(10)); // Act List result = _validator.TestValidate(bookCommand); @@ -1013,8 +941,7 @@ public class AddBookCommandValidatorTests public void Validate_WhenAsinIsNull_ShouldNotHaveValidationError() { // Arrange - AddBookCommand bookCommand = _commandBookFixture.Create(); - bookCommand = bookCommand with { ASIN = null }; + AddBookCommand bookCommand = _commandBookFixture.Create(includeOptionalProperties: false); // Act List result = _validator.TestValidate(bookCommand); @@ -1027,8 +954,7 @@ public class AddBookCommandValidatorTests public void Validate_WhenAsinIsNotTenCharacters_ShouldHaveValidationError() { // Arrange - AddBookCommand bookCommand = _commandBookFixture.Create(); - bookCommand = bookCommand with { ASIN = new Faker().Random.String2(9) }; + AddBookCommand bookCommand = _commandBookFixture.Create(asin: new Faker().Random.String2(9)); // Act List result = _validator.TestValidate(bookCommand); @@ -1041,8 +967,7 @@ public class AddBookCommandValidatorTests public void Validate_WhenGoodreadsIdIsNull_ShouldNotHaveValidationError() { // Arrange - AddBookCommand bookCommand = _commandBookFixture.Create(); - bookCommand = bookCommand with { GoodreadsId = null }; + AddBookCommand bookCommand = _commandBookFixture.Create(includeOptionalProperties: false); // Act List result = _validator.TestValidate(bookCommand); @@ -1055,8 +980,7 @@ public class AddBookCommandValidatorTests public void Validate_WhenGoodreadsIdIsValid_ShouldNotHaveValidationError() { // Arrange - AddBookCommand bookCommand = _commandBookFixture.Create(); - bookCommand = bookCommand with { GoodreadsId = "123456789" }; + AddBookCommand bookCommand = _commandBookFixture.Create(goodreadsId: "123456789"); // Act List result = _validator.TestValidate(bookCommand); @@ -1069,8 +993,7 @@ public class AddBookCommandValidatorTests public void Validate_WhenGoodreadsIdIsNonNumeric_ShouldHaveValidationError() { // Arrange - AddBookCommand bookCommand = _commandBookFixture.Create(); - bookCommand = bookCommand with { GoodreadsId = "abc123" }; + AddBookCommand bookCommand = _commandBookFixture.Create(goodreadsId: "abc123"); // Act List result = _validator.TestValidate(bookCommand); @@ -1083,8 +1006,7 @@ public class AddBookCommandValidatorTests public void Validate_WhenGoodreadsIdContainsSpaces_ShouldHaveValidationError() { // Arrange - AddBookCommand bookCommand = _commandBookFixture.Create(); - bookCommand = bookCommand with { GoodreadsId = "123 456" }; + AddBookCommand bookCommand = _commandBookFixture.Create(goodreadsId: "123 456"); // Act List result = _validator.TestValidate(bookCommand); @@ -1097,8 +1019,7 @@ public class AddBookCommandValidatorTests public void Validate_WhenGoodreadsIdContainsSpecialCharacters_ShouldHaveValidationError() { // Arrange - AddBookCommand bookCommand = _commandBookFixture.Create(); - bookCommand = bookCommand with { GoodreadsId = "123-456" }; + AddBookCommand bookCommand = _commandBookFixture.Create(goodreadsId: "123-456"); // Act List result = _validator.TestValidate(bookCommand); @@ -1111,8 +1032,7 @@ public class AddBookCommandValidatorTests public void Validate_WhenLccnIsNull_ShouldNotHaveValidationError() { // Arrange - AddBookCommand bookCommand = _commandBookFixture.Create(); - bookCommand = bookCommand with { LCCN = null }; + AddBookCommand bookCommand = _commandBookFixture.Create(includeOptionalProperties: false); // Act List result = _validator.TestValidate(bookCommand); @@ -1125,8 +1045,7 @@ public class AddBookCommandValidatorTests public void Validate_WhenLccnIsValid_ShouldNotHaveValidationError() { // Arrange - AddBookCommand bookCommand = _commandBookFixture.Create(); - bookCommand = bookCommand with { LCCN = "n78890351" }; + AddBookCommand bookCommand = _commandBookFixture.Create(lccn: "n78890351"); // Act List result = _validator.TestValidate(bookCommand); @@ -1139,8 +1058,7 @@ public class AddBookCommandValidatorTests public void Validate_WhenLccnHasInvalidFormat_ShouldHaveValidationError() { // Arrange - AddBookCommand bookCommand = _commandBookFixture.Create(); - bookCommand = bookCommand with { LCCN = "invalid123" }; + AddBookCommand bookCommand = _commandBookFixture.Create(lccn: "invalid123"); // Act List result = _validator.TestValidate(bookCommand); @@ -1153,8 +1071,7 @@ public class AddBookCommandValidatorTests public void Validate_WhenLccnIsTooLong_ShouldHaveValidationError() { // Arrange - AddBookCommand bookCommand = _commandBookFixture.Create(); - bookCommand = bookCommand with { LCCN = new Faker().Random.String2(15) }; + AddBookCommand bookCommand = _commandBookFixture.Create(lccn: new Faker().Random.String2(15)); // Act List result = _validator.TestValidate(bookCommand); @@ -1167,8 +1084,7 @@ public class AddBookCommandValidatorTests public void Validate_WhenLccnIsTooShort_ShouldHaveValidationError() { // Arrange - AddBookCommand bookCommand = _commandBookFixture.Create(); - bookCommand = bookCommand with { LCCN = "n12" }; + AddBookCommand bookCommand = _commandBookFixture.Create(lccn: "n12"); // Act List result = _validator.TestValidate(bookCommand); @@ -1181,8 +1097,7 @@ public class AddBookCommandValidatorTests public void Validate_WhenCalledWithEmptyOclcNumber_ShouldNotHaveValidationError() { // Arrange - AddBookCommand bookCommand = _commandBookFixture.Create(); - bookCommand = bookCommand with { OCLCNumber = null }; + AddBookCommand bookCommand = _commandBookFixture.Create(includeOptionalProperties: false); // Act List result = _validator.TestValidate(bookCommand); @@ -1195,8 +1110,7 @@ public class AddBookCommandValidatorTests public void Validate_WhenCalledWithValidOclcNumberFormat1_ShouldNotHaveValidationError() { // Arrange - AddBookCommand bookCommand = _commandBookFixture.Create(); - bookCommand = bookCommand with { OCLCNumber = "ocm12345678" }; + AddBookCommand bookCommand = _commandBookFixture.Create(oclcNumber: "ocm12345678"); // Act List result = _validator.TestValidate(bookCommand); @@ -1209,8 +1123,7 @@ public class AddBookCommandValidatorTests public void Validate_WhenCalledWithValidOclcNumberFormat2_ShouldNotHaveValidationError() { // Arrange - AddBookCommand bookCommand = _commandBookFixture.Create(); - bookCommand = bookCommand with { OCLCNumber = "ocn123456789" }; + AddBookCommand bookCommand = _commandBookFixture.Create(oclcNumber: "ocn123456789"); // Act List result = _validator.TestValidate(bookCommand); @@ -1223,8 +1136,7 @@ public class AddBookCommandValidatorTests public void Validate_WhenCalledWithValidOclcNumberFormat3_ShouldNotHaveValidationError() { // Arrange - AddBookCommand bookCommand = _commandBookFixture.Create(); - bookCommand = bookCommand with { OCLCNumber = "on1234567890" }; + AddBookCommand bookCommand = _commandBookFixture.Create(oclcNumber: "on1234567890"); // Act List result = _validator.TestValidate(bookCommand); @@ -1237,8 +1149,7 @@ public class AddBookCommandValidatorTests public void Validate_WhenCalledWithValidOclcNumberFormat4_ShouldNotHaveValidationError() { // Arrange - AddBookCommand bookCommand = _commandBookFixture.Create(); - bookCommand = bookCommand with { OCLCNumber = "(OCoLC)1234567890" }; + AddBookCommand bookCommand = _commandBookFixture.Create(oclcNumber: "(OCoLC)1234567890"); // Act List result = _validator.TestValidate(bookCommand); @@ -1251,8 +1162,7 @@ public class AddBookCommandValidatorTests public void Validate_WhenCalledWithValidOclcNumberFormat5_ShouldNotHaveValidationError() { // Arrange - AddBookCommand bookCommand = _commandBookFixture.Create(); - bookCommand = bookCommand with { OCLCNumber = "12345678" }; + AddBookCommand bookCommand = _commandBookFixture.Create(oclcNumber: "12345678"); // Act List result = _validator.TestValidate(bookCommand); @@ -1265,8 +1175,7 @@ public class AddBookCommandValidatorTests public void Validate_WhenCalledWithInvalidOclcNumber_ShouldHaveValidationError() { // Arrange - AddBookCommand bookCommand = _commandBookFixture.Create(); - bookCommand = bookCommand with { OCLCNumber = "invalid_oclc_number" }; + AddBookCommand bookCommand = _commandBookFixture.Create(oclcNumber: "invalid_oclc_number"); // Act List result = _validator.TestValidate(bookCommand); @@ -1279,8 +1188,7 @@ public class AddBookCommandValidatorTests public void Validate_WhenOpenLibraryIdIsNull_ShouldNotHaveValidationError() { // Arrange - AddBookCommand bookCommand = _commandBookFixture.Create(); - bookCommand = bookCommand with { OpenLibraryId = null! }; + AddBookCommand bookCommand = _commandBookFixture.Create(includeOptionalProperties: false); // Act List result = _validator.TestValidate(bookCommand); @@ -1293,8 +1201,7 @@ public class AddBookCommandValidatorTests public void Validate_WhenOpenLibraryIdIsValid_ShouldNotHaveValidationError() { // Arrange - AddBookCommand bookCommand = _commandBookFixture.Create(); - bookCommand = bookCommand with { OpenLibraryId = "OL123456M" }; + AddBookCommand bookCommand = _commandBookFixture.Create(openLibraryId: "OL123456M"); // Act List result = _validator.TestValidate(bookCommand); @@ -1307,8 +1214,7 @@ public class AddBookCommandValidatorTests public void Validate_WhenOpenLibraryIdIsInvalid_ShouldHaveValidationError() { // Arrange - AddBookCommand bookCommand = _commandBookFixture.Create(); - bookCommand = bookCommand with { OpenLibraryId = "InvalidID" }; + AddBookCommand bookCommand = _commandBookFixture.Create(openLibraryId: "InvalidID"); // Act List result = _validator.TestValidate(bookCommand); @@ -1321,8 +1227,7 @@ public class AddBookCommandValidatorTests public void Validate_WhenOpenLibraryIdStartsWithOLButIsInvalidFormat_ShouldHaveValidationError() { // Arrange - AddBookCommand bookCommand = _commandBookFixture.Create(); - bookCommand = bookCommand with { OpenLibraryId = "OL123ABC" }; + AddBookCommand bookCommand = _commandBookFixture.Create(openLibraryId: "OL123ABC"); // Act List result = _validator.TestValidate(bookCommand); @@ -1335,8 +1240,7 @@ public class AddBookCommandValidatorTests public void Validate_WhenOpenLibraryIdHasValidFormatButInvalidSuffix_ShouldHaveValidationError() { // Arrange - AddBookCommand bookCommand = _commandBookFixture.Create(); - bookCommand = bookCommand with { OpenLibraryId = "OL123456X" }; + AddBookCommand bookCommand = _commandBookFixture.Create(openLibraryId: "OL123456X"); // Act List result = _validator.TestValidate(bookCommand); @@ -1349,8 +1253,7 @@ public class AddBookCommandValidatorTests public void Validate_WhenCalledWithEmptyLibraryThingId_ShouldAddBook() { // Arrange - AddBookCommand bookCommand = _commandBookFixture.Create(); - bookCommand = bookCommand with { LibraryThingId = null }; + AddBookCommand bookCommand = _commandBookFixture.Create(includeOptionalProperties: false); // Act List result = _validator.TestValidate(bookCommand); @@ -1363,8 +1266,7 @@ public class AddBookCommandValidatorTests public void Validate_WhenCalledWithValidLibraryThingId_ShouldNotHaveValidationError() { // Arrange - AddBookCommand bookCommand = _commandBookFixture.Create(); - bookCommand = bookCommand with { LibraryThingId = new Faker().Random.String2(50) }; + AddBookCommand bookCommand = _commandBookFixture.Create(libraryThingId: new Faker().Random.String2(50)); // Act List result = _validator.TestValidate(bookCommand); @@ -1377,8 +1279,7 @@ public class AddBookCommandValidatorTests public void Validate_WhenCalledWithInvalidLengthLibraryThingId_ShouldReturnBadRequest() { // Arrange - AddBookCommand bookCommand = _commandBookFixture.Create(); - bookCommand = bookCommand with { LibraryThingId = new Faker().Random.String2(51) }; + AddBookCommand bookCommand = _commandBookFixture.Create(libraryThingId: new Faker().Random.String2(51)); // Act List result = _validator.TestValidate(bookCommand); @@ -1391,8 +1292,7 @@ public class AddBookCommandValidatorTests public void Validate_WhenCalledWithEmptyGoogleBooksId_ShouldNotHaveValidationError() { // Arrange - AddBookCommand bookCommand = _commandBookFixture.Create(); - bookCommand = bookCommand with { GoogleBooksId = null! }; + AddBookCommand bookCommand = _commandBookFixture.Create(includeOptionalProperties: false); // Act List result = _validator.TestValidate(bookCommand); @@ -1405,8 +1305,7 @@ public class AddBookCommandValidatorTests public void Validate_WhenCalledWithInvalidLengthGoogleBooksId_ShouldHaveValidationError() { // Arrange - AddBookCommand bookCommand = _commandBookFixture.Create(); - bookCommand = bookCommand with { GoogleBooksId = new Faker().Random.String2(11) }; + AddBookCommand bookCommand = _commandBookFixture.Create(googleBooksId: new Faker().Random.String2(11)); // Act List result = _validator.TestValidate(bookCommand); @@ -1419,8 +1318,7 @@ public class AddBookCommandValidatorTests public void Validate_WhenCalledWithInvalidFormatGoogleBooksId_ShouldHaveValidationError() { // Arrange - AddBookCommand bookCommand = _commandBookFixture.Create(); - bookCommand = bookCommand with { GoogleBooksId = new Faker().Random.String2(11) + " " }; + AddBookCommand bookCommand = _commandBookFixture.Create(googleBooksId: new Faker().Random.String2(11) + " "); // Act List result = _validator.TestValidate(bookCommand); @@ -1433,8 +1331,7 @@ public class AddBookCommandValidatorTests public void Validate_WhenCalledWithValidGoogleBooksId_ShouldNotHaveValidationError() { // Arrange - AddBookCommand bookCommand = _commandBookFixture.Create(); - bookCommand = bookCommand with { GoogleBooksId = new Faker().Random.String2(12, "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_-") }; + AddBookCommand bookCommand = _commandBookFixture.Create(googleBooksId: new Faker().Random.String2(12, "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_-")); // Act List result = _validator.TestValidate(bookCommand); @@ -1447,8 +1344,7 @@ public class AddBookCommandValidatorTests public void Validate_WhenCalledWithEmptyBarnesAndNobleId_ShouldNotHaveValidationError() { // Arrange - AddBookCommand bookCommand = _commandBookFixture.Create(); - bookCommand = bookCommand with { BarnesAndNobleId = null! }; + AddBookCommand bookCommand = _commandBookFixture.Create(includeOptionalProperties: false); // Act List result = _validator.TestValidate(bookCommand); @@ -1461,8 +1357,7 @@ public class AddBookCommandValidatorTests public void Validate_WhenCalledWithInvalidLengthBarnesAndNobleId_ShouldHaveValidationError() { // Arrange - AddBookCommand bookCommand = _commandBookFixture.Create(); - bookCommand = bookCommand with { BarnesAndNobleId = new Faker().Random.String2(11) }; + AddBookCommand bookCommand = _commandBookFixture.Create(barnesAndNobleId: new Faker().Random.String2(11)); // Act List result = _validator.TestValidate(bookCommand); @@ -1475,8 +1370,7 @@ public class AddBookCommandValidatorTests public void Validate_WhenCalledWithNonNumericBarnesAndNobleId_ShouldHaveValidationError() { // Arrange - AddBookCommand bookCommand = _commandBookFixture.Create(); - bookCommand = bookCommand with { BarnesAndNobleId = new Faker().Random.AlphaNumeric(10) }; + AddBookCommand bookCommand = _commandBookFixture.Create(barnesAndNobleId: new Faker().Random.AlphaNumeric(10)); // Act List result = _validator.TestValidate(bookCommand); @@ -1489,8 +1383,7 @@ public class AddBookCommandValidatorTests public void Validate_WhenCalledWithValidBarnesAndNobleId_ShouldNotHaveValidationError() { // Arrange - AddBookCommand bookCommand = _commandBookFixture.Create(); - bookCommand = bookCommand with { BarnesAndNobleId = new Faker().Random.Number(1000000000, 999999999).ToString() }; + AddBookCommand bookCommand = _commandBookFixture.Create(barnesAndNobleId: new Faker().Random.Number(1000000000, 999999999).ToString()); // Act List result = _validator.TestValidate(bookCommand); @@ -1503,8 +1396,7 @@ public class AddBookCommandValidatorTests public void AddBook_WhenCalledWithEmptyAppleBooksId_ShouldAddBook() { // Arrange - AddBookCommand bookCommand = _commandBookFixture.Create(); - bookCommand = bookCommand with { AppleBooksId = null }; + AddBookCommand bookCommand = _commandBookFixture.Create(includeOptionalProperties: false); // Act List result = _validator.TestValidate(bookCommand); @@ -1517,8 +1409,7 @@ public class AddBookCommandValidatorTests public void AddBook_WhenCalledWithValidAppleBooksId_ShouldNotHaveValidationError() { // Arrange - AddBookCommand bookCommand = _commandBookFixture.Create(); - bookCommand = bookCommand with { AppleBooksId = "id123456" }; + AddBookCommand bookCommand = _commandBookFixture.Create(appleBooksId: "id123456"); // Act List result = _validator.TestValidate(bookCommand); @@ -1531,8 +1422,7 @@ public class AddBookCommandValidatorTests public void AddBook_WhenCalledWithInvalidAppleBooksId_ShouldHaveValidationError() { // Arrange - AddBookCommand bookCommand = _commandBookFixture.Create(); - bookCommand = bookCommand with { AppleBooksId = "invalid_id" }; + AddBookCommand bookCommand = _commandBookFixture.Create(appleBooksId: "invalid_id"); // Act List result = _validator.TestValidate(bookCommand); @@ -1545,8 +1435,7 @@ public class AddBookCommandValidatorTests public void Validate_WhenCalledWithNullIsbns_ShouldHaveValidationError() { // Arrange - AddBookCommand bookCommand = _commandBookFixture.Create(); - bookCommand = bookCommand with { ISBNs = null! }; + AddBookCommand bookCommand = _commandBookFixture.Create(includeOptionalProperties: false); // Act List result = _validator.TestValidate(bookCommand); @@ -1559,8 +1448,7 @@ public class AddBookCommandValidatorTests public void Validate_WhenCalledWithEmptyIsbnValue_ShouldHaveValidationError() { // Arrange - AddBookCommand bookCommand = _commandBookFixture.Create(); - bookCommand = bookCommand with { ISBNs = [.. bookCommand.ISBNs!.Select((isbn, index) => index == 0 ? isbn with { Value = null! } : isbn)] }; + AddBookCommand bookCommand = _commandBookFixture.Create(isbns: [_isbnDtoFixture.Create(value: string.Empty)]); // Act List result = _validator.TestValidate(bookCommand); @@ -1573,8 +1461,7 @@ public class AddBookCommandValidatorTests public void Validate_WhenCalledWithInvalidIsbn10Value_ShouldHaveValidationError() { // Arrange - AddBookCommand bookCommand = _commandBookFixture.Create(); - bookCommand = bookCommand with { ISBNs = [.. bookCommand.ISBNs!.Select((isbn, index) => index == 0 ? isbn with { Value = new Faker().Random.String2(5), Format = IsbnFormat.Isbn10 } : isbn)] }; + AddBookCommand bookCommand = _commandBookFixture.Create(isbns: [_isbnDtoFixture.Create(value: new Faker().Random.String2(5), format: IsbnFormat.Isbn10)]); // Act List result = _validator.TestValidate(bookCommand); @@ -1587,8 +1474,7 @@ public class AddBookCommandValidatorTests public void Validate_WhenCalledWithInvalidIsbn13Value_ShouldHaveValidationError() { // Arrange - AddBookCommand bookCommand = _commandBookFixture.Create(); - bookCommand = bookCommand with { ISBNs = [.. bookCommand.ISBNs!.Select((isbn, index) => index == 0 ? isbn with { Value = new Faker().Random.String2(5), Format = IsbnFormat.Isbn13 } : isbn)] }; + AddBookCommand bookCommand = _commandBookFixture.Create(isbns: [_isbnDtoFixture.Create(value: new Faker().Random.String2(5), format: IsbnFormat.Isbn13)]); // Act List result = _validator.TestValidate(bookCommand); @@ -1601,8 +1487,7 @@ public class AddBookCommandValidatorTests public void Validate_WhenCalledWithInvalidIsbnFormat_ShouldHaveValidationError() { // Arrange - AddBookCommand bookCommand = _commandBookFixture.Create(); - bookCommand = bookCommand with { ISBNs = [.. bookCommand.ISBNs!.Select((isbn, index) => index == 0 ? isbn with { Format = (IsbnFormat)99 } : isbn)] }; + AddBookCommand bookCommand = _commandBookFixture.Create(isbns: [_isbnDtoFixture.Create(format: (IsbnFormat)99)]); // Act List result = _validator.TestValidate(bookCommand); @@ -1615,8 +1500,7 @@ public class AddBookCommandValidatorTests public void Validate_WhenCalledWithValidIsbn10_ShouldNotHaveValidationError() { // Arrange - AddBookCommand bookCommand = _commandBookFixture.Create(); - bookCommand = bookCommand with { ISBNs = [.. bookCommand.ISBNs!.Select((isbn, index) => index == 0 ? isbn with { Value = "0-306-40615-2", Format = IsbnFormat.Isbn10 } : isbn)] }; + AddBookCommand bookCommand = _commandBookFixture.Create(isbns: [_isbnDtoFixture.Create(value: "0-306-40615-2", format: IsbnFormat.Isbn10)]); // Act List result = _validator.TestValidate(bookCommand); @@ -1629,8 +1513,7 @@ public class AddBookCommandValidatorTests public void Validate_WhenCalledWithValidIsbn13_ShouldNotHaveValidationError() { // Arrange - AddBookCommand bookCommand = _commandBookFixture.Create(); - bookCommand = bookCommand with { ISBNs = [.. bookCommand.ISBNs!.Select((isbn, index) => index == 0 ? isbn with { Value = "978-3-16-148410-0", Format = IsbnFormat.Isbn13 } : isbn)] }; + AddBookCommand bookCommand = _commandBookFixture.Create(isbns: [_isbnDtoFixture.Create(value: "978-3-16-148410-0", format: IsbnFormat.Isbn13)]); // Act List result = _validator.TestValidate(bookCommand); @@ -1643,8 +1526,7 @@ public class AddBookCommandValidatorTests public void Validate_WhenCalledWithNullContributors_ShouldHaveValidationError() { // Arrange - AddBookCommand bookCommand = _commandBookFixture.Create(); - bookCommand = bookCommand with { Contributors = null! }; + AddBookCommand bookCommand = _commandBookFixture.Create(includeOptionalProperties: false); // Act List result = _validator.TestValidate(bookCommand); @@ -1657,8 +1539,7 @@ public class AddBookCommandValidatorTests public void Validate_WhenCalledWithNullContributorName_ShouldHaveValidationError() { // Arrange - AddBookCommand bookCommand = _commandBookFixture.Create(); - bookCommand = bookCommand with { Contributors = [.. bookCommand.Contributors!.Select((contributor, index) => index == 0 ? contributor with { Name = null! } : contributor)] }; + AddBookCommand bookCommand = _commandBookFixture.Create(contributors: [new MediaContributorDto(null, new MediaContributorRoleDto("author", MediaContributorRoleCategory.Author))]); // Act List result = _validator.TestValidate(bookCommand); @@ -1671,8 +1552,7 @@ public class AddBookCommandValidatorTests public void Validate_WhenCalledWithInvalidLengthContributorDisplayName_ShouldHaveValidationError() { // Arrange - AddBookCommand bookCommand = _commandBookFixture.Create(); - bookCommand = bookCommand with { Contributors = [.. bookCommand.Contributors!.Select((contributor, index) => index == 0 ? contributor with { Name = contributor.Name! with { DisplayName = new Faker().Random.String2(101) } } : contributor)] }; + AddBookCommand bookCommand = _commandBookFixture.Create(contributors: [_mediaContributorDtoFixture.Create(displayName: new Faker().Random.String2(101))]); // Act List result = _validator.TestValidate(bookCommand); @@ -1685,8 +1565,7 @@ public class AddBookCommandValidatorTests public void Validate_WhenCalledWithEmptyContributorDisplayName_ShouldHaveValidationError() { // Arrange - AddBookCommand bookCommand = _commandBookFixture.Create(); - bookCommand = bookCommand with { Contributors = [.. bookCommand.Contributors!.Select((contributor, index) => index == 0 ? contributor with { Name = contributor.Name! with { DisplayName = null! } } : contributor)] }; + AddBookCommand bookCommand = _commandBookFixture.Create(contributors: [_mediaContributorDtoFixture.Create(displayName: string.Empty)]); // Act List result = _validator.TestValidate(bookCommand); @@ -1699,8 +1578,7 @@ public class AddBookCommandValidatorTests public void Validate_WhenCalledWithInvalidLengthContributorLegalName_ShouldHaveValidationError() { // Arrange - AddBookCommand bookCommand = _commandBookFixture.Create(); - bookCommand = bookCommand with { Contributors = [.. bookCommand.Contributors!.Select((contributor, index) => index == 0 ? contributor with { Name = contributor.Name! with { LegalName = new Faker().Random.String2(101) } } : contributor)] }; + AddBookCommand bookCommand = _commandBookFixture.Create(contributors: [new MediaContributorDto(new MediaContributorNameDto(new Faker().Random.String2(50), new Faker().Random.String2(101)), new MediaContributorRoleDto("author", MediaContributorRoleCategory.Author))]); // Act List result = _validator.TestValidate(bookCommand); @@ -1713,8 +1591,7 @@ public class AddBookCommandValidatorTests public void Validate_WhenCalledWithNullContributorRole_ShouldHaveValidationError() { // Arrange - AddBookCommand bookCommand = _commandBookFixture.Create(); - bookCommand = bookCommand with { Contributors = [.. bookCommand.Contributors!.Select((contributor, index) => index == 0 ? contributor with { Role = null! } : contributor)] }; + AddBookCommand bookCommand = _commandBookFixture.Create(contributors: [new MediaContributorDto(new MediaContributorNameDto(new Faker().Random.String2(50), null), null)]); // Act List result = _validator.TestValidate(bookCommand); @@ -1727,8 +1604,7 @@ public class AddBookCommandValidatorTests public void Validate_WhenCalledWithEmptyContributorRoleName_ShouldHaveValidationError() { // Arrange - AddBookCommand bookCommand = _commandBookFixture.Create(); - bookCommand = bookCommand with { Contributors = [.. bookCommand.Contributors!.Select((contributor, index) => index == 0 ? contributor with { Role = contributor.Role! with { Name = null! } } : contributor)] }; + AddBookCommand bookCommand = _commandBookFixture.Create(contributors: [new MediaContributorDto(new MediaContributorNameDto(new Faker().Random.String2(50), null), new MediaContributorRoleDto(null, MediaContributorRoleCategory.Author))]); // Act List result = _validator.TestValidate(bookCommand); @@ -1741,8 +1617,7 @@ public class AddBookCommandValidatorTests public void Validate_WhenCalledWithInvalidLengthContributorRoleName_ShouldHaveValidationError() { // Arrange - AddBookCommand bookCommand = _commandBookFixture.Create(); - bookCommand = bookCommand with { Contributors = [.. bookCommand.Contributors!.Select((contributor, index) => index == 0 ? contributor with { Role = contributor.Role! with { Name = new Faker().Random.String2(51) } } : contributor)] }; + AddBookCommand bookCommand = _commandBookFixture.Create(contributors: [new MediaContributorDto(new MediaContributorNameDto(new Faker().Random.String2(50), null), new MediaContributorRoleDto(new Faker().Random.String2(51), MediaContributorRoleCategory.Author))]); // Act List result = _validator.TestValidate(bookCommand); @@ -1755,8 +1630,7 @@ public class AddBookCommandValidatorTests public void Validate_WhenCalledWithEmptyContributorRoleCategory_ShouldHaveValidationError() { // Arrange - AddBookCommand bookCommand = _commandBookFixture.Create(); - bookCommand = bookCommand with { Contributors = [.. bookCommand.Contributors!.Select((contributor, index) => index == 0 ? contributor with { Role = contributor.Role! with { Category = null! } } : contributor)] }; + AddBookCommand bookCommand = _commandBookFixture.Create(contributors: [new MediaContributorDto(new MediaContributorNameDto(new Faker().Random.String2(50), null), new MediaContributorRoleDto("author", null))]); // Act List result = _validator.TestValidate(bookCommand); @@ -1769,8 +1643,7 @@ public class AddBookCommandValidatorTests public void Validate_WhenCalledWithNullRatings_ShouldHaveValidationError() { // Arrange - AddBookCommand bookCommand = _commandBookFixture.Create(); - bookCommand = bookCommand with { Ratings = null! }; + AddBookCommand bookCommand = _commandBookFixture.Create(includeOptionalProperties: false); // Act List result = _validator.TestValidate(bookCommand); @@ -1783,8 +1656,7 @@ public class AddBookCommandValidatorTests public void Validate_WhenCalledWithNegativeRatingValue_ShouldHaveValidationError() { // Arrange - AddBookCommand bookCommand = _commandBookFixture.Create(); - bookCommand = bookCommand with { Ratings = [.. bookCommand.Ratings!.Select((rating, index) => index == 0 ? rating with { Value = -1 } : rating)] }; + AddBookCommand bookCommand = _commandBookFixture.Create(ratings: [_bookRatingDtoFixture.Create(value: -1)]); // Act List result = _validator.TestValidate(bookCommand); @@ -1797,8 +1669,7 @@ public class AddBookCommandValidatorTests public void Validate_WhenCalledWithRatingValueGreaterThanMaxValue_ShouldHaveValidationError() { // Arrange - AddBookCommand bookCommand = _commandBookFixture.Create(); - bookCommand = bookCommand with { Ratings = [.. bookCommand.Ratings!.Select((rating, index) => index == 0 ? rating with { Value = 6, MaxValue = 5 } : rating)] }; + AddBookCommand bookCommand = _commandBookFixture.Create(ratings: [_bookRatingDtoFixture.Create(value: 6, maxValue: 5)]); // Act List result = _validator.TestValidate(bookCommand); @@ -1811,8 +1682,7 @@ public class AddBookCommandValidatorTests public void Validate_WhenCalledWithNegativeMaxRatingValue_ShouldHaveValidationError() { // Arrange - AddBookCommand bookCommand = _commandBookFixture.Create(); - bookCommand = bookCommand with { Ratings = [.. bookCommand.Ratings!.Select((rating, index) => index == 0 ? rating with { MaxValue = -1 } : rating)] }; + AddBookCommand bookCommand = _commandBookFixture.Create(ratings: [_bookRatingDtoFixture.Create(maxValue: -1)]); // Act List result = _validator.TestValidate(bookCommand); @@ -1825,8 +1695,7 @@ public class AddBookCommandValidatorTests public void Validate_WhenCalledWithNegativeVoteCount_ShouldHaveValidationError() { // Arrange - AddBookCommand bookCommand = _commandBookFixture.Create(); - bookCommand = bookCommand with { Ratings = [.. bookCommand.Ratings!.Select((rating, index) => index == 0 ? rating with { VoteCount = -1 } : rating)] }; + AddBookCommand bookCommand = _commandBookFixture.Create(ratings: [_bookRatingDtoFixture.Create(voteCount: -1)]); // Act List result = _validator.TestValidate(bookCommand); @@ -1839,13 +1708,7 @@ public class AddBookCommandValidatorTests public void Validate_WhenCalledWithValidRatings_ShouldNotHaveValidationError() { // Arrange - AddBookCommand bookCommand = _commandBookFixture.Create(); - bookCommand = bookCommand with - { - Ratings = [.. bookCommand.Ratings!.Select((rating, index) => index == 0 ? rating - with - { Value = 4, MaxValue = 5, VoteCount = 100 } : rating)] - }; + AddBookCommand bookCommand = _commandBookFixture.Create(ratings: [_bookRatingDtoFixture.Create(value: 4, maxValue: 5, voteCount: 100)]); // Act List result = _validator.TestValidate(bookCommand); @@ -1858,8 +1721,7 @@ public class AddBookCommandValidatorTests public void Validate_WhenCalledWithNullVoteCount_ShouldNotHaveValidationError() { // Arrange - AddBookCommand bookCommand = _commandBookFixture.Create(); - bookCommand = bookCommand with { Ratings = [.. bookCommand.Ratings!.Select((rating, index) => index == 0 ? rating with { VoteCount = null } : rating)] }; + AddBookCommand bookCommand = _commandBookFixture.Create(ratings: [_bookRatingDtoFixture.Create(includeOptionalProperties: false)]); // Act List result = _validator.TestValidate(bookCommand); @@ -1872,8 +1734,7 @@ public class AddBookCommandValidatorTests public void Validate_WhenLibraryIdIsEmpty_ShouldHaveValidationError() { // Arrange - AddBookCommand bookCommand = _commandBookFixture.Create(); - bookCommand = bookCommand with { LibraryId = Guid.Empty }; + AddBookCommand bookCommand = _commandBookFixture.Create(libraryId: Guid.Empty); // Act List result = _validator.TestValidate(bookCommand); diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Commands/UpdateBook/UpdateBookCommandHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Commands/UpdateBook/UpdateBookCommandHandlerTests.cs new file mode 100644 index 00000000..8bc4854e --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Commands/UpdateBook/UpdateBookCommandHandlerTests.cs @@ -0,0 +1,352 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Entities.MediaContributors; +using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary; +using Lumina.Application.Common.DataAccess.Repositories.Books; +using Lumina.Application.Common.DataAccess.Repositories.MediaContributors; +using Lumina.Application.Common.DataAccess.UoW; +using Lumina.Application.Common.Infrastructure.Authentication; +using Lumina.Application.Common.Infrastructure.Authorization; +using Lumina.Application.Common.Infrastructure.Authorization.Policies.LibraryOwnership; +using Lumina.Application.Common.Infrastructure.Validation; +using Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Commands.UpdateBook; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaContributors; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary; +using Lumina.Application.Fixtures.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Commands.UpdateBook; +using Lumina.Contracts.Fixtures.Core.DTO.MediaContributors; +using Lumina.Contracts.Responses.MediaLibrary.WrittenContentLibrary.BookLibrary.Books; +using Lumina.Domain.Common.Errors; +using Lumina.Domain.Common.Primitives; +using Lumina.Domain.SharedKernel.Common.Enums.BookLibrary; +using Lumina.Domain.SharedKernel.Common.Enums.MediaContributors; +using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; +using NSubstitute; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; +using ApplicationErrors = Lumina.Application.Common.Errors.Errors; +#endregion + +namespace Lumina.Application.UnitTests.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Commands.UpdateBook; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class UpdateBookCommandHandlerTests +{ + private readonly IUnitOfWork _mockUnitOfWork; + private readonly IBookRepository _mockBookRepository; + private readonly IMediaContributorRepository _mockMediaContributorRepository; + private readonly IAuthorizationService _mockAuthorizationService; + private readonly ICurrentUserService _mockCurrentUserService; + private readonly IValidator _mockValidator; + private readonly UpdateBookCommandHandler _sut; + private readonly Guid _userId; + private static readonly Error s_findOrCreateError = Error.Validation("MediaContributor.FindOrCreate", "Could not find or create the media contributor."); + private readonly UpdateBookCommandFixture _commandBookFixture = new(); + private readonly BookEntityFixture _bookEntityFixture = new(); + private readonly MediaContributorDtoFixture _mediaContributorDtoFixture = new(); + private readonly MediaContributorEntityFixture _mediaContributorEntityFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + public UpdateBookCommandHandlerTests() + { + _mockBookRepository = Substitute.For(); + _mockMediaContributorRepository = Substitute.For(); + _mockUnitOfWork = Substitute.For(); + _mockUnitOfWork.BookRepository.Returns(_mockBookRepository); + _mockUnitOfWork.MediaContributorRepository.Returns(_mockMediaContributorRepository); + _mockAuthorizationService = Substitute.For(); + _mockCurrentUserService = Substitute.For(); + _mockValidator = Substitute.For>(); + _userId = Guid.NewGuid(); + + // Default stubs: the current user is authenticated, the library ownership policy allows access, + // the validator passes and the existing book is found in the repository. + _mockCurrentUserService.UserId.Returns(_userId); + _mockAuthorizationService.EvaluatePolicyAsync(_userId, Arg.Any(), Arg.Any()) + .Returns(true); + _mockValidator.Validate(Arg.Any()).Returns([]); + _mockMediaContributorRepository.FindOrCreateByDisplayNameAsync(Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(Result.From(_mediaContributorEntityFixture.Create())); + _mockBookRepository.UpdateAsync(Arg.Any(), Arg.Any()) + .Returns(Result.Updated); + + _sut = new UpdateBookCommandHandler(_mockUnitOfWork, _mockAuthorizationService, _mockCurrentUserService, _mockValidator); + } + + [Fact] + public async Task HandleAsync_WhenCommandIsValid_ShouldUpdateBookAndReturnResponse() + { + // Arrange + UpdateBookCommand command = _commandBookFixture.Create(); + BookEntity existingBook = _bookEntityFixture.Create(id: command.Id); + _mockBookRepository.GetByIdAsync(command.Id, Arg.Any()) + .Returns(Result.From(existingBook)); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal(command.Id, result.Value.Id); + Assert.Equal(command.Metadata!.Title, result.Value.Metadata!.Title); + Assert.Equal(command.Contributors, result.Value.Contributors); + await _mockBookRepository.Received(1).UpdateAsync(Arg.Any(), Arg.Any()); + await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenValidatorFails_ShouldReturnValidationErrorsWithoutUpdating() + { + // Arrange + UpdateBookCommand command = _commandBookFixture.Create(); + _mockValidator.Validate(Arg.Any()).Returns([Errors.WrittenContent.BookIdCannotBeEmpty]); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.WrittenContent.BookIdCannotBeEmpty, result.FirstError); + await _mockBookRepository.DidNotReceive().GetByIdAsync(Arg.Any(), Arg.Any()); + await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenUserIsNotAuthenticated_ShouldReturnNotAuthorizedError() + { + // Arrange + UpdateBookCommand command = _commandBookFixture.Create(); + _mockCurrentUserService.UserId.Returns((Guid?)null); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(ApplicationErrors.Authorization.NotAuthorized, result.FirstError); + await _mockBookRepository.DidNotReceive().GetByIdAsync(Arg.Any(), Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenBookDoesNotExist_ShouldReturnBookNotFoundError() + { + // Arrange + UpdateBookCommand command = _commandBookFixture.Create(); + _mockBookRepository.GetByIdAsync(command.Id, Arg.Any()) + .Returns(Result.From(null)); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.WrittenContent.BookNotFound, result.FirstError); + await _mockAuthorizationService.DidNotReceive().EvaluatePolicyAsync(Arg.Any(), Arg.Any(), Arg.Any()); + await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenRepositoryReturnsError_ShouldReturnFailureResult() + { + // Arrange + UpdateBookCommand command = _commandBookFixture.Create(); + _mockBookRepository.GetByIdAsync(command.Id, Arg.Any()) + .Returns(Errors.Library.LibraryIdCannotBeEmpty); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.Library.LibraryIdCannotBeEmpty, result.FirstError); + await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenPolicyDeniesAccess_ShouldReturnNotAuthorizedErrorWithoutUpdating() + { + // Arrange + UpdateBookCommand command = _commandBookFixture.Create(); + BookEntity existingBook = _bookEntityFixture.Create(id: command.Id); + _mockBookRepository.GetByIdAsync(command.Id, Arg.Any()) + .Returns(Result.From(existingBook)); + _mockAuthorizationService.EvaluatePolicyAsync(_userId, Arg.Any(), Arg.Any()) + .Returns(false); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(ApplicationErrors.Authorization.NotAuthorized, result.FirstError); + await _mockAuthorizationService.Received(1).EvaluatePolicyAsync( + _userId, Arg.Is(context => context.LibraryId == existingBook.LibraryId), Arg.Any()); + await _mockBookRepository.DidNotReceive().UpdateAsync(Arg.Any(), Arg.Any()); + await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenContributorFindOrCreateFails_ShouldReturnFailureResultWithoutSaving() + { + // Arrange + UpdateBookCommand command = _commandBookFixture.Create(); + BookEntity existingBook = _bookEntityFixture.Create(id: command.Id); + _mockBookRepository.GetByIdAsync(command.Id, Arg.Any()) + .Returns(Result.From(existingBook)); + _mockMediaContributorRepository.FindOrCreateByDisplayNameAsync(Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(s_findOrCreateError); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(s_findOrCreateError, result.FirstError); + await _mockBookRepository.DidNotReceive().UpdateAsync(Arg.Any(), Arg.Any()); + await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenRepositoryUpdateFails_ShouldReturnFailureResultWithoutSaving() + { + // Arrange + UpdateBookCommand command = _commandBookFixture.Create(); + BookEntity existingBook = _bookEntityFixture.Create(id: command.Id); + _mockBookRepository.GetByIdAsync(command.Id, Arg.Any()) + .Returns(Result.From(existingBook)); + _mockBookRepository.UpdateAsync(Arg.Any(), Arg.Any()) + .Returns(Errors.WrittenContent.BookNotFound); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.WrittenContent.BookNotFound, result.FirstError); + await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenContributorsShareTheSameDisplayName_ShouldResolveContributorOnceAndLinkEveryRole() + { + // Arrange + UpdateBookCommand command = _commandBookFixture.Create( + contributors: + [ + _mediaContributorDtoFixture.Create(displayName: "John Doe", legalName: "John Smith Doe", roleName: "author", roleCategory: MediaContributorRoleCategory.Author), + _mediaContributorDtoFixture.Create(displayName: "John Doe", legalName: "John Smith Doe", roleName: "illustrator", roleCategory: MediaContributorRoleCategory.Illustrator) + ]); + BookEntity existingBook = _bookEntityFixture.Create(id: command.Id); + _mockBookRepository.GetByIdAsync(command.Id, Arg.Any()) + .Returns(Result.From(existingBook)); + MediaContributorEntity contributor = _mediaContributorEntityFixture.Create(); + _mockMediaContributorRepository.FindOrCreateByDisplayNameAsync(Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(Result.From(contributor)); + BookEntity? updatedEntity = null; + _mockBookRepository.UpdateAsync(Arg.Any(), Arg.Any()) + .Returns(callInfo => + { + updatedEntity = callInfo.Arg(); + return Result.Updated; + }); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + await _mockMediaContributorRepository.Received(1).FindOrCreateByDisplayNameAsync( + "John Doe", "John Smith Doe", Arg.Any()); + Assert.NotNull(updatedEntity); + Assert.Equal(2, updatedEntity!.BookContributors.Count); + Assert.All(updatedEntity.BookContributors, linkedContributor => Assert.Equal(contributor.Id, linkedContributor.MediaContributorId)); + Assert.Contains(updatedEntity.BookContributors, linkedContributor => linkedContributor.RoleName == "author"); + Assert.Contains(updatedEntity.BookContributors, linkedContributor => linkedContributor.RoleName == "illustrator"); + await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenContributorsHaveDistinctDisplayNames_ShouldResolveEachContributorOnce() + { + // Arrange + UpdateBookCommand command = _commandBookFixture.Create( + contributors: + [ + _mediaContributorDtoFixture.Create(displayName: "Author One", legalName: "Author One Legal", roleName: "author", roleCategory: MediaContributorRoleCategory.Author), + _mediaContributorDtoFixture.Create(displayName: "Author Two", legalName: "Author Two Legal", roleName: "illustrator", roleCategory: MediaContributorRoleCategory.Illustrator) + ]); + BookEntity existingBook = _bookEntityFixture.Create(id: command.Id); + _mockBookRepository.GetByIdAsync(command.Id, Arg.Any()) + .Returns(Result.From(existingBook)); + MediaContributorEntity firstContributor = _mediaContributorEntityFixture.Create(); + MediaContributorEntity secondContributor = _mediaContributorEntityFixture.Create(); + _mockMediaContributorRepository.FindOrCreateByDisplayNameAsync(Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(callInfo => Result.From(callInfo.ArgAt(0) == "Author One" ? firstContributor : secondContributor)); + BookEntity? updatedEntity = null; + _mockBookRepository.UpdateAsync(Arg.Any(), Arg.Any()) + .Returns(callInfo => + { + updatedEntity = callInfo.Arg(); + return Result.Updated; + }); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + await _mockMediaContributorRepository.Received(1).FindOrCreateByDisplayNameAsync( + "Author One", "Author One Legal", Arg.Any()); + await _mockMediaContributorRepository.Received(1).FindOrCreateByDisplayNameAsync( + "Author Two", "Author Two Legal", Arg.Any()); + Assert.NotNull(updatedEntity); + Assert.Equal(2, updatedEntity!.BookContributors.Count); + Assert.Equal(firstContributor.Id, updatedEntity.BookContributors[0].MediaContributorId); + Assert.Equal(secondContributor.Id, updatedEntity.BookContributors[1].MediaContributorId); + await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenStoredBookHasEnrichmentAndCover_ShouldPreserveThemInTheResponse() + { + // Arrange + UpdateBookCommand command = _commandBookFixture.Create(); + BookEntity existingBook = _bookEntityFixture.Create(id: command.Id); + existingBook.MetadataStatus = MetadataStatus.Enriched; + existingBook.LastMetadataUpdateUtc = new DateTime(2024, 1, 2, 3, 4, 5, DateTimeKind.Utc); + existingBook.MetadataProvider = "TestProvider"; + existingBook.BookArtwork.Add(new BookArtworkEntity + { + Id = Guid.NewGuid(), + BookId = existingBook.Id, + ArtworkType = ArtworkType.Cover, + Ordinal = 0, + FileName = "/media/covers/cover.jpg", + Status = ArtworkStatus.Enriched, + CreatedOnUtc = DateTime.UtcNow, + CreatedBy = Guid.NewGuid(), + UpdatedBy = null + }); + _mockBookRepository.GetByIdAsync(command.Id, Arg.Any()) + .Returns(Result.From(existingBook)); + _mockBookRepository.UpdateAsync(Arg.Any(), Arg.Any()) + .Returns(Result.Updated); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal(MetadataStatus.Enriched, result.Value.MetadataStatus); + Assert.Equal(existingBook.LastMetadataUpdateUtc, result.Value.LastMetadataUpdateUtc); + Assert.Equal(existingBook.MetadataProvider, result.Value.MetadataProvider); + Assert.Equal("/media/covers/cover.jpg", result.Value.CoverPath); + } +} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Commands/UpdateBook/UpdateBookCommandValidatorTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Commands/UpdateBook/UpdateBookCommandValidatorTests.cs new file mode 100644 index 00000000..3decf083 --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Commands/UpdateBook/UpdateBookCommandValidatorTests.cs @@ -0,0 +1,398 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Commands.UpdateBook; +using Lumina.Application.Fixtures.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Commands.UpdateBook; +using Lumina.Application.UnitTests.Common.Setup; +using Lumina.Contracts.Fixtures.Core.DTO.Common; +using Lumina.Contracts.Fixtures.Core.DTO.MediaContributors; +using Lumina.Contracts.Fixtures.Core.DTO.MediaLibrary.WrittenContentLibrary; +using Lumina.Contracts.Fixtures.Core.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary; +using Lumina.Domain.Common.Errors; +using Lumina.Domain.Common.Primitives; +using Lumina.Domain.SharedKernel.Common.Enums.BookLibrary; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Application.UnitTests.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Commands.UpdateBook; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class UpdateBookCommandValidatorTests +{ + private readonly UpdateBookCommandFixture _commandBookFixture = new(); + private readonly UpdateBookCommandValidator _validator = new(); + private readonly WrittenContentMetadataDtoFixture _writtenContentMetadataDtoFixture = new(); + private readonly ReleaseInfoDtoFixture _releaseInfoDtoFixture = new(); + private readonly LanguageInfoDtoFixture _languageInfoDtoFixture = new(); + private readonly IsbnDtoFixture _isbnDtoFixture = new(); + private readonly MediaContributorDtoFixture _mediaContributorDtoFixture = new(); + private readonly BookRatingDtoFixture _bookRatingDtoFixture = new(); + + [Fact] + public void Validate_WhenCommandIsValid_ShouldNotHaveValidationErrors() + { + // Arrange + UpdateBookCommand bookCommand = _commandBookFixture.Create(); + + // Act + List result = _validator.TestValidate(bookCommand); + + // Assert + Assert.Empty(result); + } + + [Fact] + public void Validate_WhenIdIsEmpty_ShouldHaveValidationError() + { + // Arrange + UpdateBookCommand bookCommand = _commandBookFixture.Create(id: Guid.Empty); + + // Act + List result = _validator.TestValidate(bookCommand); + + // Assert + result.ShouldHaveValidationError(Errors.WrittenContent.BookIdCannotBeEmpty); + } + + [Fact] + public void Validate_WhenMetadataIsNull_ShouldHaveValidationError() + { + // Arrange + UpdateBookCommand bookCommand = _commandBookFixture.Create(includeMetadata: false); + + // Act + List result = _validator.TestValidate(bookCommand); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.MetadataCannotBeNull); + } + + [Fact] + public void Validate_WhenTitleIsNull_ShouldHaveValidationError() + { + // Arrange + UpdateBookCommand bookCommand = _commandBookFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(includeTitle: false)); + + // Act + List result = _validator.TestValidate(bookCommand); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.TitleCannotBeEmpty); + } + + [Fact] + public void Validate_WhenTitleExceeds255Characters_ShouldHaveValidationError() + { + // Arrange + UpdateBookCommand bookCommand = _commandBookFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(title: new Faker().Random.String2(300))); + + // Act + List result = _validator.TestValidate(bookCommand); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.TitleMustBeMaximum255CharactersLong); + } + + [Fact] + public void Validate_WhenReleaseInfoIsNull_ShouldHaveValidationError() + { + // Arrange + UpdateBookCommand bookCommand = _commandBookFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(includeReleaseInfo: false)); + + // Act + List result = _validator.TestValidate(bookCommand); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.ReleaseInfoCannotBeNull); + } + + [Fact] + public void Validate_WhenReReleaseYearIsBeforeOriginalReleaseYear_ShouldHaveValidationError() + { + // Arrange + UpdateBookCommand bookCommand = _commandBookFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(originalReleaseYear: 2001, reReleaseYear: 2000, includeReReleaseDate: false))); + + // Act + List result = _validator.TestValidate(bookCommand); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.ReReleaseYearCannotBeEarlierThanOriginalReleaseYear); + } + + [Fact] + public void Validate_WhenGenresIsNull_ShouldHaveValidationError() + { + // Arrange + UpdateBookCommand bookCommand = _commandBookFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(includeGenres: false)); + + // Act + List result = _validator.TestValidate(bookCommand); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.GenresListCannotBeNull); + } + + [Fact] + public void Validate_WhenTagsIsNull_ShouldHaveValidationError() + { + // Arrange + UpdateBookCommand bookCommand = _commandBookFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(includeTags: false)); + + // Act + List result = _validator.TestValidate(bookCommand); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.TagsListCannotBeNull); + } + + [Fact] + public void Validate_WhenLanguageCodeIsEmpty_ShouldHaveValidationError() + { + // Arrange + UpdateBookCommand bookCommand = _commandBookFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(language: _languageInfoDtoFixture.Create(languageCode: string.Empty))); + + // Act + List result = _validator.TestValidate(bookCommand); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.LanguageCodeCannotBeEmpty); + } + + [Fact] + public void Validate_WhenFormatIsInvalid_ShouldHaveValidationError() + { + // Arrange + UpdateBookCommand bookCommand = _commandBookFixture.Create(format: (BookFormat)99); + + // Act + List result = _validator.TestValidate(bookCommand); + + // Assert + result.ShouldHaveValidationError(Errors.WrittenContent.UnknownBookFormat); + } + + [Fact] + public void Validate_WhenEditionExceeds50Characters_ShouldHaveValidationError() + { + // Arrange + UpdateBookCommand bookCommand = _commandBookFixture.Create(edition: new Faker().Random.String2(51)); + + // Act + List result = _validator.TestValidate(bookCommand); + + // Assert + result.ShouldHaveValidationError(Errors.WrittenContent.EditionMustBeMaximum50CharactersLong); + } + + [Fact] + public void Validate_WhenVolumeNumberIsNegative_ShouldHaveValidationError() + { + // Arrange + UpdateBookCommand bookCommand = _commandBookFixture.Create(volumeNumber: -1); + + // Act + List result = _validator.TestValidate(bookCommand); + + // Assert + result.ShouldHaveValidationError(Errors.WrittenContent.VolumeNumberMustBeGreaterThanZero); + } + + [Fact] + public void Validate_WhenAsinIsNotTenCharacters_ShouldHaveValidationError() + { + // Arrange + UpdateBookCommand bookCommand = _commandBookFixture.Create(asin: new Faker().Random.String2(9)); + + // Act + List result = _validator.TestValidate(bookCommand); + + // Assert + result.ShouldHaveValidationError(Errors.WrittenContent.AsinMustBe10CharactersLong); + } + + [Fact] + public void Validate_WhenGoodreadsIdIsNonNumeric_ShouldHaveValidationError() + { + // Arrange + UpdateBookCommand bookCommand = _commandBookFixture.Create(goodreadsId: "abc123"); + + // Act + List result = _validator.TestValidate(bookCommand); + + // Assert + result.ShouldHaveValidationError(Errors.WrittenContent.GoodreadsIdMustBeNumeric); + } + + [Fact] + public void Validate_WhenLccnHasInvalidFormat_ShouldHaveValidationError() + { + // Arrange + UpdateBookCommand bookCommand = _commandBookFixture.Create(lccn: "invalid123"); + + // Act + List result = _validator.TestValidate(bookCommand); + + // Assert + result.ShouldHaveValidationError(Errors.WrittenContent.InvalidLccnFormat); + } + + [Fact] + public void Validate_WhenOclcNumberHasInvalidFormat_ShouldHaveValidationError() + { + // Arrange + UpdateBookCommand bookCommand = _commandBookFixture.Create(oclcNumber: "invalid_oclc_number"); + + // Act + List result = _validator.TestValidate(bookCommand); + + // Assert + result.ShouldHaveValidationError(Errors.WrittenContent.InvalidOclcFormat); + } + + [Fact] + public void Validate_WhenOpenLibraryIdHasInvalidFormat_ShouldHaveValidationError() + { + // Arrange + UpdateBookCommand bookCommand = _commandBookFixture.Create(openLibraryId: "InvalidID"); + + // Act + List result = _validator.TestValidate(bookCommand); + + // Assert + result.ShouldHaveValidationError(Errors.WrittenContent.InvalidOpenLibraryId); + } + + [Fact] + public void Validate_WhenGoogleBooksIdHasInvalidFormat_ShouldHaveValidationError() + { + // Arrange + UpdateBookCommand bookCommand = _commandBookFixture.Create(googleBooksId: "invalid!"); + + // Act + List result = _validator.TestValidate(bookCommand); + + // Assert + result.ShouldHaveValidationError(Errors.WrittenContent.GoogleBooksIdMustBe12CharactersLong); + } + + [Fact] + public void Validate_WhenBarnesAndNobleIdIsNotTenDigits_ShouldHaveValidationError() + { + // Arrange + UpdateBookCommand bookCommand = _commandBookFixture.Create(barnesAndNobleId: "abc123"); + + // Act + List result = _validator.TestValidate(bookCommand); + + // Assert + result.ShouldHaveValidationError(Errors.WrittenContent.BarnesAndNoblesIdMustBe10CharactersLong); + } + + [Fact] + public void Validate_WhenAppleBooksIdHasInvalidFormat_ShouldHaveValidationError() + { + // Arrange + UpdateBookCommand bookCommand = _commandBookFixture.Create(appleBooksId: "395211"); + + // Act + List result = _validator.TestValidate(bookCommand); + + // Assert + result.ShouldHaveValidationError(Errors.WrittenContent.InvalidAppleBooksIdFormat); + } + + [Fact] + public void Validate_WhenIsbnsIsNull_ShouldHaveValidationError() + { + // Arrange + UpdateBookCommand bookCommand = _commandBookFixture.Create(includeOptionalProperties: false); + + // Act + List result = _validator.TestValidate(bookCommand); + + // Assert + result.ShouldHaveValidationError(Errors.WrittenContent.IsbnListCannotBeNull); + } + + [Fact] + public void Validate_WhenIsbnValueIsEmpty_ShouldHaveValidationError() + { + // Arrange + UpdateBookCommand bookCommand = _commandBookFixture.Create(isbns: [_isbnDtoFixture.Create(value: string.Empty)]); + + // Act + List result = _validator.TestValidate(bookCommand); + + // Assert + result.ShouldHaveValidationError(Errors.WrittenContent.IsbnValueCannotBeEmpty); + } + + [Fact] + public void Validate_WhenIsbn13ValueIsInvalid_ShouldHaveValidationError() + { + // Arrange + UpdateBookCommand bookCommand = _commandBookFixture.Create(isbns: [_isbnDtoFixture.Create(value: "invalid", format: IsbnFormat.Isbn13)]); + + // Act + List result = _validator.TestValidate(bookCommand); + + // Assert + result.ShouldHaveValidationError(Errors.WrittenContent.InvalidIsbn13Format); + } + + [Fact] + public void Validate_WhenContributorsIsNull_ShouldHaveValidationError() + { + // Arrange + UpdateBookCommand bookCommand = _commandBookFixture.Create(includeOptionalProperties: false); + + // Act + List result = _validator.TestValidate(bookCommand); + + // Assert + result.ShouldHaveValidationError(Errors.MediaContributor.ContributorsListCannotBeNull); + } + + [Fact] + public void Validate_WhenContributorDisplayNameIsEmpty_ShouldHaveValidationError() + { + // Arrange + UpdateBookCommand bookCommand = _commandBookFixture.Create(contributors: [_mediaContributorDtoFixture.Create(displayName: string.Empty)]); + + // Act + List result = _validator.TestValidate(bookCommand); + + // Assert + result.ShouldHaveValidationError(Errors.MediaContributor.ContributorDisplayNameCannotBeEmpty); + } + + [Fact] + public void Validate_WhenRatingsIsNull_ShouldHaveValidationError() + { + // Arrange + UpdateBookCommand bookCommand = _commandBookFixture.Create(includeOptionalProperties: false); + + // Act + List result = _validator.TestValidate(bookCommand); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.RatingsListCannotBeNull); + } + + [Fact] + public void Validate_WhenRatingValueIsNegative_ShouldHaveValidationError() + { + // Arrange + UpdateBookCommand bookCommand = _commandBookFixture.Create(ratings: [_bookRatingDtoFixture.Create(value: -1)]); + + // Act + List result = _validator.TestValidate(bookCommand); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.RatingValueMustBePositive); + } +} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Commands/UpdateBookCover/UpdateBookCoverCommandHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Commands/UpdateBookCover/UpdateBookCoverCommandHandlerTests.cs new file mode 100644 index 00000000..6cab89fc --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Commands/UpdateBookCover/UpdateBookCoverCommandHandlerTests.cs @@ -0,0 +1,336 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Entities.MediaContributors; +using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management; +using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary; +using Lumina.Application.Common.DataAccess.Repositories.Books; +using Lumina.Application.Common.DataAccess.Repositories.MediaContributors; +using Lumina.Application.Common.DataAccess.Repositories.MediaLibrary; +using Lumina.Application.Common.DataAccess.UoW; +using Lumina.Application.Common.Infrastructure.Authentication; +using Lumina.Application.Common.Infrastructure.Authorization; +using Lumina.Application.Common.Infrastructure.Authorization.Policies.LibraryOwnership; +using Lumina.Application.Common.Infrastructure.Validation; +using Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Artwork; +using Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Commands.UpdateBookCover; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaContributors; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary; +using Lumina.Application.Fixtures.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Commands.UpdateBookCover; +using Lumina.Domain.Common.Errors; +using Lumina.Domain.Common.Primitives; +using Lumina.Domain.SharedKernel.Common.Enums.BookLibrary; +using Lumina.Domain.SharedKernel.Common.Enums.MediaContributors; +using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; +using NSubstitute; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Threading; +using System.Threading.Tasks; +using ApplicationErrors = Lumina.Application.Common.Errors.Errors; +#endregion + +namespace Lumina.Application.UnitTests.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Commands.UpdateBookCover; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class UpdateBookCoverCommandHandlerTests +{ + private readonly IUnitOfWork _mockUnitOfWork; + private readonly IBookRepository _mockBookRepository; + private readonly ILibraryRepository _mockLibraryRepository; + private readonly IMediaContributorRepository _mockMediaContributorRepository; + private readonly IBookArtworkService _mockBookArtworkService; + private readonly IAuthorizationService _mockAuthorizationService; + private readonly ICurrentUserService _mockCurrentUserService; + private readonly IValidator _mockValidator; + private readonly UpdateBookCoverCommandHandler _sut; + private readonly Guid _userId; + private readonly UpdateBookCoverCommandFixture _commandFixture = new(); + private readonly BookEntityFixture _bookEntityFixture = new(); + private readonly BookArtworkEntityFixture _bookArtworkEntityFixture = new(); + private readonly LibraryEntityFixture _libraryEntityFixture = new(); + private readonly MediaContributorEntityFixture _mediaContributorEntityFixture = new(); + private readonly BookContributorEntityFixture _bookContributorEntityFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + public UpdateBookCoverCommandHandlerTests() + { + _mockBookRepository = Substitute.For(); + _mockLibraryRepository = Substitute.For(); + _mockMediaContributorRepository = Substitute.For(); + _mockUnitOfWork = Substitute.For(); + _mockUnitOfWork.BookRepository.Returns(_mockBookRepository); + _mockUnitOfWork.LibraryRepository.Returns(_mockLibraryRepository); + _mockUnitOfWork.MediaContributorRepository.Returns(_mockMediaContributorRepository); + _mockBookArtworkService = Substitute.For(); + _mockAuthorizationService = Substitute.For(); + _mockCurrentUserService = Substitute.For(); + _mockValidator = Substitute.For>(); + _userId = Guid.NewGuid(); + + // Default stubs: the current user is authenticated, the library ownership policy allows access, + // the validator passes and the artwork storage succeeds. + _mockCurrentUserService.UserId.Returns(_userId); + _mockAuthorizationService.EvaluatePolicyAsync(_userId, Arg.Any(), Arg.Any()) + .Returns(true); + _mockValidator.Validate(Arg.Any()).Returns([]); + _mockBookArtworkService.SaveBookArtworkAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(Result.From("/media/books/cover.jpg")); + + _sut = new UpdateBookCoverCommandHandler(_mockUnitOfWork, _mockBookArtworkService, _mockAuthorizationService, _mockCurrentUserService, _mockValidator); + } + + [Fact] + public async Task HandleAsync_WhenBookHasNoExistingCover_ShouldStoreArtworkAndAddCoverArtwork() + { + // Arrange + UpdateBookCoverCommand command = _commandFixture.Create(); + BookEntity existingBook = _bookEntityFixture.Create(id: command.BookId); + existingBook.BookArtwork = []; + LibraryEntity library = _libraryEntityFixture.Create(id: existingBook.LibraryId); + _mockBookRepository.GetByIdAsync(command.BookId, Arg.Any()) + .Returns(Result.From(existingBook)); + _mockLibraryRepository.GetByIdAsync(existingBook.LibraryId, Arg.Any()) + .Returns(Result.From(library)); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal("/media/books/cover.jpg", result.Value); + Assert.Single(existingBook.BookArtwork); + Assert.Equal(ArtworkType.Cover, existingBook.BookArtwork[0].ArtworkType); + Assert.Equal(result.Value, existingBook.BookArtwork[0].FileName); + Assert.Equal(ArtworkStatus.Enriched, existingBook.BookArtwork[0].Status); + await _mockBookArtworkService.Received(1).SaveBookArtworkAsync( + existingBook.LibraryId, + existingBook.Id, + library.Title, + string.Empty, + existingBook.Title, + Arg.Any(), + Arg.Any(), + Arg.Any()); + await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenBookHasExistingCover_ShouldReplaceTheStoredCoverFile() + { + // Arrange + UpdateBookCoverCommand command = _commandFixture.Create(); + BookEntity existingBook = _bookEntityFixture.Create(id: command.BookId); + BookArtworkEntity existingCover = _bookArtworkEntityFixture.Create(bookId: command.BookId, artworkType: ArtworkType.Cover, fileName: "/media/books/old-cover.jpg"); + existingBook.BookArtwork = [existingCover]; + LibraryEntity library = _libraryEntityFixture.Create(id: existingBook.LibraryId); + _mockBookRepository.GetByIdAsync(command.BookId, Arg.Any()) + .Returns(Result.From(existingBook)); + _mockLibraryRepository.GetByIdAsync(existingBook.LibraryId, Arg.Any()) + .Returns(Result.From(library)); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal("/media/books/cover.jpg", result.Value); + Assert.Single(existingBook.BookArtwork); + Assert.Equal(result.Value, existingCover.FileName); + Assert.Equal(ArtworkStatus.Enriched, existingCover.Status); + Assert.Equal(_userId, existingCover.UpdatedBy); + await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenBookHasAuthorContributors_ShouldPassTheResolvedAuthorNameToArtworkService() + { + // Arrange + UpdateBookCoverCommand command = _commandFixture.Create(); + BookEntity existingBook = _bookEntityFixture.Create(id: command.BookId); + MediaContributorEntity author = _mediaContributorEntityFixture.Create(displayName: "J.R.R. Tolkien"); + MediaContributorEntity illustrator = _mediaContributorEntityFixture.Create(displayName: "Alan Lee"); + existingBook.BookContributors = + [ + _bookContributorEntityFixture.Create(bookId: command.BookId, mediaContributorId: author.Id, roleCategory: MediaContributorRoleCategory.Author), + _bookContributorEntityFixture.Create(bookId: command.BookId, mediaContributorId: illustrator.Id, roleCategory: MediaContributorRoleCategory.Illustrator) + ]; + LibraryEntity library = _libraryEntityFixture.Create(id: existingBook.LibraryId); + _mockBookRepository.GetByIdAsync(command.BookId, Arg.Any()) + .Returns(Result.From(existingBook)); + _mockLibraryRepository.GetByIdAsync(existingBook.LibraryId, Arg.Any()) + .Returns(Result.From(library)); + _mockMediaContributorRepository.GetByIdsAsync(Arg.Any>(), Arg.Any()) + .Returns(Result.From>([author, illustrator])); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + await _mockBookArtworkService.Received(1).SaveBookArtworkAsync( + existingBook.LibraryId, + existingBook.Id, + library.Title, + "J.R.R. Tolkien", + existingBook.Title, + Arg.Any(), + Arg.Any(), + Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenAuthorResolutionFails_ShouldStoreArtworkWithEmptyAuthorName() + { + // Arrange + UpdateBookCoverCommand command = _commandFixture.Create(); + BookEntity existingBook = _bookEntityFixture.Create(id: command.BookId); + existingBook.BookContributors = + [ + _bookContributorEntityFixture.Create(bookId: command.BookId, roleCategory: MediaContributorRoleCategory.Author) + ]; + LibraryEntity library = _libraryEntityFixture.Create(id: existingBook.LibraryId); + _mockBookRepository.GetByIdAsync(command.BookId, Arg.Any()) + .Returns(Result.From(existingBook)); + _mockLibraryRepository.GetByIdAsync(existingBook.LibraryId, Arg.Any()) + .Returns(Result.From(library)); + _mockMediaContributorRepository.GetByIdsAsync(Arg.Any>(), Arg.Any()) + .Returns(Errors.Library.LibraryIdCannotBeEmpty); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + await _mockBookArtworkService.Received(1).SaveBookArtworkAsync( + existingBook.LibraryId, + existingBook.Id, + library.Title, + string.Empty, + existingBook.Title, + Arg.Any(), + Arg.Any(), + Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenValidatorFails_ShouldReturnValidationErrorsWithoutStoringArtwork() + { + // Arrange + UpdateBookCoverCommand command = _commandFixture.Create(); + _mockValidator.Validate(Arg.Any()).Returns([Errors.WrittenContent.BookCoverCannotBeNull]); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.WrittenContent.BookCoverCannotBeNull, result.FirstError); + await _mockBookRepository.DidNotReceive().GetByIdAsync(Arg.Any(), Arg.Any()); + await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenUserIsNotAuthenticated_ShouldReturnNotAuthorizedError() + { + // Arrange + UpdateBookCoverCommand command = _commandFixture.Create(); + _mockCurrentUserService.UserId.Returns((Guid?)null); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(ApplicationErrors.Authorization.NotAuthorized, result.FirstError); + await _mockBookArtworkService.DidNotReceive().SaveBookArtworkAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenBookDoesNotExist_ShouldReturnBookNotFoundError() + { + // Arrange + UpdateBookCoverCommand command = _commandFixture.Create(); + _mockBookRepository.GetByIdAsync(command.BookId, Arg.Any()) + .Returns(Result.From(null)); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.WrittenContent.BookNotFound, result.FirstError); + await _mockLibraryRepository.DidNotReceive().GetByIdAsync(Arg.Any(), Arg.Any()); + await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenPolicyDeniesAccess_ShouldReturnNotAuthorizedErrorWithoutStoringArtwork() + { + // Arrange + UpdateBookCoverCommand command = _commandFixture.Create(); + BookEntity existingBook = _bookEntityFixture.Create(id: command.BookId); + _mockBookRepository.GetByIdAsync(command.BookId, Arg.Any()) + .Returns(Result.From(existingBook)); + _mockAuthorizationService.EvaluatePolicyAsync(_userId, Arg.Any(), Arg.Any()) + .Returns(false); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(ApplicationErrors.Authorization.NotAuthorized, result.FirstError); + await _mockBookArtworkService.DidNotReceive().SaveBookArtworkAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()); + await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenLibraryDoesNotExist_ShouldReturnLibraryNotFoundError() + { + // Arrange + UpdateBookCoverCommand command = _commandFixture.Create(); + BookEntity existingBook = _bookEntityFixture.Create(id: command.BookId); + _mockBookRepository.GetByIdAsync(command.BookId, Arg.Any()) + .Returns(Result.From(existingBook)); + _mockLibraryRepository.GetByIdAsync(existingBook.LibraryId, Arg.Any()) + .Returns(Result.From(null)); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.Library.LibraryNotFound, result.FirstError); + await _mockBookArtworkService.DidNotReceive().SaveBookArtworkAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()); + await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenArtworkStorageFails_ShouldReturnFailureResultWithoutSaving() + { + // Arrange + UpdateBookCoverCommand command = _commandFixture.Create(); + BookEntity existingBook = _bookEntityFixture.Create(id: command.BookId); + LibraryEntity library = _libraryEntityFixture.Create(id: existingBook.LibraryId); + _mockBookRepository.GetByIdAsync(command.BookId, Arg.Any()) + .Returns(Result.From(existingBook)); + _mockLibraryRepository.GetByIdAsync(existingBook.LibraryId, Arg.Any()) + .Returns(Result.From(library)); + _mockBookArtworkService.SaveBookArtworkAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(Errors.FileSystemManagement.FileTooLarge); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.FileSystemManagement.FileTooLarge, result.FirstError); + await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); + } +} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Commands/UpdateBookCover/UpdateBookCoverCommandValidatorTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Commands/UpdateBookCover/UpdateBookCoverCommandValidatorTests.cs new file mode 100644 index 00000000..1e400574 --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Commands/UpdateBookCover/UpdateBookCoverCommandValidatorTests.cs @@ -0,0 +1,61 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Commands.UpdateBookCover; +using Lumina.Application.Fixtures.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Commands.UpdateBookCover; +using Lumina.Application.UnitTests.Common.Setup; +using Lumina.Domain.Common.Errors; +using Lumina.Domain.Common.Primitives; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Application.UnitTests.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Commands.UpdateBookCover; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class UpdateBookCoverCommandValidatorTests +{ + private readonly UpdateBookCoverCommandFixture _commandFixture = new(); + private readonly UpdateBookCoverCommandValidator _validator = new(); + + [Fact] + public void Validate_WhenCommandIsValid_ShouldNotHaveValidationErrors() + { + // Arrange + UpdateBookCoverCommand command = _commandFixture.Create(); + + // Act + List result = _validator.TestValidate(command); + + // Assert + Assert.Empty(result); + } + + [Fact] + public void Validate_WhenBookIdIsEmpty_ShouldHaveValidationError() + { + // Arrange + UpdateBookCoverCommand command = _commandFixture.Create(bookId: Guid.Empty); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.WrittenContent.BookIdCannotBeEmpty); + } + + [Fact] + public void Validate_WhenCoverIsNull_ShouldHaveValidationError() + { + // Arrange + UpdateBookCoverCommand command = _commandFixture.Create(includeCover: false); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.WrittenContent.BookCoverCannotBeNull); + } +} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Queries/GetBook/GetBookQueryHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Queries/GetBook/GetBookQueryHandlerTests.cs new file mode 100644 index 00000000..7a956f9e --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Queries/GetBook/GetBookQueryHandlerTests.cs @@ -0,0 +1,209 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Entities.MediaContributors; +using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary; +using Lumina.Application.Common.DataAccess.Repositories.Books; +using Lumina.Application.Common.DataAccess.Repositories.MediaContributors; +using Lumina.Application.Common.DataAccess.UoW; +using Lumina.Application.Common.Infrastructure.Authentication; +using Lumina.Application.Common.Infrastructure.Authorization; +using Lumina.Application.Common.Infrastructure.Authorization.Policies.LibraryOwnership; +using Lumina.Application.Common.Infrastructure.Validation; +using Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Queries.GetBook; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaContributors; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary; +using Lumina.Application.Fixtures.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Queries.GetBook; +using Lumina.Contracts.Responses.MediaLibrary.WrittenContentLibrary.BookLibrary.Books; +using Lumina.Domain.Common.Errors; +using Lumina.Domain.Common.Primitives; +using Lumina.Domain.SharedKernel.Common.Enums.MediaContributors; +using NSubstitute; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; +using ApplicationErrors = Lumina.Application.Common.Errors.Errors; +#endregion + +namespace Lumina.Application.UnitTests.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Queries.GetBook; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class GetBookQueryHandlerTests +{ + private readonly IUnitOfWork _mockUnitOfWork; + private readonly IBookRepository _mockBookRepository; + private readonly IMediaContributorRepository _mockMediaContributorRepository; + private readonly IAuthorizationService _mockAuthorizationService; + private readonly ICurrentUserService _mockCurrentUserService; + private readonly IValidator _mockValidator; + private readonly GetBookQueryHandler _sut; + private readonly Guid _userId; + private readonly BookEntityFixture _bookEntityFixture = new(); + private readonly MediaContributorEntityFixture _mediaContributorEntityFixture = new(); + private readonly BookContributorEntityFixture _bookContributorEntityFixture = new(); + private readonly GetBookQueryFixture _getBookQueryFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + public GetBookQueryHandlerTests() + { + _mockBookRepository = Substitute.For(); + _mockMediaContributorRepository = Substitute.For(); + _mockUnitOfWork = Substitute.For(); + _mockUnitOfWork.BookRepository.Returns(_mockBookRepository); + _mockUnitOfWork.MediaContributorRepository.Returns(_mockMediaContributorRepository); + _mockAuthorizationService = Substitute.For(); + _mockCurrentUserService = Substitute.For(); + _mockValidator = Substitute.For>(); + _userId = Guid.NewGuid(); + + // Default stubs: the current user is authenticated and the library ownership policy allows access. + _mockCurrentUserService.UserId.Returns(_userId); + _mockAuthorizationService.EvaluatePolicyAsync(_userId, Arg.Any(), Arg.Any()) + .Returns(true); + _mockValidator.Validate(Arg.Any()).Returns([]); + + _sut = new GetBookQueryHandler(_mockUnitOfWork, _mockAuthorizationService, _mockCurrentUserService, _mockValidator); + } + + [Fact] + public async Task HandleAsync_WhenBookExistsWithoutContributors_ShouldReturnMappedBookResponse() + { + // Arrange + GetBookQuery query = _getBookQueryFixture.Create(); + BookEntity bookEntity = _bookEntityFixture.Create(id: query.Id); + _mockBookRepository.GetByIdAsync(query.Id, Arg.Any()) + .Returns(Result.From(bookEntity)); + + // Act + Result result = await _sut.HandleAsync(query, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal(query.Id, result.Value.Id); + Assert.Equal(bookEntity.Title, result.Value.Metadata!.Title); + Assert.Null(result.Value.Contributors); + await _mockMediaContributorRepository.DidNotReceive().GetByIdsAsync(Arg.Any>(), Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenBookHasContributors_ShouldReturnResponseWithResolvedContributorNames() + { + // Arrange + GetBookQuery query = _getBookQueryFixture.Create(); + BookEntity bookEntity = _bookEntityFixture.Create(id: query.Id); + MediaContributorEntity contributor = _mediaContributorEntityFixture.Create(); + bookEntity.BookContributors = + [ + _bookContributorEntityFixture.Create(bookId: query.Id, mediaContributorId: contributor.Id, roleName: "author", roleCategory: MediaContributorRoleCategory.Author) + ]; + _mockBookRepository.GetByIdAsync(query.Id, Arg.Any()) + .Returns(Result.From(bookEntity)); + _mockMediaContributorRepository.GetByIdsAsync(Arg.Any>(), Arg.Any()) + .Returns(Result.From>([contributor])); + + // Act + Result result = await _sut.HandleAsync(query, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + Assert.NotNull(result.Value.Contributors); + Assert.Single(result.Value.Contributors!); + Assert.Equal(contributor.DisplayName, result.Value.Contributors![0].Name!.DisplayName); + Assert.Equal("author", result.Value.Contributors![0].Role!.Name); + } + + [Fact] + public async Task HandleAsync_WhenBookNotFound_ShouldReturnBookNotFoundError() + { + // Arrange + GetBookQuery query = _getBookQueryFixture.Create(); + _mockBookRepository.GetByIdAsync(query.Id, Arg.Any()) + .Returns(Result.From(null)); + + // Act + Result result = await _sut.HandleAsync(query, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.WrittenContent.BookNotFound, result.FirstError); + await _mockAuthorizationService.DidNotReceive().EvaluatePolicyAsync(Arg.Any(), Arg.Any(), Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenRepositoryReturnsError_ShouldReturnFailureResult() + { + // Arrange + GetBookQuery query = _getBookQueryFixture.Create(); + _mockBookRepository.GetByIdAsync(query.Id, Arg.Any()) + .Returns(Errors.Library.LibraryIdCannotBeEmpty); + + // Act + Result result = await _sut.HandleAsync(query, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.Library.LibraryIdCannotBeEmpty, result.FirstError); + } + + [Fact] + public async Task HandleAsync_WhenPolicyDeniesAccess_ShouldReturnNotAuthorizedError() + { + // Arrange + GetBookQuery query = _getBookQueryFixture.Create(); + BookEntity bookEntity = _bookEntityFixture.Create(id: query.Id); + _mockBookRepository.GetByIdAsync(query.Id, Arg.Any()) + .Returns(Result.From(bookEntity)); + _mockAuthorizationService.EvaluatePolicyAsync(_userId, Arg.Any(), Arg.Any()) + .Returns(false); + + // Act + Result result = await _sut.HandleAsync(query, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(ApplicationErrors.Authorization.NotAuthorized, result.FirstError); + await _mockAuthorizationService.Received(1).EvaluatePolicyAsync( + _userId, Arg.Is(context => context.LibraryId == bookEntity.LibraryId), Arg.Any()); + await _mockMediaContributorRepository.DidNotReceive().GetByIdsAsync(Arg.Any>(), Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenUserIsNotAuthenticated_ShouldReturnNotAuthorizedError() + { + // Arrange + GetBookQuery query = _getBookQueryFixture.Create(); + _mockCurrentUserService.UserId.Returns((Guid?)null); + + // Act + Result result = await _sut.HandleAsync(query, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(ApplicationErrors.Authorization.NotAuthorized, result.FirstError); + await _mockBookRepository.DidNotReceive().GetByIdAsync(Arg.Any(), Arg.Any()); + await _mockAuthorizationService.DidNotReceive().EvaluatePolicyAsync(Arg.Any(), Arg.Any(), Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenValidationFails_ShouldReturnValidationErrorsWithoutQuerying() + { + // Arrange + GetBookQuery query = _getBookQueryFixture.Create(); + _mockValidator.Validate(Arg.Any()).Returns([Errors.WrittenContent.BookIdCannotBeEmpty]); + + // Act + Result result = await _sut.HandleAsync(query, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.WrittenContent.BookIdCannotBeEmpty, result.FirstError); + await _mockBookRepository.DidNotReceive().GetByIdAsync(Arg.Any(), Arg.Any()); + await _mockAuthorizationService.DidNotReceive().EvaluatePolicyAsync(Arg.Any(), Arg.Any(), Arg.Any()); + } +} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Queries/GetBook/GetBookQueryValidatorTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Queries/GetBook/GetBookQueryValidatorTests.cs new file mode 100644 index 00000000..222acdb4 --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Queries/GetBook/GetBookQueryValidatorTests.cs @@ -0,0 +1,48 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Queries.GetBook; +using Lumina.Application.Fixtures.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Queries.GetBook; +using Lumina.Application.UnitTests.Common.Setup; +using Lumina.Domain.Common.Errors; +using Lumina.Domain.Common.Primitives; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Application.UnitTests.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Queries.GetBook; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class GetBookQueryValidatorTests +{ + private readonly GetBookQueryFixture _queryBookFixture = new(); + private readonly GetBookQueryValidator _validator = new(); + + [Fact] + public void Validate_WhenIdIsValid_ShouldNotHaveValidationError() + { + // Arrange + GetBookQuery query = _queryBookFixture.Create(); + + // Act + List result = _validator.TestValidate(query); + + // Assert + result.ShouldNotHaveValidationError(Errors.WrittenContent.BookIdCannotBeEmpty); + } + + [Fact] + public void Validate_WhenIdIsEmpty_ShouldHaveValidationError() + { + // Arrange + GetBookQuery query = _queryBookFixture.Create(id: Guid.Empty); + + // Act + List result = _validator.TestValidate(query); + + // Assert + result.ShouldHaveValidationError(Errors.WrittenContent.BookIdCannotBeEmpty); + } +} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Queries/GetBooks/GetBooksQueryValidatorTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Queries/GetBooks/GetBooksQueryValidatorTests.cs index 8d498b17..05f8e41e 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Queries/GetBooks/GetBooksQueryValidatorTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Queries/GetBooks/GetBooksQueryValidatorTests.cs @@ -24,8 +24,7 @@ public class GetBooksQueryValidatorTests public void Validate_WhenLibraryIdIsEmpty_ShouldHaveValidationError() { // Arrange - GetBooksQuery query = _getBooksQueryFixture.Create(); - query = query with { Filter = query.Filter with { LibraryId = Guid.Empty } }; + GetBooksQuery query = _getBooksQueryFixture.Create(libraryId: Guid.Empty); // Act List result = _validator.TestValidate(query); diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Queries/GetBooksLite/GetBooksLiteQueryValidatorTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Queries/GetBooksLite/GetBooksLiteQueryValidatorTests.cs index 52d2bf0e..3d9e59d8 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Queries/GetBooksLite/GetBooksLiteQueryValidatorTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Queries/GetBooksLite/GetBooksLiteQueryValidatorTests.cs @@ -24,8 +24,7 @@ public class GetBooksLiteQueryValidatorTests public void Validate_WhenLibraryIdIsEmpty_ShouldHaveValidationError() { // Arrange - GetBooksLiteQuery query = _getBooksLiteQueryFixture.Create(); - query = query with { Filter = query.Filter with { LibraryId = Guid.Empty } }; + GetBooksLiteQuery query = _getBooksLiteQueryFixture.Create(libraryId: Guid.Empty); // Act List result = _validator.TestValidate(query); @@ -51,8 +50,7 @@ public class GetBooksLiteQueryValidatorTests public void Validate_WhenFilterAlphaKeyIsNotASingleLetterOrSpecialKey_ShouldHaveValidationError() { // Arrange - GetBooksLiteQuery query = _getBooksLiteQueryFixture.Create(); - query = query with { Filter = query.Filter with { FilterAlphaKey = "AB" } }; + GetBooksLiteQuery query = _getBooksLiteQueryFixture.Create(filterAlphaKey: "AB"); // Act List result = _validator.TestValidate(query); @@ -65,8 +63,7 @@ public class GetBooksLiteQueryValidatorTests public void Validate_WhenFilterAlphaKeyIsASingleLetter_ShouldNotHaveValidationError() { // Arrange - GetBooksLiteQuery query = _getBooksLiteQueryFixture.Create(); - query = query with { Filter = query.Filter with { FilterAlphaKey = "Q" } }; + GetBooksLiteQuery query = _getBooksLiteQueryFixture.Create(filterAlphaKey: "Q"); // Act List result = _validator.TestValidate(query); @@ -79,8 +76,7 @@ public class GetBooksLiteQueryValidatorTests public void Validate_WhenFilterAlphaKeyIsNumberOrSymbol_ShouldNotHaveValidationError() { // Arrange - GetBooksLiteQuery query = _getBooksLiteQueryFixture.Create(); - query = query with { Filter = query.Filter with { FilterAlphaKey = "#" } }; + GetBooksLiteQuery query = _getBooksLiteQueryFixture.Create(filterAlphaKey: "#"); // Act List result = _validator.TestValidate(query); diff --git a/tests/UnitTests/Lumina.Contracts.UnitTests/Requests/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/UpdateBookRequestTests.cs b/tests/UnitTests/Lumina.Contracts.UnitTests/Requests/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/UpdateBookRequestTests.cs new file mode 100644 index 00000000..be7ca823 --- /dev/null +++ b/tests/UnitTests/Lumina.Contracts.UnitTests/Requests/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/UpdateBookRequestTests.cs @@ -0,0 +1,121 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Contracts.DTO.MediaContributors; +using Lumina.Contracts.DTO.MediaLibrary.WrittenContentLibrary; +using Lumina.Contracts.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary; +using Lumina.Contracts.Fixtures.Core.Requests.MediaLibrary.WrittenContentLibrary.BookLibrary.Books; +using Lumina.Contracts.Requests.MediaLibrary.WrittenContentLibrary.BookLibrary.Books; +using Lumina.Domain.SharedKernel.Common.Enums.BookLibrary; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Text.Json; +using System.Text.Json.Serialization; +#endregion + +namespace Lumina.Contracts.UnitTests.Requests.MediaLibrary.WrittenContentLibrary.BookLibrary.Books; + +/// +/// Contains unit tests for the record. +/// +[ExcludeFromCodeCoverage] +public class UpdateBookRequestTests +{ + private readonly UpdateBookRequestFixture _updateBookRequestFixture = new(); + + private readonly JsonSerializerOptions _jsonOptions = new() + { + PropertyNameCaseInsensitive = true, + Converters = { new JsonStringEnumConverter(JsonNamingPolicy.CamelCase) } + }; + + [Fact] + public void Create_WhenCalled_ShouldReturnValidUpdateBookRequest() + { + // Act + UpdateBookRequest sut = _updateBookRequestFixture.Create(); + + // Assert + Assert.NotNull(sut); + Assert.False(string.IsNullOrWhiteSpace(sut.Id)); + Assert.NotNull(sut.Metadata); + Assert.NotNull(sut.ISBNs); + Assert.NotEmpty(sut.ISBNs); + Assert.NotNull(sut.Contributors); + Assert.NotEmpty(sut.Contributors); + Assert.NotNull(sut.Ratings); + Assert.NotEmpty(sut.Ratings); + } + + [Fact] + public void RoundTrip_WhenSerializingUpdateBookRequest_ShouldPreserveValues() + { + // Arrange + UpdateBookRequest expected = _updateBookRequestFixture.Create(); + + // Act + string json = JsonSerializer.Serialize(expected, _jsonOptions); + UpdateBookRequest? actual = JsonSerializer.Deserialize(json, _jsonOptions); + + // Assert + Assert.NotNull(actual); + Assert.Equivalent(expected, actual); + } + + [Fact] + public void Serialize_WhenSerializingUpdateBookRequest_ShouldSerializeFormatAsCamelCaseString() + { + // Arrange + UpdateBookRequest sut = _updateBookRequestFixture.Create(); + + // Act + string json = JsonSerializer.Serialize(sut, _jsonOptions); + + // Assert + Assert.Contains("\"Format\":\"", json, StringComparison.Ordinal); + Assert.DoesNotContain("\"Format\":\"0\"", json, StringComparison.Ordinal); + } + + [Fact] + public void Deconstruct_WhenCalled_ShouldReturnAllProperties() + { + // Arrange + UpdateBookRequest sut = _updateBookRequestFixture.Create(); + + // Act + (string? id, WrittenContentMetadataDto? metadata, BookFormat? format, string? edition, float? 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) = sut; + + // Assert + Assert.Equal(sut.Id, id); + Assert.Equal(sut.Metadata, metadata); + Assert.Equal(sut.Format, format); + Assert.Equal(sut.Edition, edition); + Assert.Equal(sut.VolumeNumber, volumeNumber); + Assert.Equal(sut.Series, series); + Assert.Equal(sut.ASIN, asin); + Assert.Equal(sut.GoodreadsId, goodreadsId); + Assert.Equal(sut.LCCN, lccn); + Assert.Equal(sut.OCLCNumber, oclcNumber); + Assert.Equal(sut.OpenLibraryId, openLibraryId); + Assert.Equal(sut.LibraryThingId, libraryThingId); + Assert.Equal(sut.GoogleBooksId, googleBooksId); + Assert.Equal(sut.BarnesAndNobleId, barnesAndNobleId); + Assert.Equal(sut.AppleBooksId, appleBooksId); + Assert.Equal(sut.ISBNs, isbns); + Assert.Equal(sut.Contributors, contributors); + Assert.Equal(sut.Ratings, ratings); + } + + [Fact] + public void Equality_WhenTwoInstancesHaveSameValues_ShouldBeEqual() + { + // Arrange + UpdateBookRequest first = _updateBookRequestFixture.Create(); + UpdateBookRequest second = first with { }; + + // Act + bool areEqual = first == second; + + // Assert + Assert.True(areEqual); + } +} diff --git a/tests/UnitTests/Lumina.Contracts.UnitTests/Responses/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/BookLiteResponseTests.cs b/tests/UnitTests/Lumina.Contracts.UnitTests/Responses/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/BookLiteResponseTests.cs index 2b8b51bc..4afd31eb 100644 --- a/tests/UnitTests/Lumina.Contracts.UnitTests/Responses/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/BookLiteResponseTests.cs +++ b/tests/UnitTests/Lumina.Contracts.UnitTests/Responses/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/BookLiteResponseTests.cs @@ -39,7 +39,7 @@ public class BookLiteResponseTests public void RoundTrip_WhenSerializingBookLiteResponseWithNullValues_ShouldPreserveNulls() { // Arrange - BookLiteResponse expected = _bookLiteResponseFixture.Create() with { ReleaseYear = null, CoverPath = null }; + BookLiteResponse expected = _bookLiteResponseFixture.Create(includeReleaseYear: false, includeCoverPath: false); // Act string json = JsonSerializer.Serialize(expected, _jsonOptions); 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 e80bfb33..7152cdab 100644 --- a/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Repositories/Books/BookRepositoryTests.cs +++ b/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Repositories/Books/BookRepositoryTests.cs @@ -347,6 +347,129 @@ public class BookRepositoryTests Assert.Equal(Errors.WrittenContent.BookNotFound, result.FirstError); } + [Fact] + public async Task UpdateAsync_WhenChangingIdentityAndEnrichmentColumns_ShouldPreserveTheStoredValues() + { + // Arrange + BookEntity storedBook = _bookEntityFixture.Create(); + _mockContext.Books.Add(storedBook); + await _mockContext.SaveChangesAsync(); + + Guid storedLibraryId = storedBook.LibraryId; + string storedPath = storedBook.Path; + MetadataStatus storedMetadataStatus = storedBook.MetadataStatus; + DateTime? storedLastMetadataUpdateUtc = storedBook.LastMetadataUpdateUtc; + string? storedMetadataProvider = storedBook.MetadataProvider; + DateTime storedCreatedOnUtc = storedBook.CreatedOnUtc; + Guid storedCreatedBy = storedBook.CreatedBy; + + BookEntity data = _bookEntityFixture.Create(id: storedBook.Id); + data.Title = "Updated Title"; + data.LibraryId = Guid.NewGuid(); + data.Path = "/books/updated.epub"; + data.MetadataStatus = MetadataStatus.Enriched; + data.LastMetadataUpdateUtc = DateTime.UtcNow; + data.MetadataProvider = "UpdatedProvider"; + data.CreatedOnUtc = DateTime.UtcNow.AddYears(-10); + data.CreatedBy = Guid.NewGuid(); + + // Act + Result result = await _sut.UpdateAsync(data, CancellationToken.None); + await _mockContext.SaveChangesAsync(); + + // Assert + Assert.False(result.IsFailure); + BookEntity? retrievedBook = await _mockContext.Books + .Include(book => book.Tags) + .Include(book => book.Genres) + .Include(book => book.ISBNs) + .Include(book => book.Ratings) + .Include(book => book.BookContributors) + .FirstOrDefaultAsync(book => book.Id == storedBook.Id); + Assert.NotNull(retrievedBook); + Assert.Equal("Updated Title", retrievedBook!.Title); + // The identity, enrichment and audit columns of the stored book are never overwritten by an edit. + Assert.Equal(storedLibraryId, retrievedBook.LibraryId); + Assert.Equal(storedPath, retrievedBook.Path); + Assert.Equal(storedMetadataStatus, retrievedBook.MetadataStatus); + Assert.Equal(storedLastMetadataUpdateUtc, retrievedBook.LastMetadataUpdateUtc); + Assert.Equal(storedMetadataProvider, retrievedBook.MetadataProvider); + Assert.Equal(storedCreatedOnUtc, retrievedBook.CreatedOnUtc); + Assert.Equal(storedCreatedBy, retrievedBook.CreatedBy); + } + + [Fact] + public async Task UpdateAsync_WhenDataContainsExistingTagAndGenreNames_ShouldReuseTheStoredTagAndGenreEntities() + { + // Arrange + TagEntity existingTag = _tagEntityFixture.Create(name: "ExistingTag"); + GenreEntity existingGenre = _genreEntityFixture.Create(name: "ExistingGenre"); + BookEntity storedBook = _bookEntityFixture.Create(); + storedBook.Tags = [existingTag]; + storedBook.Genres = [existingGenre]; + _mockContext.Books.Add(storedBook); + await _mockContext.SaveChangesAsync(); + + BookEntity data = _bookEntityFixture.Create(id: storedBook.Id); + data.Tags = [_tagEntityFixture.Create(name: "ExistingTag")]; + data.Genres = [_genreEntityFixture.Create(name: "ExistingGenre")]; + + // Act + Result result = await _sut.UpdateAsync(data, CancellationToken.None); + await _mockContext.SaveChangesAsync(); + + // Assert + Assert.False(result.IsFailure); + BookEntity? retrievedBook = await _mockContext.Books + .Include(book => book.Tags) + .Include(book => book.Genres) + .FirstOrDefaultAsync(book => book.Id == storedBook.Id); + Assert.NotNull(retrievedBook); + TagEntity retrievedTag = Assert.Single(retrievedBook!.Tags); + GenreEntity retrievedGenre = Assert.Single(retrievedBook.Genres); + Assert.Equal("ExistingTag", retrievedTag.Name); + Assert.Equal("ExistingGenre", retrievedGenre.Name); + // The stored rows of the shared tables are not duplicated by the update. + Assert.Single(_mockContext.Set().Where(tag => tag.Name == "ExistingTag")); + Assert.Single(_mockContext.Set().Where(genre => genre.Name == "ExistingGenre")); + } + + [Fact] + public async Task UpdateAsync_WhenReplacingOwnedCollections_ShouldReplaceIsbnsRatingsAndBookContributors() + { + // Arrange + BookEntity storedBook = _bookEntityFixture.Create(); + storedBook.ISBNs = [_isbnEntityFixture.Create(value: "9780395272237", format: IsbnFormat.Isbn13)]; + storedBook.Ratings = [_bookRatingEntityFixture.Create(value: 4.5M, maxValue: 5, source: BookRatingSource.Goodreads, voteCount: 100)]; + storedBook.BookContributors = [_bookContributorEntityFixture.Create(bookId: storedBook.Id, roleCategory: MediaContributorRoleCategory.Author)]; + _mockContext.Books.Add(storedBook); + await _mockContext.SaveChangesAsync(); + + BookEntity data = _bookEntityFixture.Create(id: storedBook.Id); + data.ISBNs = [_isbnEntityFixture.Create(value: "9780261102693", format: IsbnFormat.Isbn13)]; + data.Ratings = [_bookRatingEntityFixture.Create(value: 3.5M, maxValue: 5, source: BookRatingSource.Amazon, voteCount: 50)]; + data.BookContributors = [_bookContributorEntityFixture.Create(bookId: storedBook.Id, mediaContributorId: Guid.NewGuid(), roleCategory: MediaContributorRoleCategory.Illustrator)]; + + // Act + Result result = await _sut.UpdateAsync(data, CancellationToken.None); + await _mockContext.SaveChangesAsync(); + + // Assert + Assert.False(result.IsFailure); + BookEntity? retrievedBook = await _mockContext.Books + .Include(book => book.ISBNs) + .Include(book => book.Ratings) + .Include(book => book.BookContributors) + .FirstOrDefaultAsync(book => book.Id == storedBook.Id); + Assert.NotNull(retrievedBook); + IsbnEntity retrievedIsbn = Assert.Single(retrievedBook!.ISBNs); + BookRatingEntity retrievedRating = Assert.Single(retrievedBook.Ratings); + BookContributorEntity retrievedContributor = Assert.Single(retrievedBook.BookContributors); + Assert.Equal("9780261102693", retrievedIsbn.Value); + Assert.Equal(3.5M, retrievedRating.Value); + Assert.Equal(MediaContributorRoleCategory.Illustrator, retrievedContributor.RoleCategory); + } + [Fact] public async Task GetPaginatedAsync_WhenFilterIncludesLibraryId_ShouldReturnPaginatedBooks() { diff --git a/tests/UnitTests/Lumina.Domain.UnitTests/Common/Errors/ErrorsTests.cs b/tests/UnitTests/Lumina.Domain.UnitTests/Common/Errors/ErrorsTests.cs index 986db136..0d57f868 100644 --- a/tests/UnitTests/Lumina.Domain.UnitTests/Common/Errors/ErrorsTests.cs +++ b/tests/UnitTests/Lumina.Domain.UnitTests/Common/Errors/ErrorsTests.cs @@ -125,7 +125,7 @@ public class ErrorsTests { // Assert // The count assertion fails when an error is added or removed, reminding to update the assertions below. - Assert.Equal(27, typeof(DomainErrors.WrittenContent).GetProperties().Length); + Assert.Equal(29, typeof(DomainErrors.WrittenContent).GetProperties().Length); AssertError(DomainErrors.WrittenContent.BookAlreadyExists, ErrorType.Conflict); AssertError(DomainErrors.WrittenContent.IsbnValueCannotBeEmpty, ErrorType.Validation); AssertError(DomainErrors.WrittenContent.IsbnListCannotBeNull, ErrorType.Validation); @@ -152,6 +152,8 @@ public class ErrorsTests AssertError(DomainErrors.WrittenContent.VolumeNumberMustBeGreaterThanZero, ErrorType.Validation); AssertError(DomainErrors.WrittenContent.BookLibraryCannotBeNull, ErrorType.Validation); AssertError(DomainErrors.WrittenContent.BookPathCannotBeEmpty, ErrorType.Validation); + AssertError(DomainErrors.WrittenContent.BookIdCannotBeEmpty, ErrorType.Validation); + AssertError(DomainErrors.WrittenContent.BookCoverCannotBeNull, ErrorType.Validation); AssertError(DomainErrors.WrittenContent.BookNotFound, ErrorType.NotFound); } diff --git a/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Services/FileProviderServiceTests.cs b/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Services/FileProviderServiceTests.cs index ab1424a5..8088d6fe 100644 --- a/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Services/FileProviderServiceTests.cs +++ b/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Services/FileProviderServiceTests.cs @@ -700,7 +700,6 @@ public class FileProviderServiceTests _mockFileSystem.FileInfo.New(path.Path).Returns(fileInfo); _mockFileSystem.Path.Combine(parentPath, newName).Returns(newPath); _mockFileSystemPermissionsService.CanAccessPath(Arg.Any(), FileAccessMode.Write).Returns(true); - _mockFileSystemPermissionsService.CanAccessPath(path, FileAccessMode.Execute).Returns(true); // Act Result result = _sut.RenameFile(path, newName); @@ -737,33 +736,6 @@ public class FileProviderServiceTests _mockFileSystem.File.DidNotReceive().Move(Arg.Any(), Arg.Any()); } - [Fact] - public void RenameFile_WhenFileIsNotExecutable_ShouldReturnUnauthorizedAccessError() - { - // Arrange - FileSystemPathId path = _fileSystemPathIdFixture.Create( - s_isUnix ? "/OldName.txt" : @"C:\OldName.txt" - ); - string newName = "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); - _mockFileSystem.Path.Combine(parentPath, newName).Returns(newPath); - _mockFileSystemPermissionsService.CanAccessPath(Arg.Any(), FileAccessMode.Write).Returns(true); - _mockFileSystemPermissionsService.CanAccessPath(path, FileAccessMode.Execute).Returns(false); - - // Act - Result result = _sut.RenameFile(path, newName); - - // Assert - Assert.True(result.IsFailure); - Assert.Equal(Errors.Permission.UnauthorizedAccess, result.FirstError); - _mockFileSystem.File.DidNotReceive().Move(Arg.Any(), Arg.Any()); - } - [Fact] public void RenameFile_WhenParentDirectoryIsNull_ShouldReturnInvalidPathError() { diff --git a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Artwork/BookArtworkServiceTests.cs b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Artwork/BookArtworkServiceTests.cs index 28a526c2..2c2f28fd 100644 --- a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Artwork/BookArtworkServiceTests.cs +++ b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Artwork/BookArtworkServiceTests.cs @@ -224,4 +224,46 @@ public class BookArtworkServiceTests authorName, $"{bookTitle}-{bookId}"); } + + [Fact] + public async Task SaveBookArtworkAsync_WhenUploadedStreamIsNull_ShouldReturnFileNotFound() + { + // Act + Result result = await _sut.SaveBookArtworkAsync(Guid.NewGuid(), Guid.NewGuid(), "Library", "Author", "Title", null!, "cover.jpg", CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.FileSystemManagement.FileNotFound, result.FirstError); + } + + [Fact] + public async Task SaveBookArtworkAsync_WhenUploadedStreamIsEmpty_ShouldReturnFileNotFound() + { + // Arrange + await using MemoryStream emptyStream = new([]); + + // Act + Result result = await _sut.SaveBookArtworkAsync(Guid.NewGuid(), Guid.NewGuid(), "Library", "Author", "Title", emptyStream, "cover.jpg", CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.FileSystemManagement.FileNotFound, result.FirstError); + await _mockFileTypeService.DidNotReceive().GetImageTypeAsync(Arg.Any(), Arg.Any()); + } + + [Fact] + public async Task SaveBookArtworkAsync_WhenUploadedStreamExceedsTheMaximumSize_ShouldReturnFileTooLarge() + { + // Arrange + await using MemoryStream oversizedStream = new(new byte[(10 * 1024 * 1024) + 1]); + + // Act + Result result = await _sut.SaveBookArtworkAsync(Guid.NewGuid(), Guid.NewGuid(), "Library", "Author", "Title", oversizedStream, "cover.jpg", CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.FileSystemManagement.FileTooLarge, result.FirstError); + await _mockFileTypeService.DidNotReceive().GetImageTypeAsync(Arg.Any(), Arg.Any()); + } } + diff --git a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/GetBook/GetBookEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/GetBook/GetBookEndpointTests.cs index 7465f8f2..5e024bed 100644 --- a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/GetBook/GetBookEndpointTests.cs +++ b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/GetBook/GetBookEndpointTests.cs @@ -1,10 +1,16 @@ #region ========================================================================= USING ===================================================================================== using FastEndpoints; +using Lumina.Application.Common.CQRS; +using Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Queries.GetBook; using Lumina.Contracts.Fixtures.Core.Requests.MediaLibrary.WrittenContentLibrary.BookLibrary.Books; +using Lumina.Contracts.Fixtures.Core.Responses.MediaLibrary.WrittenContentLibrary.BookLibrary.Books; using Lumina.Contracts.Requests.MediaLibrary.WrittenContentLibrary.BookLibrary.Books; +using Lumina.Contracts.Responses.MediaLibrary.WrittenContentLibrary.BookLibrary.Books; +using Lumina.Domain.Common.Primitives; using Lumina.Presentation.Api.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.Books.GetBook; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Http.HttpResults; +using NSubstitute; using System; using System.Diagnostics.CodeAnalysis; using System.Threading; @@ -19,20 +25,131 @@ namespace Lumina.Presentation.Api.UnitTests.Core.Endpoints.Library.WrittenConten [ExcludeFromCodeCoverage] public class GetBookEndpointTests { - private readonly GetBookEndpoint _sut = Factory.Create(); + private readonly IQueryHandler> _mockHandler; + private readonly GetBookEndpoint _sut; private readonly GetBookRequestFixture _getBookRequestFixture = new(); + private readonly BookResponseFixture _bookResponseFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + public GetBookEndpointTests() + { + _mockHandler = Substitute.For>>(); + _sut = Factory.Create(_mockHandler); + } [Fact] - public async Task ExecuteAsync_WhenCalled_ShouldReturnOkResult() + public async Task ExecuteAsync_WhenSuccessful_ShouldReturnOkResultWithBookResponse() { // Arrange - GetBookRequest request = _getBookRequestFixture.Create(id: Guid.NewGuid().ToString()); + GetBookRequest request = _getBookRequestFixture.Create(); CancellationToken cancellationToken = CancellationToken.None; + BookResponse expectedResponse = _bookResponseFixture.Create(); + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From(expectedResponse)); // Act IResult result = await _sut.ExecuteAsync(request, cancellationToken); // Assert - Assert.IsType(result); + Ok okResult = Assert.IsType>(result); + Assert.Equal(expectedResponse, okResult.Value); + } + + [Fact] + public async Task ExecuteAsync_WhenHandlerReturnsNotFoundError_ShouldReturnProblemResult() + { + // Arrange + GetBookRequest request = _getBookRequestFixture.Create(); + CancellationToken cancellationToken = CancellationToken.None; + Error expectedError = Error.NotFound("Book.NotFound", "BookNotFound"); + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(expectedError); + + // Act + IResult result = await _sut.ExecuteAsync(request, cancellationToken); + + // Assert + ProblemHttpResult problemDetails = Assert.IsType(result); + Assert.Equal(StatusCodes.Status404NotFound, problemDetails.StatusCode); + Assert.Equal("application/problem+json", problemDetails.ContentType); + Microsoft.AspNetCore.Mvc.ProblemDetails problemDetailsBody = Assert.IsType(problemDetails.ProblemDetails); + Assert.Equal(StatusCodes.Status404NotFound, problemDetailsBody.Status); + Assert.Equal("Book.NotFound", problemDetailsBody.Title); + Assert.Equal("BookNotFound", problemDetailsBody.Detail); + Assert.NotNull(problemDetailsBody.Extensions["traceId"]); + } + + [Fact] + public async Task ExecuteAsync_WhenHandlerReturnsValidationErrors_ShouldReturnValidationProblemResult() + { + // Arrange + GetBookRequest request = _getBookRequestFixture.Create(); + CancellationToken cancellationToken = CancellationToken.None; + Error validationError = Error.Validation(description: "BookIdCannotBeEmpty"); + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(validationError); + + // Act + IResult result = await _sut.ExecuteAsync(request, cancellationToken); + + // Assert + ProblemHttpResult problemDetails = Assert.IsType(result); + Assert.Equal(StatusCodes.Status422UnprocessableEntity, problemDetails.StatusCode); + Assert.Equal("application/problem+json", problemDetails.ContentType); + HttpValidationProblemDetails validationProblemDetails = Assert.IsType(problemDetails.ProblemDetails); + Assert.Equal(StatusCodes.Status422UnprocessableEntity, validationProblemDetails.Status); + Assert.Equal("General.Validation", validationProblemDetails.Title); + Assert.Equal("https://tools.ietf.org/html/rfc4918#section-11.2", validationProblemDetails.Type); + Assert.Single(validationProblemDetails.Errors); + Assert.Equal(new[] { "BookIdCannotBeEmpty" }, validationProblemDetails.Errors["General.Validation"]); + } + + [Fact] + public async Task ExecuteAsync_WhenCalled_ShouldSendGetBookQueryToHandler() + { + // Arrange + Guid bookId = Guid.NewGuid(); + GetBookRequest request = _getBookRequestFixture.Create(id: bookId.ToString()); + CancellationToken cancellationToken = CancellationToken.None; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From(_bookResponseFixture.Create())); + + // Act + await _sut.ExecuteAsync(request, cancellationToken); + + // Assert + await _mockHandler.Received(1).HandleAsync( + Arg.Is(query => query.Id == bookId), + Arg.Is(cancellationToken)); + } + + [Fact] + public async Task ExecuteAsync_WhenCancellationRequested_ShouldCancelOperation() + { + // Arrange + GetBookRequest request = _getBookRequestFixture.Create(); + CancellationTokenSource cts = new(); + TaskCompletionSource operationStarted = new(); + TaskCompletionSource cancellationRequested = new(); + + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(callInfo => Task.Run(async () => + { + operationStarted.SetResult(true); + await cancellationRequested.Task; + callInfo.Arg().ThrowIfCancellationRequested(); + return Result.From(_bookResponseFixture.Create()); + }, callInfo.Arg())); + + // Act + Task operationTask = _sut.ExecuteAsync(request, cts.Token); + await operationStarted.Task; + cts.Cancel(); + cancellationRequested.SetResult(true); + + // Assert + await Assert.ThrowsAnyAsync(() => operationTask); } } diff --git a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/UpdateBook/UpdateBookEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/UpdateBook/UpdateBookEndpointTests.cs new file mode 100644 index 00000000..ce8b42b6 --- /dev/null +++ b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/UpdateBook/UpdateBookEndpointTests.cs @@ -0,0 +1,266 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Commands.UpdateBook; +using Lumina.Contracts.Fixtures.Core.Requests.MediaLibrary.WrittenContentLibrary.BookLibrary.Books; +using Lumina.Contracts.Fixtures.Core.Responses.MediaLibrary.WrittenContentLibrary.BookLibrary.Books; +using Lumina.Contracts.Requests.MediaLibrary.WrittenContentLibrary.BookLibrary.Books; +using Lumina.Contracts.Responses.MediaLibrary.WrittenContentLibrary.BookLibrary.Books; +using Lumina.Domain.Common.Primitives; +using Lumina.Presentation.Api.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.Books.UpdateBook; +using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Http.HttpResults; +using NSubstitute; +using System; +using System.Diagnostics.CodeAnalysis; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Api.UnitTests.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.Books.UpdateBook; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class UpdateBookEndpointTests +{ + private readonly Application.Common.CQRS.ICommandHandler> _mockHandler; + private readonly UpdateBookEndpoint _sut; + private readonly UpdateBookRequestFixture _updateBookRequestFixture = new(); + private readonly BookResponseFixture _bookResponseFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + public UpdateBookEndpointTests() + { + _mockHandler = Substitute.For>>(); + _sut = Factory.Create(_mockHandler); + } + + [Fact] + public async Task ExecuteAsync_WhenSuccessful_ShouldReturnOkResultWithBookResponse() + { + // Arrange + Guid routeId = Guid.NewGuid(); + UpdateBookRequest request = _updateBookRequestFixture.Create(id: routeId); + CancellationToken cancellationToken = CancellationToken.None; + BookResponse expectedResponse = _bookResponseFixture.Create(); + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From(expectedResponse)); + ConfigureRequest(routeId.ToString()); + + // Act + IResult result = await _sut.ExecuteAsync(request, cancellationToken); + + // Assert + Ok okResult = Assert.IsType>(result); + Assert.Equal(expectedResponse, okResult.Value); + } + + [Fact] + public async Task ExecuteAsync_WhenHandlerReturnsNotFoundError_ShouldReturnProblemResult() + { + // Arrange + Guid routeId = Guid.NewGuid(); + UpdateBookRequest request = _updateBookRequestFixture.Create(id: routeId); + CancellationToken cancellationToken = CancellationToken.None; + Error expectedError = Error.NotFound("Book.NotFound", "BookNotFound"); + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(expectedError); + ConfigureRequest(routeId.ToString()); + + // Act + IResult result = await _sut.ExecuteAsync(request, cancellationToken); + + // Assert + ProblemHttpResult problemDetails = Assert.IsType(result); + Assert.Equal(StatusCodes.Status404NotFound, problemDetails.StatusCode); + Assert.Equal("application/problem+json", problemDetails.ContentType); + Microsoft.AspNetCore.Mvc.ProblemDetails problemDetailsBody = Assert.IsType(problemDetails.ProblemDetails); + Assert.Equal(StatusCodes.Status404NotFound, problemDetailsBody.Status); + Assert.Equal("Book.NotFound", problemDetailsBody.Title); + Assert.Equal("BookNotFound", problemDetailsBody.Detail); + Assert.NotNull(problemDetailsBody.Extensions["traceId"]); + } + + [Fact] + public async Task ExecuteAsync_WhenHandlerReturnsValidationErrors_ShouldReturnValidationProblemResult() + { + // Arrange + Guid routeId = Guid.NewGuid(); + UpdateBookRequest request = _updateBookRequestFixture.Create(id: routeId); + CancellationToken cancellationToken = CancellationToken.None; + Error validationError = Error.Validation(description: "BookIdCannotBeEmpty"); + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(validationError); + ConfigureRequest(routeId.ToString()); + + // Act + IResult result = await _sut.ExecuteAsync(request, cancellationToken); + + // Assert + ProblemHttpResult problemDetails = Assert.IsType(result); + Assert.Equal(StatusCodes.Status422UnprocessableEntity, problemDetails.StatusCode); + Assert.Equal("application/problem+json", problemDetails.ContentType); + HttpValidationProblemDetails validationProblemDetails = Assert.IsType(problemDetails.ProblemDetails); + Assert.Equal(StatusCodes.Status422UnprocessableEntity, validationProblemDetails.Status); + Assert.Equal("General.Validation", validationProblemDetails.Title); + Assert.Equal("https://tools.ietf.org/html/rfc4918#section-11.2", validationProblemDetails.Type); + Assert.Single(validationProblemDetails.Errors); + Assert.Equal(new[] { "BookIdCannotBeEmpty" }, validationProblemDetails.Errors["General.Validation"]); + } + + [Fact] + public async Task ExecuteAsync_WhenCalledWithMatchingRouteId_ShouldSendUpdateBookCommandToHandler() + { + // Arrange + Guid routeId = Guid.NewGuid(); + UpdateBookRequest request = _updateBookRequestFixture.Create(id: routeId); + CancellationToken cancellationToken = CancellationToken.None; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From(_bookResponseFixture.Create())); + ConfigureRequest(routeId.ToString()); + + // Act + await _sut.ExecuteAsync(request, cancellationToken); + + // Assert + await _mockHandler.Received(1).HandleAsync( + Arg.Is(command => + command.Id == routeId && + command.Metadata == request.Metadata && + command.Format == request.Format && + command.Edition == request.Edition && + command.ASIN == request.ASIN && + command.ISBNs == request.ISBNs && + command.Contributors == request.Contributors && + command.Ratings == request.Ratings), + Arg.Is(cancellationToken)); + } + + [Fact] + public async Task ExecuteAsync_WhenRouteIdDiffersFromBodyId_ShouldSendCommandWithRouteId() + { + // Arrange + Guid routeId = Guid.NewGuid(); + Guid bodyId = Guid.NewGuid(); + UpdateBookRequest request = _updateBookRequestFixture.Create(id: bodyId); + CancellationToken cancellationToken = CancellationToken.None; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From(_bookResponseFixture.Create())); + ConfigureRequest(routeId.ToString()); + + // Act + await _sut.ExecuteAsync(request, cancellationToken); + + // Assert + await _mockHandler.Received(1).HandleAsync( + Arg.Is(command => command.Id == routeId && command.Id != bodyId), + Arg.Is(cancellationToken)); + } + + [Fact] + public async Task ExecuteAsync_WhenRouteIdIsNotParseable_ShouldSendCommandWithEmptyBookId() + { + // Arrange + UpdateBookRequest request = _updateBookRequestFixture.Create(); + CancellationToken cancellationToken = CancellationToken.None; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From(_bookResponseFixture.Create())); + ConfigureRequest("not-a-guid"); + + // Act + await _sut.ExecuteAsync(request, cancellationToken); + + // Assert + await _mockHandler.Received(1).HandleAsync( + Arg.Is(command => command.Id == Guid.Empty), + Arg.Is(cancellationToken)); + } + + [Fact] + public async Task ExecuteAsync_WhenRouteIdIsEmpty_ShouldSendCommandWithEmptyBookId() + { + // Arrange + UpdateBookRequest request = _updateBookRequestFixture.Create(); + CancellationToken cancellationToken = CancellationToken.None; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From(_bookResponseFixture.Create())); + ConfigureRequest(string.Empty); + + // Act + await _sut.ExecuteAsync(request, cancellationToken); + + // Assert + await _mockHandler.Received(1).HandleAsync( + Arg.Is(command => command.Id == Guid.Empty), + Arg.Is(cancellationToken)); + } + + [Fact] + public async Task ExecuteAsync_WhenRouteIdIsMissing_ShouldSendCommandWithEmptyBookId() + { + // Arrange + UpdateBookRequest request = _updateBookRequestFixture.Create(); + CancellationToken cancellationToken = CancellationToken.None; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From(_bookResponseFixture.Create())); + ConfigureRequestWithoutId(); + + // Act + await _sut.ExecuteAsync(request, cancellationToken); + + // Assert + await _mockHandler.Received(1).HandleAsync( + Arg.Is(command => command.Id == Guid.Empty), + Arg.Is(cancellationToken)); + } + + [Fact] + public async Task ExecuteAsync_WhenCancellationRequested_ShouldCancelOperation() + { + // Arrange + Guid routeId = Guid.NewGuid(); + UpdateBookRequest request = _updateBookRequestFixture.Create(id: routeId); + CancellationTokenSource cts = new(); + TaskCompletionSource operationStarted = new(); + TaskCompletionSource cancellationRequested = new(); + + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(callInfo => Task.Run(async () => + { + operationStarted.SetResult(true); + await cancellationRequested.Task; + callInfo.Arg().ThrowIfCancellationRequested(); + return Result.From(_bookResponseFixture.Create()); + }, callInfo.Arg())); + ConfigureRequest(routeId.ToString()); + + // Act + Task operationTask = _sut.ExecuteAsync(request, cts.Token); + await operationStarted.Task; + cts.Cancel(); + cancellationRequested.SetResult(true); + + // Assert + await Assert.ThrowsAnyAsync(() => operationTask); + } + + /// + /// Sets the id route value the endpoint reads the book Id from. + /// + /// The raw route value of the book Id. + private void ConfigureRequest(string routeId) + { + _sut.HttpContext.Request.RouteValues["id"] = routeId; + } + + /// + /// Leaves the id route value unset. + /// + private void ConfigureRequestWithoutId() + { + _sut.HttpContext.Request.RouteValues.Remove("id"); + } +} diff --git a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/UpdateBookCover/UpdateBookCoverEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/UpdateBookCover/UpdateBookCoverEndpointTests.cs new file mode 100644 index 00000000..ccc440d2 --- /dev/null +++ b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/UpdateBookCover/UpdateBookCoverEndpointTests.cs @@ -0,0 +1,164 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Commands.UpdateBookCover; +using Lumina.Domain.Common.Primitives; +using Lumina.Presentation.Api.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.Books.UpdateBookCover; +using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Http.Features; +using Microsoft.AspNetCore.Http.HttpResults; +using NSubstitute; +using System; +using System.Diagnostics.CodeAnalysis; +using System.IO; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Api.UnitTests.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.Books.UpdateBookCover; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class UpdateBookCoverEndpointTests +{ + private readonly Application.Common.CQRS.ICommandHandler> _mockHandler; + private readonly UpdateBookCoverEndpoint _sut; + + /// + /// Initializes a new instance of the class. + /// + public UpdateBookCoverEndpointTests() + { + _mockHandler = Substitute.For>>(); + _sut = Factory.Create(_mockHandler); + } + + [Fact] + public async Task ExecuteAsync_WhenSuccessful_ShouldReturnOkResultWithCoverPath() + { + // Arrange + Guid bookId = Guid.NewGuid(); + CancellationToken cancellationToken = CancellationToken.None; + string expectedPath = "/media/books/cover.jpg"; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From(expectedPath)); + ConfigureRequest(bookId, [1, 2, 3], "cover.jpg"); + + // Act + IResult result = await _sut.ExecuteAsync(EmptyRequest.Instance, cancellationToken); + + // Assert + Ok okResult = Assert.IsType>(result); + Assert.Equal(expectedPath, okResult.Value); + } + + [Fact] + public async Task ExecuteAsync_WhenCalledWithValidRouteIdAndFile_ShouldSendUpdateBookCoverCommand() + { + // Arrange + Guid bookId = Guid.NewGuid(); + CancellationToken cancellationToken = CancellationToken.None; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From("/media/books/cover.jpg")); + ConfigureRequest(bookId, [1, 2, 3], "cover.jpg"); + + // Act + await _sut.ExecuteAsync(EmptyRequest.Instance, cancellationToken); + + // Assert + await _mockHandler.Received(1).HandleAsync( + Arg.Is(command => + command.BookId == bookId && + command.Cover != null && + command.FileName == "cover.jpg"), + Arg.Is(cancellationToken)); + } + + [Fact] + public async Task ExecuteAsync_WhenRouteIdIsNotParseable_ShouldSendCommandWithEmptyBookId() + { + // Arrange + CancellationToken cancellationToken = CancellationToken.None; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From("/media/books/cover.jpg")); + ConfigureRequest("not-a-guid", [1, 2, 3], "cover.jpg"); + + // Act + await _sut.ExecuteAsync(EmptyRequest.Instance, cancellationToken); + + // Assert + await _mockHandler.Received(1).HandleAsync( + Arg.Is(command => command.BookId == Guid.Empty && command.Cover != null), + Arg.Any()); + } + + [Fact] + public async Task ExecuteAsync_WhenFormHasNoFiles_ShouldSendCommandWithNullCover() + { + // Arrange + Guid bookId = Guid.NewGuid(); + CancellationToken cancellationToken = CancellationToken.None; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From("/media/books/cover.jpg")); + ConfigureRequestWithoutFiles(bookId); + + // Act + IResult result = await _sut.ExecuteAsync(EmptyRequest.Instance, cancellationToken); + + // Assert + Assert.IsType>(result); + await _mockHandler.Received(1).HandleAsync( + Arg.Is(command => command.BookId == bookId && command.Cover == null && command.FileName == null), + Arg.Any()); + } + + [Fact] + public async Task ExecuteAsync_WhenHandlerReturnsError_ShouldReturnProblemResult() + { + // Arrange + Guid bookId = Guid.NewGuid(); + CancellationToken cancellationToken = CancellationToken.None; + Error expectedError = Error.NotFound("Book.NotFound", "BookNotFound"); + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(expectedError); + ConfigureRequest(bookId, [1, 2, 3], "cover.jpg"); + + // Act + IResult result = await _sut.ExecuteAsync(EmptyRequest.Instance, cancellationToken); + + // Assert + ProblemHttpResult problemDetails = Assert.IsType(result); + Assert.Equal(StatusCodes.Status404NotFound, problemDetails.StatusCode); + Assert.Equal("application/problem+json", problemDetails.ContentType); + Microsoft.AspNetCore.Mvc.ProblemDetails problemDetailsBody = Assert.IsType(problemDetails.ProblemDetails); + Assert.Equal(StatusCodes.Status404NotFound, problemDetailsBody.Status); + Assert.Equal("Book.NotFound", problemDetailsBody.Title); + Assert.Equal("BookNotFound", problemDetailsBody.Detail); + Assert.NotNull(problemDetailsBody.Extensions["traceId"]); + } + + private void ConfigureRequest(Guid bookId, byte[] content, string fileName) + { + ConfigureRequest(bookId.ToString(), content, fileName); + } + + private void ConfigureRequest(string bookId, byte[] content, string fileName) + { + _sut.HttpContext.Request.RouteValues["id"] = bookId; + MemoryStream coverStream = new(content); + IFormFile formFile = new FormFile(coverStream, 0, content.Length, "cover", fileName); + FormFileCollection files = [formFile]; + IFormCollection form = new FormCollection([], files); + _sut.HttpContext.Request.ContentType = "multipart/form-data; boundary=----test"; + _sut.HttpContext.Features.Set(new FormFeature(form)); + } + + private void ConfigureRequestWithoutFiles(Guid bookId) + { + _sut.HttpContext.Request.RouteValues["id"] = bookId.ToString(); + IFormCollection form = new FormCollection([]); + _sut.HttpContext.Request.ContentType = "multipart/form-data; boundary=----test"; + _sut.HttpContext.Features.Set(new FormFeature(form)); + } +} diff --git a/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/GetBookDetails/GetBookDetailsEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/GetBookDetails/GetBookDetailsEndpointTests.cs new file mode 100644 index 00000000..f2f5755b --- /dev/null +++ b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/GetBookDetails/GetBookDetailsEndpointTests.cs @@ -0,0 +1,78 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Presentation.Web.Common.Api; +using Lumina.Presentation.Web.Common.DTO.WrittenContentLibrary.BookLibrary; +using Lumina.Presentation.Web.Common.Requests.Library.WrittenContentLibrary.BookLibrary.Books; +using Lumina.Presentation.Web.Common.Routes; +using Lumina.Presentation.Web.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.Books.GetBookDetails; +using Lumina.Presentation.Web.Fixtures.Common.DTO.WrittenContentLibrary.BookLibrary; +using Lumina.Presentation.Web.Fixtures.Common.Requests.Library.WrittenContentLibrary.BookLibrary.Books; +using Lumina.Presentation.Web.Fixtures.Common.TestHelpers; +using Microsoft.AspNetCore.Http; +using NSubstitute; +using System; +using System.Diagnostics.CodeAnalysis; +using System.Text.Json; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.UnitTests.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.Books.GetBookDetails; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class GetBookDetailsEndpointTests +{ + private readonly IApiHttpClient _mockApiHttpClient; + private readonly GetBookDetailsEndpoint _sut; + private readonly GetBookRequestFixture _getBookRequestFixture = new(); + private readonly BookDetailsDtoFixture _bookDetailsDtoFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + public GetBookDetailsEndpointTests() + { + _mockApiHttpClient = Substitute.For(); + _sut = Factory.Create(_mockApiHttpClient); + } + + [Fact] + public async Task ExecuteAsync_WhenCalled_ShouldRequestBookDetailsFromApi() + { + // Arrange + GetBookRequest request = _getBookRequestFixture.Create(); + BookDetailsDto expectedBook = _bookDetailsDtoFixture.Create(id: Guid.Parse(request.Id)); + _mockApiHttpClient.GetAsync(Arg.Any(), Arg.Any()) + .Returns(expectedBook); + + // Act + await _sut.ExecuteAsync(request, CancellationToken.None); + + // Assert + await _mockApiHttpClient.Received(1).GetAsync( + Arg.Is(endpoint => endpoint == ApiRoutes.Books.GET_BOOK.Replace("{id}", request.Id)), + Arg.Any()); + } + + [Fact] + public async Task ExecuteAsync_WhenApiReturnsBookDetails_ShouldReturnSuccessJsonWithBook() + { + // Arrange + GetBookRequest request = _getBookRequestFixture.Create(); + BookDetailsDto expectedBook = _bookDetailsDtoFixture.Create(id: Guid.Parse(request.Id)); + _mockApiHttpClient.GetAsync(Arg.Any(), Arg.Any()) + .Returns(expectedBook); + + // Act + IResult result = await _sut.ExecuteAsync(request, CancellationToken.None); + string body = await JsonResultTestHelper.GetResponseBodyAsync(result); + + // Assert + using JsonDocument jsonDocument = JsonDocument.Parse(body); + Assert.True(jsonDocument.RootElement.GetProperty("success").GetBoolean()); + Assert.Equal(expectedBook.Id, jsonDocument.RootElement.GetProperty("data").GetProperty("id").GetGuid()); + } +} diff --git a/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/SaveBook/SaveBookEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/SaveBook/SaveBookEndpointTests.cs new file mode 100644 index 00000000..e52f6031 --- /dev/null +++ b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/SaveBook/SaveBookEndpointTests.cs @@ -0,0 +1,166 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Presentation.Web.Common.Api; +using Lumina.Presentation.Web.Common.DTO.WrittenContentLibrary.BookLibrary; +using Lumina.Presentation.Web.Common.Requests.Library.WrittenContentLibrary.BookLibrary.Books; +using Lumina.Presentation.Web.Common.Routes; +using Lumina.Presentation.Web.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.Books.SaveBook; +using Lumina.Presentation.Web.Fixtures.Common.DTO.WrittenContentLibrary.BookLibrary; +using Lumina.Presentation.Web.Fixtures.Common.Requests.Library.WrittenContentLibrary.BookLibrary.Books; +using Lumina.Presentation.Web.Fixtures.Common.TestHelpers; +using Microsoft.AspNetCore.Http; +using NSubstitute; +using System; +using System.Diagnostics.CodeAnalysis; +using System.Text.Json; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.UnitTests.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.Books.SaveBook; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class SaveBookEndpointTests +{ + private readonly IApiHttpClient _mockApiHttpClient; + private readonly SaveBookEndpoint _sut; + private readonly UpdateBookRequestFixture _updateBookRequestFixture = new(); + private readonly BookDetailsDtoFixture _bookDetailsDtoFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + public SaveBookEndpointTests() + { + _mockApiHttpClient = Substitute.For(); + _sut = Factory.Create(_mockApiHttpClient); + } + + [Fact] + public async Task ExecuteAsync_WhenCalledWithMatchingRouteId_ShouldForwardUpdateBookRequestToApi() + { + // Arrange + string routeId = Guid.NewGuid().ToString(); + UpdateBookRequest request = _updateBookRequestFixture.Create(); + BookDetailsDto expectedBook = _bookDetailsDtoFixture.Create(); + _mockApiHttpClient.PutAsync(Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(expectedBook); + ConfigureRequest(routeId); + + // Act + await _sut.ExecuteAsync(request, CancellationToken.None); + + // Assert + await _mockApiHttpClient.Received(1).PutAsync( + Arg.Is(endpoint => endpoint == ApiRoutes.Books.UPDATE_BOOK.Replace("{id}", routeId)), + Arg.Is(forwardedRequest => forwardedRequest == request && forwardedRequest.Id == routeId), + Arg.Any()); + } + + [Fact] + public async Task ExecuteAsync_WhenRouteIdDiffersFromBodyId_ShouldForwardTheRouteIdToApi() + { + // Arrange + string routeId = Guid.NewGuid().ToString(); + string bodyId = Guid.NewGuid().ToString(); + UpdateBookRequest request = _updateBookRequestFixture.Create(); + request.Id = bodyId; + BookDetailsDto expectedBook = _bookDetailsDtoFixture.Create(); + _mockApiHttpClient.PutAsync(Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(expectedBook); + ConfigureRequest(routeId); + + // Act + await _sut.ExecuteAsync(request, CancellationToken.None); + + // Assert + await _mockApiHttpClient.Received(1).PutAsync( + Arg.Is(endpoint => endpoint == ApiRoutes.Books.UPDATE_BOOK.Replace("{id}", routeId)), + Arg.Is(forwardedRequest => forwardedRequest == request && forwardedRequest.Id == routeId && forwardedRequest.Id != bodyId), + Arg.Any()); + } + + [Fact] + public async Task ExecuteAsync_WhenRouteIdIsNotParseable_ShouldForwardGuidEmptyToApi() + { + // Arrange + const string ROUTE_ID = "not-a-guid"; + string expectedId = Guid.Empty.ToString(); + UpdateBookRequest request = _updateBookRequestFixture.Create(); + BookDetailsDto expectedBook = _bookDetailsDtoFixture.Create(); + _mockApiHttpClient.PutAsync(Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(expectedBook); + ConfigureRequest(ROUTE_ID); + + // Act + await _sut.ExecuteAsync(request, CancellationToken.None); + + // Assert + await _mockApiHttpClient.Received(1).PutAsync( + Arg.Is(endpoint => endpoint == ApiRoutes.Books.UPDATE_BOOK.Replace("{id}", expectedId)), + Arg.Is(forwardedRequest => forwardedRequest == request && forwardedRequest.Id == expectedId), + Arg.Any()); + } + + [Fact] + public async Task ExecuteAsync_WhenRouteIdIsMissing_ShouldForwardGuidEmptyToApi() + { + // Arrange + string expectedId = Guid.Empty.ToString(); + UpdateBookRequest request = _updateBookRequestFixture.Create(); + BookDetailsDto expectedBook = _bookDetailsDtoFixture.Create(); + _mockApiHttpClient.PutAsync(Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(expectedBook); + ConfigureRequestWithoutId(); + + // Act + await _sut.ExecuteAsync(request, CancellationToken.None); + + // Assert + await _mockApiHttpClient.Received(1).PutAsync( + Arg.Is(endpoint => endpoint == ApiRoutes.Books.UPDATE_BOOK.Replace("{id}", expectedId)), + Arg.Is(forwardedRequest => forwardedRequest == request && forwardedRequest.Id == expectedId), + Arg.Any()); + } + + [Fact] + public async Task ExecuteAsync_WhenApiReturnsUpdatedBook_ShouldReturnSuccessJsonWithBook() + { + // Arrange + string routeId = Guid.NewGuid().ToString(); + UpdateBookRequest request = _updateBookRequestFixture.Create(); + BookDetailsDto expectedBook = _bookDetailsDtoFixture.Create(); + _mockApiHttpClient.PutAsync(Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(expectedBook); + ConfigureRequest(routeId); + + // Act + IResult result = await _sut.ExecuteAsync(request, CancellationToken.None); + string body = await JsonResultTestHelper.GetResponseBodyAsync(result); + + // Assert + using JsonDocument jsonDocument = JsonDocument.Parse(body); + Assert.True(jsonDocument.RootElement.GetProperty("success").GetBoolean()); + Assert.Equal(expectedBook.Id, jsonDocument.RootElement.GetProperty("data").GetProperty("id").GetGuid()); + } + + /// + /// Sets the id route value the endpoint reads the book Id from. + /// + /// The raw route value of the book Id. + private void ConfigureRequest(string routeId) + { + _sut.HttpContext.Request.RouteValues["id"] = routeId; + } + + /// + /// Leaves the id route value unset. + /// + private void ConfigureRequestWithoutId() + { + _sut.HttpContext.Request.RouteValues.Remove("id"); + } +} diff --git a/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/UpdateBookCover/UpdateBookCoverEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/UpdateBookCover/UpdateBookCoverEndpointTests.cs new file mode 100644 index 00000000..3c1cce1c --- /dev/null +++ b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/UpdateBookCover/UpdateBookCoverEndpointTests.cs @@ -0,0 +1,140 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Presentation.Web.Common.Api; +using Lumina.Presentation.Web.Common.Routes; +using Lumina.Presentation.Web.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.Books.UpdateBookCover; +using Lumina.Presentation.Web.Fixtures.Common.TestHelpers; +using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Http.Features; +using Microsoft.AspNetCore.Http.HttpResults; +using NSubstitute; +using System; +using System.Diagnostics.CodeAnalysis; +using System.IO; +using System.Text.Json; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.UnitTests.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.Books.UpdateBookCover; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class UpdateBookCoverEndpointTests +{ + private readonly IApiHttpClient _mockApiHttpClient; + private readonly UpdateBookCoverEndpoint _sut; + + /// + /// Initializes a new instance of the class. + /// + public UpdateBookCoverEndpointTests() + { + _mockApiHttpClient = Substitute.For(); + _sut = Factory.Create(_mockApiHttpClient); + } + + [Fact] + public async Task ExecuteAsync_WhenCalledWithFile_ShouldUploadCoverToApi() + { + // Arrange + Guid bookId = Guid.NewGuid(); + _mockApiHttpClient.PutMultipartAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()) + .Returns("/media/books/cover.jpg"); + ConfigureRequest(bookId, [1, 2, 3], "cover.jpg"); + + // Act + await _sut.ExecuteAsync(EmptyRequest.Instance, CancellationToken.None); + + // Assert + await _mockApiHttpClient.Received(1).PutMultipartAsync( + Arg.Is(endpoint => endpoint == ApiRoutes.Books.UPDATE_BOOK_COVER.Replace("{id}", bookId.ToString())), + Arg.Any(), + Arg.Is(fileName => fileName == "cover.jpg"), + Arg.Is(fieldName => fieldName == "cover"), + Arg.Any()); + } + + [Fact] + public async Task ExecuteAsync_WhenRouteIdIsNotParseable_ShouldUploadCoverWithEmptyBookId() + { + // Arrange + _mockApiHttpClient.PutMultipartAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()) + .Returns("/media/books/cover.jpg"); + ConfigureRequest("not-a-guid", [1, 2, 3], "cover.jpg"); + + // Act + await _sut.ExecuteAsync(EmptyRequest.Instance, CancellationToken.None); + + // Assert + await _mockApiHttpClient.Received(1).PutMultipartAsync( + Arg.Is(endpoint => endpoint == ApiRoutes.Books.UPDATE_BOOK_COVER.Replace("{id}", Guid.Empty.ToString())), + Arg.Any(), + Arg.Any(), + Arg.Any(), + Arg.Any()); + } + + [Fact] + public async Task ExecuteAsync_WhenApiReturnsCoverPath_ShouldReturnSuccessJsonWithPath() + { + // Arrange + Guid bookId = Guid.NewGuid(); + string expectedPath = "/media/books/cover.jpg"; + _mockApiHttpClient.PutMultipartAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(expectedPath); + ConfigureRequest(bookId, [1, 2, 3], "cover.jpg"); + + // Act + IResult result = await _sut.ExecuteAsync(EmptyRequest.Instance, CancellationToken.None); + string body = await JsonResultTestHelper.GetResponseBodyAsync(result); + + // Assert + using JsonDocument jsonDocument = JsonDocument.Parse(body); + Assert.True(jsonDocument.RootElement.GetProperty("success").GetBoolean()); + Assert.Equal(expectedPath, jsonDocument.RootElement.GetProperty("data").GetString()); + } + + [Fact] + public async Task ExecuteAsync_WhenFormHasNoFile_ShouldReturnBadRequestProblem() + { + // Arrange + Guid bookId = Guid.NewGuid(); + ConfigureRequestWithoutFiles(bookId); + + // Act + IResult result = await _sut.ExecuteAsync(EmptyRequest.Instance, CancellationToken.None); + + // Assert + ProblemHttpResult problemDetails = Assert.IsType(result); + Assert.Equal(StatusCodes.Status400BadRequest, problemDetails.StatusCode); + Assert.Equal("The uploaded cover image is missing.", problemDetails.ProblemDetails.Detail); + await _mockApiHttpClient.DidNotReceive().PutMultipartAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()); + } + + private void ConfigureRequest(Guid bookId, byte[] content, string fileName) + { + ConfigureRequest(bookId.ToString(), content, fileName); + } + + private void ConfigureRequest(string bookId, byte[] content, string fileName) + { + _sut.HttpContext.Request.RouteValues["id"] = bookId; + MemoryStream coverStream = new(content); + IFormFile formFile = new FormFile(coverStream, 0, content.Length, "cover", fileName); + FormFileCollection files = [formFile]; + IFormCollection form = new FormCollection([], files); + _sut.HttpContext.Request.ContentType = "multipart/form-data; boundary=----test"; + _sut.HttpContext.Features.Set(new FormFeature(form)); + } + + private void ConfigureRequestWithoutFiles(Guid bookId) + { + _sut.HttpContext.Request.RouteValues["id"] = bookId.ToString(); + IFormCollection form = new FormCollection([]); + _sut.HttpContext.Request.ContentType = "multipart/form-data; boundary=----test"; + _sut.HttpContext.Features.Set(new FormFeature(form)); + } +}