Refactors the book, artist, and album slices across the stack

This commit is contained in:
BinaryAlley committed 2026-09-17 13:30:48 -07:00
1 parent 8aaf9fe64e
commit ea6eb9f796
439 files changed
+28235 -3156

No files matched your search

@@ -49,8 +49,9 @@ public class BookMappingTests
Assert.Equal(book.Metadata.OriginalLanguage.HasValue ? book.Metadata.OriginalLanguage.Value.LanguageCode : null, result.OriginalLanguageCode);
Assert.Equal(book.Metadata.OriginalLanguage.HasValue ? book.Metadata.OriginalLanguage.Value.LanguageName : null, result.OriginalLanguageName);
Assert.Equal(book.Metadata.OriginalLanguage.HasValue ? book.Metadata.OriginalLanguage.Value.NativeName.Value : null, result.OriginalLanguageNativeName);
Assert.Equal(book.Metadata.Tags.ToRepositoryEntities().OrderBy(tag => tag.Name), result.Tags.OrderBy(tag => tag.Name));
Assert.Equal(book.Metadata.Genres.ToRepositoryEntities().OrderBy(genre => genre.Name), result.Genres.OrderBy(genre => genre.Name));
// The repository entity stores tags and genres as sets, so duplicate names in the domain collection collapse into a single entry.
Assert.Equal(book.Metadata.Tags.ToRepositoryEntities().Distinct().OrderBy(tag => tag.Name), result.Tags.OrderBy(tag => tag.Name));
Assert.Equal(book.Metadata.Genres.ToRepositoryEntities().Distinct().OrderBy(genre => genre.Name), result.Genres.OrderBy(genre => genre.Name));
Assert.Equal(book.Metadata.Publisher.HasValue ? book.Metadata.Publisher.Value : null, result.Publisher);
Assert.Equal(book.Metadata.PageCount.HasValue ? book.Metadata.PageCount.Value : null, result.PageCount);
Assert.Equal(book.Format.HasValue ? book.Format.Value : null, result.Format);
@@ -1,32 +0,0 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.Mapping.MediaLibrary.WrittenContentLibrary.BookLibrary.Books;
using Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Reading.Queries.GetReadingAvailability;
using Lumina.Contracts.Fixtures.Core.Requests.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Reading;
using Lumina.Contracts.Requests.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Reading;
using System;
using System.Diagnostics.CodeAnalysis;
#endregion
namespace Lumina.Application.UnitTests.Common.Mapping.MediaLibrary.WrittenContentLibrary.BookLibrary.Books;
/// <summary>
/// Contains unit tests for the <see cref="GetReadingAvailabilityRequestMapping"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetReadingAvailabilityRequestMappingTests
{
private readonly GetReadingAvailabilityRequestFixture _getReadingAvailabilityRequestFixture = new();
[Fact]
public void ToQuery_WhenMappingValidRequest_ShouldMapCorrectly()
{
// Arrange
GetReadingAvailabilityRequest request = _getReadingAvailabilityRequestFixture.Create();
// Act
GetReadingAvailabilityQuery result = request.ToQuery();
// Assert
Assert.Equal(request.BookId, result.BookId);
}
}
@@ -1,32 +0,0 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.Mapping.MediaLibrary.WrittenContentLibrary.BookLibrary.Books;
using Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Reading.Queries.GetReadingManifest;
using Lumina.Contracts.Fixtures.Core.Requests.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Reading;
using Lumina.Contracts.Requests.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Reading;
using System.Diagnostics.CodeAnalysis;
#endregion
namespace Lumina.Application.UnitTests.Common.Mapping.MediaLibrary.WrittenContentLibrary.BookLibrary.Books;
/// <summary>
/// Contains unit tests for the <see cref="GetReadingManifestRequestMapping"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetReadingManifestRequestMappingTests
{
private readonly GetReadingManifestRequestFixture _requestFixture = new();
[Fact]
public void ToQuery_WhenMappingValidRequest_ShouldMapCorrectly()
{
// Arrange
GetReadingManifestRequest request = _requestFixture.Create();
// Act
GetReadingManifestQuery result = request.ToQuery();
// Assert
Assert.NotNull(result);
Assert.Equal(request.BookId, result.BookId);
}
}
@@ -1,33 +0,0 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.Mapping.MediaLibrary.WrittenContentLibrary.BookLibrary.Books;
using Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Reading.Queries.GetReadingResource;
using Lumina.Contracts.Fixtures.Core.Requests.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Reading;
using Lumina.Contracts.Requests.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Reading;
using System.Diagnostics.CodeAnalysis;
#endregion
namespace Lumina.Application.UnitTests.Common.Mapping.MediaLibrary.WrittenContentLibrary.BookLibrary.Books;
/// <summary>
/// Contains unit tests for the <see cref="GetReadingResourceRequestMapping"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetReadingResourceRequestMappingTests
{
private readonly GetReadingResourceRequestFixture _requestFixture = new();
[Fact]
public void ToQuery_WhenMappingValidRequest_ShouldMapCorrectly()
{
// Arrange
GetReadingResourceRequest request = _requestFixture.Create();
// Act
GetReadingResourceQuery result = request.ToQuery();
// Assert
Assert.NotNull(result);
Assert.Equal(request.BookId, result.BookId);
Assert.Equal(request.ResourceKey, result.ResourceKey);
}
}
@@ -1,33 +0,0 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.Mapping.MediaLibrary.WrittenContentLibrary.BookLibrary.Books;
using Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Reading.Queries.GetReadingSection;
using Lumina.Contracts.Fixtures.Core.Requests.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Reading;
using Lumina.Contracts.Requests.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Reading;
using System.Diagnostics.CodeAnalysis;
#endregion
namespace Lumina.Application.UnitTests.Common.Mapping.MediaLibrary.WrittenContentLibrary.BookLibrary.Books;
/// <summary>
/// Contains unit tests for the <see cref="GetReadingSectionRequestMapping"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetReadingSectionRequestMappingTests
{
private readonly GetReadingSectionRequestFixture _requestFixture = new();
[Fact]
public void ToQuery_WhenMappingValidRequest_ShouldMapCorrectly()
{
// Arrange
GetReadingSectionRequest request = _requestFixture.Create();
// Act
GetReadingSectionQuery result = request.ToQuery();
// Assert
Assert.NotNull(result);
Assert.Equal(request.BookId, result.BookId);
Assert.Equal(request.LocationRef, result.LocationRef);
}
}
@@ -0,0 +1,68 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary;
using Lumina.Application.Common.Mapping.MediaLibrary.WrittenContentLibrary.BookLibrary.Books;
using Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Commands.UpdateBookCover;
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary;
using Lumina.Application.Fixtures.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Commands.UpdateBookCover;
using Lumina.Domain.SharedKernel.Common.Enums.BookLibrary;
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
using System;
using System.Diagnostics.CodeAnalysis;
#endregion
namespace Lumina.Application.UnitTests.Common.Mapping.MediaLibrary.WrittenContentLibrary.BookLibrary.Books;
/// <summary>
/// Contains unit tests for the <see cref="UpdateBookCoverCommandMapping"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class UpdateBookCoverCommandMappingTests
{
private readonly UpdateBookCoverCommandFixture _commandFixture = new();
private readonly BookArtworkEntityFixture _bookArtworkEntityFixture = new();
[Fact]
public void ToRepositoryEntity_WhenBookHasNoCover_ShouldReturnANewEnrichedCoverArtwork()
{
// Arrange
Guid userId = Guid.NewGuid();
Guid bookId = Guid.NewGuid();
UpdateBookCoverCommand command = _commandFixture.Create(bookId: bookId.ToString());
string storedCoverPath = "/media/books/cover.jpg";
// Act
BookArtworkEntity cover = command.ToRepositoryEntity(null, bookId, storedCoverPath, userId);
// Assert
Assert.Equal(bookId, cover.BookId);
Assert.Equal(ArtworkType.Cover, cover.ArtworkType);
Assert.Equal(0, cover.Ordinal);
Assert.Equal(storedCoverPath, cover.FileName);
Assert.Equal(ArtworkStatus.Enriched, cover.Status);
Assert.Equal(userId, cover.CreatedBy);
Assert.NotEqual(default, cover.CreatedOnUtc);
Assert.Null(cover.UpdatedBy);
}
[Fact]
public void ToRepositoryEntity_WhenBookHasAnExistingCover_ShouldReplaceAndReturnTheStoredCover()
{
// Arrange
Guid userId = Guid.NewGuid();
Guid bookId = Guid.NewGuid();
UpdateBookCoverCommand command = _commandFixture.Create(bookId: bookId.ToString());
BookArtworkEntity existingCover = _bookArtworkEntityFixture.Create(bookId: bookId, artworkType: ArtworkType.Cover, fileName: "/media/books/old-cover.jpg", status: ArtworkStatus.Pending);
string storedCoverPath = "/media/books/cover.jpg";
// Act
BookArtworkEntity cover = command.ToRepositoryEntity(existingCover, bookId, storedCoverPath, userId);
// Assert
Assert.Same(existingCover, cover);
Assert.Equal(storedCoverPath, cover.FileName);
Assert.Equal(ArtworkStatus.Enriched, cover.Status);
Assert.Equal(userId, cover.UpdatedBy);
Assert.NotNull(cover.UpdatedOnUtc);
Assert.NotNull(cover.LastUpdateUtc);
}
}
@@ -0,0 +1,119 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.Mapping.MediaLibrary.WrittenContentLibrary.Common;
using Lumina.Contracts.DTO.MediaLibrary.WrittenContentLibrary;
using Lumina.Contracts.Fixtures.Core.DTO.Common;
using Lumina.Contracts.Fixtures.Core.DTO.MediaLibrary.WrittenContentLibrary;
using Lumina.Domain.Common.Primitives;
using Lumina.Domain.Core.BoundedContexts.WrittenContentLibraryBoundedContext.BookLibraryAggregate.ValueObjects;
using System;
using System.Diagnostics.CodeAnalysis;
#endregion
namespace Lumina.Application.UnitTests.Common.Mapping.MediaLibrary.WrittenContentLibrary.Common;
/// <summary>
/// Contains unit tests for the <see cref="WrittenContentMetadataDtoMapping"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class WrittenContentMetadataDtoMappingTests
{
private readonly WrittenContentMetadataDtoFixture _writtenContentMetadataDtoFixture = new();
private readonly ReleaseInfoDtoFixture _releaseInfoDtoFixture = new();
private readonly GenreDtoFixture _genreDtoFixture = new();
private readonly TagDtoFixture _tagDtoFixture = new();
[Fact]
public void ToDomainEntity_WhenMappingCompleteWrittenContentMetadataDto_ShouldMapAllPropertiesCorrectly()
{
// Arrange
WrittenContentMetadataDto dto = _writtenContentMetadataDtoFixture.Create();
// Act
Result<WrittenContentMetadata> result = dto.ToDomainEntity();
// Assert
Assert.False(result.IsFailure);
Assert.Equal(dto.Title, result.Value.Title);
Assert.True(result.Value.OriginalTitle.HasValue);
Assert.Equal(dto.OriginalTitle, result.Value.OriginalTitle.Value);
Assert.True(result.Value.Description.HasValue);
Assert.Equal(dto.Description, result.Value.Description.Value);
Assert.Equal(dto.Genres!.Count, result.Value.Genres.Count);
Assert.Equal(dto.Tags!.Count, result.Value.Tags.Count);
Assert.True(result.Value.Language.HasValue);
Assert.Equal(dto.Language!.LanguageCode!.ToLowerInvariant(), result.Value.Language.Value.LanguageCode);
Assert.True(result.Value.OriginalLanguage.HasValue);
Assert.Equal(dto.OriginalLanguage!.LanguageCode!.ToLowerInvariant(), result.Value.OriginalLanguage.Value.LanguageCode);
Assert.True(result.Value.Publisher.HasValue);
Assert.Equal(dto.Publisher, result.Value.Publisher.Value);
Assert.True(result.Value.PageCount.HasValue);
Assert.Equal(dto.PageCount!.Value, result.Value.PageCount.Value);
}
[Fact]
public void ToDomainEntity_WhenOptionalValuesAreMissing_ShouldMapWithoutOptionalValues()
{
// Arrange
WrittenContentMetadataDto dto = _writtenContentMetadataDtoFixture.Create(
includeOriginalTitle: false,
includeDescription: false,
includeLanguage: false,
includeOriginalLanguage: false,
includePublisher: false,
includePageCount: false);
// Act
Result<WrittenContentMetadata> result = dto.ToDomainEntity();
// Assert
Assert.False(result.IsFailure);
Assert.False(result.Value.OriginalTitle.HasValue);
Assert.False(result.Value.Description.HasValue);
Assert.False(result.Value.Language.HasValue);
Assert.False(result.Value.OriginalLanguage.HasValue);
Assert.False(result.Value.Publisher.HasValue);
Assert.False(result.Value.PageCount.HasValue);
}
[Fact]
public void ToDomainEntity_WhenReleaseInfoCreationFails_ShouldReturnError()
{
// Arrange
WrittenContentMetadataDto dto = _writtenContentMetadataDtoFixture.Create(
releaseInfo: _releaseInfoDtoFixture.Create(
originalReleaseDate: new DateOnly(2025, 1, 1),
originalReleaseYear: 2024));
// Act
Result<WrittenContentMetadata> result = dto.ToDomainEntity();
// Assert
Assert.True(result.IsFailure);
}
[Fact]
public void ToDomainEntity_WhenGenreCreationFails_ShouldReturnError()
{
// Arrange
WrittenContentMetadataDto dto = _writtenContentMetadataDtoFixture.Create(genres: [_genreDtoFixture.Create(name: "")]);
// Act
Result<WrittenContentMetadata> result = dto.ToDomainEntity();
// Assert
Assert.True(result.IsFailure);
}
[Fact]
public void ToDomainEntity_WhenTagCreationFails_ShouldReturnError()
{
// Arrange
WrittenContentMetadataDto dto = _writtenContentMetadataDtoFixture.Create(tags: [_tagDtoFixture.Create(name: "")]);
// Act
Result<WrittenContentMetadata> result = dto.ToDomainEntity();
// Assert
Assert.True(result.IsFailure);
}
}
@@ -1,10 +1,10 @@
#region ========================================================================= USING =====================================================================================
#region ========================================================================= USING =====================================================================================
using AutoFixture;
using AutoFixture.AutoNSubstitute;
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.BookLibrary;
using Lumina.Application.Common.DataAccess.Repositories.MediaContributors;
using Lumina.Application.Common.DataAccess.Repositories.MediaLibrary;
using Lumina.Application.Common.DataAccess.UoW;
@@ -321,9 +321,9 @@ public class AddBookCommandHandlerTests
// Assert
Assert.False(result.IsFailure);
Assert.NotNull(insertedEntity);
Assert.Equal(2, insertedEntity!.BookContributors.Count);
Assert.Contains(insertedEntity.BookContributors, contributor => contributor.MediaContributorId == firstContributorId && contributor.Role == MediaContributorRole.Author);
Assert.Contains(insertedEntity.BookContributors, contributor => contributor.MediaContributorId == secondContributorId && contributor.Role == MediaContributorRole.Illustrator);
Assert.Equal(2, insertedEntity!.Contributors.Count);
Assert.Contains(insertedEntity.Contributors, contributor => contributor.MediaContributorId == firstContributorId && contributor.Role == MediaContributorRole.Author);
Assert.Contains(insertedEntity.Contributors, contributor => contributor.MediaContributorId == secondContributorId && contributor.Role == MediaContributorRole.Illustrator);
await _mockBookRepository.Received(1).InsertAsync(Arg.Any<BookEntity>(), Arg.Any<CancellationToken>());
await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any<CancellationToken>());
}
@@ -355,10 +355,10 @@ public class AddBookCommandHandlerTests
// Assert
Assert.False(result.IsFailure);
Assert.NotNull(insertedEntity);
Assert.Equal(2, insertedEntity!.BookContributors.Count);
Assert.All(insertedEntity.BookContributors, linkedContributor => Assert.Equal(contributorId, linkedContributor.MediaContributorId));
Assert.Contains(insertedEntity.BookContributors, linkedContributor => linkedContributor.Role == MediaContributorRole.Author);
Assert.Contains(insertedEntity.BookContributors, linkedContributor => linkedContributor.Role == MediaContributorRole.Illustrator);
Assert.Equal(2, insertedEntity!.Contributors.Count);
Assert.All(insertedEntity.Contributors, linkedContributor => Assert.Equal(contributorId, linkedContributor.MediaContributorId));
Assert.Contains(insertedEntity.Contributors, linkedContributor => linkedContributor.Role == MediaContributorRole.Author);
Assert.Contains(insertedEntity.Contributors, linkedContributor => linkedContributor.Role == MediaContributorRole.Illustrator);
await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any<CancellationToken>());
}
@@ -1545,7 +1545,7 @@ public class AddBookCommandValidatorTests
List<Error> result = _validator.TestValidate(bookCommand);
// Assert
result.ShouldHaveValidationError(Errors.WrittenContent.ContributorsListCannotBeNull);
result.ShouldHaveValidationError(Errors.MediaContributor.ContributorsListCannotBeNull);
}
[Fact]
@@ -1558,7 +1558,7 @@ public class AddBookCommandValidatorTests
List<Error> result = _validator.TestValidate(bookCommand);
// Assert
result.ShouldNotHaveValidationError(Errors.WrittenContent.ContributorsListCannotBeNull);
result.ShouldNotHaveValidationError(Errors.MediaContributor.ContributorsListCannotBeNull);
}
[Fact]
@@ -1,8 +1,10 @@
#region ========================================================================= USING =====================================================================================
#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.BookLibrary;
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;
@@ -10,6 +12,7 @@ using Lumina.Application.Common.Infrastructure.Authorization.Policies.LibraryOwn
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.Management;
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.Common;
@@ -42,6 +45,7 @@ public class UpdateBookCommandHandlerTests
{
private readonly IUnitOfWork _mockUnitOfWork;
private readonly IBookRepository _mockBookRepository;
private readonly ILibraryRepository _mockLibraryRepository;
private readonly IMediaContributorRepository _mockMediaContributorRepository;
private readonly IAuthorizationService _mockAuthorizationService;
private readonly ICurrentUserService _mockCurrentUserService;
@@ -57,6 +61,7 @@ public class UpdateBookCommandHandlerTests
private readonly ReleaseInfoDtoFixture _releaseInfoDtoFixture = new();
private readonly WrittenContentMetadataDtoFixture _writtenContentMetadataDtoFixture = new();
private readonly MediaContributorReferenceDtoFixture _mediaContributorReferenceDtoFixture = new();
private readonly LibraryEntityFixture _libraryEntityFixture = new();
/// <summary>
/// Initializes a new instance of the <see cref="UpdateBookCommandHandlerTests"/> class.
@@ -64,10 +69,12 @@ public class UpdateBookCommandHandlerTests
public UpdateBookCommandHandlerTests()
{
_mockBookRepository = Substitute.For<IBookRepository>();
_mockLibraryRepository = Substitute.For<ILibraryRepository>();
_mockMediaContributorRepository = Substitute.For<IMediaContributorRepository>();
_mockUnitOfWork = Substitute.For<IUnitOfWork>();
_mockUnitOfWork.SaveChangesAsync(Arg.Any<CancellationToken>()).Returns(Result.Success);
_mockUnitOfWork.BookRepository.Returns(_mockBookRepository);
_mockUnitOfWork.LibraryRepository.Returns(_mockLibraryRepository);
_mockUnitOfWork.MediaContributorRepository.Returns(_mockMediaContributorRepository);
_mockAuthorizationService = Substitute.For<IAuthorizationService>();
_mockCurrentUserService = Substitute.For<ICurrentUserService>();
@@ -82,6 +89,9 @@ public class UpdateBookCommandHandlerTests
_mockValidator.Validate(Arg.Any<UpdateBookCommand>()).Returns([]);
_mockBookRepository.UpdateAsync(Arg.Any<BookEntity>(), Arg.Any<CancellationToken>())
.Returns(Result.Updated);
// Default stub: the library of the book exists.
_mockLibraryRepository.GetByIdAsync(Arg.Any<Guid>(), Arg.Any<bool>(), Arg.Any<bool>(), Arg.Any<CancellationToken>())
.Returns(_ => Result.From<LibraryEntity?>(_libraryEntityFixture.Create()));
// Default stub: every referenced media contributor already exists.
_mockMediaContributorRepository.GetByIdsAsync(Arg.Any<IReadOnlyCollection<Guid>>(), Arg.Any<CancellationToken>())
.Returns(callInfo =>
@@ -268,10 +278,10 @@ public class UpdateBookCommandHandlerTests
// Assert
Assert.False(result.IsFailure);
Assert.NotNull(updatedEntity);
Assert.Equal(2, updatedEntity!.BookContributors.Count);
Assert.All(updatedEntity.BookContributors, linkedContributor => Assert.Equal(contributorId, linkedContributor.MediaContributorId));
Assert.Contains(updatedEntity.BookContributors, linkedContributor => linkedContributor.Role == MediaContributorRole.Author);
Assert.Contains(updatedEntity.BookContributors, linkedContributor => linkedContributor.Role == MediaContributorRole.Illustrator);
Assert.Equal(2, updatedEntity!.Contributors.Count);
Assert.All(updatedEntity.Contributors, linkedContributor => Assert.Equal(contributorId, linkedContributor.MediaContributorId));
Assert.Contains(updatedEntity.Contributors, linkedContributor => linkedContributor.Role == MediaContributorRole.Author);
Assert.Contains(updatedEntity.Contributors, linkedContributor => linkedContributor.Role == MediaContributorRole.Illustrator);
await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any<CancellationToken>());
}
@@ -304,54 +314,12 @@ public class UpdateBookCommandHandlerTests
// Assert
Assert.False(result.IsFailure);
Assert.NotNull(updatedEntity);
Assert.Equal(2, updatedEntity!.BookContributors.Count);
Assert.Equal(firstContributorId, updatedEntity.BookContributors[0].MediaContributorId);
Assert.Equal(secondContributorId, updatedEntity.BookContributors[1].MediaContributorId);
Assert.Equal(2, updatedEntity!.Contributors.Count);
Assert.Equal(firstContributorId, updatedEntity.Contributors[0].MediaContributorId);
Assert.Equal(secondContributorId, updatedEntity.Contributors[1].MediaContributorId);
await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenStoredBookHasEnrichmentAndCover_ShouldPreserveThemInTheResponse()
{
// Arrange
UpdateBookCommand command = _commandBookFixture.Create();
BookEntity existingBook = _bookEntityFixture.Create(id: Guid.Parse(command.BookId!), libraryId: Guid.Parse(command.LibraryId!));
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
});
BookEntity? updatedBook = null;
_mockBookRepository.GetByIdAsync(Arg.Any<Guid>(), Arg.Any<bool>(), Arg.Any<bool>(), Arg.Any<CancellationToken>())
.Returns(callInfo => Result.From<BookEntity?>(callInfo.ArgAt<bool>(2) ? existingBook : updatedBook));
_mockBookRepository.UpdateAsync(Arg.Any<BookEntity>(), Arg.Any<CancellationToken>())
.Returns(callInfo =>
{
updatedBook = callInfo.Arg<BookEntity>();
return Result.Updated;
});
// Act
Result<BookResponse> 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);
}
[Fact]
public async Task HandleAsync_WhenCalledWithInvalidIsbn_ShouldReturnFailureResult()
{
@@ -492,4 +460,25 @@ public class UpdateBookCommandHandlerTests
await _mockBookRepository.DidNotReceive().UpdateAsync(Arg.Any<BookEntity>(), Arg.Any<CancellationToken>());
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenLibraryDoesNotExist_ShouldReturnLibraryNotFoundErrorWithoutUpdating()
{
// Arrange
UpdateBookCommand command = _commandBookFixture.Create();
BookEntity existingBook = _bookEntityFixture.Create(id: Guid.Parse(command.BookId!), libraryId: Guid.Parse(command.LibraryId!));
_mockBookRepository.GetByIdAsync(Arg.Any<Guid>(), Arg.Any<bool>(), Arg.Any<bool>(), Arg.Any<CancellationToken>())
.Returns(Result.From<BookEntity?>(existingBook));
_mockLibraryRepository.GetByIdAsync(Arg.Any<Guid>(), Arg.Any<bool>(), Arg.Any<bool>(), Arg.Any<CancellationToken>())
.Returns(Result.From<LibraryEntity?>(null));
// Act
Result<BookResponse> result = await _sut.HandleAsync(command, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(Errors.Library.LibraryNotFound, result.FirstError);
await _mockBookRepository.DidNotReceive().UpdateAsync(Arg.Any<BookEntity>(), Arg.Any<CancellationToken>());
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
}
}
@@ -1532,7 +1532,7 @@ public class UpdateBookCommandValidatorTests
List<Error> result = _validator.TestValidate(bookCommand);
// Assert
result.ShouldHaveValidationError(Errors.WrittenContent.ContributorsListCannotBeNull);
result.ShouldHaveValidationError(Errors.MediaContributor.ContributorsListCannotBeNull);
}
[Fact]
@@ -1545,7 +1545,7 @@ public class UpdateBookCommandValidatorTests
List<Error> result = _validator.TestValidate(bookCommand);
// Assert
result.ShouldNotHaveValidationError(Errors.WrittenContent.ContributorsListCannotBeNull);
result.ShouldNotHaveValidationError(Errors.MediaContributor.ContributorsListCannotBeNull);
}
[Fact]
@@ -2,7 +2,7 @@
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.BookLibrary;
using Lumina.Application.Common.DataAccess.Repositories.MediaContributors;
using Lumina.Application.Common.DataAccess.Repositories.MediaLibrary;
using Lumina.Application.Common.DataAccess.UoW;
@@ -12,6 +12,7 @@ using Lumina.Application.Common.Infrastructure.Authorization.Policies.LibraryOwn
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.Contracts.Responses.MediaLibrary.WrittenContentLibrary.BookLibrary.Books;
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;
@@ -64,6 +65,7 @@ public class UpdateBookCoverCommandHandlerTests
_mockLibraryRepository = Substitute.For<ILibraryRepository>();
_mockMediaContributorRepository = Substitute.For<IMediaContributorRepository>();
_mockUnitOfWork = Substitute.For<IUnitOfWork>();
_mockUnitOfWork.SaveChangesAsync(Arg.Any<CancellationToken>()).Returns(Result.Success);
_mockUnitOfWork.BookRepository.Returns(_mockBookRepository);
_mockUnitOfWork.LibraryRepository.Returns(_mockLibraryRepository);
_mockUnitOfWork.MediaContributorRepository.Returns(_mockMediaContributorRepository);
@@ -90,24 +92,24 @@ public class UpdateBookCoverCommandHandlerTests
{
// Arrange
UpdateBookCoverCommand command = _commandFixture.Create();
BookEntity existingBook = _bookEntityFixture.Create(id: command.BookId);
existingBook.BookArtwork = [];
BookEntity existingBook = _bookEntityFixture.Create(id: Guid.Parse(command.BookId!), libraryId: Guid.Parse(command.LibraryId!));
existingBook.Artwork = [];
LibraryEntity library = _libraryEntityFixture.Create(id: existingBook.LibraryId);
_mockBookRepository.GetByIdAsync(command.BookId, Arg.Any<CancellationToken>())
_mockBookRepository.GetByIdAsync(Guid.Parse(command.BookId!), cancellationToken: Arg.Any<CancellationToken>())
.Returns(Result.From<BookEntity?>(existingBook));
_mockLibraryRepository.GetByIdAsync(existingBook.LibraryId, Arg.Any<CancellationToken>())
_mockLibraryRepository.GetByIdAsync(existingBook.LibraryId, cancellationToken: Arg.Any<CancellationToken>())
.Returns(Result.From<LibraryEntity?>(library));
// Act
Result<string> result = await _sut.HandleAsync(command, CancellationToken.None);
Result<UpdateBookCoverResponse> 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);
Assert.Equal("/media/books/cover.jpg", result.Value.CoverPath);
Assert.Single(existingBook.Artwork);
Assert.Equal(ArtworkType.Cover, existingBook.Artwork[0].ArtworkType);
Assert.Equal(result.Value.CoverPath, existingBook.Artwork[0].FileName);
Assert.Equal(ArtworkStatus.Enriched, existingBook.Artwork[0].Status);
await _mockBookArtworkService.Received(1).SaveBookArtworkAsync(
existingBook.LibraryId,
existingBook.Id,
@@ -125,23 +127,23 @@ public class UpdateBookCoverCommandHandlerTests
{
// 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];
BookEntity existingBook = _bookEntityFixture.Create(id: Guid.Parse(command.BookId!), libraryId: Guid.Parse(command.LibraryId!));
BookArtworkEntity existingCover = _bookArtworkEntityFixture.Create(bookId: Guid.Parse(command.BookId!), artworkType: ArtworkType.Cover, fileName: "/media/books/old-cover.jpg");
existingBook.Artwork = [existingCover];
LibraryEntity library = _libraryEntityFixture.Create(id: existingBook.LibraryId);
_mockBookRepository.GetByIdAsync(command.BookId, Arg.Any<CancellationToken>())
_mockBookRepository.GetByIdAsync(Guid.Parse(command.BookId!), cancellationToken: Arg.Any<CancellationToken>())
.Returns(Result.From<BookEntity?>(existingBook));
_mockLibraryRepository.GetByIdAsync(existingBook.LibraryId, Arg.Any<CancellationToken>())
_mockLibraryRepository.GetByIdAsync(existingBook.LibraryId, cancellationToken: Arg.Any<CancellationToken>())
.Returns(Result.From<LibraryEntity?>(library));
// Act
Result<string> result = await _sut.HandleAsync(command, CancellationToken.None);
Result<UpdateBookCoverResponse> 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("/media/books/cover.jpg", result.Value.CoverPath);
Assert.Single(existingBook.Artwork);
Assert.Equal(result.Value.CoverPath, existingCover.FileName);
Assert.Equal(ArtworkStatus.Enriched, existingCover.Status);
Assert.Equal(_userId, existingCover.UpdatedBy);
await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any<CancellationToken>());
@@ -152,24 +154,24 @@ public class UpdateBookCoverCommandHandlerTests
{
// Arrange
UpdateBookCoverCommand command = _commandFixture.Create();
BookEntity existingBook = _bookEntityFixture.Create(id: command.BookId);
BookEntity existingBook = _bookEntityFixture.Create(id: Guid.Parse(command.BookId!), libraryId: Guid.Parse(command.LibraryId!));
MediaContributorEntity author = _mediaContributorEntityFixture.Create(displayName: "J.R.R. Tolkien");
MediaContributorEntity illustrator = _mediaContributorEntityFixture.Create(displayName: "Alan Lee");
existingBook.BookContributors =
existingBook.Contributors =
[
_bookContributorEntityFixture.Create(bookId: command.BookId, mediaContributorId: author.Id, roleCategory: MediaContributorRoleCategory.Author),
_bookContributorEntityFixture.Create(bookId: command.BookId, mediaContributorId: illustrator.Id, roleCategory: MediaContributorRoleCategory.Illustrator)
_bookContributorEntityFixture.Create(bookId: Guid.Parse(command.BookId!), mediaContributorId: author.Id, role: MediaContributorRole.Author),
_bookContributorEntityFixture.Create(bookId: Guid.Parse(command.BookId!), mediaContributorId: illustrator.Id, role: MediaContributorRole.Illustrator)
];
LibraryEntity library = _libraryEntityFixture.Create(id: existingBook.LibraryId);
_mockBookRepository.GetByIdAsync(command.BookId, Arg.Any<CancellationToken>())
_mockBookRepository.GetByIdAsync(Guid.Parse(command.BookId!), cancellationToken: Arg.Any<CancellationToken>())
.Returns(Result.From<BookEntity?>(existingBook));
_mockLibraryRepository.GetByIdAsync(existingBook.LibraryId, Arg.Any<CancellationToken>())
_mockLibraryRepository.GetByIdAsync(existingBook.LibraryId, cancellationToken: Arg.Any<CancellationToken>())
.Returns(Result.From<LibraryEntity?>(library));
_mockMediaContributorRepository.GetByIdsAsync(Arg.Any<IReadOnlyCollection<Guid>>(), Arg.Any<CancellationToken>())
.Returns(Result.From<IReadOnlyList<MediaContributorEntity>>([author, illustrator]));
// Act
Result<string> result = await _sut.HandleAsync(command, CancellationToken.None);
Result<UpdateBookCoverResponse> result = await _sut.HandleAsync(command, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
@@ -185,37 +187,31 @@ public class UpdateBookCoverCommandHandlerTests
}
[Fact]
public async Task HandleAsync_WhenAuthorResolutionFails_ShouldStoreArtworkWithEmptyAuthorName()
public async Task HandleAsync_WhenAuthorResolutionFails_ShouldReturnFailureResultWithoutStoringArtwork()
{
// Arrange
UpdateBookCoverCommand command = _commandFixture.Create();
BookEntity existingBook = _bookEntityFixture.Create(id: command.BookId);
existingBook.BookContributors =
BookEntity existingBook = _bookEntityFixture.Create(id: Guid.Parse(command.BookId!), libraryId: Guid.Parse(command.LibraryId!));
existingBook.Contributors =
[
_bookContributorEntityFixture.Create(bookId: command.BookId, roleCategory: MediaContributorRoleCategory.Author)
_bookContributorEntityFixture.Create(bookId: Guid.Parse(command.BookId!), role: MediaContributorRole.Author)
];
LibraryEntity library = _libraryEntityFixture.Create(id: existingBook.LibraryId);
_mockBookRepository.GetByIdAsync(command.BookId, Arg.Any<CancellationToken>())
_mockBookRepository.GetByIdAsync(Guid.Parse(command.BookId!), cancellationToken: Arg.Any<CancellationToken>())
.Returns(Result.From<BookEntity?>(existingBook));
_mockLibraryRepository.GetByIdAsync(existingBook.LibraryId, Arg.Any<CancellationToken>())
_mockLibraryRepository.GetByIdAsync(existingBook.LibraryId, cancellationToken: Arg.Any<CancellationToken>())
.Returns(Result.From<LibraryEntity?>(library));
_mockMediaContributorRepository.GetByIdsAsync(Arg.Any<IReadOnlyCollection<Guid>>(), Arg.Any<CancellationToken>())
.Returns(Errors.Library.LibraryIdCannotBeEmpty);
// Act
Result<string> result = await _sut.HandleAsync(command, CancellationToken.None);
Result<UpdateBookCoverResponse> 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<System.IO.Stream>(),
Arg.Any<string>(),
Arg.Any<CancellationToken>());
Assert.True(result.IsFailure);
Assert.Equal(Errors.Library.LibraryIdCannotBeEmpty, result.FirstError);
await _mockBookArtworkService.DidNotReceive().SaveBookArtworkAsync(Arg.Any<Guid>(), Arg.Any<Guid>(), Arg.Any<string>(), Arg.Any<string>(), Arg.Any<string>(), Arg.Any<System.IO.Stream>(), Arg.Any<string>(), Arg.Any<CancellationToken>());
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
}
[Fact]
@@ -226,12 +222,12 @@ public class UpdateBookCoverCommandHandlerTests
_mockValidator.Validate(Arg.Any<UpdateBookCoverCommand>()).Returns([Errors.WrittenContent.BookCoverCannotBeNull]);
// Act
Result<string> result = await _sut.HandleAsync(command, CancellationToken.None);
Result<UpdateBookCoverResponse> 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<Guid>(), Arg.Any<CancellationToken>());
await _mockBookRepository.DidNotReceive().GetByIdAsync(Arg.Any<Guid>(), cancellationToken: Arg.Any<CancellationToken>());
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
}
@@ -243,7 +239,7 @@ public class UpdateBookCoverCommandHandlerTests
_mockCurrentUserService.UserId.Returns((Guid?)null);
// Act
Result<string> result = await _sut.HandleAsync(command, CancellationToken.None);
Result<UpdateBookCoverResponse> result = await _sut.HandleAsync(command, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
@@ -256,16 +252,16 @@ public class UpdateBookCoverCommandHandlerTests
{
// Arrange
UpdateBookCoverCommand command = _commandFixture.Create();
_mockBookRepository.GetByIdAsync(command.BookId, Arg.Any<CancellationToken>())
_mockBookRepository.GetByIdAsync(Guid.Parse(command.BookId!), cancellationToken: Arg.Any<CancellationToken>())
.Returns(Result.From<BookEntity?>(null));
// Act
Result<string> result = await _sut.HandleAsync(command, CancellationToken.None);
Result<UpdateBookCoverResponse> 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<Guid>(), Arg.Any<CancellationToken>());
await _mockLibraryRepository.DidNotReceive().GetByIdAsync(Arg.Any<Guid>(), cancellationToken: Arg.Any<CancellationToken>());
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
}
@@ -274,14 +270,14 @@ public class UpdateBookCoverCommandHandlerTests
{
// Arrange
UpdateBookCoverCommand command = _commandFixture.Create();
BookEntity existingBook = _bookEntityFixture.Create(id: command.BookId);
_mockBookRepository.GetByIdAsync(command.BookId, Arg.Any<CancellationToken>())
BookEntity existingBook = _bookEntityFixture.Create(id: Guid.Parse(command.BookId!), libraryId: Guid.Parse(command.LibraryId!));
_mockBookRepository.GetByIdAsync(Guid.Parse(command.BookId!), cancellationToken: Arg.Any<CancellationToken>())
.Returns(Result.From<BookEntity?>(existingBook));
_mockAuthorizationService.EvaluatePolicyAsync<ILibraryOwnershipPolicy>(_userId, Arg.Any<LibraryOwnershipPolicyContext>(), Arg.Any<CancellationToken>())
.Returns(false);
// Act
Result<string> result = await _sut.HandleAsync(command, CancellationToken.None);
Result<UpdateBookCoverResponse> result = await _sut.HandleAsync(command, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
@@ -295,14 +291,14 @@ public class UpdateBookCoverCommandHandlerTests
{
// Arrange
UpdateBookCoverCommand command = _commandFixture.Create();
BookEntity existingBook = _bookEntityFixture.Create(id: command.BookId);
_mockBookRepository.GetByIdAsync(command.BookId, Arg.Any<CancellationToken>())
BookEntity existingBook = _bookEntityFixture.Create(id: Guid.Parse(command.BookId!), libraryId: Guid.Parse(command.LibraryId!));
_mockBookRepository.GetByIdAsync(Guid.Parse(command.BookId!), cancellationToken: Arg.Any<CancellationToken>())
.Returns(Result.From<BookEntity?>(existingBook));
_mockLibraryRepository.GetByIdAsync(existingBook.LibraryId, Arg.Any<CancellationToken>())
_mockLibraryRepository.GetByIdAsync(existingBook.LibraryId, cancellationToken: Arg.Any<CancellationToken>())
.Returns(Result.From<LibraryEntity?>(null));
// Act
Result<string> result = await _sut.HandleAsync(command, CancellationToken.None);
Result<UpdateBookCoverResponse> result = await _sut.HandleAsync(command, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
@@ -316,21 +312,106 @@ public class UpdateBookCoverCommandHandlerTests
{
// Arrange
UpdateBookCoverCommand command = _commandFixture.Create();
BookEntity existingBook = _bookEntityFixture.Create(id: command.BookId);
BookEntity existingBook = _bookEntityFixture.Create(id: Guid.Parse(command.BookId!), libraryId: Guid.Parse(command.LibraryId!));
LibraryEntity library = _libraryEntityFixture.Create(id: existingBook.LibraryId);
_mockBookRepository.GetByIdAsync(command.BookId, Arg.Any<CancellationToken>())
_mockBookRepository.GetByIdAsync(Guid.Parse(command.BookId!), cancellationToken: Arg.Any<CancellationToken>())
.Returns(Result.From<BookEntity?>(existingBook));
_mockLibraryRepository.GetByIdAsync(existingBook.LibraryId, Arg.Any<CancellationToken>())
_mockLibraryRepository.GetByIdAsync(existingBook.LibraryId, cancellationToken: Arg.Any<CancellationToken>())
.Returns(Result.From<LibraryEntity?>(library));
_mockBookArtworkService.SaveBookArtworkAsync(Arg.Any<Guid>(), Arg.Any<Guid>(), Arg.Any<string>(), Arg.Any<string>(), Arg.Any<string>(), Arg.Any<System.IO.Stream>(), Arg.Any<string>(), Arg.Any<CancellationToken>())
.Returns(Errors.FileSystemManagement.FileTooLarge);
// Act
Result<string> result = await _sut.HandleAsync(command, CancellationToken.None);
Result<UpdateBookCoverResponse> 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<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenBookBelongsToAnotherLibrary_ShouldReturnBookNotFoundError()
{
// Arrange
UpdateBookCoverCommand command = _commandFixture.Create();
// The stored book belongs to a different library than the one named by the route.
BookEntity existingBook = _bookEntityFixture.Create(id: Guid.Parse(command.BookId!), libraryId: Guid.NewGuid());
_mockBookRepository.GetByIdAsync(Guid.Parse(command.BookId!), cancellationToken: Arg.Any<CancellationToken>())
.Returns(Result.From<BookEntity?>(existingBook));
// Act
Result<UpdateBookCoverResponse> result = await _sut.HandleAsync(command, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(Errors.WrittenContent.BookNotFound, result.FirstError);
await _mockAuthorizationService.DidNotReceive().EvaluatePolicyAsync<ILibraryOwnershipPolicy>(Arg.Any<Guid>(), Arg.Any<LibraryOwnershipPolicyContext>(), Arg.Any<CancellationToken>());
await _mockBookArtworkService.DidNotReceive().SaveBookArtworkAsync(Arg.Any<Guid>(), Arg.Any<Guid>(), Arg.Any<string>(), Arg.Any<string>(), Arg.Any<string>(), Arg.Any<System.IO.Stream>(), Arg.Any<string>(), Arg.Any<CancellationToken>());
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenBookRepositoryReturnsError_ShouldReturnFailureResult()
{
// Arrange
UpdateBookCoverCommand command = _commandFixture.Create();
_mockBookRepository.GetByIdAsync(Guid.Parse(command.BookId!), cancellationToken: Arg.Any<CancellationToken>())
.Returns(Errors.Library.LibraryIdCannotBeEmpty);
// Act
Result<UpdateBookCoverResponse> result = await _sut.HandleAsync(command, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(Errors.Library.LibraryIdCannotBeEmpty, result.FirstError);
await _mockLibraryRepository.DidNotReceive().GetByIdAsync(Arg.Any<Guid>(), cancellationToken: Arg.Any<CancellationToken>());
await _mockBookArtworkService.DidNotReceive().SaveBookArtworkAsync(Arg.Any<Guid>(), Arg.Any<Guid>(), Arg.Any<string>(), Arg.Any<string>(), Arg.Any<string>(), Arg.Any<System.IO.Stream>(), Arg.Any<string>(), Arg.Any<CancellationToken>());
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenLibraryRepositoryReturnsError_ShouldReturnFailureResult()
{
// Arrange
UpdateBookCoverCommand command = _commandFixture.Create();
BookEntity existingBook = _bookEntityFixture.Create(id: Guid.Parse(command.BookId!), libraryId: Guid.Parse(command.LibraryId!));
_mockBookRepository.GetByIdAsync(Guid.Parse(command.BookId!), cancellationToken: Arg.Any<CancellationToken>())
.Returns(Result.From<BookEntity?>(existingBook));
_mockLibraryRepository.GetByIdAsync(existingBook.LibraryId, cancellationToken: Arg.Any<CancellationToken>())
.Returns(Errors.Library.LibraryIdCannotBeEmpty);
// Act
Result<UpdateBookCoverResponse> result = await _sut.HandleAsync(command, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(Errors.Library.LibraryIdCannotBeEmpty, result.FirstError);
await _mockBookArtworkService.DidNotReceive().SaveBookArtworkAsync(Arg.Any<Guid>(), Arg.Any<Guid>(), Arg.Any<string>(), Arg.Any<string>(), Arg.Any<string>(), Arg.Any<System.IO.Stream>(), Arg.Any<string>(), Arg.Any<CancellationToken>());
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenSaveChangesFails_ShouldReturnFailureResultWithoutReturningTheCoverPath()
{
// Arrange
UpdateBookCoverCommand command = _commandFixture.Create();
BookEntity existingBook = _bookEntityFixture.Create(id: Guid.Parse(command.BookId!), libraryId: Guid.Parse(command.LibraryId!));
LibraryEntity library = _libraryEntityFixture.Create(id: existingBook.LibraryId);
_mockBookRepository.GetByIdAsync(Guid.Parse(command.BookId!), cancellationToken: Arg.Any<CancellationToken>())
.Returns(Result.From<BookEntity?>(existingBook));
_mockLibraryRepository.GetByIdAsync(existingBook.LibraryId, cancellationToken: Arg.Any<CancellationToken>())
.Returns(Result.From<LibraryEntity?>(library));
_mockUnitOfWork.SaveChangesAsync(Arg.Any<CancellationToken>())
.Returns(ApplicationErrors.Persistence.UniqueConstraintViolation);
// Act
Result<UpdateBookCoverResponse> result = await _sut.HandleAsync(command, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(ApplicationErrors.Persistence.UniqueConstraintViolation, result.FirstError);
await _mockBookArtworkService.Received(1).SaveBookArtworkAsync(Arg.Any<Guid>(), Arg.Any<Guid>(), Arg.Any<string>(), Arg.Any<string>(), Arg.Any<string>(), Arg.Any<System.IO.Stream>(), Arg.Any<string>(), Arg.Any<CancellationToken>());
await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any<CancellationToken>());
}
}
@@ -33,11 +33,50 @@ public class UpdateBookCoverCommandValidatorTests
Assert.Empty(result);
}
[Fact]
public void Validate_WhenLibraryIdIsEmpty_ShouldHaveValidationError()
{
// Arrange
UpdateBookCoverCommand command = _commandFixture.Create(libraryId: Guid.Empty.ToString());
// Act
List<Error> result = _validator.TestValidate(command);
// Assert
result.ShouldHaveValidationError(Errors.Library.LibraryIdCannotBeEmpty);
}
[Fact]
public void Validate_WhenLibraryIdIsNotAGuid_ShouldHaveValidationError()
{
// Arrange
UpdateBookCoverCommand command = _commandFixture.Create(libraryId: "not-a-guid");
// Act
List<Error> result = _validator.TestValidate(command);
// Assert
result.ShouldHaveValidationError(Errors.Library.LibraryIdCannotBeEmpty);
}
[Fact]
public void Validate_WhenLibraryIdIsValid_ShouldNotHaveValidationError()
{
// Arrange
UpdateBookCoverCommand command = _commandFixture.Create(libraryId: Guid.NewGuid().ToString());
// Act
List<Error> result = _validator.TestValidate(command);
// Assert
result.ShouldNotHaveValidationError(Errors.Library.LibraryIdCannotBeEmpty);
}
[Fact]
public void Validate_WhenBookIdIsEmpty_ShouldHaveValidationError()
{
// Arrange
UpdateBookCoverCommand command = _commandFixture.Create(bookId: Guid.Empty);
UpdateBookCoverCommand command = _commandFixture.Create(bookId: Guid.Empty.ToString());
// Act
List<Error> result = _validator.TestValidate(command);
@@ -46,6 +85,32 @@ public class UpdateBookCoverCommandValidatorTests
result.ShouldHaveValidationError(Errors.WrittenContent.BookIdCannotBeEmpty);
}
[Fact]
public void Validate_WhenBookIdIsNotAGuid_ShouldHaveValidationError()
{
// Arrange
UpdateBookCoverCommand command = _commandFixture.Create(bookId: "not-a-guid");
// Act
List<Error> result = _validator.TestValidate(command);
// Assert
result.ShouldHaveValidationError(Errors.WrittenContent.BookIdCannotBeEmpty);
}
[Fact]
public void Validate_WhenBookIdIsValid_ShouldNotHaveValidationError()
{
// Arrange
UpdateBookCoverCommand command = _commandFixture.Create(bookId: Guid.NewGuid().ToString());
// Act
List<Error> result = _validator.TestValidate(command);
// Assert
result.ShouldNotHaveValidationError(Errors.WrittenContent.BookIdCannotBeEmpty);
}
[Fact]
public void Validate_WhenCoverIsNull_ShouldHaveValidationError()
{
@@ -58,4 +123,30 @@ public class UpdateBookCoverCommandValidatorTests
// Assert
result.ShouldHaveValidationError(Errors.WrittenContent.BookCoverCannotBeNull);
}
[Fact]
public void Validate_WhenCoverIsPresentAndFileNameIsEmpty_ShouldHaveValidationError()
{
// Arrange
UpdateBookCoverCommand command = _commandFixture.Create(fileName: string.Empty);
// Act
List<Error> result = _validator.TestValidate(command);
// Assert
result.ShouldHaveValidationError(Errors.FileSystemManagement.FileNameCannotBeEmpty);
}
[Fact]
public void Validate_WhenCoverIsMissingAndFileNameIsEmpty_ShouldNotHaveFileNameValidationError()
{
// Arrange
UpdateBookCoverCommand command = _commandFixture.Create(fileName: string.Empty, includeCover: false);
// Act
List<Error> result = _validator.TestValidate(command);
// Assert
result.ShouldNotHaveValidationError(Errors.FileSystemManagement.FileNameCannotBeEmpty);
}
}
@@ -1,6 +1,6 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary;
using Lumina.Application.Common.DataAccess.Repositories.Books;
using Lumina.Application.Common.DataAccess.Repositories.BookLibrary;
using Lumina.Application.Common.DataAccess.UoW;
using Lumina.Application.Common.Infrastructure.Authentication;
using Lumina.Application.Common.Infrastructure.Authorization;
@@ -94,7 +94,7 @@ public class GetBookQueryHandlerTests
Guid bookId = Guid.Parse(query.BookId!);
BookEntity bookEntity = _bookEntityFixture.Create(id: bookId, libraryId: libraryId);
Guid contributorId = Guid.NewGuid();
bookEntity.BookContributors =
bookEntity.Contributors =
[
_bookContributorEntityFixture.Create(bookId: bookId, mediaContributorId: contributorId, role: MediaContributorRole.Author)
];
@@ -1,6 +1,6 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary;
using Lumina.Application.Common.DataAccess.Repositories.Books;
using Lumina.Application.Common.DataAccess.Repositories.BookLibrary;
using Lumina.Application.Common.DataAccess.UoW;
using Lumina.Application.Common.DTO.Filtering;
using Lumina.Application.Common.DTO.Pagination;
@@ -1,5 +1,5 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DataAccess.Repositories.Books;
using Lumina.Application.Common.DataAccess.Repositories.BookLibrary;
using Lumina.Application.Common.DataAccess.UoW;
using Lumina.Application.Common.DTO.Filtering;
using Lumina.Application.Common.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary;
@@ -1,7 +1,7 @@
#region ========================================================================= USING =====================================================================================
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.BookLibrary;
using Lumina.Application.Common.DataAccess.Repositories.MediaLibrary;
using Lumina.Application.Common.DataAccess.UoW;
using Lumina.Application.Common.Infrastructure.Authentication;
@@ -57,6 +57,7 @@ public class GetReadingAvailabilityQueryHandlerTests
_mockBookRepository = Substitute.For<IBookRepository>();
_mockLibraryRepository = Substitute.For<ILibraryRepository>();
_mockUnitOfWork = Substitute.For<IUnitOfWork>();
_mockUnitOfWork.SaveChangesAsync(Arg.Any<CancellationToken>()).Returns(Result.Success);
_mockUnitOfWork.BookRepository.Returns(_mockBookRepository);
_mockUnitOfWork.LibraryRepository.Returns(_mockLibraryRepository);
_mockAuthorizationService = Substitute.For<IAuthorizationService>();
@@ -79,12 +80,14 @@ public class GetReadingAvailabilityQueryHandlerTests
{
// Arrange
GetReadingAvailabilityQuery query = _getReadingAvailabilityQueryFixture.Create();
Guid libraryId = Guid.Parse(query.LibraryId!);
Guid bookId = Guid.Parse(query.BookId!);
CancellationToken cancellationToken = CancellationToken.None;
BookEntity book = _bookEntityFixture.Create(id: query.BookId);
BookEntity book = _bookEntityFixture.Create(id: bookId, libraryId: libraryId);
LibraryEntity library = _libraryEntityFixture.Create(id: book.LibraryId, libraryType: LibraryType.EBook);
ReadingAvailabilityResponse expectedResponse = _readingAvailabilityResponseFixture.Create(bookId: book.Id, libraryId: book.LibraryId, isAvailable: true);
_mockBookRepository.GetByIdAsync(query.BookId, cancellationToken).Returns(Result.From<BookEntity?>(book));
_mockLibraryRepository.GetByIdAsync(book.LibraryId, cancellationToken).Returns(Result.From<LibraryEntity?>(library));
_mockBookRepository.GetByIdAsync(bookId, shouldTrackEntities: false, cancellationToken: cancellationToken).Returns(Result.From<BookEntity?>(book));
_mockLibraryRepository.GetByIdAsync(book.LibraryId, shouldTrackEntities: false, cancellationToken: cancellationToken).Returns(Result.From<LibraryEntity?>(library));
_mockBookReadingService.GetAvailabilityAsync(book.Id, book.LibraryId, book.Path, library.LibraryType, cancellationToken).Returns(expectedResponse);
// Act
@@ -100,12 +103,14 @@ public class GetReadingAvailabilityQueryHandlerTests
{
// Arrange
GetReadingAvailabilityQuery query = _getReadingAvailabilityQueryFixture.Create();
Guid libraryId = Guid.Parse(query.LibraryId!);
Guid bookId = Guid.Parse(query.BookId!);
CancellationToken cancellationToken = CancellationToken.None;
BookEntity book = _bookEntityFixture.Create(id: query.BookId);
BookEntity book = _bookEntityFixture.Create(id: bookId, libraryId: libraryId);
LibraryEntity library = _libraryEntityFixture.Create(id: book.LibraryId, libraryType: LibraryType.EBook);
ReadingAvailabilityResponse expectedResponse = _readingAvailabilityResponseFixture.Create(bookId: book.Id, libraryId: book.LibraryId, isAvailable: false, errorCode: nameof(Errors.Reading.ReaderDisabled));
_mockBookRepository.GetByIdAsync(query.BookId, cancellationToken).Returns(Result.From<BookEntity?>(book));
_mockLibraryRepository.GetByIdAsync(book.LibraryId, cancellationToken).Returns(Result.From<LibraryEntity?>(library));
_mockBookRepository.GetByIdAsync(bookId, shouldTrackEntities: false, cancellationToken: cancellationToken).Returns(Result.From<BookEntity?>(book));
_mockLibraryRepository.GetByIdAsync(book.LibraryId, shouldTrackEntities: false, cancellationToken: cancellationToken).Returns(Result.From<LibraryEntity?>(library));
_mockBookReadingService.GetAvailabilityAsync(book.Id, book.LibraryId, book.Path, library.LibraryType, cancellationToken).Returns(expectedResponse);
// Act
@@ -122,7 +127,8 @@ public class GetReadingAvailabilityQueryHandlerTests
{
// Arrange
GetReadingAvailabilityQuery query = _getReadingAvailabilityQueryFixture.Create();
_mockBookRepository.GetByIdAsync(query.BookId, Arg.Any<CancellationToken>()).Returns(Result.From<BookEntity?>(null));
Guid bookId = Guid.Parse(query.BookId!);
_mockBookRepository.GetByIdAsync(bookId, shouldTrackEntities: false, cancellationToken: Arg.Any<CancellationToken>()).Returns(Result.From<BookEntity?>(null));
// Act
Result<ReadingAvailabilityResponse> result = await _sut.HandleAsync(query, CancellationToken.None);
@@ -133,14 +139,35 @@ public class GetReadingAvailabilityQueryHandlerTests
await _mockBookReadingService.DidNotReceive().GetAvailabilityAsync(Arg.Any<Guid>(), Arg.Any<Guid>(), Arg.Any<string>(), Arg.Any<LibraryType>(), Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenBookBelongsToAnotherLibrary_ShouldReturnBookNotFoundError()
{
// Arrange
GetReadingAvailabilityQuery query = _getReadingAvailabilityQueryFixture.Create();
Guid bookId = Guid.Parse(query.BookId!);
BookEntity book = _bookEntityFixture.Create(id: bookId, libraryId: Guid.NewGuid());
_mockBookRepository.GetByIdAsync(bookId, shouldTrackEntities: false, cancellationToken: Arg.Any<CancellationToken>()).Returns(Result.From<BookEntity?>(book));
// Act
Result<ReadingAvailabilityResponse> result = await _sut.HandleAsync(query, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(DomainErrors.Reading.BookNotFound, result.FirstError);
await _mockLibraryRepository.DidNotReceive().GetByIdAsync(Arg.Any<Guid>(), shouldTrackEntities: false, cancellationToken: Arg.Any<CancellationToken>());
await _mockBookReadingService.DidNotReceive().GetAvailabilityAsync(Arg.Any<Guid>(), Arg.Any<Guid>(), Arg.Any<string>(), Arg.Any<LibraryType>(), Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenLibraryDoesNotExist_ShouldReturnLibraryNotFoundError()
{
// Arrange
GetReadingAvailabilityQuery query = _getReadingAvailabilityQueryFixture.Create();
BookEntity book = _bookEntityFixture.Create(id: query.BookId);
_mockBookRepository.GetByIdAsync(query.BookId, Arg.Any<CancellationToken>()).Returns(Result.From<BookEntity?>(book));
_mockLibraryRepository.GetByIdAsync(book.LibraryId, Arg.Any<CancellationToken>()).Returns(Result.From<LibraryEntity?>(null));
Guid libraryId = Guid.Parse(query.LibraryId!);
Guid bookId = Guid.Parse(query.BookId!);
BookEntity book = _bookEntityFixture.Create(id: bookId, libraryId: libraryId);
_mockBookRepository.GetByIdAsync(bookId, shouldTrackEntities: false, cancellationToken: Arg.Any<CancellationToken>()).Returns(Result.From<BookEntity?>(book));
_mockLibraryRepository.GetByIdAsync(book.LibraryId, shouldTrackEntities: false, cancellationToken: Arg.Any<CancellationToken>()).Returns(Result.From<LibraryEntity?>(null));
// Act
Result<ReadingAvailabilityResponse> result = await _sut.HandleAsync(query, CancellationToken.None);
@@ -156,8 +183,10 @@ public class GetReadingAvailabilityQueryHandlerTests
{
// Arrange
GetReadingAvailabilityQuery query = _getReadingAvailabilityQueryFixture.Create();
BookEntity book = _bookEntityFixture.Create(id: query.BookId);
_mockBookRepository.GetByIdAsync(query.BookId, Arg.Any<CancellationToken>()).Returns(Result.From<BookEntity?>(book));
Guid libraryId = Guid.Parse(query.LibraryId!);
Guid bookId = Guid.Parse(query.BookId!);
BookEntity book = _bookEntityFixture.Create(id: bookId, libraryId: libraryId);
_mockBookRepository.GetByIdAsync(bookId, shouldTrackEntities: false, cancellationToken: Arg.Any<CancellationToken>()).Returns(Result.From<BookEntity?>(book));
_mockAuthorizationService.EvaluatePolicyAsync<ILibraryOwnershipPolicy>(_userId, Arg.Any<LibraryOwnershipPolicyContext>(), Arg.Any<CancellationToken>())
.Returns(false);
@@ -167,7 +196,7 @@ public class GetReadingAvailabilityQueryHandlerTests
// Assert
Assert.True(result.IsFailure);
Assert.Equal(ApplicationErrors.Authorization.NotAuthorized, result.FirstError);
await _mockLibraryRepository.DidNotReceive().GetByIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
await _mockLibraryRepository.DidNotReceive().GetByIdAsync(Arg.Any<Guid>(), shouldTrackEntities: false, cancellationToken: Arg.Any<CancellationToken>());
await _mockBookReadingService.DidNotReceive().GetAvailabilityAsync(Arg.Any<Guid>(), Arg.Any<Guid>(), Arg.Any<string>(), Arg.Any<LibraryType>(), Arg.Any<CancellationToken>());
}
@@ -185,7 +214,24 @@ public class GetReadingAvailabilityQueryHandlerTests
Assert.True(result.IsFailure);
Assert.Equal(ApplicationErrors.Authorization.NotAuthorized, result.FirstError);
await _mockAuthorizationService.DidNotReceive().EvaluatePolicyAsync<ILibraryOwnershipPolicy>(Arg.Any<Guid>(), Arg.Any<LibraryOwnershipPolicyContext>(), Arg.Any<CancellationToken>());
await _mockBookRepository.DidNotReceive().GetByIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
await _mockBookRepository.DidNotReceive().GetByIdAsync(Arg.Any<Guid>(), shouldTrackEntities: false, cancellationToken: Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenRepositoryReturnsError_ShouldReturnFailureResult()
{
// Arrange
GetReadingAvailabilityQuery query = _getReadingAvailabilityQueryFixture.Create();
Guid bookId = Guid.Parse(query.BookId!);
_mockBookRepository.GetByIdAsync(bookId, shouldTrackEntities: false, cancellationToken: Arg.Any<CancellationToken>())
.Returns(Errors.Library.LibraryIdCannotBeEmpty);
// Act
Result<ReadingAvailabilityResponse> result = await _sut.HandleAsync(query, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(Errors.Library.LibraryIdCannotBeEmpty, result.FirstError);
}
[Fact]
@@ -193,16 +239,16 @@ public class GetReadingAvailabilityQueryHandlerTests
{
// Arrange
GetReadingAvailabilityQuery query = _getReadingAvailabilityQueryFixture.Create();
_mockValidator.Validate(Arg.Any<GetReadingAvailabilityQuery>()).Returns([Errors.Reading.BookIdCannotBeEmpty]);
_mockValidator.Validate(Arg.Any<GetReadingAvailabilityQuery>()).Returns([Errors.WrittenContent.BookIdCannotBeEmpty]);
// Act
Result<ReadingAvailabilityResponse> result = await _sut.HandleAsync(query, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(Errors.Reading.BookIdCannotBeEmpty, result.FirstError);
Assert.Equal(Errors.WrittenContent.BookIdCannotBeEmpty, result.FirstError);
await _mockAuthorizationService.DidNotReceive().EvaluatePolicyAsync<ILibraryOwnershipPolicy>(Arg.Any<Guid>(), Arg.Any<LibraryOwnershipPolicyContext>(), Arg.Any<CancellationToken>());
await _mockBookRepository.DidNotReceive().GetByIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
await _mockBookRepository.DidNotReceive().GetByIdAsync(Arg.Any<Guid>(), shouldTrackEntities: false, cancellationToken: Arg.Any<CancellationToken>());
await _mockBookReadingService.DidNotReceive().GetAvailabilityAsync(Arg.Any<Guid>(), Arg.Any<Guid>(), Arg.Any<string>(), Arg.Any<LibraryType>(), Arg.Any<CancellationToken>());
}
}
@@ -4,7 +4,6 @@ using Lumina.Application.Fixtures.Core.MediaLibrary.WrittenContentLibrary.BookLi
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
@@ -21,20 +20,7 @@ public class GetReadingAvailabilityQueryValidatorTests
private readonly GetReadingAvailabilityQueryFixture _getReadingAvailabilityQueryFixture = new();
[Fact]
public void Validate_WhenBookIdIsEmpty_ShouldHaveValidationError()
{
// Arrange
GetReadingAvailabilityQuery query = _getReadingAvailabilityQueryFixture.Create(bookId: Guid.Empty);
// Act
List<Error> result = _validator.TestValidate(query);
// Assert
result.ShouldHaveValidationError(Errors.Reading.BookIdCannotBeEmpty);
}
[Fact]
public void Validate_WhenBookIdIsValid_ShouldNotHaveValidationError()
public void Validate_WhenIdsAreValid_ShouldNotHaveValidationError()
{
// Arrange
GetReadingAvailabilityQuery query = _getReadingAvailabilityQueryFixture.Create();
@@ -43,6 +29,41 @@ public class GetReadingAvailabilityQueryValidatorTests
List<Error> result = _validator.TestValidate(query);
// Assert
result.ShouldNotHaveValidationError(Errors.Reading.BookIdCannotBeEmpty);
result.ShouldNotHaveValidationError(Errors.Library.LibraryIdCannotBeEmpty);
result.ShouldNotHaveValidationError(Errors.WrittenContent.BookIdCannotBeEmpty);
}
[Theory]
[InlineData(null)] // missing route value
[InlineData("")] // empty route value
[InlineData("not-a-library-guid")] // non-Guid route value
[InlineData("00000000-0000-0000-0000-000000000000")] // empty Guid route value
public void Validate_WhenLibraryIdIsEmptyOrInvalid_ShouldHaveValidationError(string? libraryId)
{
// Arrange
GetReadingAvailabilityQuery query = _getReadingAvailabilityQueryFixture.Create() with { LibraryId = libraryId };
// Act
List<Error> result = _validator.TestValidate(query);
// Assert
result.ShouldHaveValidationError(Errors.Library.LibraryIdCannotBeEmpty);
}
[Theory]
[InlineData(null)] // missing route value
[InlineData("")] // empty route value
[InlineData("not-a-guid")] // non-Guid route value
[InlineData("00000000-0000-0000-0000-000000000000")] // empty Guid route value
public void Validate_WhenBookIdIsEmptyOrInvalid_ShouldHaveValidationError(string? bookId)
{
// Arrange
GetReadingAvailabilityQuery query = _getReadingAvailabilityQueryFixture.Create() with { BookId = bookId };
// Act
List<Error> result = _validator.TestValidate(query);
// Assert
result.ShouldHaveValidationError(Errors.WrittenContent.BookIdCannotBeEmpty);
}
}
@@ -2,7 +2,7 @@
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.Common.DataAccess.Repositories.Books;
using Lumina.Application.Common.DataAccess.Repositories.BookLibrary;
using Lumina.Application.Common.DataAccess.Repositories.MediaLibrary;
using Lumina.Application.Common.DataAccess.Repositories.Users;
using Lumina.Application.Common.DataAccess.UoW;
@@ -63,6 +63,7 @@ public class GetReadingManifestQueryHandlerTests
_mockLibraryRepository = Substitute.For<ILibraryRepository>();
_mockUserSettingsRepository = Substitute.For<IUserSettingsRepository>();
_mockUnitOfWork = Substitute.For<IUnitOfWork>();
_mockUnitOfWork.SaveChangesAsync(Arg.Any<CancellationToken>()).Returns(Result.Success);
_mockUnitOfWork.BookRepository.Returns(_mockBookRepository);
_mockUnitOfWork.LibraryRepository.Returns(_mockLibraryRepository);
_mockUnitOfWork.UserSettingsRepository.Returns(_mockUserSettingsRepository);
@@ -87,12 +88,14 @@ public class GetReadingManifestQueryHandlerTests
{
// Arrange
GetReadingManifestQuery query = _getReadingManifestQueryFixture.Create();
Guid libraryId = Guid.Parse(query.LibraryId!);
Guid bookId = Guid.Parse(query.BookId!);
CancellationToken cancellationToken = CancellationToken.None;
BookEntity book = _bookEntityFixture.Create(id: query.BookId);
BookEntity book = _bookEntityFixture.Create(id: bookId, libraryId: libraryId);
LibraryEntity library = _libraryEntityFixture.Create(id: book.LibraryId, libraryType: LibraryType.EBook);
ReadingManifestResponse expectedResponse = _readingManifestResponseFixture.Create();
_mockBookRepository.GetByIdAsync(query.BookId, cancellationToken).Returns(Result.From<BookEntity?>(book));
_mockLibraryRepository.GetByIdAsync(book.LibraryId, cancellationToken).Returns(Result.From<LibraryEntity?>(library));
_mockBookRepository.GetByIdAsync(bookId, shouldTrackEntities: false, cancellationToken: cancellationToken).Returns(Result.From<BookEntity?>(book));
_mockLibraryRepository.GetByIdAsync(book.LibraryId, shouldTrackEntities: false, cancellationToken: cancellationToken).Returns(Result.From<LibraryEntity?>(library));
_mockBookReadingService.GetManifestAsync(book.Id, book.LibraryId, book.Path, library.LibraryType, shouldRenderPdfAsImages: false, cancellationToken).Returns(expectedResponse);
// Act
@@ -108,14 +111,16 @@ public class GetReadingManifestQueryHandlerTests
{
// Arrange
GetReadingManifestQuery query = _getReadingManifestQueryFixture.Create();
Guid libraryId = Guid.Parse(query.LibraryId!);
Guid bookId = Guid.Parse(query.BookId!);
CancellationToken cancellationToken = CancellationToken.None;
BookEntity book = _bookEntityFixture.Create(id: query.BookId);
BookEntity book = _bookEntityFixture.Create(id: bookId, libraryId: libraryId);
LibraryEntity library = _libraryEntityFixture.Create(id: book.LibraryId, libraryType: LibraryType.EBook);
UserSettingsEntity settings = _userSettingsEntityFixture.Create(userId: _userId, shouldRenderPdfAsImages: true);
ReadingManifestResponse expectedResponse = _readingManifestResponseFixture.Create();
_mockUserSettingsRepository.GetByUserIdAsync(_userId, cancellationToken).Returns(Result.From<UserSettingsEntity?>(settings));
_mockBookRepository.GetByIdAsync(query.BookId, cancellationToken).Returns(Result.From<BookEntity?>(book));
_mockLibraryRepository.GetByIdAsync(book.LibraryId, cancellationToken).Returns(Result.From<LibraryEntity?>(library));
_mockBookRepository.GetByIdAsync(bookId, shouldTrackEntities: false, cancellationToken: cancellationToken).Returns(Result.From<BookEntity?>(book));
_mockLibraryRepository.GetByIdAsync(book.LibraryId, shouldTrackEntities: false, cancellationToken: cancellationToken).Returns(Result.From<LibraryEntity?>(library));
_mockBookReadingService.GetManifestAsync(book.Id, book.LibraryId, book.Path, library.LibraryType, shouldRenderPdfAsImages: true, cancellationToken).Returns(expectedResponse);
// Act
@@ -131,7 +136,8 @@ public class GetReadingManifestQueryHandlerTests
{
// Arrange
GetReadingManifestQuery query = _getReadingManifestQueryFixture.Create();
_mockBookRepository.GetByIdAsync(query.BookId, Arg.Any<CancellationToken>()).Returns(Result.From<BookEntity?>(null));
Guid bookId = Guid.Parse(query.BookId!);
_mockBookRepository.GetByIdAsync(bookId, shouldTrackEntities: false, cancellationToken: Arg.Any<CancellationToken>()).Returns(Result.From<BookEntity?>(null));
// Act
Result<ReadingManifestResponse> result = await _sut.HandleAsync(query, CancellationToken.None);
@@ -142,14 +148,35 @@ public class GetReadingManifestQueryHandlerTests
await _mockBookReadingService.DidNotReceive().GetManifestAsync(Arg.Any<Guid>(), Arg.Any<Guid>(), Arg.Any<string>(), Arg.Any<LibraryType>(), Arg.Any<bool>(), Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenBookBelongsToAnotherLibrary_ShouldReturnBookNotFoundError()
{
// Arrange
GetReadingManifestQuery query = _getReadingManifestQueryFixture.Create();
Guid bookId = Guid.Parse(query.BookId!);
BookEntity book = _bookEntityFixture.Create(id: bookId, libraryId: Guid.NewGuid());
_mockBookRepository.GetByIdAsync(bookId, shouldTrackEntities: false, cancellationToken: Arg.Any<CancellationToken>()).Returns(Result.From<BookEntity?>(book));
// Act
Result<ReadingManifestResponse> result = await _sut.HandleAsync(query, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(DomainErrors.Reading.BookNotFound, result.FirstError);
await _mockLibraryRepository.DidNotReceive().GetByIdAsync(Arg.Any<Guid>(), shouldTrackEntities: false, cancellationToken: Arg.Any<CancellationToken>());
await _mockBookReadingService.DidNotReceive().GetManifestAsync(Arg.Any<Guid>(), Arg.Any<Guid>(), Arg.Any<string>(), Arg.Any<LibraryType>(), Arg.Any<bool>(), Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenLibraryDoesNotExist_ShouldReturnLibraryNotFoundError()
{
// Arrange
GetReadingManifestQuery query = _getReadingManifestQueryFixture.Create();
BookEntity book = _bookEntityFixture.Create(id: query.BookId);
_mockBookRepository.GetByIdAsync(query.BookId, Arg.Any<CancellationToken>()).Returns(Result.From<BookEntity?>(book));
_mockLibraryRepository.GetByIdAsync(book.LibraryId, Arg.Any<CancellationToken>()).Returns(Result.From<LibraryEntity?>(null));
Guid libraryId = Guid.Parse(query.LibraryId!);
Guid bookId = Guid.Parse(query.BookId!);
BookEntity book = _bookEntityFixture.Create(id: bookId, libraryId: libraryId);
_mockBookRepository.GetByIdAsync(bookId, shouldTrackEntities: false, cancellationToken: Arg.Any<CancellationToken>()).Returns(Result.From<BookEntity?>(book));
_mockLibraryRepository.GetByIdAsync(book.LibraryId, shouldTrackEntities: false, cancellationToken: Arg.Any<CancellationToken>()).Returns(Result.From<LibraryEntity?>(null));
// Act
Result<ReadingManifestResponse> result = await _sut.HandleAsync(query, CancellationToken.None);
@@ -165,8 +192,10 @@ public class GetReadingManifestQueryHandlerTests
{
// Arrange
GetReadingManifestQuery query = _getReadingManifestQueryFixture.Create();
BookEntity book = _bookEntityFixture.Create(id: query.BookId);
_mockBookRepository.GetByIdAsync(query.BookId, Arg.Any<CancellationToken>()).Returns(Result.From<BookEntity?>(book));
Guid libraryId = Guid.Parse(query.LibraryId!);
Guid bookId = Guid.Parse(query.BookId!);
BookEntity book = _bookEntityFixture.Create(id: bookId, libraryId: libraryId);
_mockBookRepository.GetByIdAsync(bookId, shouldTrackEntities: false, cancellationToken: Arg.Any<CancellationToken>()).Returns(Result.From<BookEntity?>(book));
_mockAuthorizationService.EvaluatePolicyAsync<ILibraryOwnershipPolicy>(_userId, Arg.Any<LibraryOwnershipPolicyContext>(), Arg.Any<CancellationToken>())
.Returns(false);
@@ -176,7 +205,7 @@ public class GetReadingManifestQueryHandlerTests
// Assert
Assert.True(result.IsFailure);
Assert.Equal(ApplicationErrors.Authorization.NotAuthorized, result.FirstError);
await _mockLibraryRepository.DidNotReceive().GetByIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
await _mockLibraryRepository.DidNotReceive().GetByIdAsync(Arg.Any<Guid>(), shouldTrackEntities: false, cancellationToken: Arg.Any<CancellationToken>());
await _mockBookReadingService.DidNotReceive().GetManifestAsync(Arg.Any<Guid>(), Arg.Any<Guid>(), Arg.Any<string>(), Arg.Any<LibraryType>(), Arg.Any<bool>(), Arg.Any<CancellationToken>());
}
@@ -194,7 +223,24 @@ public class GetReadingManifestQueryHandlerTests
Assert.True(result.IsFailure);
Assert.Equal(ApplicationErrors.Authorization.NotAuthorized, result.FirstError);
await _mockAuthorizationService.DidNotReceive().EvaluatePolicyAsync<ILibraryOwnershipPolicy>(Arg.Any<Guid>(), Arg.Any<LibraryOwnershipPolicyContext>(), Arg.Any<CancellationToken>());
await _mockBookRepository.DidNotReceive().GetByIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
await _mockBookRepository.DidNotReceive().GetByIdAsync(Arg.Any<Guid>(), shouldTrackEntities: false, cancellationToken: Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenRepositoryReturnsError_ShouldReturnFailureResult()
{
// Arrange
GetReadingManifestQuery query = _getReadingManifestQueryFixture.Create();
Guid bookId = Guid.Parse(query.BookId!);
_mockBookRepository.GetByIdAsync(bookId, shouldTrackEntities: false, cancellationToken: Arg.Any<CancellationToken>())
.Returns(Errors.Library.LibraryIdCannotBeEmpty);
// Act
Result<ReadingManifestResponse> result = await _sut.HandleAsync(query, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(Errors.Library.LibraryIdCannotBeEmpty, result.FirstError);
}
[Fact]
@@ -202,16 +248,16 @@ public class GetReadingManifestQueryHandlerTests
{
// Arrange
GetReadingManifestQuery query = _getReadingManifestQueryFixture.Create();
_mockValidator.Validate(Arg.Any<GetReadingManifestQuery>()).Returns([Errors.Reading.BookIdCannotBeEmpty]);
_mockValidator.Validate(Arg.Any<GetReadingManifestQuery>()).Returns([Errors.WrittenContent.BookIdCannotBeEmpty]);
// Act
Result<ReadingManifestResponse> result = await _sut.HandleAsync(query, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(Errors.Reading.BookIdCannotBeEmpty, result.FirstError);
Assert.Equal(Errors.WrittenContent.BookIdCannotBeEmpty, result.FirstError);
await _mockAuthorizationService.DidNotReceive().EvaluatePolicyAsync<ILibraryOwnershipPolicy>(Arg.Any<Guid>(), Arg.Any<LibraryOwnershipPolicyContext>(), Arg.Any<CancellationToken>());
await _mockBookRepository.DidNotReceive().GetByIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
await _mockBookRepository.DidNotReceive().GetByIdAsync(Arg.Any<Guid>(), shouldTrackEntities: false, cancellationToken: Arg.Any<CancellationToken>());
await _mockBookReadingService.DidNotReceive().GetManifestAsync(Arg.Any<Guid>(), Arg.Any<Guid>(), Arg.Any<string>(), Arg.Any<LibraryType>(), Arg.Any<bool>(), Arg.Any<CancellationToken>());
}
}
@@ -4,7 +4,6 @@ using Lumina.Application.Fixtures.Core.MediaLibrary.WrittenContentLibrary.BookLi
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
@@ -21,20 +20,7 @@ public class GetReadingManifestQueryValidatorTests
private readonly GetReadingManifestQueryFixture _getReadingManifestQueryFixture = new();
[Fact]
public void Validate_WhenBookIdIsEmpty_ShouldHaveValidationError()
{
// Arrange
GetReadingManifestQuery query = _getReadingManifestQueryFixture.Create(bookId: Guid.Empty);
// Act
List<Error> result = _validator.TestValidate(query);
// Assert
result.ShouldHaveValidationError(Errors.Reading.BookIdCannotBeEmpty);
}
[Fact]
public void Validate_WhenBookIdIsValid_ShouldNotHaveValidationError()
public void Validate_WhenIdsAreValid_ShouldNotHaveValidationError()
{
// Arrange
GetReadingManifestQuery query = _getReadingManifestQueryFixture.Create();
@@ -43,6 +29,41 @@ public class GetReadingManifestQueryValidatorTests
List<Error> result = _validator.TestValidate(query);
// Assert
result.ShouldNotHaveValidationError(Errors.Reading.BookIdCannotBeEmpty);
result.ShouldNotHaveValidationError(Errors.Library.LibraryIdCannotBeEmpty);
result.ShouldNotHaveValidationError(Errors.WrittenContent.BookIdCannotBeEmpty);
}
[Theory]
[InlineData(null)] // missing route value
[InlineData("")] // empty route value
[InlineData("not-a-library-guid")] // non-Guid route value
[InlineData("00000000-0000-0000-0000-000000000000")] // empty Guid route value
public void Validate_WhenLibraryIdIsEmptyOrInvalid_ShouldHaveValidationError(string? libraryId)
{
// Arrange
GetReadingManifestQuery query = _getReadingManifestQueryFixture.Create() with { LibraryId = libraryId };
// Act
List<Error> result = _validator.TestValidate(query);
// Assert
result.ShouldHaveValidationError(Errors.Library.LibraryIdCannotBeEmpty);
}
[Theory]
[InlineData(null)] // missing route value
[InlineData("")] // empty route value
[InlineData("not-a-guid")] // non-Guid route value
[InlineData("00000000-0000-0000-0000-000000000000")] // empty Guid route value
public void Validate_WhenBookIdIsEmptyOrInvalid_ShouldHaveValidationError(string? bookId)
{
// Arrange
GetReadingManifestQuery query = _getReadingManifestQueryFixture.Create() with { BookId = bookId };
// Act
List<Error> result = _validator.TestValidate(query);
// Assert
result.ShouldHaveValidationError(Errors.WrittenContent.BookIdCannotBeEmpty);
}
}
@@ -2,7 +2,7 @@
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.Common.DataAccess.Repositories.Books;
using Lumina.Application.Common.DataAccess.Repositories.BookLibrary;
using Lumina.Application.Common.DataAccess.Repositories.MediaLibrary;
using Lumina.Application.Common.DataAccess.Repositories.Users;
using Lumina.Application.Common.DataAccess.UoW;
@@ -63,6 +63,7 @@ public class GetReadingResourceQueryHandlerTests
_mockLibraryRepository = Substitute.For<ILibraryRepository>();
_mockUserSettingsRepository = Substitute.For<IUserSettingsRepository>();
_mockUnitOfWork = Substitute.For<IUnitOfWork>();
_mockUnitOfWork.SaveChangesAsync(Arg.Any<CancellationToken>()).Returns(Result.Success);
_mockUnitOfWork.BookRepository.Returns(_mockBookRepository);
_mockUnitOfWork.LibraryRepository.Returns(_mockLibraryRepository);
_mockUnitOfWork.UserSettingsRepository.Returns(_mockUserSettingsRepository);
@@ -87,12 +88,14 @@ public class GetReadingResourceQueryHandlerTests
{
// Arrange
GetReadingResourceQuery query = _getReadingResourceQueryFixture.Create();
Guid libraryId = Guid.Parse(query.LibraryId!);
Guid bookId = Guid.Parse(query.BookId!);
CancellationToken cancellationToken = CancellationToken.None;
BookEntity book = _bookEntityFixture.Create(id: query.BookId);
BookEntity book = _bookEntityFixture.Create(id: bookId, libraryId: libraryId);
LibraryEntity library = _libraryEntityFixture.Create(id: book.LibraryId, libraryType: LibraryType.EBook);
ReadingResourceDataDto expectedResponse = _readingResourceDataDtoFixture.Create();
_mockBookRepository.GetByIdAsync(query.BookId, cancellationToken).Returns(Result.From<BookEntity?>(book));
_mockLibraryRepository.GetByIdAsync(book.LibraryId, cancellationToken).Returns(Result.From<LibraryEntity?>(library));
_mockBookRepository.GetByIdAsync(bookId, shouldTrackEntities: false, cancellationToken: cancellationToken).Returns(Result.From<BookEntity?>(book));
_mockLibraryRepository.GetByIdAsync(book.LibraryId, shouldTrackEntities: false, cancellationToken: cancellationToken).Returns(Result.From<LibraryEntity?>(library));
_mockBookReadingService.GetResourceAsync(book.Id, book.LibraryId, book.Path, library.LibraryType, query.ResourceKey, shouldRenderPdfAsImages: false, cancellationToken).Returns(expectedResponse);
// Act
@@ -108,14 +111,16 @@ public class GetReadingResourceQueryHandlerTests
{
// Arrange
GetReadingResourceQuery query = _getReadingResourceQueryFixture.Create();
Guid libraryId = Guid.Parse(query.LibraryId!);
Guid bookId = Guid.Parse(query.BookId!);
CancellationToken cancellationToken = CancellationToken.None;
BookEntity book = _bookEntityFixture.Create(id: query.BookId);
BookEntity book = _bookEntityFixture.Create(id: bookId, libraryId: libraryId);
LibraryEntity library = _libraryEntityFixture.Create(id: book.LibraryId, libraryType: LibraryType.EBook);
UserSettingsEntity settings = _userSettingsEntityFixture.Create(userId: _userId, shouldRenderPdfAsImages: true);
ReadingResourceDataDto expectedResponse = _readingResourceDataDtoFixture.Create();
_mockUserSettingsRepository.GetByUserIdAsync(_userId, cancellationToken).Returns(Result.From<UserSettingsEntity?>(settings));
_mockBookRepository.GetByIdAsync(query.BookId, cancellationToken).Returns(Result.From<BookEntity?>(book));
_mockLibraryRepository.GetByIdAsync(book.LibraryId, cancellationToken).Returns(Result.From<LibraryEntity?>(library));
_mockBookRepository.GetByIdAsync(bookId, shouldTrackEntities: false, cancellationToken: cancellationToken).Returns(Result.From<BookEntity?>(book));
_mockLibraryRepository.GetByIdAsync(book.LibraryId, shouldTrackEntities: false, cancellationToken: cancellationToken).Returns(Result.From<LibraryEntity?>(library));
_mockBookReadingService.GetResourceAsync(book.Id, book.LibraryId, book.Path, library.LibraryType, query.ResourceKey, shouldRenderPdfAsImages: true, cancellationToken).Returns(expectedResponse);
// Act
@@ -131,7 +136,8 @@ public class GetReadingResourceQueryHandlerTests
{
// Arrange
GetReadingResourceQuery query = _getReadingResourceQueryFixture.Create();
_mockBookRepository.GetByIdAsync(query.BookId, Arg.Any<CancellationToken>()).Returns(Result.From<BookEntity?>(null));
Guid bookId = Guid.Parse(query.BookId!);
_mockBookRepository.GetByIdAsync(bookId, shouldTrackEntities: false, cancellationToken: Arg.Any<CancellationToken>()).Returns(Result.From<BookEntity?>(null));
// Act
Result<ReadingResourceDataDto> result = await _sut.HandleAsync(query, CancellationToken.None);
@@ -142,14 +148,35 @@ public class GetReadingResourceQueryHandlerTests
await _mockBookReadingService.DidNotReceive().GetResourceAsync(Arg.Any<Guid>(), Arg.Any<Guid>(), Arg.Any<string>(), Arg.Any<LibraryType>(), Arg.Any<string>(), Arg.Any<bool>(), Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenBookBelongsToAnotherLibrary_ShouldReturnBookNotFoundError()
{
// Arrange
GetReadingResourceQuery query = _getReadingResourceQueryFixture.Create();
Guid bookId = Guid.Parse(query.BookId!);
BookEntity book = _bookEntityFixture.Create(id: bookId, libraryId: Guid.NewGuid());
_mockBookRepository.GetByIdAsync(bookId, shouldTrackEntities: false, cancellationToken: Arg.Any<CancellationToken>()).Returns(Result.From<BookEntity?>(book));
// Act
Result<ReadingResourceDataDto> result = await _sut.HandleAsync(query, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(DomainErrors.Reading.BookNotFound, result.FirstError);
await _mockLibraryRepository.DidNotReceive().GetByIdAsync(Arg.Any<Guid>(), shouldTrackEntities: false, cancellationToken: Arg.Any<CancellationToken>());
await _mockBookReadingService.DidNotReceive().GetResourceAsync(Arg.Any<Guid>(), Arg.Any<Guid>(), Arg.Any<string>(), Arg.Any<LibraryType>(), Arg.Any<string>(), Arg.Any<bool>(), Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenLibraryDoesNotExist_ShouldReturnLibraryNotFoundError()
{
// Arrange
GetReadingResourceQuery query = _getReadingResourceQueryFixture.Create();
BookEntity book = _bookEntityFixture.Create(id: query.BookId);
_mockBookRepository.GetByIdAsync(query.BookId, Arg.Any<CancellationToken>()).Returns(Result.From<BookEntity?>(book));
_mockLibraryRepository.GetByIdAsync(book.LibraryId, Arg.Any<CancellationToken>()).Returns(Result.From<LibraryEntity?>(null));
Guid libraryId = Guid.Parse(query.LibraryId!);
Guid bookId = Guid.Parse(query.BookId!);
BookEntity book = _bookEntityFixture.Create(id: bookId, libraryId: libraryId);
_mockBookRepository.GetByIdAsync(bookId, shouldTrackEntities: false, cancellationToken: Arg.Any<CancellationToken>()).Returns(Result.From<BookEntity?>(book));
_mockLibraryRepository.GetByIdAsync(book.LibraryId, shouldTrackEntities: false, cancellationToken: Arg.Any<CancellationToken>()).Returns(Result.From<LibraryEntity?>(null));
// Act
Result<ReadingResourceDataDto> result = await _sut.HandleAsync(query, CancellationToken.None);
@@ -165,8 +192,10 @@ public class GetReadingResourceQueryHandlerTests
{
// Arrange
GetReadingResourceQuery query = _getReadingResourceQueryFixture.Create();
BookEntity book = _bookEntityFixture.Create(id: query.BookId);
_mockBookRepository.GetByIdAsync(query.BookId, Arg.Any<CancellationToken>()).Returns(Result.From<BookEntity?>(book));
Guid libraryId = Guid.Parse(query.LibraryId!);
Guid bookId = Guid.Parse(query.BookId!);
BookEntity book = _bookEntityFixture.Create(id: bookId, libraryId: libraryId);
_mockBookRepository.GetByIdAsync(bookId, shouldTrackEntities: false, cancellationToken: Arg.Any<CancellationToken>()).Returns(Result.From<BookEntity?>(book));
_mockAuthorizationService.EvaluatePolicyAsync<ILibraryOwnershipPolicy>(_userId, Arg.Any<LibraryOwnershipPolicyContext>(), Arg.Any<CancellationToken>())
.Returns(false);
@@ -192,7 +221,24 @@ public class GetReadingResourceQueryHandlerTests
// Assert
Assert.True(result.IsFailure);
Assert.Equal(ApplicationErrors.Authorization.NotAuthorized, result.FirstError);
await _mockBookRepository.DidNotReceive().GetByIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
await _mockBookRepository.DidNotReceive().GetByIdAsync(Arg.Any<Guid>(), shouldTrackEntities: false, cancellationToken: Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenRepositoryReturnsError_ShouldReturnFailureResult()
{
// Arrange
GetReadingResourceQuery query = _getReadingResourceQueryFixture.Create();
Guid bookId = Guid.Parse(query.BookId!);
_mockBookRepository.GetByIdAsync(bookId, shouldTrackEntities: false, cancellationToken: Arg.Any<CancellationToken>())
.Returns(Errors.Library.LibraryIdCannotBeEmpty);
// Act
Result<ReadingResourceDataDto> result = await _sut.HandleAsync(query, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(Errors.Library.LibraryIdCannotBeEmpty, result.FirstError);
}
[Fact]
@@ -208,7 +254,7 @@ public class GetReadingResourceQueryHandlerTests
// Assert
Assert.True(result.IsFailure);
Assert.Equal(Errors.Reading.ResourceKeyCannotBeEmpty, result.FirstError);
await _mockBookRepository.DidNotReceive().GetByIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
await _mockBookRepository.DidNotReceive().GetByIdAsync(Arg.Any<Guid>(), shouldTrackEntities: false, cancellationToken: Arg.Any<CancellationToken>());
await _mockBookReadingService.DidNotReceive().GetResourceAsync(Arg.Any<Guid>(), Arg.Any<Guid>(), Arg.Any<string>(), Arg.Any<LibraryType>(), Arg.Any<string>(), Arg.Any<bool>(), Arg.Any<CancellationToken>());
}
}
@@ -4,7 +4,6 @@ using Lumina.Application.Fixtures.Core.MediaLibrary.WrittenContentLibrary.BookLi
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
@@ -20,32 +19,6 @@ public class GetReadingResourceQueryValidatorTests
private readonly GetReadingResourceQueryValidator _validator = new();
private readonly GetReadingResourceQueryFixture _getReadingResourceQueryFixture = new();
[Fact]
public void Validate_WhenBookIdIsEmpty_ShouldHaveValidationError()
{
// Arrange
GetReadingResourceQuery query = _getReadingResourceQueryFixture.Create(bookId: Guid.Empty);
// Act
List<Error> result = _validator.TestValidate(query);
// Assert
result.ShouldHaveValidationError(Errors.Reading.BookIdCannotBeEmpty);
}
[Fact]
public void Validate_WhenResourceKeyIsEmpty_ShouldHaveValidationError()
{
// Arrange
GetReadingResourceQuery query = _getReadingResourceQueryFixture.Create(resourceKey: string.Empty);
// Act
List<Error> result = _validator.TestValidate(query);
// Assert
result.ShouldHaveValidationError(Errors.Reading.ResourceKeyCannotBeEmpty);
}
[Fact]
public void Validate_WhenQueryIsValid_ShouldNotHaveValidationError()
{
@@ -56,7 +29,57 @@ public class GetReadingResourceQueryValidatorTests
List<Error> result = _validator.TestValidate(query);
// Assert
result.ShouldNotHaveValidationError(Errors.Reading.BookIdCannotBeEmpty);
result.ShouldNotHaveValidationError(Errors.Library.LibraryIdCannotBeEmpty);
result.ShouldNotHaveValidationError(Errors.WrittenContent.BookIdCannotBeEmpty);
result.ShouldNotHaveValidationError(Errors.Reading.ResourceKeyCannotBeEmpty);
}
[Theory]
[InlineData(null)] // missing route value
[InlineData("")] // empty route value
[InlineData("not-a-library-guid")] // non-Guid route value
[InlineData("00000000-0000-0000-0000-000000000000")] // empty Guid route value
public void Validate_WhenLibraryIdIsEmptyOrInvalid_ShouldHaveValidationError(string? libraryId)
{
// Arrange
GetReadingResourceQuery query = _getReadingResourceQueryFixture.Create() with { LibraryId = libraryId };
// Act
List<Error> result = _validator.TestValidate(query);
// Assert
result.ShouldHaveValidationError(Errors.Library.LibraryIdCannotBeEmpty);
}
[Theory]
[InlineData(null)] // missing route value
[InlineData("")] // empty route value
[InlineData("not-a-guid")] // non-Guid route value
[InlineData("00000000-0000-0000-0000-000000000000")] // empty Guid route value
public void Validate_WhenBookIdIsEmptyOrInvalid_ShouldHaveValidationError(string? bookId)
{
// Arrange
GetReadingResourceQuery query = _getReadingResourceQueryFixture.Create() with { BookId = bookId };
// Act
List<Error> result = _validator.TestValidate(query);
// Assert
result.ShouldHaveValidationError(Errors.WrittenContent.BookIdCannotBeEmpty);
}
[Theory]
[InlineData(null)] // missing route value
[InlineData("")] // empty route value
public void Validate_WhenResourceKeyIsEmpty_ShouldHaveValidationError(string? resourceKey)
{
// Arrange
GetReadingResourceQuery query = _getReadingResourceQueryFixture.Create() with { ResourceKey = resourceKey };
// Act
List<Error> result = _validator.TestValidate(query);
// Assert
result.ShouldHaveValidationError(Errors.Reading.ResourceKeyCannotBeEmpty);
}
}
@@ -2,7 +2,7 @@
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.Common.DataAccess.Repositories.Books;
using Lumina.Application.Common.DataAccess.Repositories.BookLibrary;
using Lumina.Application.Common.DataAccess.Repositories.MediaLibrary;
using Lumina.Application.Common.DataAccess.Repositories.Users;
using Lumina.Application.Common.DataAccess.UoW;
@@ -63,6 +63,7 @@ public class GetReadingSectionQueryHandlerTests
_mockLibraryRepository = Substitute.For<ILibraryRepository>();
_mockUserSettingsRepository = Substitute.For<IUserSettingsRepository>();
_mockUnitOfWork = Substitute.For<IUnitOfWork>();
_mockUnitOfWork.SaveChangesAsync(Arg.Any<CancellationToken>()).Returns(Result.Success);
_mockUnitOfWork.BookRepository.Returns(_mockBookRepository);
_mockUnitOfWork.LibraryRepository.Returns(_mockLibraryRepository);
_mockUnitOfWork.UserSettingsRepository.Returns(_mockUserSettingsRepository);
@@ -87,12 +88,14 @@ public class GetReadingSectionQueryHandlerTests
{
// Arrange
GetReadingSectionQuery query = _getReadingSectionQueryFixture.Create();
Guid libraryId = Guid.Parse(query.LibraryId!);
Guid bookId = Guid.Parse(query.BookId!);
CancellationToken cancellationToken = CancellationToken.None;
BookEntity book = _bookEntityFixture.Create(id: query.BookId);
BookEntity book = _bookEntityFixture.Create(id: bookId, libraryId: libraryId);
LibraryEntity library = _libraryEntityFixture.Create(id: book.LibraryId, libraryType: LibraryType.EBook);
ReadingSectionDto expectedResponse = _readingSectionDtoFixture.Create(locationRef: query.LocationRef);
_mockBookRepository.GetByIdAsync(query.BookId, cancellationToken).Returns(Result.From<BookEntity?>(book));
_mockLibraryRepository.GetByIdAsync(book.LibraryId, cancellationToken).Returns(Result.From<LibraryEntity?>(library));
_mockBookRepository.GetByIdAsync(bookId, shouldTrackEntities: false, cancellationToken: cancellationToken).Returns(Result.From<BookEntity?>(book));
_mockLibraryRepository.GetByIdAsync(book.LibraryId, shouldTrackEntities: false, cancellationToken: cancellationToken).Returns(Result.From<LibraryEntity?>(library));
_mockBookReadingService.GetSectionAsync(book.Id, book.LibraryId, book.Path, library.LibraryType, query.LocationRef, shouldRenderPdfAsImages: false, shouldPreserveStyles: true, cancellationToken).Returns(expectedResponse);
// Act
@@ -108,14 +111,16 @@ public class GetReadingSectionQueryHandlerTests
{
// Arrange
GetReadingSectionQuery query = _getReadingSectionQueryFixture.Create();
Guid libraryId = Guid.Parse(query.LibraryId!);
Guid bookId = Guid.Parse(query.BookId!);
CancellationToken cancellationToken = CancellationToken.None;
BookEntity book = _bookEntityFixture.Create(id: query.BookId);
BookEntity book = _bookEntityFixture.Create(id: bookId, libraryId: libraryId);
LibraryEntity library = _libraryEntityFixture.Create(id: book.LibraryId, libraryType: LibraryType.EBook);
UserSettingsEntity settings = _userSettingsEntityFixture.Create(userId: _userId, shouldRenderPdfAsImages: true, shouldPreserveBookStyles: true);
ReadingSectionDto expectedResponse = _readingSectionDtoFixture.Create(locationRef: query.LocationRef);
_mockUserSettingsRepository.GetByUserIdAsync(_userId, cancellationToken).Returns(Result.From<UserSettingsEntity?>(settings));
_mockBookRepository.GetByIdAsync(query.BookId, cancellationToken).Returns(Result.From<BookEntity?>(book));
_mockLibraryRepository.GetByIdAsync(book.LibraryId, cancellationToken).Returns(Result.From<LibraryEntity?>(library));
_mockBookRepository.GetByIdAsync(bookId, shouldTrackEntities: false, cancellationToken: cancellationToken).Returns(Result.From<BookEntity?>(book));
_mockLibraryRepository.GetByIdAsync(book.LibraryId, shouldTrackEntities: false, cancellationToken: cancellationToken).Returns(Result.From<LibraryEntity?>(library));
_mockBookReadingService.GetSectionAsync(book.Id, book.LibraryId, book.Path, library.LibraryType, query.LocationRef, shouldRenderPdfAsImages: true, shouldPreserveStyles: true, cancellationToken).Returns(expectedResponse);
// Act
@@ -133,14 +138,16 @@ public class GetReadingSectionQueryHandlerTests
{
// Arrange
GetReadingSectionQuery query = _getReadingSectionQueryFixture.Create();
Guid libraryId = Guid.Parse(query.LibraryId!);
Guid bookId = Guid.Parse(query.BookId!);
CancellationToken cancellationToken = CancellationToken.None;
BookEntity book = _bookEntityFixture.Create(id: query.BookId);
BookEntity book = _bookEntityFixture.Create(id: bookId, libraryId: libraryId);
LibraryEntity library = _libraryEntityFixture.Create(id: book.LibraryId, libraryType: LibraryType.EBook);
UserSettingsEntity settings = _userSettingsEntityFixture.Create(userId: _userId, shouldRenderPdfAsImages: false, shouldPreserveBookStyles: shouldPreserveBookStyles);
ReadingSectionDto expectedResponse = _readingSectionDtoFixture.Create(locationRef: query.LocationRef);
_mockUserSettingsRepository.GetByUserIdAsync(_userId, cancellationToken).Returns(Result.From<UserSettingsEntity?>(settings));
_mockBookRepository.GetByIdAsync(query.BookId, cancellationToken).Returns(Result.From<BookEntity?>(book));
_mockLibraryRepository.GetByIdAsync(book.LibraryId, cancellationToken).Returns(Result.From<LibraryEntity?>(library));
_mockBookRepository.GetByIdAsync(bookId, shouldTrackEntities: false, cancellationToken: cancellationToken).Returns(Result.From<BookEntity?>(book));
_mockLibraryRepository.GetByIdAsync(book.LibraryId, shouldTrackEntities: false, cancellationToken: cancellationToken).Returns(Result.From<LibraryEntity?>(library));
_mockBookReadingService.GetSectionAsync(Arg.Any<Guid>(), Arg.Any<Guid>(), Arg.Any<string>(), Arg.Any<LibraryType>(), Arg.Any<string>(), Arg.Any<bool>(), Arg.Any<bool>(), Arg.Any<CancellationToken>()).Returns(expectedResponse);
// Act
@@ -157,12 +164,14 @@ public class GetReadingSectionQueryHandlerTests
{
// Arrange
GetReadingSectionQuery query = _getReadingSectionQueryFixture.Create();
Guid libraryId = Guid.Parse(query.LibraryId!);
Guid bookId = Guid.Parse(query.BookId!);
CancellationToken cancellationToken = CancellationToken.None;
BookEntity book = _bookEntityFixture.Create(id: query.BookId);
BookEntity book = _bookEntityFixture.Create(id: bookId, libraryId: libraryId);
LibraryEntity library = _libraryEntityFixture.Create(id: book.LibraryId, libraryType: LibraryType.EBook);
ReadingSectionDto expectedResponse = _readingSectionDtoFixture.Create(locationRef: query.LocationRef);
_mockBookRepository.GetByIdAsync(query.BookId, cancellationToken).Returns(Result.From<BookEntity?>(book));
_mockLibraryRepository.GetByIdAsync(book.LibraryId, cancellationToken).Returns(Result.From<LibraryEntity?>(library));
_mockBookRepository.GetByIdAsync(bookId, shouldTrackEntities: false, cancellationToken: cancellationToken).Returns(Result.From<BookEntity?>(book));
_mockLibraryRepository.GetByIdAsync(book.LibraryId, shouldTrackEntities: false, cancellationToken: cancellationToken).Returns(Result.From<LibraryEntity?>(library));
_mockBookReadingService.GetSectionAsync(Arg.Any<Guid>(), Arg.Any<Guid>(), Arg.Any<string>(), Arg.Any<LibraryType>(), Arg.Any<string>(), Arg.Any<bool>(), Arg.Any<bool>(), Arg.Any<CancellationToken>()).Returns(expectedResponse);
// Act
@@ -180,7 +189,8 @@ public class GetReadingSectionQueryHandlerTests
{
// Arrange
GetReadingSectionQuery query = _getReadingSectionQueryFixture.Create();
_mockBookRepository.GetByIdAsync(query.BookId, Arg.Any<CancellationToken>()).Returns(Result.From<BookEntity?>(null));
Guid bookId = Guid.Parse(query.BookId!);
_mockBookRepository.GetByIdAsync(bookId, shouldTrackEntities: false, cancellationToken: Arg.Any<CancellationToken>()).Returns(Result.From<BookEntity?>(null));
// Act
Result<ReadingSectionDto> result = await _sut.HandleAsync(query, CancellationToken.None);
@@ -191,14 +201,35 @@ public class GetReadingSectionQueryHandlerTests
await _mockBookReadingService.DidNotReceive().GetSectionAsync(Arg.Any<Guid>(), Arg.Any<Guid>(), Arg.Any<string>(), Arg.Any<LibraryType>(), Arg.Any<string>(), Arg.Any<bool>(), Arg.Any<bool>(), Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenBookBelongsToAnotherLibrary_ShouldReturnBookNotFoundError()
{
// Arrange
GetReadingSectionQuery query = _getReadingSectionQueryFixture.Create();
Guid bookId = Guid.Parse(query.BookId!);
BookEntity book = _bookEntityFixture.Create(id: bookId, libraryId: Guid.NewGuid());
_mockBookRepository.GetByIdAsync(bookId, shouldTrackEntities: false, cancellationToken: Arg.Any<CancellationToken>()).Returns(Result.From<BookEntity?>(book));
// Act
Result<ReadingSectionDto> result = await _sut.HandleAsync(query, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(DomainErrors.Reading.BookNotFound, result.FirstError);
await _mockLibraryRepository.DidNotReceive().GetByIdAsync(Arg.Any<Guid>(), shouldTrackEntities: false, cancellationToken: Arg.Any<CancellationToken>());
await _mockBookReadingService.DidNotReceive().GetSectionAsync(Arg.Any<Guid>(), Arg.Any<Guid>(), Arg.Any<string>(), Arg.Any<LibraryType>(), Arg.Any<string>(), Arg.Any<bool>(), Arg.Any<bool>(), Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenLibraryDoesNotExist_ShouldReturnLibraryNotFoundError()
{
// Arrange
GetReadingSectionQuery query = _getReadingSectionQueryFixture.Create();
BookEntity book = _bookEntityFixture.Create(id: query.BookId);
_mockBookRepository.GetByIdAsync(query.BookId, Arg.Any<CancellationToken>()).Returns(Result.From<BookEntity?>(book));
_mockLibraryRepository.GetByIdAsync(book.LibraryId, Arg.Any<CancellationToken>()).Returns(Result.From<LibraryEntity?>(null));
Guid libraryId = Guid.Parse(query.LibraryId!);
Guid bookId = Guid.Parse(query.BookId!);
BookEntity book = _bookEntityFixture.Create(id: bookId, libraryId: libraryId);
_mockBookRepository.GetByIdAsync(bookId, shouldTrackEntities: false, cancellationToken: Arg.Any<CancellationToken>()).Returns(Result.From<BookEntity?>(book));
_mockLibraryRepository.GetByIdAsync(book.LibraryId, shouldTrackEntities: false, cancellationToken: Arg.Any<CancellationToken>()).Returns(Result.From<LibraryEntity?>(null));
// Act
Result<ReadingSectionDto> result = await _sut.HandleAsync(query, CancellationToken.None);
@@ -214,8 +245,10 @@ public class GetReadingSectionQueryHandlerTests
{
// Arrange
GetReadingSectionQuery query = _getReadingSectionQueryFixture.Create();
BookEntity book = _bookEntityFixture.Create(id: query.BookId);
_mockBookRepository.GetByIdAsync(query.BookId, Arg.Any<CancellationToken>()).Returns(Result.From<BookEntity?>(book));
Guid libraryId = Guid.Parse(query.LibraryId!);
Guid bookId = Guid.Parse(query.BookId!);
BookEntity book = _bookEntityFixture.Create(id: bookId, libraryId: libraryId);
_mockBookRepository.GetByIdAsync(bookId, shouldTrackEntities: false, cancellationToken: Arg.Any<CancellationToken>()).Returns(Result.From<BookEntity?>(book));
_mockAuthorizationService.EvaluatePolicyAsync<ILibraryOwnershipPolicy>(_userId, Arg.Any<LibraryOwnershipPolicyContext>(), Arg.Any<CancellationToken>())
.Returns(false);
@@ -241,7 +274,24 @@ public class GetReadingSectionQueryHandlerTests
// Assert
Assert.True(result.IsFailure);
Assert.Equal(ApplicationErrors.Authorization.NotAuthorized, result.FirstError);
await _mockBookRepository.DidNotReceive().GetByIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
await _mockBookRepository.DidNotReceive().GetByIdAsync(Arg.Any<Guid>(), shouldTrackEntities: false, cancellationToken: Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenRepositoryReturnsError_ShouldReturnFailureResult()
{
// Arrange
GetReadingSectionQuery query = _getReadingSectionQueryFixture.Create();
Guid bookId = Guid.Parse(query.BookId!);
_mockBookRepository.GetByIdAsync(bookId, shouldTrackEntities: false, cancellationToken: Arg.Any<CancellationToken>())
.Returns(Errors.Library.LibraryIdCannotBeEmpty);
// Act
Result<ReadingSectionDto> result = await _sut.HandleAsync(query, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(Errors.Library.LibraryIdCannotBeEmpty, result.FirstError);
}
[Fact]
@@ -257,7 +307,7 @@ public class GetReadingSectionQueryHandlerTests
// Assert
Assert.True(result.IsFailure);
Assert.Equal(Errors.Reading.LocationRefCannotBeEmpty, result.FirstError);
await _mockBookRepository.DidNotReceive().GetByIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
await _mockBookRepository.DidNotReceive().GetByIdAsync(Arg.Any<Guid>(), shouldTrackEntities: false, cancellationToken: Arg.Any<CancellationToken>());
await _mockBookReadingService.DidNotReceive().GetSectionAsync(Arg.Any<Guid>(), Arg.Any<Guid>(), Arg.Any<string>(), Arg.Any<LibraryType>(), Arg.Any<string>(), Arg.Any<bool>(), Arg.Any<bool>(), Arg.Any<CancellationToken>());
}
}
@@ -4,7 +4,6 @@ using Lumina.Application.Fixtures.Core.MediaLibrary.WrittenContentLibrary.BookLi
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
@@ -20,32 +19,6 @@ public class GetReadingSectionQueryValidatorTests
private readonly GetReadingSectionQueryValidator _validator = new();
private readonly GetReadingSectionQueryFixture _getReadingSectionQueryFixture = new();
[Fact]
public void Validate_WhenBookIdIsEmpty_ShouldHaveValidationError()
{
// Arrange
GetReadingSectionQuery query = _getReadingSectionQueryFixture.Create(bookId: Guid.Empty);
// Act
List<Error> result = _validator.TestValidate(query);
// Assert
result.ShouldHaveValidationError(Errors.Reading.BookIdCannotBeEmpty);
}
[Fact]
public void Validate_WhenLocationRefIsEmpty_ShouldHaveValidationError()
{
// Arrange
GetReadingSectionQuery query = _getReadingSectionQueryFixture.Create(locationRef: string.Empty);
// Act
List<Error> result = _validator.TestValidate(query);
// Assert
result.ShouldHaveValidationError(Errors.Reading.LocationRefCannotBeEmpty);
}
[Fact]
public void Validate_WhenQueryIsValid_ShouldNotHaveValidationError()
{
@@ -56,7 +29,57 @@ public class GetReadingSectionQueryValidatorTests
List<Error> result = _validator.TestValidate(query);
// Assert
result.ShouldNotHaveValidationError(Errors.Reading.BookIdCannotBeEmpty);
result.ShouldNotHaveValidationError(Errors.Library.LibraryIdCannotBeEmpty);
result.ShouldNotHaveValidationError(Errors.WrittenContent.BookIdCannotBeEmpty);
result.ShouldNotHaveValidationError(Errors.Reading.LocationRefCannotBeEmpty);
}
[Theory]
[InlineData(null)] // missing route value
[InlineData("")] // empty route value
[InlineData("not-a-library-guid")] // non-Guid route value
[InlineData("00000000-0000-0000-0000-000000000000")] // empty Guid route value
public void Validate_WhenLibraryIdIsEmptyOrInvalid_ShouldHaveValidationError(string? libraryId)
{
// Arrange
GetReadingSectionQuery query = _getReadingSectionQueryFixture.Create() with { LibraryId = libraryId };
// Act
List<Error> result = _validator.TestValidate(query);
// Assert
result.ShouldHaveValidationError(Errors.Library.LibraryIdCannotBeEmpty);
}
[Theory]
[InlineData(null)] // missing route value
[InlineData("")] // empty route value
[InlineData("not-a-guid")] // non-Guid route value
[InlineData("00000000-0000-0000-0000-000000000000")] // empty Guid route value
public void Validate_WhenBookIdIsEmptyOrInvalid_ShouldHaveValidationError(string? bookId)
{
// Arrange
GetReadingSectionQuery query = _getReadingSectionQueryFixture.Create() with { BookId = bookId };
// Act
List<Error> result = _validator.TestValidate(query);
// Assert
result.ShouldHaveValidationError(Errors.WrittenContent.BookIdCannotBeEmpty);
}
[Theory]
[InlineData(null)] // missing route value
[InlineData("")] // empty route value
public void Validate_WhenLocationRefIsEmpty_ShouldHaveValidationError(string? locationRef)
{
// Arrange
GetReadingSectionQuery query = _getReadingSectionQueryFixture.Create() with { LocationRef = locationRef };
// Act
List<Error> result = _validator.TestValidate(query);
// Assert
result.ShouldHaveValidationError(Errors.Reading.LocationRefCannotBeEmpty);
}
}
@@ -45,6 +45,7 @@ public class SetLibraryBookReaderEnabledCommandHandlerTests
public SetLibraryBookReaderEnabledCommandHandlerTests()
{
_mockUnitOfWork = Substitute.For<IUnitOfWork>();
_mockUnitOfWork.SaveChangesAsync(Arg.Any<CancellationToken>()).Returns(Result.Success);
_mockLibraryBookReaderConfigurationRepository = Substitute.For<ILibraryBookReaderConfigurationRepository>();
_mockUnitOfWork.LibraryBookReaderConfigurationRepository.Returns(_mockLibraryBookReaderConfigurationRepository);
_mockAuthorizationService = Substitute.For<IAuthorizationService>();
@@ -2,6 +2,8 @@
using Lumina.Application.Common.DataAccess.Entities.Plugins;
using Lumina.Application.Common.DataAccess.Repositories.Plugins;
using Lumina.Application.Common.DataAccess.UoW;
using Lumina.Application.Common.DTO.Filtering;
using Lumina.Application.Common.DTO.Pagination;
using Lumina.Application.Common.Infrastructure.Authentication;
using Lumina.Application.Common.Infrastructure.Authorization;
using Lumina.Application.Common.Infrastructure.Authorization.Policies.LibraryOwnership;
@@ -49,6 +51,7 @@ public class GetLibraryBookReadersQueryHandlerTests
public GetLibraryBookReadersQueryHandlerTests()
{
_mockUnitOfWork = Substitute.For<IUnitOfWork>();
_mockUnitOfWork.SaveChangesAsync(Arg.Any<CancellationToken>()).Returns(Result.Success);
_mockLibraryBookReaderConfigurationRepository = Substitute.For<ILibraryBookReaderConfigurationRepository>();
_mockPluginRepository = Substitute.For<IPluginRepository>();
_mockUnitOfWork.LibraryBookReaderConfigurationRepository.Returns(_mockLibraryBookReaderConfigurationRepository);
@@ -104,7 +107,8 @@ public class GetLibraryBookReadersQueryHandlerTests
_pluginEntityFixture.Create(enabledPluginId, "A Reader"),
_pluginEntityFixture.Create(disabledPluginId, "B Reader")
];
_mockPluginRepository.GetAllAsync(Arg.Any<CancellationToken>()).Returns(plugins);
_mockPluginRepository.GetAllAsync<BaseFilterDto>(cancellationToken: Arg.Any<CancellationToken>())
.Returns(Result.From(new PaginatedResultDto<PluginEntity> { Data = plugins, CurrentPage = 1, PerPage = plugins.Count, Count = plugins.Count, NumberOfPages = 1 }));
Dictionary<Guid, IReadOnlyList<string>> supportedExtensions = new()
{
[enabledPluginId] = [".epub"],
@@ -138,8 +142,8 @@ public class GetLibraryBookReadersQueryHandlerTests
];
_mockLibraryBookReaderConfigurationRepository.GetByLibraryIdAsync(query.LibraryId, Arg.Any<CancellationToken>())
.Returns(Result.From<IReadOnlyList<LibraryBookReaderConfigurationEntity>>(configurations));
_mockPluginRepository.GetAllAsync(Arg.Any<CancellationToken>())
.Returns(Result.From<IEnumerable<PluginEntity>>([_pluginEntityFixture.Create()]));
_mockPluginRepository.GetAllAsync<BaseFilterDto>(cancellationToken: Arg.Any<CancellationToken>())
.Returns(Result.From(new PaginatedResultDto<PluginEntity> { Data = [_pluginEntityFixture.Create()], CurrentPage = 1, PerPage = 1, Count = 1, NumberOfPages = 1 }));
// Act
Result<IReadOnlyList<LibraryBookReaderResponse>> result = await _sut.HandleAsync(query, CancellationToken.None);
@@ -159,8 +163,8 @@ public class GetLibraryBookReadersQueryHandlerTests
GetLibraryBookReadersQuery query = _getLibraryBookReadersQueryFixture.Create();
_mockLibraryBookReaderConfigurationRepository.GetByLibraryIdAsync(query.LibraryId, Arg.Any<CancellationToken>())
.Returns(Result.From<IReadOnlyList<LibraryBookReaderConfigurationEntity>>([]));
_mockPluginRepository.GetAllAsync(Arg.Any<CancellationToken>())
.Returns(Result.From<IEnumerable<PluginEntity>>([]));
_mockPluginRepository.GetAllAsync<BaseFilterDto>(cancellationToken: Arg.Any<CancellationToken>())
.Returns(Result.From(new PaginatedResultDto<PluginEntity> { Data = [], CurrentPage = 1, PerPage = 0, Count = 0, NumberOfPages = 1 }));
// Act
Result<IReadOnlyList<LibraryBookReaderResponse>> result = await _sut.HandleAsync(query, CancellationToken.None);
@@ -184,7 +188,7 @@ public class GetLibraryBookReadersQueryHandlerTests
// Assert
Assert.True(result.IsFailure);
await _mockPluginRepository.DidNotReceive().GetAllAsync(Arg.Any<CancellationToken>());
await _mockPluginRepository.DidNotReceive().GetAllAsync<BaseFilterDto>(cancellationToken: Arg.Any<CancellationToken>());
}
[Fact]
@@ -194,7 +198,7 @@ public class GetLibraryBookReadersQueryHandlerTests
GetLibraryBookReadersQuery query = _getLibraryBookReadersQueryFixture.Create();
_mockLibraryBookReaderConfigurationRepository.GetByLibraryIdAsync(query.LibraryId, Arg.Any<CancellationToken>())
.Returns(Result.From<IReadOnlyList<LibraryBookReaderConfigurationEntity>>([]));
_mockPluginRepository.GetAllAsync(Arg.Any<CancellationToken>())
_mockPluginRepository.GetAllAsync<BaseFilterDto>(cancellationToken: Arg.Any<CancellationToken>())
.Returns(Error.Failure(description: "Failed to get plugins"));
// Act
@@ -219,7 +223,7 @@ public class GetLibraryBookReadersQueryHandlerTests
Assert.True(result.IsFailure);
Assert.Equal(ApplicationErrors.Authorization.NotAuthorized, result.FirstError);
await _mockLibraryBookReaderConfigurationRepository.DidNotReceive().GetByLibraryIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
await _mockPluginRepository.DidNotReceive().GetAllAsync(Arg.Any<CancellationToken>());
await _mockPluginRepository.DidNotReceive().GetAllAsync<BaseFilterDto>(cancellationToken: Arg.Any<CancellationToken>());
}
[Fact]
@@ -55,7 +55,7 @@ public class BookMetadataDtoTests
"1234567890",
"id12345",
[new IsbnDto("978-0-306-40615-7", IsbnFormat.Isbn13)],
[new MediaContributorDto(new MediaContributorNameDto("Frank Herbert", "Frank Herbert"), new MediaContributorRoleDto("Author", MediaContributorRoleCategory.Author))],
[new MediaContributorDto(new MediaContributorNameDto("Frank Herbert", "Frank Herbert"), MediaContributorRole.Author)],
[new BookRatingDto(4.5m, 5m, BookRatingSource.Goodreads, 1000)],
"https://example.com/dune.jpg"
);
@@ -1,49 +0,0 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Contracts.Fixtures.Core.Requests.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Reading;
using Lumina.Contracts.Requests.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Reading;
using System;
using System.Diagnostics.CodeAnalysis;
using System.Text.Json;
#endregion
namespace Lumina.Contracts.UnitTests.Requests.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Reading;
/// <summary>
/// Contains unit tests for the <see cref="GetReadingAvailabilityRequest"/> record.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetReadingAvailabilityRequestTests
{
private readonly GetReadingAvailabilityRequestFixture _getReadingAvailabilityRequestFixture = new();
private readonly JsonSerializerOptions _jsonOptions = new()
{
PropertyNameCaseInsensitive = true
};
[Fact]
public void Create_WhenCalled_ShouldReturnValidGetReadingAvailabilityRequest()
{
// Act
GetReadingAvailabilityRequest sut = _getReadingAvailabilityRequestFixture.Create();
// Assert
Assert.NotNull(sut);
Assert.NotEqual(Guid.Empty, sut.BookId);
}
[Fact]
public void RoundTrip_WhenSerializingGetReadingAvailabilityRequest_ShouldPreserveValues()
{
// Arrange
GetReadingAvailabilityRequest expected = _getReadingAvailabilityRequestFixture.Create();
// Act
string json = JsonSerializer.Serialize(expected, _jsonOptions);
GetReadingAvailabilityRequest? actual = JsonSerializer.Deserialize<GetReadingAvailabilityRequest>(json, _jsonOptions);
// Assert
Assert.NotNull(actual);
Assert.Equal(expected, actual);
}
}
@@ -1,49 +0,0 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Contracts.Fixtures.Core.Requests.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Reading;
using Lumina.Contracts.Requests.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Reading;
using System;
using System.Diagnostics.CodeAnalysis;
using System.Text.Json;
#endregion
namespace Lumina.Contracts.UnitTests.Requests.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Reading;
/// <summary>
/// Contains unit tests for the <see cref="GetReadingManifestRequest"/> record.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetReadingManifestRequestTests
{
private readonly GetReadingManifestRequestFixture _getReadingManifestRequestFixture = new();
private readonly JsonSerializerOptions _jsonOptions = new()
{
PropertyNameCaseInsensitive = true
};
[Fact]
public void Create_WhenCalled_ShouldReturnValidGetReadingManifestRequest()
{
// Act
GetReadingManifestRequest sut = _getReadingManifestRequestFixture.Create();
// Assert
Assert.NotNull(sut);
Assert.NotEqual(Guid.Empty, sut.BookId);
}
[Fact]
public void RoundTrip_WhenSerializingGetReadingManifestRequest_ShouldPreserveValues()
{
// Arrange
GetReadingManifestRequest expected = _getReadingManifestRequestFixture.Create();
// Act
string json = JsonSerializer.Serialize(expected, _jsonOptions);
GetReadingManifestRequest? actual = JsonSerializer.Deserialize<GetReadingManifestRequest>(json, _jsonOptions);
// Assert
Assert.NotNull(actual);
Assert.Equal(expected, actual);
}
}
@@ -1,50 +0,0 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Contracts.Fixtures.Core.Requests.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Reading;
using Lumina.Contracts.Requests.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Reading;
using System;
using System.Diagnostics.CodeAnalysis;
using System.Text.Json;
#endregion
namespace Lumina.Contracts.UnitTests.Requests.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Reading;
/// <summary>
/// Contains unit tests for the <see cref="GetReadingResourceRequest"/> record.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetReadingResourceRequestTests
{
private readonly GetReadingResourceRequestFixture _getReadingResourceRequestFixture = new();
private readonly JsonSerializerOptions _jsonOptions = new()
{
PropertyNameCaseInsensitive = true
};
[Fact]
public void Create_WhenCalled_ShouldReturnValidGetReadingResourceRequest()
{
// Act
GetReadingResourceRequest sut = _getReadingResourceRequestFixture.Create();
// Assert
Assert.NotNull(sut);
Assert.NotEqual(Guid.Empty, sut.BookId);
Assert.False(string.IsNullOrWhiteSpace(sut.ResourceKey));
}
[Fact]
public void RoundTrip_WhenSerializingGetReadingResourceRequest_ShouldPreserveValues()
{
// Arrange
GetReadingResourceRequest expected = _getReadingResourceRequestFixture.Create();
// Act
string json = JsonSerializer.Serialize(expected, _jsonOptions);
GetReadingResourceRequest? actual = JsonSerializer.Deserialize<GetReadingResourceRequest>(json, _jsonOptions);
// Assert
Assert.NotNull(actual);
Assert.Equal(expected, actual);
}
}
@@ -1,50 +0,0 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Contracts.Fixtures.Core.Requests.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Reading;
using Lumina.Contracts.Requests.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Reading;
using System;
using System.Diagnostics.CodeAnalysis;
using System.Text.Json;
#endregion
namespace Lumina.Contracts.UnitTests.Requests.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Reading;
/// <summary>
/// Contains unit tests for the <see cref="GetReadingSectionRequest"/> record.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetReadingSectionRequestTests
{
private readonly GetReadingSectionRequestFixture _getReadingSectionRequestFixture = new();
private readonly JsonSerializerOptions _jsonOptions = new()
{
PropertyNameCaseInsensitive = true
};
[Fact]
public void Create_WhenCalled_ShouldReturnValidGetReadingSectionRequest()
{
// Act
GetReadingSectionRequest sut = _getReadingSectionRequestFixture.Create();
// Assert
Assert.NotNull(sut);
Assert.NotEqual(Guid.Empty, sut.BookId);
Assert.False(string.IsNullOrWhiteSpace(sut.LocationRef));
}
[Fact]
public void RoundTrip_WhenSerializingGetReadingSectionRequest_ShouldPreserveValues()
{
// Arrange
GetReadingSectionRequest expected = _getReadingSectionRequestFixture.Create();
// Act
string json = JsonSerializer.Serialize(expected, _jsonOptions);
GetReadingSectionRequest? actual = JsonSerializer.Deserialize<GetReadingSectionRequest>(json, _jsonOptions);
// Assert
Assert.NotNull(actual);
Assert.Equal(expected, actual);
}
}
@@ -0,0 +1,49 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Contracts.Fixtures.Core.Responses.MediaLibrary.WrittenContentLibrary.BookLibrary.Books;
using Lumina.Contracts.Responses.MediaLibrary.WrittenContentLibrary.BookLibrary.Books;
using System.Diagnostics.CodeAnalysis;
using System.Text.Json;
#endregion
namespace Lumina.Contracts.UnitTests.Responses.MediaLibrary.WrittenContentLibrary.BookLibrary.Books;
/// <summary>
/// Contains unit tests for the <see cref="UpdateBookCoverResponse"/> record.
/// </summary>
[ExcludeFromCodeCoverage]
public class UpdateBookCoverResponseTests
{
private readonly UpdateBookCoverResponseFixture _updateBookCoverResponseFixture = new();
private readonly JsonSerializerOptions _jsonOptions = new()
{
PropertyNameCaseInsensitive = true
};
[Fact]
public void RoundTrip_WhenSerializingUpdateBookCoverResponse_ShouldPreserveValues()
{
// Arrange
UpdateBookCoverResponse expected = _updateBookCoverResponseFixture.Create();
// Act
string json = JsonSerializer.Serialize(expected, _jsonOptions);
UpdateBookCoverResponse? actual = JsonSerializer.Deserialize<UpdateBookCoverResponse>(json, _jsonOptions);
// Assert
Assert.NotNull(actual);
Assert.Equal(expected, actual);
}
[Fact]
public void Deconstruct_WhenCalled_ShouldReturnAllProperties()
{
// Arrange
UpdateBookCoverResponse sut = _updateBookCoverResponseFixture.Create();
// Act
sut.Deconstruct(out string coverPath);
// Assert
Assert.Equal(sut.CoverPath, coverPath);
}
}
@@ -11,7 +11,7 @@ using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaContributors;
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary;
using Lumina.Application.Fixtures.Common.DTO.Filtering;
using Lumina.Application.Fixtures.Common.DTO.Pagination;
using Lumina.DataAccess.Core.Repositories.Books;
using Lumina.DataAccess.Core.Repositories.BookLibrary;
using Lumina.DataAccess.Core.UoW;
using Lumina.Domain.Common.Errors;
using Lumina.Domain.Common.Primitives;
@@ -29,7 +29,7 @@ using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.DataAccess.UnitTests.Core.Repositories.Books;
namespace Lumina.DataAccess.UnitTests.Core.Repositories.BookLibrary;
/// <summary>
/// Contains unit tests for the <see cref="BookRepository"/> class.
@@ -441,7 +441,7 @@ public class BookRepositoryTests
.Include(book => book.Genres)
.Include(book => book.ISBNs)
.Include(book => book.Ratings)
.Include(book => book.BookContributors)
.Include(book => book.Contributors)
.FirstOrDefaultAsync(book => book.Id == storedBook.Id);
Assert.NotNull(retrievedBook);
Assert.Equal("Updated Title", retrievedBook!.Title);
@@ -455,6 +455,33 @@ public class BookRepositoryTests
Assert.Equal(storedCreatedBy, retrievedBook.CreatedBy);
}
[Fact]
public async Task UpdateAsync_WhenStoredBookHasArtwork_ShouldPreserveTheStoredArtwork()
{
// Arrange
BookEntity storedBook = _bookEntityFixture.Create();
storedBook.Artwork = [_bookArtworkEntityFixture.Create(bookId: storedBook.Id, artworkType: ArtworkType.Cover, ordinal: 0, status: ArtworkStatus.Enriched, fileName: "cover.jpg")];
_mockContext.Books.Add(storedBook);
await _mockContext.SaveChangesAsync();
BookEntity data = _bookEntityFixture.Create(id: storedBook.Id);
data.Title = "Updated Title";
// Act
Result<Updated> result = await _sut.UpdateAsync(data, CancellationToken.None);
await _mockContext.SaveChangesAsync();
// Assert
Assert.False(result.IsFailure);
BookEntity? retrievedBook = await _mockContext.Books
.Include(book => book.Artwork)
.FirstOrDefaultAsync(book => book.Id == storedBook.Id);
Assert.NotNull(retrievedBook);
BookArtworkEntity retrievedArtwork = Assert.Single(retrievedBook!.Artwork);
Assert.Equal("cover.jpg", retrievedArtwork.FileName);
Assert.Equal(ArtworkStatus.Enriched, retrievedArtwork.Status);
}
[Fact]
public async Task UpdateAsync_WhenDataContainsExistingTagAndGenreNames_ShouldReuseTheStoredTagAndGenreEntities()
{
@@ -498,14 +525,14 @@ public class BookRepositoryTests
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, role: MediaContributorRole.Author)];
storedBook.Contributors = [_bookContributorEntityFixture.Create(bookId: storedBook.Id, role: MediaContributorRole.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(), role: MediaContributorRole.Illustrator)];
data.Contributors = [_bookContributorEntityFixture.Create(bookId: storedBook.Id, mediaContributorId: Guid.NewGuid(), role: MediaContributorRole.Illustrator)];
// Act
Result<Updated> result = await _sut.UpdateAsync(data, CancellationToken.None);
@@ -516,12 +543,12 @@ public class BookRepositoryTests
BookEntity? retrievedBook = await _mockContext.Books
.Include(book => book.ISBNs)
.Include(book => book.Ratings)
.Include(book => book.BookContributors)
.Include(book => book.Contributors)
.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);
BookContributorEntity retrievedContributor = Assert.Single(retrievedBook.Contributors);
Assert.Equal("9780261102693", retrievedIsbn.Value);
Assert.Equal(3.5M, retrievedRating.Value);
Assert.Equal(MediaContributorRole.Illustrator, retrievedContributor.Role);
@@ -724,18 +751,18 @@ public class BookRepositoryTests
BookEntity bookWithoutCover = _bookEntityFixture.Create();
bookWithoutCover.LibraryId = libraryId;
bookWithoutCover.Path = "/books/a.epub";
bookWithoutCover.BookArtwork = [];
bookWithoutCover.Artwork = [];
BookEntity bookWithEnrichedCover = _bookEntityFixture.Create();
bookWithEnrichedCover.LibraryId = libraryId;
bookWithEnrichedCover.Path = "/books/b.epub";
bookWithEnrichedCover.BookArtwork = [_bookArtworkEntityFixture.Create(bookId: bookWithEnrichedCover.Id, artworkType: ArtworkType.Cover, ordinal: 0, status: ArtworkStatus.Enriched)];
bookWithEnrichedCover.Artwork = [_bookArtworkEntityFixture.Create(bookId: bookWithEnrichedCover.Id, artworkType: ArtworkType.Cover, ordinal: 0, status: ArtworkStatus.Enriched)];
BookEntity bookWithFailedCover = _bookEntityFixture.Create();
bookWithFailedCover.LibraryId = libraryId;
bookWithFailedCover.Path = "/books/c.epub";
bookWithFailedCover.BookArtwork = [_bookArtworkEntityFixture.Create(bookId: bookWithFailedCover.Id, artworkType: ArtworkType.Cover, ordinal: 0, status: ArtworkStatus.Failed)];
bookWithFailedCover.Artwork = [_bookArtworkEntityFixture.Create(bookId: bookWithFailedCover.Id, artworkType: ArtworkType.Cover, ordinal: 0, status: ArtworkStatus.Failed)];
BookEntity bookOfAnotherLibrary = _bookEntityFixture.Create();
bookOfAnotherLibrary.LibraryId = Guid.NewGuid();
bookOfAnotherLibrary.BookArtwork = [];
bookOfAnotherLibrary.Artwork = [];
_mockContext.Books.AddRange(bookWithoutCover, bookWithEnrichedCover, bookWithFailedCover, bookOfAnotherLibrary);
await _mockContext.SaveChangesAsync();
@@ -756,13 +783,13 @@ public class BookRepositoryTests
Guid libraryId = Guid.NewGuid();
BookEntity bookWithoutCover = _bookEntityFixture.Create();
bookWithoutCover.LibraryId = libraryId;
bookWithoutCover.BookArtwork = [];
bookWithoutCover.Artwork = [];
BookEntity bookWithEnrichedCover = _bookEntityFixture.Create();
bookWithEnrichedCover.LibraryId = libraryId;
bookWithEnrichedCover.BookArtwork = [_bookArtworkEntityFixture.Create(bookId: bookWithEnrichedCover.Id, artworkType: ArtworkType.Cover, ordinal: 0, status: ArtworkStatus.Enriched)];
bookWithEnrichedCover.Artwork = [_bookArtworkEntityFixture.Create(bookId: bookWithEnrichedCover.Id, artworkType: ArtworkType.Cover, ordinal: 0, status: ArtworkStatus.Enriched)];
BookEntity bookOfAnotherLibrary = _bookEntityFixture.Create();
bookOfAnotherLibrary.LibraryId = Guid.NewGuid();
bookOfAnotherLibrary.BookArtwork = [];
bookOfAnotherLibrary.Artwork = [];
_mockContext.Books.AddRange(bookWithoutCover, bookWithEnrichedCover, bookOfAnotherLibrary);
await _mockContext.SaveChangesAsync();
@@ -813,7 +840,7 @@ public class BookRepositoryTests
await _mockContext.SaveChangesAsync();
// Act
Result<Deleted> result = await _sut.DeleteAsync(book.Id, CancellationToken.None);
Result<Deleted> result = await _sut.DeleteByIdAsync(book.Id, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
@@ -827,7 +854,7 @@ public class BookRepositoryTests
public async Task DeleteAsync_WhenBookDoesNotExist_ShouldReturnError()
{
// Act
Result<Deleted> result = await _sut.DeleteAsync(Guid.NewGuid(), CancellationToken.None);
Result<Deleted> result = await _sut.DeleteByIdAsync(Guid.NewGuid(), CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
@@ -869,7 +896,7 @@ public class BookRepositoryTests
book.Tags = [_tagEntityFixture.Create(name: "Tag1"), _tagEntityFixture.Create(name: "Tag2")];
book.Genres = [_genreEntityFixture.Create(name: "Genre1"), _genreEntityFixture.Create(name: "Genre2")];
book.ISBNs = [_isbnEntityFixture.Create(value: "1234567890", format: IsbnFormat.Isbn10), _isbnEntityFixture.Create(value: "1234567890123", format: IsbnFormat.Isbn13)];
book.BookArtwork = [_bookArtworkEntityFixture.Create(bookId: book.Id, artworkType: ArtworkType.Cover, ordinal: 0, status: ArtworkStatus.Enriched)];
book.Artwork = [_bookArtworkEntityFixture.Create(bookId: book.Id, artworkType: ArtworkType.Cover, ordinal: 0, status: ArtworkStatus.Enriched)];
_mockContext.Books.Add(book);
await _mockContext.SaveChangesAsync();
@@ -882,7 +909,7 @@ public class BookRepositoryTests
Assert.Equal(2, retrievedBook.Tags.Count);
Assert.Equal(2, retrievedBook.Genres.Count);
Assert.Equal(2, retrievedBook.ISBNs.Count);
Assert.Single(retrievedBook.BookArtwork);
Assert.Single(retrievedBook.Artwork);
}
[Fact]
@@ -1320,7 +1347,7 @@ public class BookRepositoryTests
Guid libraryId = Guid.NewGuid();
BookEntity book = _bookEntityFixture.Create();
book.LibraryId = libraryId;
book.BookArtwork = [_bookArtworkEntityFixture.Create(bookId: book.Id, artworkType: ArtworkType.Cover, fileName: "cover.jpg")];
book.Artwork = [_bookArtworkEntityFixture.Create(bookId: book.Id, artworkType: ArtworkType.Cover, fileName: "cover.jpg")];
_mockContext.Books.Add(book);
await _mockContext.SaveChangesAsync();
@@ -1342,7 +1369,7 @@ public class BookRepositoryTests
Guid libraryId = Guid.NewGuid();
BookEntity book = _bookEntityFixture.Create();
book.LibraryId = libraryId;
book.BookArtwork = [];
book.Artwork = [];
_mockContext.Books.Add(book);
await _mockContext.SaveChangesAsync();
@@ -0,0 +1,190 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary;
using Lumina.Application.Common.DTO.Filtering;
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary;
using Lumina.DataAccess.Core.Repositories.BookLibrary.Specifications;
using Lumina.DataAccess.Core.UoW;
using Microsoft.Data.Sqlite;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
#endregion
namespace Lumina.DataAccess.UnitTests.Core.Repositories.BookLibrary.Specifications;
/// <summary>
/// Contains unit tests for the <see cref="BookAlphaFilterSpecification"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class BookAlphaFilterSpecificationTests : IDisposable
{
private readonly SqliteConnection _connection;
private readonly LuminaDbContext _context;
private readonly BookEntityFixture _bookEntityFixture = new();
/// <summary>
/// Initializes a new instance of the <see cref="BookAlphaFilterSpecificationTests"/> class.
/// </summary>
public BookAlphaFilterSpecificationTests()
{
// the specification translates to the SQLite glob() function, so it can only be exercised against a real SQLite database
_connection = new SqliteConnection("Data Source=:memory:");
_connection.Open();
_context = new LuminaDbContext(new DbContextOptionsBuilder<LuminaDbContext>().UseSqlite(_connection).Options);
_context.Database.EnsureCreated();
}
[Fact]
public void ToExpression_WhenAlphaKeyIsNull_ShouldMatchEveryBook()
{
// Arrange
List<BookEntity> books = SeedBooks(("Alpha", null), ("Beta", null), ("1984", null));
BookAlphaFilterSpecification specification = new(null, false);
// Act
List<BookEntity> result = [.. _context.Books.Where(specification.ToExpression())];
// Assert
Assert.Equal(books.Count, result.Count);
}
[Fact]
public void ToExpression_WhenAlphaKeyIsALowercaseLetter_ShouldMatchOnlyBooksWhoseTitleStartsWithIt()
{
// Arrange
SeedBooks(("Fellowship", null), ("Hobbit", null), ("The Two Towers", null));
BookAlphaFilterSpecification specification = new("f", false);
// Act
List<string> result = [.. _context.Books.Where(specification.ToExpression()).Select(book => book.Title)];
// Assert
Assert.Equal(["Fellowship"], result);
}
[Fact]
public void ToExpression_WhenAlphaKeyIsAnUppercaseLetter_ShouldMatchBooksWhoseTitleStartsWithItsLowercase()
{
// Arrange
SeedBooks(("Fellowship", null), ("Hobbit", null));
BookAlphaFilterSpecification specification = new("F", false);
// Act
List<string> result = [.. _context.Books.Where(specification.ToExpression()).Select(book => book.Title)];
// Assert
Assert.Equal(["Fellowship"], result);
}
[Fact]
public void ToExpression_WhenNoTitleStartsWithTheAlphaKey_ShouldNotMatchAnyBook()
{
// Arrange
SeedBooks(("Fellowship", null), ("Hobbit", null));
BookAlphaFilterSpecification specification = new("z", false);
// Act
List<BookEntity> result = [.. _context.Books.Where(specification.ToExpression())];
// Assert
Assert.Empty(result);
}
[Fact]
public void ToExpression_WhenAlphaKeyIsTheNumberKey_ShouldMatchOnlyBooksWhoseTitleStartsWithADigit()
{
// Arrange
SeedBooks(("1984", null), ("Alpha", null), ("Beta", null));
BookAlphaFilterSpecification specification = new(LibraryItemAlphaKeys.NUMBER, false);
// Act
List<string> result = [.. _context.Books.Where(specification.ToExpression()).Select(book => book.Title)];
// Assert
Assert.Equal(["1984"], result);
}
[Fact]
public void ToExpression_WhenAlphaKeyIsTheSymbolKey_ShouldMatchOnlyBooksWhoseTitleStartsWithASymbol()
{
// Arrange
SeedBooks(("!Important", null), ("1984", null), ("Alpha", null));
BookAlphaFilterSpecification specification = new(LibraryItemAlphaKeys.SYMBOL, false);
// Act
List<string> result = [.. _context.Books.Where(specification.ToExpression()).Select(book => book.Title)];
// Assert
Assert.Equal(["!Important"], result);
}
[Fact]
public void ToExpression_WhenTitleIsEmpty_ShouldMatchOnTheOriginalTitle()
{
// Arrange
BookEntity book = _bookEntityFixture.Create(title: string.Empty, originalTitle: "Rendezvous", includeMetadata: false);
_context.Books.Add(book);
_context.SaveChanges();
BookAlphaFilterSpecification specification = new("r", false);
// Act
List<string> result = [.. _context.Books.Where(specification.ToExpression()).Select(entity => entity.OriginalTitle!)];
// Assert
Assert.Equal(["Rendezvous"], result);
}
[Fact]
public void ToExpression_WhenIgnoringThePrefixAndTitleStartsWithThe_ShouldMatchOnTheStrippedTitle()
{
// Arrange
SeedBooks(("The Art of War", null), ("Beneath the Surface", null));
BookAlphaFilterSpecification specification = new("a", true);
// Act
List<string> result = [.. _context.Books.Where(specification.ToExpression()).Select(book => book.Title)];
// Assert
Assert.Equal(["The Art of War"], result);
}
[Fact]
public void ToExpression_WhenNotIgnoringThePrefixAndTitleStartsWithThe_ShouldNotMatchOnTheStrippedTitle()
{
// Arrange
SeedBooks(("The Art of War", null), ("Beneath the Surface", null));
BookAlphaFilterSpecification specification = new("a", false);
// Act
List<BookEntity> result = [.. _context.Books.Where(specification.ToExpression())];
// Assert
Assert.Empty(result);
}
/// <summary>
/// Seeds books with the provided titles.
/// </summary>
/// <param name="books">The title and original title pairs of the books to seed.</param>
/// <returns>The seeded <see cref="BookEntity"/> instances.</returns>
private List<BookEntity> SeedBooks(params (string Title, string? OriginalTitle)[] books)
{
List<BookEntity> entities = [];
foreach ((string title, string? originalTitle) in books)
entities.Add(_bookEntityFixture.Create(title: title, originalTitle: originalTitle, includeMetadata: false));
_context.Books.AddRange(entities);
_context.SaveChanges();
return entities;
}
/// <summary>
/// Disposes the database context and its underlying connection.
/// </summary>
public void Dispose()
{
_context.Dispose();
_connection.Dispose();
}
}
@@ -1,14 +1,14 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary;
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary;
using Lumina.DataAccess.Core.Repositories.Books.Specifications;
using Lumina.DataAccess.Core.Repositories.BookLibrary.Specifications;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
#endregion
namespace Lumina.DataAccess.UnitTests.Core.Repositories.Books.Specifications;
namespace Lumina.DataAccess.UnitTests.Core.Repositories.BookLibrary.Specifications;
/// <summary>
/// Contains unit tests for the <see cref="BookSearchSpecification"/> class.
@@ -1,9 +1,10 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Domain.Common.Primitives;
using Lumina.Domain.Core.BoundedContexts.MediaContributorBoundedContext.MediaContributorAggregate.ValueObjects;
using Lumina.Domain.Core.BoundedContexts.WrittenContentLibraryBoundedContext.BookLibraryAggregate;
using Lumina.Domain.Fixtures.Core.BoundedContexts.MediaContributorBoundedContext.MediaContributorAggregate.ValueObjects;
using Lumina.Domain.Core.BoundedContexts.WrittenContentLibraryBoundedContext.BookLibraryAggregate.ValueObjects;
using Lumina.Domain.Core.BoundedContexts.WrittenContentLibraryBoundedContext.ExternalIdentifiers.MediaContributorBoundedContext.MediaContributorAggregate;
using Lumina.Domain.Fixtures.Core.BoundedContexts.WrittenContentLibraryBoundedContext.BookLibraryAggregate;
using Lumina.Domain.SharedKernel.Common.Enums.MediaContributors;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
@@ -18,7 +19,6 @@ namespace Lumina.Domain.UnitTests.Core.BoundedContexts.WrittenContentLibraryBoun
public class BookTests
{
private readonly BookFixture _bookFixture = new();
private readonly MediaContributorIdFixture _mediaContributorIdFixture = new();
[Fact]
public void Create_WhenCalledWithValidData_ShouldCreateBook()
@@ -38,16 +38,16 @@ public class BookTests
{
// Arrange
Book book = _bookFixture.Create();
MediaContributorId firstContributorId = _mediaContributorIdFixture.Create();
MediaContributorId secondContributorId = _mediaContributorIdFixture.Create();
BookMediaContributor firstContributor = CreateAuthorContributor();
BookMediaContributor secondContributor = CreateAuthorContributor();
// Act
book.UpdateContributors([firstContributorId, secondContributorId]);
book.UpdateContributors([firstContributor, secondContributor]);
// Assert
Assert.Equal(2, book.Contributors.Count);
Assert.Contains(book.Contributors, contributorId => contributorId == firstContributorId);
Assert.Contains(book.Contributors, contributorId => contributorId == secondContributorId);
Assert.Contains(book.Contributors, contributor => contributor == firstContributor);
Assert.Contains(book.Contributors, contributor => contributor == secondContributor);
}
[Fact]
@@ -55,16 +55,45 @@ public class BookTests
{
// Arrange
Book book = _bookFixture.Create();
book.UpdateContributors([_mediaContributorIdFixture.Create()]);
MediaContributorId replacementContributorId = _mediaContributorIdFixture.Create();
book.UpdateContributors([CreateAuthorContributor()]);
BookMediaContributor replacementContributor = CreateAuthorContributor();
// Act
book.UpdateContributors([replacementContributorId]);
book.UpdateContributors([replacementContributor]);
// Assert
// the previous contributors are replaced, not appended
MediaContributorId contributorId = Assert.Single(book.Contributors);
Assert.Equal(replacementContributorId, contributorId);
BookMediaContributor contributor = Assert.Single(book.Contributors);
Assert.Equal(replacementContributor, contributor);
}
[Fact]
public void Create_WhenContributorsContainDuplicates_ShouldKeepOnlyUniqueContributors()
{
// Arrange
BookMediaContributor contributor = CreateAuthorContributor();
// Act
Book book = _bookFixture.Create(contributors: [contributor, contributor]);
// Assert
BookMediaContributor storedContributor = Assert.Single(book.Contributors);
Assert.Equal(contributor, storedContributor);
}
[Fact]
public void UpdateContributors_WhenCalledWithDuplicates_ShouldKeepOnlyUniqueContributors()
{
// Arrange
Book book = _bookFixture.Create();
BookMediaContributor contributor = CreateAuthorContributor();
// Act
book.UpdateContributors([contributor, contributor]);
// Assert
BookMediaContributor storedContributor = Assert.Single(book.Contributors);
Assert.Equal(contributor, storedContributor);
}
[Fact]
@@ -229,4 +258,13 @@ public class BookTests
Assert.False(hasMetadataProvider);
Assert.False(hasCoverImagePath);
}
/// <summary>
/// Creates a <see cref="BookMediaContributor"/> of a random media contributor playing the Author role.
/// </summary>
/// <returns>The created <see cref="BookMediaContributor"/>.</returns>
private static BookMediaContributor CreateAuthorContributor()
{
return BookMediaContributor.Create(MediaContributorId.CreateUnique(), MediaContributorRole.Author).Value;
}
}
@@ -1,24 +0,0 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Domain.Core.BoundedContexts.WrittenContentLibraryBoundedContext.BookLibraryAggregate.Services;
using System;
using System.Diagnostics.CodeAnalysis;
#endregion
namespace Lumina.Domain.UnitTests.Core.BoundedContexts.WrittenContentLibraryBoundedContext.BookLibraryAggregate.Services;
/// <summary>
/// Contains unit tests for the <see cref="BookLibraryService"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class BookLibraryServiceTests
{
[Fact]
public void Books_WhenAccessed_ShouldThrowNotImplementedException()
{
// Arrange
BookLibraryService sut = new();
// Act & Assert
Assert.Throws<NotImplementedException>(() => sut.Books);
}
}
@@ -1,72 +0,0 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Domain.Common.Primitives;
using Lumina.Domain.Core.BoundedContexts.WrittenContentLibraryBoundedContext.BookLibraryAggregate.ValueObjects;
using Lumina.Domain.Fixtures.Core.BoundedContexts.WrittenContentLibraryBoundedContext.BookLibraryAggregate.ValueObjects;
using System;
using System.Diagnostics.CodeAnalysis;
#endregion
namespace Lumina.Domain.UnitTests.Core.BoundedContexts.WrittenContentLibraryBoundedContext.BookLibraryAggregate.ValueObjects;
/// <summary>
/// Contains unit tests for the <see cref="BookLibraryId"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class BookLibraryIdTests
{
private readonly BookLibraryIdFixture _bookLibraryIdFixture = new();
[Fact]
public void CreateUnique_WhenCalled_ShouldReturnIdWithNonEmptyValue()
{
// Act
Result<BookLibraryId> result = BookLibraryId.CreateUnique();
// Assert
Assert.False(result.IsFailure);
Assert.NotEqual(default, result.Value.Value);
}
[Fact]
public void Create_WhenCalledWithValue_ShouldReturnIdWithThatValue()
{
// Arrange
Guid value = Guid.NewGuid();
// Act
Result<BookLibraryId> result = BookLibraryId.Create(value);
// Assert
Assert.False(result.IsFailure);
Assert.Equal(value, result.Value.Value);
}
[Fact]
public void Equals_WithSameValue_ShouldReturnTrue()
{
// Arrange
Guid value = Guid.NewGuid();
BookLibraryId firstId = _bookLibraryIdFixture.Create(value);
BookLibraryId secondId = _bookLibraryIdFixture.Create(value);
// Act
bool result = firstId.Equals(secondId);
// Assert
Assert.True(result);
}
[Fact]
public void Equals_WithDifferentValue_ShouldReturnFalse()
{
// Arrange
BookLibraryId firstId = _bookLibraryIdFixture.Create();
BookLibraryId secondId = _bookLibraryIdFixture.Create();
// Act
bool result = firstId.Equals(secondId);
// Assert
Assert.False(result);
}
}
@@ -58,6 +58,7 @@ public class BooksFileSystemDiscoveryJobTests
_mockServiceScope.ServiceProvider.Returns(_mockServiceProvider);
_mockUnitOfWork = Substitute.For<IUnitOfWork>();
_mockUnitOfWork.SaveChangesAsync(Arg.Any<CancellationToken>()).Returns(Result.Success);
_mockLibraryRepository = Substitute.For<ILibraryRepository>();
_mockStagingResultsRepository = Substitute.For<ILibraryScanStagingResultsRepository>();
_mockUnitOfWork.LibraryRepository.Returns(_mockLibraryRepository);
@@ -84,7 +85,7 @@ public class BooksFileSystemDiscoveryJobTests
public async Task ExecuteAsync_WhenGettingTheLibraryFails_ShouldMarkJobAsFailedAndPublishFailureEvent()
{
// Arrange
_mockLibraryRepository.GetByIdAsync(_libraryId.Value, Arg.Any<CancellationToken>())
_mockLibraryRepository.GetByIdAsync(_libraryId.Value, cancellationToken: Arg.Any<CancellationToken>())
.Returns(Error.Failure("Database.Error", "Failed to retrieve the library"));
// Act
@@ -103,7 +104,7 @@ public class BooksFileSystemDiscoveryJobTests
public async Task ExecuteAsync_WhenLibraryDoesNotExist_ShouldMarkJobAsFailedAndPublishFailureEvent()
{
// Arrange
_mockLibraryRepository.GetByIdAsync(_libraryId.Value, Arg.Any<CancellationToken>())
_mockLibraryRepository.GetByIdAsync(_libraryId.Value, cancellationToken: Arg.Any<CancellationToken>())
.Returns(Result.From<LibraryEntity?>(null));
// Act
@@ -58,6 +58,7 @@ public class BookReadingServiceTests
_mockPluginManager.GetPlugins().Returns([_mockPlugin]);
_mockUnitOfWork = Substitute.For<IUnitOfWork>();
_mockUnitOfWork.SaveChangesAsync(Arg.Any<CancellationToken>()).Returns(Result.Success);
_mockConfigurationRepository = Substitute.For<ILibraryBookReaderConfigurationRepository>();
_mockUnitOfWork.LibraryBookReaderConfigurationRepository.Returns(_mockConfigurationRepository);
LibraryBookReaderConfigurationEntity enabledConfiguration = _configurationEntityFixture.Create(libraryId: _libraryId, pluginId: _pluginId, isEnabled: true);
@@ -210,33 +210,27 @@ public class CalibreMapperTests
MediaContributorDto author = result.Contributors[0];
Assert.Equal("Test Author", author.Name!.DisplayName);
Assert.Equal("Author", author.Role!.Name);
Assert.Equal(MediaContributorRoleCategory.Author, author.Role.Category);
Assert.Equal(MediaContributorRole.Author, author.Role);
MediaContributorDto coAuthor = result.Contributors[1];
Assert.Equal("Co Author", coAuthor.Name!.DisplayName);
Assert.Equal("Author", coAuthor.Role!.Name);
Assert.Equal(MediaContributorRoleCategory.Author, coAuthor.Role.Category);
Assert.Equal(MediaContributorRole.Author, coAuthor.Role);
MediaContributorDto translator = result.Contributors[2];
Assert.Equal("Test Translator", translator.Name!.DisplayName);
Assert.Equal("trl", translator.Role!.Name);
Assert.Equal(MediaContributorRoleCategory.Translator, translator.Role.Category);
Assert.Equal(MediaContributorRole.Translator, translator.Role);
MediaContributorDto illustrator = result.Contributors[3];
Assert.Equal("Test Illustrator", illustrator.Name!.DisplayName);
Assert.Equal("ill", illustrator.Role!.Name);
Assert.Equal(MediaContributorRoleCategory.Illustrator, illustrator.Role.Category);
Assert.Equal(MediaContributorRole.Illustrator, illustrator.Role);
MediaContributorDto production = result.Contributors[4];
Assert.Equal("calibre (3.48.0) [https://calibre-ebook.com]", production.Name!.DisplayName);
Assert.Equal("bkp", production.Role!.Name);
Assert.Equal(MediaContributorRoleCategory.Publisher, production.Role.Category);
Assert.Equal(MediaContributorRole.Publisher, production.Role);
MediaContributorDto misc = result.Contributors[5];
Assert.Equal("Misc Contributor", misc.Name!.DisplayName);
Assert.Equal("Contributor", misc.Role!.Name);
Assert.Equal(MediaContributorRoleCategory.Other, misc.Role.Category);
Assert.Equal(MediaContributorRole.Other, misc.Role);
}
[Fact]
@@ -170,20 +170,18 @@ public class OpenLibraryMapperTests
oclc: ["123456789"]);
// Act
AddBookRequest result = OpenLibraryMapper.MapSearchCandidate(lookup, document);
BookMetadataDto result = OpenLibraryMapper.MapSearchCandidate(lookup, document);
// Assert
Assert.Equal(lookup.LibraryId, result.LibraryId);
Assert.Equal(lookup.Path, result.Path);
Assert.Equal("Search Title", result.Metadata!.Title);
Assert.Equal(2003, result.Metadata.ReleaseInfo!.OriginalReleaseYear);
Assert.Equal("Search Publisher", result.Metadata.Publisher);
Assert.Equal(250, result.Metadata.PageCount);
Assert.Contains(result.Metadata.Genres!, genre => genre.Name == "Science fiction");
Assert.DoesNotContain(result.Metadata.Genres!, genre => genre.Name == "Space");
Assert.Contains(result.Metadata.Tags!, tag => tag.Name == "Science fiction");
Assert.Contains(result.Metadata.Tags!, tag => tag.Name == "Space");
Assert.Null(result.Metadata.ReleaseInfo.ReleaseCountry);
Assert.Equal("Search Title", result.Title);
Assert.Equal(2003, result.ReleaseInfo!.OriginalReleaseYear);
Assert.Equal("Search Publisher", result.Publisher);
Assert.Equal(250, result.PageCount);
Assert.Contains(result.Genres!, genre => genre.Name == "Science fiction");
Assert.DoesNotContain(result.Genres!, genre => genre.Name == "Space");
Assert.Contains(result.Tags!, tag => tag.Name == "Science fiction");
Assert.Contains(result.Tags!, tag => tag.Name == "Space");
Assert.Null(result.ReleaseInfo.ReleaseCountry);
BookRatingDto rating = Assert.Single(result.Ratings!);
Assert.Equal(4.1m, rating.Value);
Assert.Equal(5m, rating.MaxValue);
@@ -192,8 +190,8 @@ public class OpenLibraryMapperTests
Assert.Equal("79042755", result.LCCN);
Assert.Equal("123456789", result.OCLCNumber);
Assert.Equal("OL12345W", result.OpenLibraryId);
Assert.Contains(result.ISBNs!, isbn => isbn.Value == "9780306406157" && isbn.Format == IsbnFormat.Isbn13);
Assert.Contains(result.Contributors!, contributor => contributor.Name!.DisplayName == "Search Author" && contributor.Role!.Name == "Author");
Assert.Contains(result.Isbns!, isbn => isbn.Value == "9780306406157" && isbn.Format == IsbnFormat.Isbn13);
Assert.Contains(result.Contributors!, contributor => contributor.Name!.DisplayName == "Search Author" && contributor.Role == MediaContributorRole.Author);
}
[Fact]
@@ -235,33 +233,31 @@ public class OpenLibraryMapperTests
OpenLibraryRatingsResponse ratings = _ratingsResponseFixture.Create(_ratingSummaryResponseFixture.Create(average: 4.2m, count: 100));
// Act
AddBookRequest result = OpenLibraryMapper.MapDetailed(lookup, edition, work, [author], ratings);
BookMetadataDto result = OpenLibraryMapper.MapDetailed(lookup, edition, work, [author], ratings);
// Assert
Assert.Equal(lookup.LibraryId, result.LibraryId);
Assert.Equal(lookup.Path, result.Path);
Assert.Equal("Edition Title", result.Metadata!.Title);
Assert.Equal("Original Title", result.Metadata.OriginalTitle);
Assert.Equal("A work description", result.Metadata.Description);
Assert.Equal(new DateOnly(1987, 6, 1), result.Metadata.ReleaseInfo!.OriginalReleaseDate);
Assert.Equal(1987, result.Metadata.ReleaseInfo.OriginalReleaseYear);
Assert.Equal(new DateOnly(2010, 5, 1), result.Metadata.ReleaseInfo.ReReleaseDate);
Assert.Equal(2010, result.Metadata.ReleaseInfo.ReReleaseYear);
Assert.Null(result.Metadata.ReleaseInfo.ReleaseCountry);
Assert.Equal("First Edition", result.Metadata.ReleaseInfo.ReleaseVersion);
GenreDto genre = Assert.Single(result.Metadata.Genres!);
Assert.Equal("Edition Title", result.Title);
Assert.Equal("Original Title", result.OriginalTitle);
Assert.Equal("A work description", result.Description);
Assert.Equal(new DateOnly(1987, 6, 1), result.ReleaseInfo!.OriginalReleaseDate);
Assert.Equal(1987, result.ReleaseInfo.OriginalReleaseYear);
Assert.Equal(new DateOnly(2010, 5, 1), result.ReleaseInfo.ReReleaseDate);
Assert.Equal(2010, result.ReleaseInfo.ReReleaseYear);
Assert.Null(result.ReleaseInfo.ReleaseCountry);
Assert.Equal("First Edition", result.ReleaseInfo.ReleaseVersion);
GenreDto genre = Assert.Single(result.Genres!);
Assert.Equal("Fantasy", genre.Name);
Assert.Equal(3, result.Metadata.Tags!.Count);
Assert.Contains(result.Metadata.Tags, tag => tag.Name == "Science fiction");
Assert.Contains(result.Metadata.Tags, tag => tag.Name == "History");
Assert.Contains(result.Metadata.Tags, tag => tag.Name == "Space");
Assert.Equal("en", result.Metadata.Language!.LanguageCode);
Assert.False(string.IsNullOrWhiteSpace(result.Metadata.Language.LanguageName));
Assert.Equal("fre", result.Metadata.OriginalLanguage!.LanguageCode);
Assert.Equal("fre", result.Metadata.OriginalLanguage.LanguageName);
Assert.Null(result.Metadata.OriginalLanguage.NativeName);
Assert.Equal("Publisher Co", result.Metadata.Publisher);
Assert.Equal(320, result.Metadata.PageCount);
Assert.Equal(3, result.Tags!.Count);
Assert.Contains(result.Tags, tag => tag.Name == "Science fiction");
Assert.Contains(result.Tags, tag => tag.Name == "History");
Assert.Contains(result.Tags, tag => tag.Name == "Space");
Assert.Equal("en", result.Language!.LanguageCode);
Assert.False(string.IsNullOrWhiteSpace(result.Language.LanguageName));
Assert.Equal("fre", result.OriginalLanguage!.LanguageCode);
Assert.Equal("fre", result.OriginalLanguage.LanguageName);
Assert.Null(result.OriginalLanguage.NativeName);
Assert.Equal("Publisher Co", result.Publisher);
Assert.Equal(320, result.PageCount);
Assert.Equal(BookFormat.Hardcover, result.Format);
Assert.Equal("First Edition", result.Edition);
Assert.Equal(3, result.VolumeNumber);
@@ -275,10 +271,10 @@ public class OpenLibraryMapperTests
Assert.Equal("gid", result.GoogleBooksId);
Assert.Equal("bnid", result.BarnesAndNobleId);
Assert.Equal("apid", result.AppleBooksId);
Assert.Contains(result.ISBNs!, isbn => isbn.Value == "9780306406157" && isbn.Format == IsbnFormat.Isbn13);
Assert.Contains(result.ISBNs!, isbn => isbn.Value == "0306406152" && isbn.Format == IsbnFormat.Isbn10);
Assert.Contains(result.Contributors!, contributor => contributor.Name!.DisplayName == "Test Author" && contributor.Name.LegalName == "Test Personal Name" && contributor.Role!.Name == "Author");
Assert.Contains(result.Contributors!, contributor => contributor.Name!.DisplayName == "John Smith" && contributor.Role!.Name == "Illustrator" && contributor.Role.Category == MediaContributorRoleCategory.Illustrator);
Assert.Contains(result.Isbns!, isbn => isbn.Value == "9780306406157" && isbn.Format == IsbnFormat.Isbn13);
Assert.Contains(result.Isbns!, isbn => isbn.Value == "0306406152" && isbn.Format == IsbnFormat.Isbn10);
Assert.Contains(result.Contributors!, contributor => contributor.Name!.DisplayName == "Test Author" && contributor.Name.LegalName == "Test Personal Name" && contributor.Role == MediaContributorRole.Author);
Assert.Contains(result.Contributors!, contributor => contributor.Name!.DisplayName == "John Smith" && contributor.Role == MediaContributorRole.Illustrator);
BookRatingDto mappedRating = Assert.Single(result.Ratings!);
Assert.Equal(4.2m, mappedRating.Value);
Assert.Equal(5m, mappedRating.MaxValue);
@@ -294,13 +290,13 @@ public class OpenLibraryMapperTests
OpenLibraryWorkResponse work = _workResponseFixture.Create(subjects: ["Science fiction", "History", "Space"]);
// Act
AddBookRequest result = OpenLibraryMapper.MapDetailed(lookup, null, work, [], null);
BookMetadataDto result = OpenLibraryMapper.MapDetailed(lookup, null, work, [], null);
// Assert
Assert.Equal(2, result.Metadata!.Genres!.Count);
Assert.Contains(result.Metadata.Genres, genre => genre.Name == "Science fiction");
Assert.Contains(result.Metadata.Genres, genre => genre.Name == "History");
Assert.DoesNotContain(result.Metadata.Genres, genre => genre.Name == "Space");
Assert.Equal(2, result.Genres!.Count);
Assert.Contains(result.Genres, genre => genre.Name == "Science fiction");
Assert.Contains(result.Genres, genre => genre.Name == "History");
Assert.DoesNotContain(result.Genres, genre => genre.Name == "Space");
}
[Fact]
@@ -311,11 +307,11 @@ public class OpenLibraryMapperTests
OpenLibrarySearchDocumentResponse fallback = _searchDocumentResponseFixture.Create(firstPublishYear: 2001);
// Act
AddBookRequest result = OpenLibraryMapper.MapDetailed(lookup, null, null, [], null, fallback);
BookMetadataDto result = OpenLibraryMapper.MapDetailed(lookup, null, null, [], null, fallback);
// Assert
Assert.Equal(2001, result.Metadata!.ReleaseInfo!.OriginalReleaseYear);
Assert.Null(result.Metadata.ReleaseInfo.OriginalReleaseDate);
Assert.Equal(2001, result.ReleaseInfo!.OriginalReleaseYear);
Assert.Null(result.ReleaseInfo.OriginalReleaseDate);
}
[Fact]
@@ -326,13 +322,13 @@ public class OpenLibraryMapperTests
OpenLibraryEditionResponse edition = _editionResponseFixture.Create(languages: [_keyReferenceResponseFixture.Create(key: "/languages/xxq")]);
// Act
AddBookRequest result = OpenLibraryMapper.MapDetailed(lookup, edition, null, [], null);
BookMetadataDto result = OpenLibraryMapper.MapDetailed(lookup, edition, null, [], null);
// Assert
Assert.NotNull(result.Metadata!.Language);
Assert.Equal("xxq", result.Metadata.Language!.LanguageCode);
Assert.Equal("xxq", result.Metadata.Language.LanguageName);
Assert.Null(result.Metadata.Language.NativeName);
Assert.NotNull(result.Language);
Assert.Equal("xxq", result.Language!.LanguageCode);
Assert.Equal("xxq", result.Language.LanguageName);
Assert.Null(result.Language.NativeName);
}
[Fact]
@@ -343,10 +339,10 @@ public class OpenLibraryMapperTests
OpenLibraryWorkResponse work = _workResponseFixture.Create(description: JsonDocument.Parse("\"A plain description\"").RootElement);
// Act
AddBookRequest result = OpenLibraryMapper.MapDetailed(lookup, null, work, [], null);
BookMetadataDto result = OpenLibraryMapper.MapDetailed(lookup, null, work, [], null);
// Assert
Assert.Equal("A plain description", result.Metadata!.Description);
Assert.Equal("A plain description", result.Description);
}
[Fact]
@@ -356,17 +352,15 @@ public class OpenLibraryMapperTests
BookMetadataLookupDto lookup = _bookMetadataLookupDtoFixture.Create(isbn: "978-0-306-40615-7");
// Act
AddBookRequest result = OpenLibraryMapper.MapDetailed(lookup, null, null, [], null, null);
BookMetadataDto result = OpenLibraryMapper.MapDetailed(lookup, null, null, [], null, null);
// Assert
Assert.Equal(lookup.LibraryId, result.LibraryId);
Assert.Equal(lookup.Path, result.Path);
Assert.NotNull(result.Metadata);
Assert.Null(result.Metadata!.Title);
Assert.NotNull(result);
Assert.Null(result.Title);
Assert.Null(result.Format);
Assert.Null(result.Edition);
Assert.Null(result.OpenLibraryId);
Assert.Contains(result.ISBNs!, isbn => isbn.Value == "9780306406157");
Assert.Contains(result.Isbns!, isbn => isbn.Value == "9780306406157");
Assert.Empty(result.Ratings!);
Assert.Empty(result.Contributors!);
}
@@ -379,7 +373,7 @@ public class OpenLibraryMapperTests
OpenLibrarySearchDocumentResponse fallback = _searchDocumentResponseFixture.Create(ratingsAverage: 3.5m, ratingsCount: 10);
// Act
AddBookRequest result = OpenLibraryMapper.MapDetailed(lookup, null, null, [], null, fallback);
BookMetadataDto result = OpenLibraryMapper.MapDetailed(lookup, null, null, [], null, fallback);
// Assert
BookRatingDto rating = Assert.Single(result.Ratings!);
@@ -395,7 +389,7 @@ public class OpenLibraryMapperTests
OpenLibraryEditionResponse edition = _editionResponseFixture.Create(series: ["Book 2 of the trilogy"]);
// Act
AddBookRequest result = OpenLibraryMapper.MapDetailed(lookup, edition, null, [], null);
BookMetadataDto result = OpenLibraryMapper.MapDetailed(lookup, edition, null, [], null);
// Assert
Assert.Equal(2, result.VolumeNumber);
@@ -420,7 +414,7 @@ public class OpenLibraryMapperTests
oclc: ["888888"]);
// Act
AddBookRequest result = OpenLibraryMapper.MapDetailed(lookup, edition, null, [], null, fallback);
BookMetadataDto result = OpenLibraryMapper.MapDetailed(lookup, edition, null, [], null, fallback);
// Assert
Assert.Equal("B000002", result.ASIN);
@@ -339,12 +339,12 @@ public class OpenLibraryBookMetadataProviderTests
OpenLibraryBookMetadataProvider sut = CreateProvider(handler);
// Act
AddBookRequest? result = await sut.GetBookAsync(lookup);
BookMetadataDto? result = await sut.GetBookAsync(lookup);
// Assert
Assert.NotNull(result);
Assert.Equal("Edition Title", result!.Metadata!.Title);
Assert.Equal("A work description", result.Metadata.Description);
Assert.Equal("Edition Title", result.Title);
Assert.Equal("A work description", result.Description);
Assert.Equal("OL100M", result.OpenLibraryId);
Assert.Equal(BookFormat.Hardcover, result.Format);
Assert.Equal(3, result.VolumeNumber);
@@ -370,11 +370,11 @@ public class OpenLibraryBookMetadataProviderTests
OpenLibraryBookMetadataProvider sut = CreateProvider(handler);
// Act
AddBookRequest? result = await sut.GetBookAsync(lookup);
BookMetadataDto? result = await sut.GetBookAsync(lookup);
// Assert
Assert.NotNull(result);
Assert.Equal("Work Title", result!.Metadata!.Title);
Assert.Equal("Work Title", result.Title);
Assert.Equal("OL200W", result.OpenLibraryId);
}
@@ -389,11 +389,11 @@ public class OpenLibraryBookMetadataProviderTests
OpenLibraryBookMetadataProvider sut = CreateProvider(handler);
// Act
AddBookRequest? result = await sut.GetBookAsync(lookup);
BookMetadataDto? result = await sut.GetBookAsync(lookup);
// Assert
Assert.NotNull(result);
Assert.Equal("Fallback Edition", result!.Metadata!.Title);
Assert.Equal("Fallback Edition", result.Title);
Assert.Equal("OL600M", result.OpenLibraryId);
Assert.Contains(handler.Requests, request => request.RequestUri!.AbsolutePath == "/books/OL600M.json");
}
@@ -408,7 +408,7 @@ public class OpenLibraryBookMetadataProviderTests
OpenLibraryBookMetadataProvider sut = CreateProvider(handler);
// Act
AddBookRequest? result = await sut.GetBookAsync(lookup);
BookMetadataDto? result = await sut.GetBookAsync(lookup);
// Assert
Assert.Null(result);
@@ -6,6 +6,7 @@ using Lumina.Contracts.Fixtures.Core.Requests.MediaLibrary.WrittenContentLibrary
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.Errors;
using Lumina.Domain.Common.Primitives;
using Lumina.Presentation.Api.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.Books.AddBook;
using Microsoft.AspNetCore.Http;
@@ -49,7 +50,7 @@ public class AddBookEndpointTests
BookResponse expectedResponse = _bookResponseFixture.Create();
_mockHandler.HandleAsync(Arg.Any<AddBookCommand>(), Arg.Any<CancellationToken>())
.Returns(Result.From(expectedResponse));
ConfigureRequest(libraryId.ToString());
_sut.HttpContext.Request.RouteValues["libraryId"] = libraryId.ToString();
// Act
IResult result = await _sut.ExecuteAsync(request, cancellationToken);
@@ -86,7 +87,7 @@ public class AddBookEndpointTests
}
[Fact]
public async Task ExecuteAsync_WhenCalled_ShouldSendAddBookCommandToHandler()
public async Task ExecuteAsync_WhenCalled_ShouldSendAddBookCommandToSender()
{
// Arrange
Guid libraryId = Guid.NewGuid();
@@ -94,7 +95,7 @@ public class AddBookEndpointTests
CancellationToken cancellationToken = CancellationToken.None;
_mockHandler.HandleAsync(Arg.Any<AddBookCommand>(), Arg.Any<CancellationToken>())
.Returns(Result.From(_bookResponseFixture.Create()));
ConfigureRequest(libraryId.ToString());
_sut.HttpContext.Request.RouteValues["libraryId"] = libraryId.ToString();
// Act
await _sut.ExecuteAsync(request, cancellationToken);
@@ -142,10 +143,10 @@ public class AddBookEndpointTests
Guid libraryId = Guid.NewGuid();
AddBookRequest request = _addBookRequestFixture.Create();
CancellationToken cancellationToken = CancellationToken.None;
Error validationError = Error.Validation(description: "LibraryIdCannotBeEmpty");
Error validationError = Errors.Library.LibraryIdCannotBeEmpty;
_mockHandler.HandleAsync(Arg.Any<AddBookCommand>(), Arg.Any<CancellationToken>())
.Returns(validationError);
ConfigureRequest(libraryId.ToString());
_sut.HttpContext.Request.RouteValues["libraryId"] = libraryId.ToString();
// Act
IResult result = await _sut.ExecuteAsync(request, cancellationToken);
@@ -157,6 +158,7 @@ public class AddBookEndpointTests
HttpValidationProblemDetails validationProblemDetails = Assert.IsType<HttpValidationProblemDetails>(problemDetails.ProblemDetails);
Assert.Equal(StatusCodes.Status422UnprocessableEntity, validationProblemDetails.Status);
Assert.Equal("General.Validation", validationProblemDetails.Title);
Assert.Equal("OneOrMoreValidationErrorsOccurred", validationProblemDetails.Detail);
Assert.Equal("https://tools.ietf.org/html/rfc4918#section-11.2", validationProblemDetails.Type);
Assert.Single(validationProblemDetails.Errors);
Assert.Equal(new[] { "LibraryIdCannotBeEmpty" }, validationProblemDetails.Errors["General.Validation"]);
@@ -170,7 +172,7 @@ public class AddBookEndpointTests
CancellationToken cancellationToken = CancellationToken.None;
_mockHandler.HandleAsync(Arg.Any<AddBookCommand>(), Arg.Any<CancellationToken>())
.Returns(Result.From(_bookResponseFixture.Create()));
ConfigureRequest("not-a-library-guid");
_sut.HttpContext.Request.RouteValues["libraryId"] = "not-a-library-guid";
// Act
await _sut.ExecuteAsync(request, cancellationToken);
@@ -189,7 +191,7 @@ public class AddBookEndpointTests
CancellationToken cancellationToken = CancellationToken.None;
_mockHandler.HandleAsync(Arg.Any<AddBookCommand>(), Arg.Any<CancellationToken>())
.Returns(Result.From(_bookResponseFixture.Create()));
ConfigureRequestWithoutLibraryId();
_sut.HttpContext.Request.RouteValues.Remove("libraryId");
// Act
await _sut.ExecuteAsync(request, cancellationToken);
@@ -199,21 +201,4 @@ public class AddBookEndpointTests
Arg.Is<AddBookCommand>(command => command.LibraryId == null),
Arg.Is(cancellationToken));
}
/// <summary>
/// Sets the <c>libraryId</c> route value the endpoint reads the identifier from.
/// </summary>
/// <param name="libraryId">The raw route value of the library Id.</param>
private void ConfigureRequest(string libraryId)
{
_sut.HttpContext.Request.RouteValues["libraryId"] = libraryId;
}
/// <summary>
/// Leaves the <c>libraryId</c> route value unset.
/// </summary>
private void ConfigureRequestWithoutLibraryId()
{
_sut.HttpContext.Request.RouteValues.Remove("libraryId");
}
}
@@ -1,11 +1,9 @@
#region ========================================================================= USING =====================================================================================
using FastEndpoints;
using Lumina.Application.Common.CQRS;
using Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Reading.Queries.GetReadingAvailability;
using Lumina.Contracts.Fixtures.Core.Requests.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Reading;
using Lumina.Contracts.Fixtures.Core.Responses.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Reading;
using Lumina.Contracts.Requests.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Reading;
using Lumina.Contracts.Responses.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Reading;
using Lumina.Domain.Common.Errors;
using Lumina.Domain.Common.Primitives;
using Lumina.Presentation.Api.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.Books.Reading.GetReadingAvailability;
using Microsoft.AspNetCore.Http;
@@ -27,7 +25,6 @@ public class GetReadingAvailabilityEndpointTests
{
private readonly IQueryHandler<GetReadingAvailabilityQuery, Result<ReadingAvailabilityResponse>> _mockHandler;
private readonly GetReadingAvailabilityEndpoint _sut;
private readonly GetReadingAvailabilityRequestFixture _getReadingAvailabilityRequestFixture = new();
private readonly ReadingAvailabilityResponseFixture _readingAvailabilityResponseFixture = new();
/// <summary>
@@ -36,21 +33,24 @@ public class GetReadingAvailabilityEndpointTests
public GetReadingAvailabilityEndpointTests()
{
_mockHandler = Substitute.For<IQueryHandler<GetReadingAvailabilityQuery, Result<ReadingAvailabilityResponse>>>();
_sut = Factory.Create<GetReadingAvailabilityEndpoint>(_mockHandler);
_sut = FastEndpoints.Factory.Create<GetReadingAvailabilityEndpoint>(_mockHandler);
}
[Fact]
public async Task ExecuteAsync_WhenSuccessful_ShouldReturnOkResultWithReadingAvailability()
{
// Arrange
GetReadingAvailabilityRequest request = _getReadingAvailabilityRequestFixture.Create();
Guid libraryId = Guid.NewGuid();
Guid bookId = Guid.NewGuid();
CancellationToken cancellationToken = CancellationToken.None;
ReadingAvailabilityResponse expectedResponse = _readingAvailabilityResponseFixture.Create(bookId: request.BookId, isAvailable: true, errorCode: null);
ReadingAvailabilityResponse expectedResponse = _readingAvailabilityResponseFixture.Create(bookId: bookId, libraryId: libraryId, isAvailable: true, errorCode: null);
_mockHandler.HandleAsync(Arg.Any<GetReadingAvailabilityQuery>(), Arg.Any<CancellationToken>())
.Returns(Result.From(expectedResponse));
_sut.HttpContext.Request.RouteValues["libraryId"] = libraryId.ToString();
_sut.HttpContext.Request.RouteValues["bookId"] = bookId.ToString();
// Act
IResult result = await _sut.ExecuteAsync(request, cancellationToken);
IResult result = await _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, cancellationToken);
// Assert
Ok<ReadingAvailabilityResponse> okResult = Assert.IsType<Ok<ReadingAvailabilityResponse>>(result);
@@ -61,14 +61,17 @@ public class GetReadingAvailabilityEndpointTests
public async Task ExecuteAsync_WhenBookIsNotAvailable_ShouldReturnOkResultWithUnavailableReadingAvailability()
{
// Arrange
GetReadingAvailabilityRequest request = _getReadingAvailabilityRequestFixture.Create();
Guid libraryId = Guid.NewGuid();
Guid bookId = Guid.NewGuid();
CancellationToken cancellationToken = CancellationToken.None;
ReadingAvailabilityResponse expectedResponse = _readingAvailabilityResponseFixture.Create(bookId: request.BookId, isAvailable: false, errorCode: "ReaderDisabled");
ReadingAvailabilityResponse expectedResponse = _readingAvailabilityResponseFixture.Create(bookId: bookId, libraryId: libraryId, isAvailable: false, errorCode: "ReaderDisabled");
_mockHandler.HandleAsync(Arg.Any<GetReadingAvailabilityQuery>(), Arg.Any<CancellationToken>())
.Returns(Result.From(expectedResponse));
_sut.HttpContext.Request.RouteValues["libraryId"] = libraryId.ToString();
_sut.HttpContext.Request.RouteValues["bookId"] = bookId.ToString();
// Act
IResult result = await _sut.ExecuteAsync(request, cancellationToken);
IResult result = await _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, cancellationToken);
// Assert
Ok<ReadingAvailabilityResponse> okResult = Assert.IsType<Ok<ReadingAvailabilityResponse>>(result);
@@ -78,17 +81,20 @@ public class GetReadingAvailabilityEndpointTests
}
[Fact]
public async Task ExecuteAsync_WhenHandlerReturnsError_ShouldReturnProblemResult()
public async Task ExecuteAsync_WhenHandlerReturnsNotFoundError_ShouldReturnProblemResult()
{
// Arrange
GetReadingAvailabilityRequest request = _getReadingAvailabilityRequestFixture.Create();
Guid libraryId = Guid.NewGuid();
Guid bookId = Guid.NewGuid();
CancellationToken cancellationToken = CancellationToken.None;
Error expectedError = Error.NotFound("Reading.BookNotFound", "BookNotFound");
_mockHandler.HandleAsync(Arg.Any<GetReadingAvailabilityQuery>(), Arg.Any<CancellationToken>())
.Returns(expectedError);
_sut.HttpContext.Request.RouteValues["libraryId"] = libraryId.ToString();
_sut.HttpContext.Request.RouteValues["bookId"] = bookId.ToString();
// Act
IResult result = await _sut.ExecuteAsync(request, cancellationToken);
IResult result = await _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, cancellationToken);
// Assert
ProblemHttpResult problemResult = Assert.IsType<ProblemHttpResult>(result);
@@ -98,22 +104,91 @@ public class GetReadingAvailabilityEndpointTests
Assert.Equal("BookNotFound", problemResult.ProblemDetails.Detail);
}
[Fact]
public async Task ExecuteAsync_WhenHandlerReturnsValidationErrors_ShouldReturnValidationProblemResult()
{
// Arrange
Guid libraryId = Guid.NewGuid();
Guid bookId = Guid.NewGuid();
CancellationToken cancellationToken = CancellationToken.None;
Error validationError = Errors.WrittenContent.BookIdCannotBeEmpty;
_mockHandler.HandleAsync(Arg.Any<GetReadingAvailabilityQuery>(), Arg.Any<CancellationToken>())
.Returns(validationError);
_sut.HttpContext.Request.RouteValues["libraryId"] = libraryId.ToString();
_sut.HttpContext.Request.RouteValues["bookId"] = bookId.ToString();
// Act
IResult result = await _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, cancellationToken);
// Assert
ProblemHttpResult problemDetails = Assert.IsType<ProblemHttpResult>(result);
Assert.Equal(StatusCodes.Status422UnprocessableEntity, problemDetails.StatusCode);
Assert.Equal("application/problem+json", problemDetails.ContentType);
HttpValidationProblemDetails validationProblemDetails = Assert.IsType<HttpValidationProblemDetails>(problemDetails.ProblemDetails);
Assert.Equal(StatusCodes.Status422UnprocessableEntity, validationProblemDetails.Status);
Assert.Equal("General.Validation", validationProblemDetails.Title);
Assert.Equal("OneOrMoreValidationErrorsOccurred", validationProblemDetails.Detail);
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_ShouldSendGetReadingAvailabilityQueryToSender()
{
// Arrange
GetReadingAvailabilityRequest request = _getReadingAvailabilityRequestFixture.Create();
Guid libraryId = Guid.NewGuid();
Guid bookId = Guid.NewGuid();
CancellationToken cancellationToken = CancellationToken.None;
ReadingAvailabilityResponse response = _readingAvailabilityResponseFixture.Create(bookId: request.BookId, isAvailable: true, errorCode: null);
_mockHandler.HandleAsync(Arg.Any<GetReadingAvailabilityQuery>(), Arg.Any<CancellationToken>())
.Returns(Result.From(response));
.Returns(Result.From(_readingAvailabilityResponseFixture.Create(bookId: bookId, libraryId: libraryId, isAvailable: true, errorCode: null)));
_sut.HttpContext.Request.RouteValues["libraryId"] = libraryId.ToString();
_sut.HttpContext.Request.RouteValues["bookId"] = bookId.ToString();
// Act
await _sut.ExecuteAsync(request, cancellationToken);
await _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, cancellationToken);
// Assert
await _mockHandler.Received(1).HandleAsync(
Arg.Is<GetReadingAvailabilityQuery>(query => query.BookId == request.BookId),
Arg.Is<GetReadingAvailabilityQuery>(query => query.LibraryId == libraryId.ToString() && query.BookId == bookId.ToString()),
Arg.Is(cancellationToken));
}
[Fact]
public async Task ExecuteAsync_WhenRouteValuesAreNotParseable_ShouldSendQueryWithRawRouteValues()
{
// Arrange
CancellationToken cancellationToken = CancellationToken.None;
_mockHandler.HandleAsync(Arg.Any<GetReadingAvailabilityQuery>(), Arg.Any<CancellationToken>())
.Returns(Result.From(_readingAvailabilityResponseFixture.Create()));
_sut.HttpContext.Request.RouteValues["libraryId"] = "not-a-library-guid";
_sut.HttpContext.Request.RouteValues["bookId"] = "not-a-guid";
// Act
await _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, cancellationToken);
// Assert
await _mockHandler.Received(1).HandleAsync(
Arg.Is<GetReadingAvailabilityQuery>(query => query.LibraryId == "not-a-library-guid" && query.BookId == "not-a-guid"),
Arg.Is(cancellationToken));
}
[Fact]
public async Task ExecuteAsync_WhenRouteValuesAreMissing_ShouldSendQueryWithNullIds()
{
// Arrange
CancellationToken cancellationToken = CancellationToken.None;
_mockHandler.HandleAsync(Arg.Any<GetReadingAvailabilityQuery>(), Arg.Any<CancellationToken>())
.Returns(Result.From(_readingAvailabilityResponseFixture.Create()));
_sut.HttpContext.Request.RouteValues.Remove("libraryId");
_sut.HttpContext.Request.RouteValues.Remove("bookId");
// Act
await _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, cancellationToken);
// Assert
await _mockHandler.Received(1).HandleAsync(
Arg.Is<GetReadingAvailabilityQuery>(query => query.LibraryId == null && query.BookId == null),
Arg.Is(cancellationToken));
}
@@ -121,7 +196,8 @@ public class GetReadingAvailabilityEndpointTests
public async Task ExecuteAsync_WhenCancellationRequested_ShouldCancelOperation()
{
// Arrange
GetReadingAvailabilityRequest request = _getReadingAvailabilityRequestFixture.Create();
Guid libraryId = Guid.NewGuid();
Guid bookId = Guid.NewGuid();
CancellationTokenSource cts = new();
TaskCompletionSource<bool> operationStarted = new();
TaskCompletionSource<bool> cancellationRequested = new();
@@ -132,11 +208,13 @@ public class GetReadingAvailabilityEndpointTests
operationStarted.SetResult(true);
await cancellationRequested.Task;
info.Arg<CancellationToken>().ThrowIfCancellationRequested();
return Result.From(_readingAvailabilityResponseFixture.Create(bookId: request.BookId, isAvailable: true, errorCode: null));
return Result.From(_readingAvailabilityResponseFixture.Create());
}, info.Arg<CancellationToken>()));
_sut.HttpContext.Request.RouteValues["libraryId"] = libraryId.ToString();
_sut.HttpContext.Request.RouteValues["bookId"] = bookId.ToString();
// Act
Task<IResult> operationTask = _sut.ExecuteAsync(request, cts.Token);
Task<IResult> operationTask = _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, cts.Token);
await operationStarted.Task;
cts.Cancel();
cancellationRequested.SetResult(true);
@@ -1,11 +1,9 @@
#region ========================================================================= USING =====================================================================================
using FastEndpoints;
using Lumina.Application.Common.CQRS;
using Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Reading.Queries.GetReadingManifest;
using Lumina.Contracts.Fixtures.Core.Requests.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Reading;
using Lumina.Contracts.Fixtures.Core.Responses.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Reading;
using Lumina.Contracts.Requests.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Reading;
using Lumina.Contracts.Responses.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Reading;
using Lumina.Domain.Common.Errors;
using Lumina.Domain.Common.Primitives;
using Lumina.Presentation.Api.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.Books.Reading.GetReadingManifest;
using Microsoft.AspNetCore.Http;
@@ -27,7 +25,6 @@ public class GetReadingManifestEndpointTests
{
private readonly IQueryHandler<GetReadingManifestQuery, Result<ReadingManifestResponse>> _mockHandler;
private readonly GetReadingManifestEndpoint _sut;
private readonly GetReadingManifestRequestFixture _getReadingManifestRequestFixture = new();
private readonly ReadingManifestResponseFixture _readingManifestResponseFixture = new();
/// <summary>
@@ -36,21 +33,24 @@ public class GetReadingManifestEndpointTests
public GetReadingManifestEndpointTests()
{
_mockHandler = Substitute.For<IQueryHandler<GetReadingManifestQuery, Result<ReadingManifestResponse>>>();
_sut = Factory.Create<GetReadingManifestEndpoint>(_mockHandler);
_sut = FastEndpoints.Factory.Create<GetReadingManifestEndpoint>(_mockHandler);
}
[Fact]
public async Task ExecuteAsync_WhenSuccessful_ShouldReturnOkResultWithReadingManifest()
{
// Arrange
GetReadingManifestRequest request = _getReadingManifestRequestFixture.Create();
Guid libraryId = Guid.NewGuid();
Guid bookId = Guid.NewGuid();
CancellationToken cancellationToken = CancellationToken.None;
ReadingManifestResponse expectedResponse = _readingManifestResponseFixture.Create();
_mockHandler.HandleAsync(Arg.Any<GetReadingManifestQuery>(), Arg.Any<CancellationToken>())
.Returns(Result.From(expectedResponse));
_sut.HttpContext.Request.RouteValues["libraryId"] = libraryId.ToString();
_sut.HttpContext.Request.RouteValues["bookId"] = bookId.ToString();
// Act
IResult result = await _sut.ExecuteAsync(request, cancellationToken);
IResult result = await _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, cancellationToken);
// Assert
Ok<ReadingManifestResponse> okResult = Assert.IsType<Ok<ReadingManifestResponse>>(result);
@@ -58,17 +58,20 @@ public class GetReadingManifestEndpointTests
}
[Fact]
public async Task ExecuteAsync_WhenHandlerReturnsError_ShouldReturnProblemResult()
public async Task ExecuteAsync_WhenHandlerReturnsNotFoundError_ShouldReturnProblemResult()
{
// Arrange
GetReadingManifestRequest request = _getReadingManifestRequestFixture.Create();
Guid libraryId = Guid.NewGuid();
Guid bookId = Guid.NewGuid();
CancellationToken cancellationToken = CancellationToken.None;
Error expectedError = Error.NotFound("Reading.BookNotFound", "BookNotFound");
_mockHandler.HandleAsync(Arg.Any<GetReadingManifestQuery>(), Arg.Any<CancellationToken>())
.Returns(expectedError);
_sut.HttpContext.Request.RouteValues["libraryId"] = libraryId.ToString();
_sut.HttpContext.Request.RouteValues["bookId"] = bookId.ToString();
// Act
IResult result = await _sut.ExecuteAsync(request, cancellationToken);
IResult result = await _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, cancellationToken);
// Assert
ProblemHttpResult problemResult = Assert.IsType<ProblemHttpResult>(result);
@@ -78,22 +81,91 @@ public class GetReadingManifestEndpointTests
Assert.Equal("BookNotFound", problemResult.ProblemDetails.Detail);
}
[Fact]
public async Task ExecuteAsync_WhenHandlerReturnsValidationErrors_ShouldReturnValidationProblemResult()
{
// Arrange
Guid libraryId = Guid.NewGuid();
Guid bookId = Guid.NewGuid();
CancellationToken cancellationToken = CancellationToken.None;
Error validationError = Errors.WrittenContent.BookIdCannotBeEmpty;
_mockHandler.HandleAsync(Arg.Any<GetReadingManifestQuery>(), Arg.Any<CancellationToken>())
.Returns(validationError);
_sut.HttpContext.Request.RouteValues["libraryId"] = libraryId.ToString();
_sut.HttpContext.Request.RouteValues["bookId"] = bookId.ToString();
// Act
IResult result = await _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, cancellationToken);
// Assert
ProblemHttpResult problemDetails = Assert.IsType<ProblemHttpResult>(result);
Assert.Equal(StatusCodes.Status422UnprocessableEntity, problemDetails.StatusCode);
Assert.Equal("application/problem+json", problemDetails.ContentType);
HttpValidationProblemDetails validationProblemDetails = Assert.IsType<HttpValidationProblemDetails>(problemDetails.ProblemDetails);
Assert.Equal(StatusCodes.Status422UnprocessableEntity, validationProblemDetails.Status);
Assert.Equal("General.Validation", validationProblemDetails.Title);
Assert.Equal("OneOrMoreValidationErrorsOccurred", validationProblemDetails.Detail);
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_ShouldSendGetReadingManifestQueryToSender()
{
// Arrange
GetReadingManifestRequest request = _getReadingManifestRequestFixture.Create();
Guid libraryId = Guid.NewGuid();
Guid bookId = Guid.NewGuid();
CancellationToken cancellationToken = CancellationToken.None;
ReadingManifestResponse response = _readingManifestResponseFixture.Create();
_mockHandler.HandleAsync(Arg.Any<GetReadingManifestQuery>(), Arg.Any<CancellationToken>())
.Returns(Result.From(response));
.Returns(Result.From(_readingManifestResponseFixture.Create()));
_sut.HttpContext.Request.RouteValues["libraryId"] = libraryId.ToString();
_sut.HttpContext.Request.RouteValues["bookId"] = bookId.ToString();
// Act
await _sut.ExecuteAsync(request, cancellationToken);
await _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, cancellationToken);
// Assert
await _mockHandler.Received(1).HandleAsync(
Arg.Is<GetReadingManifestQuery>(query => query.BookId == request.BookId),
Arg.Is<GetReadingManifestQuery>(query => query.LibraryId == libraryId.ToString() && query.BookId == bookId.ToString()),
Arg.Is(cancellationToken));
}
[Fact]
public async Task ExecuteAsync_WhenRouteValuesAreNotParseable_ShouldSendQueryWithRawRouteValues()
{
// Arrange
CancellationToken cancellationToken = CancellationToken.None;
_mockHandler.HandleAsync(Arg.Any<GetReadingManifestQuery>(), Arg.Any<CancellationToken>())
.Returns(Result.From(_readingManifestResponseFixture.Create()));
_sut.HttpContext.Request.RouteValues["libraryId"] = "not-a-library-guid";
_sut.HttpContext.Request.RouteValues["bookId"] = "not-a-guid";
// Act
await _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, cancellationToken);
// Assert
await _mockHandler.Received(1).HandleAsync(
Arg.Is<GetReadingManifestQuery>(query => query.LibraryId == "not-a-library-guid" && query.BookId == "not-a-guid"),
Arg.Is(cancellationToken));
}
[Fact]
public async Task ExecuteAsync_WhenRouteValuesAreMissing_ShouldSendQueryWithNullIds()
{
// Arrange
CancellationToken cancellationToken = CancellationToken.None;
_mockHandler.HandleAsync(Arg.Any<GetReadingManifestQuery>(), Arg.Any<CancellationToken>())
.Returns(Result.From(_readingManifestResponseFixture.Create()));
_sut.HttpContext.Request.RouteValues.Remove("libraryId");
_sut.HttpContext.Request.RouteValues.Remove("bookId");
// Act
await _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, cancellationToken);
// Assert
await _mockHandler.Received(1).HandleAsync(
Arg.Is<GetReadingManifestQuery>(query => query.LibraryId == null && query.BookId == null),
Arg.Is(cancellationToken));
}
@@ -101,7 +173,8 @@ public class GetReadingManifestEndpointTests
public async Task ExecuteAsync_WhenCancellationRequested_ShouldCancelOperation()
{
// Arrange
GetReadingManifestRequest request = _getReadingManifestRequestFixture.Create();
Guid libraryId = Guid.NewGuid();
Guid bookId = Guid.NewGuid();
CancellationTokenSource cts = new();
TaskCompletionSource<bool> operationStarted = new();
TaskCompletionSource<bool> cancellationRequested = new();
@@ -114,9 +187,11 @@ public class GetReadingManifestEndpointTests
info.Arg<CancellationToken>().ThrowIfCancellationRequested();
return Result.From(_readingManifestResponseFixture.Create());
}, info.Arg<CancellationToken>()));
_sut.HttpContext.Request.RouteValues["libraryId"] = libraryId.ToString();
_sut.HttpContext.Request.RouteValues["bookId"] = bookId.ToString();
// Act
Task<IResult> operationTask = _sut.ExecuteAsync(request, cts.Token);
Task<IResult> operationTask = _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, cts.Token);
await operationStarted.Task;
cts.Cancel();
cancellationRequested.SetResult(true);
@@ -1,11 +1,9 @@
#region ========================================================================= USING =====================================================================================
using FastEndpoints;
using Lumina.Application.Common.CQRS;
using Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Reading.Queries.GetReadingResource;
using Lumina.Contracts.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary.Reading;
using Lumina.Contracts.Fixtures.Core.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary.Reading;
using Lumina.Contracts.Fixtures.Core.Requests.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Reading;
using Lumina.Contracts.Requests.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Reading;
using Lumina.Domain.Common.Errors;
using Lumina.Domain.Common.Primitives;
using Lumina.Presentation.Api.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.Books.Reading.GetReadingResource;
using Microsoft.AspNetCore.Http;
@@ -27,7 +25,6 @@ public class GetReadingResourceEndpointTests
{
private readonly IQueryHandler<GetReadingResourceQuery, Result<ReadingResourceDataDto>> _mockHandler;
private readonly GetReadingResourceEndpoint _sut;
private readonly GetReadingResourceRequestFixture _getReadingResourceRequestFixture = new();
private readonly ReadingResourceDataDtoFixture _readingResourceDataDtoFixture = new();
/// <summary>
@@ -36,21 +33,25 @@ public class GetReadingResourceEndpointTests
public GetReadingResourceEndpointTests()
{
_mockHandler = Substitute.For<IQueryHandler<GetReadingResourceQuery, Result<ReadingResourceDataDto>>>();
_sut = Factory.Create<GetReadingResourceEndpoint>(_mockHandler);
_sut = FastEndpoints.Factory.Create<GetReadingResourceEndpoint>(_mockHandler);
}
[Fact]
public async Task ExecuteAsync_WhenSuccessful_ShouldReturnBytesResultWithResourceData()
{
// Arrange
GetReadingResourceRequest request = _getReadingResourceRequestFixture.Create();
Guid libraryId = Guid.NewGuid();
Guid bookId = Guid.NewGuid();
CancellationToken cancellationToken = CancellationToken.None;
ReadingResourceDataDto expectedResponse = _readingResourceDataDtoFixture.Create();
_mockHandler.HandleAsync(Arg.Any<GetReadingResourceQuery>(), Arg.Any<CancellationToken>())
.Returns(Result.From(expectedResponse));
_sut.HttpContext.Request.RouteValues["libraryId"] = libraryId.ToString();
_sut.HttpContext.Request.RouteValues["bookId"] = bookId.ToString();
_sut.HttpContext.Request.RouteValues["resourceKey"] = "cover-image";
// Act
IResult result = await _sut.ExecuteAsync(request, cancellationToken);
IResult result = await _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, cancellationToken);
// Assert
FileContentHttpResult bytesResult = Assert.IsType<FileContentHttpResult>(result);
@@ -59,17 +60,21 @@ public class GetReadingResourceEndpointTests
}
[Fact]
public async Task ExecuteAsync_WhenHandlerReturnsError_ShouldReturnProblemResult()
public async Task ExecuteAsync_WhenHandlerReturnsNotFoundError_ShouldReturnProblemResult()
{
// Arrange
GetReadingResourceRequest request = _getReadingResourceRequestFixture.Create();
Guid libraryId = Guid.NewGuid();
Guid bookId = Guid.NewGuid();
CancellationToken cancellationToken = CancellationToken.None;
Error expectedError = Error.NotFound("Reading.ResourceNotFound", "ResourceNotFound");
_mockHandler.HandleAsync(Arg.Any<GetReadingResourceQuery>(), Arg.Any<CancellationToken>())
.Returns(expectedError);
_sut.HttpContext.Request.RouteValues["libraryId"] = libraryId.ToString();
_sut.HttpContext.Request.RouteValues["bookId"] = bookId.ToString();
_sut.HttpContext.Request.RouteValues["resourceKey"] = "cover-image";
// Act
IResult result = await _sut.ExecuteAsync(request, cancellationToken);
IResult result = await _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, cancellationToken);
// Assert
ProblemHttpResult problemResult = Assert.IsType<ProblemHttpResult>(result);
@@ -79,6 +84,36 @@ public class GetReadingResourceEndpointTests
Assert.Equal("ResourceNotFound", problemResult.ProblemDetails.Detail);
}
[Fact]
public async Task ExecuteAsync_WhenHandlerReturnsValidationErrors_ShouldReturnValidationProblemResult()
{
// Arrange
Guid libraryId = Guid.NewGuid();
Guid bookId = Guid.NewGuid();
CancellationToken cancellationToken = CancellationToken.None;
Error validationError = Errors.WrittenContent.BookIdCannotBeEmpty;
_mockHandler.HandleAsync(Arg.Any<GetReadingResourceQuery>(), Arg.Any<CancellationToken>())
.Returns(validationError);
_sut.HttpContext.Request.RouteValues["libraryId"] = libraryId.ToString();
_sut.HttpContext.Request.RouteValues["bookId"] = bookId.ToString();
_sut.HttpContext.Request.RouteValues["resourceKey"] = "cover-image";
// Act
IResult result = await _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, cancellationToken);
// Assert
ProblemHttpResult problemDetails = Assert.IsType<ProblemHttpResult>(result);
Assert.Equal(StatusCodes.Status422UnprocessableEntity, problemDetails.StatusCode);
Assert.Equal("application/problem+json", problemDetails.ContentType);
HttpValidationProblemDetails validationProblemDetails = Assert.IsType<HttpValidationProblemDetails>(problemDetails.ProblemDetails);
Assert.Equal(StatusCodes.Status422UnprocessableEntity, validationProblemDetails.Status);
Assert.Equal("General.Validation", validationProblemDetails.Title);
Assert.Equal("OneOrMoreValidationErrorsOccurred", validationProblemDetails.Detail);
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"]);
}
[Theory]
[InlineData("image/png", "image/png")] // a non-svg image is inert content
[InlineData("image/svg+xml", "application/octet-stream")] // an svg can be executed, so it is served as an opaque download
@@ -95,14 +130,18 @@ public class GetReadingResourceEndpointTests
public async Task ExecuteAsync_WhenServingAResource_ShouldUseTheSafeContentType(string mimeType, string expectedContentType)
{
// Arrange
GetReadingResourceRequest request = _getReadingResourceRequestFixture.Create();
Guid libraryId = Guid.NewGuid();
Guid bookId = Guid.NewGuid();
CancellationToken cancellationToken = CancellationToken.None;
ReadingResourceDataDto response = new(Guid.NewGuid().ToByteArray(), mimeType);
_mockHandler.HandleAsync(Arg.Any<GetReadingResourceQuery>(), Arg.Any<CancellationToken>())
.Returns(Result.From(response));
_sut.HttpContext.Request.RouteValues["libraryId"] = libraryId.ToString();
_sut.HttpContext.Request.RouteValues["bookId"] = bookId.ToString();
_sut.HttpContext.Request.RouteValues["resourceKey"] = "cover-image";
// Act
IResult result = await _sut.ExecuteAsync(request, cancellationToken);
IResult result = await _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, cancellationToken);
// Assert
FileContentHttpResult bytesResult = Assert.IsType<FileContentHttpResult>(result);
@@ -115,18 +154,67 @@ public class GetReadingResourceEndpointTests
public async Task ExecuteAsync_WhenCalled_ShouldSendGetReadingResourceQueryToSender()
{
// Arrange
GetReadingResourceRequest request = _getReadingResourceRequestFixture.Create();
Guid libraryId = Guid.NewGuid();
Guid bookId = Guid.NewGuid();
CancellationToken cancellationToken = CancellationToken.None;
ReadingResourceDataDto response = _readingResourceDataDtoFixture.Create();
_mockHandler.HandleAsync(Arg.Any<GetReadingResourceQuery>(), Arg.Any<CancellationToken>())
.Returns(Result.From(response));
.Returns(Result.From(_readingResourceDataDtoFixture.Create()));
_sut.HttpContext.Request.RouteValues["libraryId"] = libraryId.ToString();
_sut.HttpContext.Request.RouteValues["bookId"] = bookId.ToString();
_sut.HttpContext.Request.RouteValues["resourceKey"] = "cover-image";
// Act
await _sut.ExecuteAsync(request, cancellationToken);
await _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, cancellationToken);
// Assert
await _mockHandler.Received(1).HandleAsync(
Arg.Is<GetReadingResourceQuery>(query => query.BookId == request.BookId && query.ResourceKey == request.ResourceKey),
Arg.Is<GetReadingResourceQuery>(query =>
query.LibraryId == libraryId.ToString() &&
query.BookId == bookId.ToString() &&
query.ResourceKey == "cover-image"),
Arg.Is(cancellationToken));
}
[Fact]
public async Task ExecuteAsync_WhenRouteValuesAreNotParseable_ShouldSendQueryWithRawRouteValues()
{
// Arrange
CancellationToken cancellationToken = CancellationToken.None;
_mockHandler.HandleAsync(Arg.Any<GetReadingResourceQuery>(), Arg.Any<CancellationToken>())
.Returns(Result.From(_readingResourceDataDtoFixture.Create()));
_sut.HttpContext.Request.RouteValues["libraryId"] = "not-a-library-guid";
_sut.HttpContext.Request.RouteValues["bookId"] = "not-a-guid";
_sut.HttpContext.Request.RouteValues["resourceKey"] = "cover-image";
// Act
await _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, cancellationToken);
// Assert
await _mockHandler.Received(1).HandleAsync(
Arg.Is<GetReadingResourceQuery>(query =>
query.LibraryId == "not-a-library-guid" &&
query.BookId == "not-a-guid" &&
query.ResourceKey == "cover-image"),
Arg.Is(cancellationToken));
}
[Fact]
public async Task ExecuteAsync_WhenRouteValuesAreMissing_ShouldSendQueryWithNullValues()
{
// Arrange
CancellationToken cancellationToken = CancellationToken.None;
_mockHandler.HandleAsync(Arg.Any<GetReadingResourceQuery>(), Arg.Any<CancellationToken>())
.Returns(Result.From(_readingResourceDataDtoFixture.Create()));
_sut.HttpContext.Request.RouteValues.Remove("libraryId");
_sut.HttpContext.Request.RouteValues.Remove("bookId");
_sut.HttpContext.Request.RouteValues.Remove("resourceKey");
// Act
await _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, cancellationToken);
// Assert
await _mockHandler.Received(1).HandleAsync(
Arg.Is<GetReadingResourceQuery>(query => query.LibraryId == null && query.BookId == null && query.ResourceKey == null),
Arg.Is(cancellationToken));
}
@@ -134,7 +222,8 @@ public class GetReadingResourceEndpointTests
public async Task ExecuteAsync_WhenCancellationRequested_ShouldCancelOperation()
{
// Arrange
GetReadingResourceRequest request = _getReadingResourceRequestFixture.Create();
Guid libraryId = Guid.NewGuid();
Guid bookId = Guid.NewGuid();
CancellationTokenSource cts = new();
TaskCompletionSource<bool> operationStarted = new();
TaskCompletionSource<bool> cancellationRequested = new();
@@ -147,9 +236,12 @@ public class GetReadingResourceEndpointTests
info.Arg<CancellationToken>().ThrowIfCancellationRequested();
return Result.From(_readingResourceDataDtoFixture.Create());
}, info.Arg<CancellationToken>()));
_sut.HttpContext.Request.RouteValues["libraryId"] = libraryId.ToString();
_sut.HttpContext.Request.RouteValues["bookId"] = bookId.ToString();
_sut.HttpContext.Request.RouteValues["resourceKey"] = "cover-image";
// Act
Task<IResult> operationTask = _sut.ExecuteAsync(request, cts.Token);
Task<IResult> operationTask = _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, cts.Token);
await operationStarted.Task;
cts.Cancel();
cancellationRequested.SetResult(true);
@@ -1,11 +1,9 @@
#region ========================================================================= USING =====================================================================================
using FastEndpoints;
using Lumina.Application.Common.CQRS;
using Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Reading.Queries.GetReadingSection;
using Lumina.Contracts.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary.Reading;
using Lumina.Contracts.Fixtures.Core.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary.Reading;
using Lumina.Contracts.Fixtures.Core.Requests.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Reading;
using Lumina.Contracts.Requests.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Reading;
using Lumina.Domain.Common.Errors;
using Lumina.Domain.Common.Primitives;
using Lumina.Presentation.Api.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.Books.Reading.GetReadingSection;
using Microsoft.AspNetCore.Http;
@@ -27,7 +25,6 @@ public class GetReadingSectionEndpointTests
{
private readonly IQueryHandler<GetReadingSectionQuery, Result<ReadingSectionDto>> _mockHandler;
private readonly GetReadingSectionEndpoint _sut;
private readonly GetReadingSectionRequestFixture _getReadingSectionRequestFixture = new();
private readonly ReadingSectionDtoFixture _readingSectionDtoFixture = new();
/// <summary>
@@ -36,21 +33,25 @@ public class GetReadingSectionEndpointTests
public GetReadingSectionEndpointTests()
{
_mockHandler = Substitute.For<IQueryHandler<GetReadingSectionQuery, Result<ReadingSectionDto>>>();
_sut = Factory.Create<GetReadingSectionEndpoint>(_mockHandler);
_sut = FastEndpoints.Factory.Create<GetReadingSectionEndpoint>(_mockHandler);
}
[Fact]
public async Task ExecuteAsync_WhenSuccessful_ShouldReturnOkResultWithReadingSection()
{
// Arrange
GetReadingSectionRequest request = _getReadingSectionRequestFixture.Create();
Guid libraryId = Guid.NewGuid();
Guid bookId = Guid.NewGuid();
CancellationToken cancellationToken = CancellationToken.None;
ReadingSectionDto expectedResponse = _readingSectionDtoFixture.Create(locationRef: request.LocationRef);
ReadingSectionDto expectedResponse = _readingSectionDtoFixture.Create(locationRef: "chapter-1");
_mockHandler.HandleAsync(Arg.Any<GetReadingSectionQuery>(), Arg.Any<CancellationToken>())
.Returns(Result.From(expectedResponse));
_sut.HttpContext.Request.RouteValues["libraryId"] = libraryId.ToString();
_sut.HttpContext.Request.RouteValues["bookId"] = bookId.ToString();
_sut.HttpContext.Request.RouteValues["locationRef"] = "chapter-1";
// Act
IResult result = await _sut.ExecuteAsync(request, cancellationToken);
IResult result = await _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, cancellationToken);
// Assert
Ok<ReadingSectionDto> okResult = Assert.IsType<Ok<ReadingSectionDto>>(result);
@@ -58,17 +59,21 @@ public class GetReadingSectionEndpointTests
}
[Fact]
public async Task ExecuteAsync_WhenHandlerReturnsError_ShouldReturnProblemResult()
public async Task ExecuteAsync_WhenHandlerReturnsNotFoundError_ShouldReturnProblemResult()
{
// Arrange
GetReadingSectionRequest request = _getReadingSectionRequestFixture.Create();
Guid libraryId = Guid.NewGuid();
Guid bookId = Guid.NewGuid();
CancellationToken cancellationToken = CancellationToken.None;
Error expectedError = Error.NotFound("Reading.SectionNotFound", "SectionNotFound");
_mockHandler.HandleAsync(Arg.Any<GetReadingSectionQuery>(), Arg.Any<CancellationToken>())
.Returns(expectedError);
_sut.HttpContext.Request.RouteValues["libraryId"] = libraryId.ToString();
_sut.HttpContext.Request.RouteValues["bookId"] = bookId.ToString();
_sut.HttpContext.Request.RouteValues["locationRef"] = "chapter-1";
// Act
IResult result = await _sut.ExecuteAsync(request, cancellationToken);
IResult result = await _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, cancellationToken);
// Assert
ProblemHttpResult problemResult = Assert.IsType<ProblemHttpResult>(result);
@@ -78,22 +83,101 @@ public class GetReadingSectionEndpointTests
Assert.Equal("SectionNotFound", problemResult.ProblemDetails.Detail);
}
[Fact]
public async Task ExecuteAsync_WhenHandlerReturnsValidationErrors_ShouldReturnValidationProblemResult()
{
// Arrange
Guid libraryId = Guid.NewGuid();
Guid bookId = Guid.NewGuid();
CancellationToken cancellationToken = CancellationToken.None;
Error validationError = Errors.WrittenContent.BookIdCannotBeEmpty;
_mockHandler.HandleAsync(Arg.Any<GetReadingSectionQuery>(), Arg.Any<CancellationToken>())
.Returns(validationError);
_sut.HttpContext.Request.RouteValues["libraryId"] = libraryId.ToString();
_sut.HttpContext.Request.RouteValues["bookId"] = bookId.ToString();
_sut.HttpContext.Request.RouteValues["locationRef"] = "chapter-1";
// Act
IResult result = await _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, cancellationToken);
// Assert
ProblemHttpResult problemDetails = Assert.IsType<ProblemHttpResult>(result);
Assert.Equal(StatusCodes.Status422UnprocessableEntity, problemDetails.StatusCode);
Assert.Equal("application/problem+json", problemDetails.ContentType);
HttpValidationProblemDetails validationProblemDetails = Assert.IsType<HttpValidationProblemDetails>(problemDetails.ProblemDetails);
Assert.Equal(StatusCodes.Status422UnprocessableEntity, validationProblemDetails.Status);
Assert.Equal("General.Validation", validationProblemDetails.Title);
Assert.Equal("OneOrMoreValidationErrorsOccurred", validationProblemDetails.Detail);
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_ShouldSendGetReadingSectionQueryToSender()
{
// Arrange
GetReadingSectionRequest request = _getReadingSectionRequestFixture.Create();
Guid libraryId = Guid.NewGuid();
Guid bookId = Guid.NewGuid();
CancellationToken cancellationToken = CancellationToken.None;
ReadingSectionDto response = _readingSectionDtoFixture.Create(locationRef: request.LocationRef);
_mockHandler.HandleAsync(Arg.Any<GetReadingSectionQuery>(), Arg.Any<CancellationToken>())
.Returns(Result.From(response));
.Returns(Result.From(_readingSectionDtoFixture.Create(locationRef: "chapter-1")));
_sut.HttpContext.Request.RouteValues["libraryId"] = libraryId.ToString();
_sut.HttpContext.Request.RouteValues["bookId"] = bookId.ToString();
_sut.HttpContext.Request.RouteValues["locationRef"] = "chapter-1";
// Act
await _sut.ExecuteAsync(request, cancellationToken);
await _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, cancellationToken);
// Assert
await _mockHandler.Received(1).HandleAsync(
Arg.Is<GetReadingSectionQuery>(query => query.BookId == request.BookId && query.LocationRef == request.LocationRef),
Arg.Is<GetReadingSectionQuery>(query =>
query.LibraryId == libraryId.ToString() &&
query.BookId == bookId.ToString() &&
query.LocationRef == "chapter-1"),
Arg.Is(cancellationToken));
}
[Fact]
public async Task ExecuteAsync_WhenRouteValuesAreNotParseable_ShouldSendQueryWithRawRouteValues()
{
// Arrange
CancellationToken cancellationToken = CancellationToken.None;
_mockHandler.HandleAsync(Arg.Any<GetReadingSectionQuery>(), Arg.Any<CancellationToken>())
.Returns(Result.From(_readingSectionDtoFixture.Create()));
_sut.HttpContext.Request.RouteValues["libraryId"] = "not-a-library-guid";
_sut.HttpContext.Request.RouteValues["bookId"] = "not-a-guid";
_sut.HttpContext.Request.RouteValues["locationRef"] = "chapter-1";
// Act
await _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, cancellationToken);
// Assert
await _mockHandler.Received(1).HandleAsync(
Arg.Is<GetReadingSectionQuery>(query =>
query.LibraryId == "not-a-library-guid" &&
query.BookId == "not-a-guid" &&
query.LocationRef == "chapter-1"),
Arg.Is(cancellationToken));
}
[Fact]
public async Task ExecuteAsync_WhenRouteValuesAreMissing_ShouldSendQueryWithNullValues()
{
// Arrange
CancellationToken cancellationToken = CancellationToken.None;
_mockHandler.HandleAsync(Arg.Any<GetReadingSectionQuery>(), Arg.Any<CancellationToken>())
.Returns(Result.From(_readingSectionDtoFixture.Create()));
_sut.HttpContext.Request.RouteValues.Remove("libraryId");
_sut.HttpContext.Request.RouteValues.Remove("bookId");
_sut.HttpContext.Request.RouteValues.Remove("locationRef");
// Act
await _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, cancellationToken);
// Assert
await _mockHandler.Received(1).HandleAsync(
Arg.Is<GetReadingSectionQuery>(query => query.LibraryId == null && query.BookId == null && query.LocationRef == null),
Arg.Is(cancellationToken));
}
@@ -101,7 +185,8 @@ public class GetReadingSectionEndpointTests
public async Task ExecuteAsync_WhenCancellationRequested_ShouldCancelOperation()
{
// Arrange
GetReadingSectionRequest request = _getReadingSectionRequestFixture.Create();
Guid libraryId = Guid.NewGuid();
Guid bookId = Guid.NewGuid();
CancellationTokenSource cts = new();
TaskCompletionSource<bool> operationStarted = new();
TaskCompletionSource<bool> cancellationRequested = new();
@@ -112,11 +197,14 @@ public class GetReadingSectionEndpointTests
operationStarted.SetResult(true);
await cancellationRequested.Task;
info.Arg<CancellationToken>().ThrowIfCancellationRequested();
return Result.From(_readingSectionDtoFixture.Create(locationRef: request.LocationRef));
return Result.From(_readingSectionDtoFixture.Create());
}, info.Arg<CancellationToken>()));
_sut.HttpContext.Request.RouteValues["libraryId"] = libraryId.ToString();
_sut.HttpContext.Request.RouteValues["bookId"] = bookId.ToString();
_sut.HttpContext.Request.RouteValues["locationRef"] = "chapter-1";
// Act
Task<IResult> operationTask = _sut.ExecuteAsync(request, cts.Token);
Task<IResult> operationTask = _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, cts.Token);
await operationStarted.Task;
cts.Cancel();
cancellationRequested.SetResult(true);
@@ -5,6 +5,7 @@ using Lumina.Contracts.Fixtures.Core.Requests.MediaLibrary.WrittenContentLibrary
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.Errors;
using Lumina.Domain.Common.Primitives;
using Lumina.Presentation.Api.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.Books.UpdateBook;
using Microsoft.AspNetCore.Http;
@@ -49,7 +50,8 @@ public class UpdateBookEndpointTests
BookResponse expectedResponse = _bookResponseFixture.Create();
_mockHandler.HandleAsync(Arg.Any<UpdateBookCommand>(), Arg.Any<CancellationToken>())
.Returns(Result.From(expectedResponse));
ConfigureRequest(libraryId.ToString(), routeId.ToString());
_sut.HttpContext.Request.RouteValues["libraryId"] = libraryId.ToString();
_sut.HttpContext.Request.RouteValues["bookId"] = routeId.ToString();
// Act
IResult result = await _sut.ExecuteAsync(request, cancellationToken);
@@ -70,7 +72,8 @@ public class UpdateBookEndpointTests
Error expectedError = Error.NotFound("Book.NotFound", "BookNotFound");
_mockHandler.HandleAsync(Arg.Any<UpdateBookCommand>(), Arg.Any<CancellationToken>())
.Returns(expectedError);
ConfigureRequest(libraryId.ToString(), routeId.ToString());
_sut.HttpContext.Request.RouteValues["libraryId"] = libraryId.ToString();
_sut.HttpContext.Request.RouteValues["bookId"] = routeId.ToString();
// Act
IResult result = await _sut.ExecuteAsync(request, cancellationToken);
@@ -94,10 +97,11 @@ public class UpdateBookEndpointTests
Guid routeId = Guid.NewGuid();
UpdateBookRequest request = _updateBookRequestFixture.Create();
CancellationToken cancellationToken = CancellationToken.None;
Error validationError = Error.Validation(description: "BookIdCannotBeEmpty");
Error validationError = Errors.WrittenContent.BookIdCannotBeEmpty;
_mockHandler.HandleAsync(Arg.Any<UpdateBookCommand>(), Arg.Any<CancellationToken>())
.Returns(validationError);
ConfigureRequest(libraryId.ToString(), routeId.ToString());
_sut.HttpContext.Request.RouteValues["libraryId"] = libraryId.ToString();
_sut.HttpContext.Request.RouteValues["bookId"] = routeId.ToString();
// Act
IResult result = await _sut.ExecuteAsync(request, cancellationToken);
@@ -109,13 +113,14 @@ public class UpdateBookEndpointTests
HttpValidationProblemDetails validationProblemDetails = Assert.IsType<HttpValidationProblemDetails>(problemDetails.ProblemDetails);
Assert.Equal(StatusCodes.Status422UnprocessableEntity, validationProblemDetails.Status);
Assert.Equal("General.Validation", validationProblemDetails.Title);
Assert.Equal("OneOrMoreValidationErrorsOccurred", validationProblemDetails.Detail);
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_ShouldSendUpdateBookCommandToHandler()
public async Task ExecuteAsync_WhenCalled_ShouldSendUpdateBookCommandToSender()
{
// Arrange
Guid libraryId = Guid.NewGuid();
@@ -124,7 +129,8 @@ public class UpdateBookEndpointTests
CancellationToken cancellationToken = CancellationToken.None;
_mockHandler.HandleAsync(Arg.Any<UpdateBookCommand>(), Arg.Any<CancellationToken>())
.Returns(Result.From(_bookResponseFixture.Create()));
ConfigureRequest(libraryId.ToString(), routeId.ToString());
_sut.HttpContext.Request.RouteValues["libraryId"] = libraryId.ToString();
_sut.HttpContext.Request.RouteValues["bookId"] = routeId.ToString();
// Act
await _sut.ExecuteAsync(request, cancellationToken);
@@ -152,7 +158,8 @@ public class UpdateBookEndpointTests
CancellationToken cancellationToken = CancellationToken.None;
_mockHandler.HandleAsync(Arg.Any<UpdateBookCommand>(), Arg.Any<CancellationToken>())
.Returns(Result.From(_bookResponseFixture.Create()));
ConfigureRequest("not-a-library-guid", "not-a-guid");
_sut.HttpContext.Request.RouteValues["libraryId"] = "not-a-library-guid";
_sut.HttpContext.Request.RouteValues["bookId"] = "not-a-guid";
// Act
await _sut.ExecuteAsync(request, cancellationToken);
@@ -171,7 +178,8 @@ public class UpdateBookEndpointTests
CancellationToken cancellationToken = CancellationToken.None;
_mockHandler.HandleAsync(Arg.Any<UpdateBookCommand>(), Arg.Any<CancellationToken>())
.Returns(Result.From(_bookResponseFixture.Create()));
ConfigureRequestWithoutIds();
_sut.HttpContext.Request.RouteValues.Remove("libraryId");
_sut.HttpContext.Request.RouteValues.Remove("bookId");
// Act
await _sut.ExecuteAsync(request, cancellationToken);
@@ -201,7 +209,8 @@ public class UpdateBookEndpointTests
callInfo.Arg<CancellationToken>().ThrowIfCancellationRequested();
return Result.From(_bookResponseFixture.Create());
}, callInfo.Arg<CancellationToken>()));
ConfigureRequest(libraryId.ToString(), routeId.ToString());
_sut.HttpContext.Request.RouteValues["libraryId"] = libraryId.ToString();
_sut.HttpContext.Request.RouteValues["bookId"] = routeId.ToString();
// Act
Task<IResult> operationTask = _sut.ExecuteAsync(request, cts.Token);
@@ -212,24 +221,4 @@ public class UpdateBookEndpointTests
// Assert
await Assert.ThrowsAnyAsync<OperationCanceledException>(() => operationTask);
}
/// <summary>
/// Sets the <c>libraryId</c> and <c>id</c> route values the endpoint reads the identifiers from.
/// </summary>
/// <param name="libraryId">The raw route value of the library Id.</param>
/// <param name="bookId">The raw route value of the book Id.</param>
private void ConfigureRequest(string libraryId, string bookId)
{
_sut.HttpContext.Request.RouteValues["libraryId"] = libraryId;
_sut.HttpContext.Request.RouteValues["bookId"] = bookId;
}
/// <summary>
/// Leaves the <c>libraryId</c> and <c>id</c> route values unset.
/// </summary>
private void ConfigureRequestWithoutIds()
{
_sut.HttpContext.Request.RouteValues.Remove("libraryId");
_sut.HttpContext.Request.RouteValues.Remove("bookId");
}
}
@@ -1,6 +1,9 @@
#region ========================================================================= USING =====================================================================================
using FastEndpoints;
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.CQRS;
using Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Commands.UpdateBookCover;
using Lumina.Contracts.Fixtures.Core.Responses.MediaLibrary.WrittenContentLibrary.BookLibrary.Books;
using Lumina.Contracts.Responses.MediaLibrary.WrittenContentLibrary.BookLibrary.Books;
using Lumina.Domain.Common.Errors;
using Lumina.Domain.Common.Primitives;
using Lumina.Presentation.Api.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.Books.UpdateBookCover;
using Microsoft.AspNetCore.Http;
@@ -22,110 +25,178 @@ namespace Lumina.Presentation.Api.UnitTests.Core.Endpoints.Library.WrittenConten
[ExcludeFromCodeCoverage]
public class UpdateBookCoverEndpointTests
{
private readonly Application.Common.CQRS.ICommandHandler<UpdateBookCoverCommand, Result<string>> _mockHandler;
private readonly ICommandHandler<UpdateBookCoverCommand, Result<UpdateBookCoverResponse>> _mockHandler;
private readonly UpdateBookCoverEndpoint _sut;
private readonly UpdateBookCoverResponseFixture _updateBookCoverResponseFixture = new();
/// <summary>
/// Initializes a new instance of the <see cref="UpdateBookCoverEndpointTests"/> class.
/// </summary>
public UpdateBookCoverEndpointTests()
{
_mockHandler = Substitute.For<Application.Common.CQRS.ICommandHandler<UpdateBookCoverCommand, Result<string>>>();
_sut = Factory.Create<UpdateBookCoverEndpoint>(_mockHandler);
_mockHandler = Substitute.For<ICommandHandler<UpdateBookCoverCommand, Result<UpdateBookCoverResponse>>>();
_sut = FastEndpoints.Factory.Create<UpdateBookCoverEndpoint>(_mockHandler);
}
[Fact]
public async Task ExecuteAsync_WhenSuccessful_ShouldReturnOkResultWithCoverPath()
{
// Arrange
Guid libraryId = Guid.NewGuid();
Guid bookId = Guid.NewGuid();
CancellationToken cancellationToken = CancellationToken.None;
string expectedPath = "/media/books/cover.jpg";
_mockHandler.HandleAsync(Arg.Any<UpdateBookCoverCommand>(), Arg.Any<CancellationToken>())
.Returns(Result.From(expectedPath));
ConfigureRequest(bookId, [1, 2, 3], "cover.jpg");
.Returns(Result.From(_updateBookCoverResponseFixture.Create(coverPath: expectedPath)));
_sut.HttpContext.Request.RouteValues["libraryId"] = libraryId.ToString();
_sut.HttpContext.Request.RouteValues["bookId"] = bookId.ToString();
ConfigureForm([1, 2, 3], "cover.jpg");
// Act
IResult result = await _sut.ExecuteAsync(EmptyRequest.Instance, cancellationToken);
IResult result = await _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, cancellationToken);
// Assert
Ok<string> okResult = Assert.IsType<Ok<string>>(result);
Assert.Equal(expectedPath, okResult.Value);
Ok<UpdateBookCoverResponse> okResult = Assert.IsType<Ok<UpdateBookCoverResponse>>(result);
Assert.Equal(expectedPath, okResult.Value.CoverPath);
}
[Fact]
public async Task ExecuteAsync_WhenCalledWithValidRouteIdAndFile_ShouldSendUpdateBookCoverCommand()
public async Task ExecuteAsync_WhenCalledWithValidRouteIdsAndFile_ShouldSendUpdateBookCoverCommandToSender()
{
// Arrange
Guid libraryId = Guid.NewGuid();
Guid bookId = Guid.NewGuid();
CancellationToken cancellationToken = CancellationToken.None;
_mockHandler.HandleAsync(Arg.Any<UpdateBookCoverCommand>(), Arg.Any<CancellationToken>())
.Returns(Result.From("/media/books/cover.jpg"));
ConfigureRequest(bookId, [1, 2, 3], "cover.jpg");
.Returns(Result.From(_updateBookCoverResponseFixture.Create(coverPath: "/media/books/cover.jpg")));
_sut.HttpContext.Request.RouteValues["libraryId"] = libraryId.ToString();
_sut.HttpContext.Request.RouteValues["bookId"] = bookId.ToString();
ConfigureForm([1, 2, 3], "cover.jpg");
// Act
await _sut.ExecuteAsync(EmptyRequest.Instance, cancellationToken);
await _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, cancellationToken);
// Assert
await _mockHandler.Received(1).HandleAsync(
Arg.Is<UpdateBookCoverCommand>(command =>
command.BookId == bookId &&
command.LibraryId == libraryId.ToString() &&
command.BookId == bookId.ToString() &&
command.Cover != null &&
command.FileName == "cover.jpg"),
Arg.Is(cancellationToken));
}
[Fact]
public async Task ExecuteAsync_WhenRouteIdIsNotParseable_ShouldSendCommandWithEmptyBookId()
public async Task ExecuteAsync_WhenRouteValuesAreNotParseable_ShouldSendCommandWithRawRouteValues()
{
// Arrange
CancellationToken cancellationToken = CancellationToken.None;
_mockHandler.HandleAsync(Arg.Any<UpdateBookCoverCommand>(), Arg.Any<CancellationToken>())
.Returns(Result.From("/media/books/cover.jpg"));
ConfigureRequest("not-a-guid", [1, 2, 3], "cover.jpg");
.Returns(Result.From(_updateBookCoverResponseFixture.Create(coverPath: "/media/books/cover.jpg")));
_sut.HttpContext.Request.RouteValues["libraryId"] = "not-a-library-guid";
_sut.HttpContext.Request.RouteValues["bookId"] = "not-a-guid";
ConfigureForm([1, 2, 3], "cover.jpg");
// Act
await _sut.ExecuteAsync(EmptyRequest.Instance, cancellationToken);
await _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, cancellationToken);
// Assert
await _mockHandler.Received(1).HandleAsync(
Arg.Is<UpdateBookCoverCommand>(command => command.BookId == Guid.Empty && command.Cover != null),
Arg.Any<CancellationToken>());
Arg.Is<UpdateBookCoverCommand>(command => command.LibraryId == "not-a-library-guid" && command.BookId == "not-a-guid"),
Arg.Is(cancellationToken));
}
[Fact]
public async Task ExecuteAsync_WhenRouteValuesAreMissing_ShouldSendCommandWithNullIds()
{
// Arrange
CancellationToken cancellationToken = CancellationToken.None;
_mockHandler.HandleAsync(Arg.Any<UpdateBookCoverCommand>(), Arg.Any<CancellationToken>())
.Returns(Result.From(_updateBookCoverResponseFixture.Create(coverPath: "/media/books/cover.jpg")));
_sut.HttpContext.Request.RouteValues.Remove("libraryId");
_sut.HttpContext.Request.RouteValues.Remove("bookId");
ConfigureForm([1, 2, 3], "cover.jpg");
// Act
await _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, cancellationToken);
// Assert
await _mockHandler.Received(1).HandleAsync(
Arg.Is<UpdateBookCoverCommand>(command => command.LibraryId == null && command.BookId == null),
Arg.Is(cancellationToken));
}
[Fact]
public async Task ExecuteAsync_WhenFormHasNoFiles_ShouldSendCommandWithNullCover()
{
// Arrange
Guid libraryId = Guid.NewGuid();
Guid bookId = Guid.NewGuid();
CancellationToken cancellationToken = CancellationToken.None;
_mockHandler.HandleAsync(Arg.Any<UpdateBookCoverCommand>(), Arg.Any<CancellationToken>())
.Returns(Result.From("/media/books/cover.jpg"));
ConfigureRequestWithoutFiles(bookId);
.Returns(Result.From(_updateBookCoverResponseFixture.Create(coverPath: "/media/books/cover.jpg")));
_sut.HttpContext.Request.RouteValues["libraryId"] = libraryId.ToString();
_sut.HttpContext.Request.RouteValues["bookId"] = bookId.ToString();
IFormCollection form = new FormCollection([]);
_sut.HttpContext.Request.ContentType = "multipart/form-data; boundary=----test";
_sut.HttpContext.Features.Set<IFormFeature>(new FormFeature(form));
// Act
IResult result = await _sut.ExecuteAsync(EmptyRequest.Instance, cancellationToken);
IResult result = await _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, cancellationToken);
// Assert
Assert.IsType<Ok<string>>(result);
Assert.IsType<Ok<UpdateBookCoverResponse>>(result);
await _mockHandler.Received(1).HandleAsync(
Arg.Is<UpdateBookCoverCommand>(command => command.BookId == bookId && command.Cover == null && command.FileName == null),
Arg.Is<UpdateBookCoverCommand>(command => command.BookId == bookId.ToString() && command.Cover == null && command.FileName == null),
Arg.Any<CancellationToken>());
}
[Fact]
public async Task ExecuteAsync_WhenHandlerReturnsError_ShouldReturnProblemResult()
public async Task ExecuteAsync_WhenHandlerReturnsValidationErrors_ShouldReturnValidationProblemResult()
{
// Arrange
Guid libraryId = Guid.NewGuid();
Guid bookId = Guid.NewGuid();
CancellationToken cancellationToken = CancellationToken.None;
Error validationError = Errors.WrittenContent.BookIdCannotBeEmpty;
_mockHandler.HandleAsync(Arg.Any<UpdateBookCoverCommand>(), Arg.Any<CancellationToken>())
.Returns(validationError);
_sut.HttpContext.Request.RouteValues["libraryId"] = libraryId.ToString();
_sut.HttpContext.Request.RouteValues["bookId"] = bookId.ToString();
ConfigureForm([1, 2, 3], "cover.jpg");
// Act
IResult result = await _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, cancellationToken);
// Assert
ProblemHttpResult problemDetails = Assert.IsType<ProblemHttpResult>(result);
Assert.Equal(StatusCodes.Status422UnprocessableEntity, problemDetails.StatusCode);
Assert.Equal("application/problem+json", problemDetails.ContentType);
HttpValidationProblemDetails validationProblemDetails = Assert.IsType<HttpValidationProblemDetails>(problemDetails.ProblemDetails);
Assert.Equal(StatusCodes.Status422UnprocessableEntity, validationProblemDetails.Status);
Assert.Equal("General.Validation", validationProblemDetails.Title);
Assert.Equal("OneOrMoreValidationErrorsOccurred", validationProblemDetails.Detail);
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_WhenHandlerReturnsNotFoundError_ShouldReturnProblemResult()
{
// Arrange
Guid libraryId = Guid.NewGuid();
Guid bookId = Guid.NewGuid();
CancellationToken cancellationToken = CancellationToken.None;
Error expectedError = Error.NotFound("Book.NotFound", "BookNotFound");
_mockHandler.HandleAsync(Arg.Any<UpdateBookCoverCommand>(), Arg.Any<CancellationToken>())
.Returns(expectedError);
ConfigureRequest(bookId, [1, 2, 3], "cover.jpg");
_sut.HttpContext.Request.RouteValues["libraryId"] = libraryId.ToString();
_sut.HttpContext.Request.RouteValues["bookId"] = bookId.ToString();
ConfigureForm([1, 2, 3], "cover.jpg");
// Act
IResult result = await _sut.ExecuteAsync(EmptyRequest.Instance, cancellationToken);
IResult result = await _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, cancellationToken);
// Assert
ProblemHttpResult problemDetails = Assert.IsType<ProblemHttpResult>(result);
@@ -138,14 +209,8 @@ public class UpdateBookCoverEndpointTests
Assert.NotNull(problemDetailsBody.Extensions["traceId"]);
}
private void ConfigureRequest(Guid bookId, byte[] content, string fileName)
private void ConfigureForm(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];
@@ -153,12 +218,4 @@ public class UpdateBookCoverEndpointTests
_sut.HttpContext.Request.ContentType = "multipart/form-data; boundary=----test";
_sut.HttpContext.Features.Set<IFormFeature>(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<IFormFeature>(new FormFeature(form));
}
}
@@ -59,7 +59,7 @@ public class GetLibraryBookReadersEndpointTests
}
[Fact]
public async Task ExecuteAsync_WhenHandlerReturnsError_ShouldReturnProblemResult()
public async Task ExecuteAsync_WhenHandlerReturnsFailureError_ShouldReturnProblemResult()
{
// Arrange
GetLibraryBookReadersRequest request = _getLibraryBookReadersRequestFixture.Create();
@@ -53,7 +53,7 @@ public class SetLibraryBookReaderEnabledEndpointTests
}
[Fact]
public async Task ExecuteAsync_WhenHandlerReturnsError_ShouldReturnProblemResult()
public async Task ExecuteAsync_WhenHandlerReturnsFailureError_ShouldReturnProblemResult()
{
// Arrange
SetLibraryBookReaderEnabledRequest request = _setLibraryBookReaderEnabledRequestFixture.Create();
@@ -44,7 +44,7 @@ public class GetBookDetailsEndpointTests
{
// Arrange
GetBookRequest request = _getBookRequestFixture.Create();
BookDetailsDto expectedBook = _bookDetailsDtoFixture.Create(id: Guid.Parse(request.Id));
BookDetailsDto expectedBook = _bookDetailsDtoFixture.Create(id: Guid.Parse(request.BookId));
_mockApiHttpClient.GetAsync<BookDetailsDto>(Arg.Any<string>(), Arg.Any<CancellationToken>())
.Returns(expectedBook);
@@ -53,7 +53,7 @@ public class GetBookDetailsEndpointTests
// Assert
await _mockApiHttpClient.Received(1).GetAsync<BookDetailsDto>(
Arg.Is<string>(endpoint => endpoint == ApiRoutes.Books.GET_BOOK.Replace("{id}", request.Id)),
Arg.Is<string>(endpoint => endpoint == ApiRoutes.Books.GET_BOOK.Replace("{libraryId}", request.LibraryId.ToString()).Replace("{bookId}", request.BookId)),
Arg.Any<CancellationToken>());
}
@@ -62,7 +62,7 @@ public class GetBookDetailsEndpointTests
{
// Arrange
GetBookRequest request = _getBookRequestFixture.Create();
BookDetailsDto expectedBook = _bookDetailsDtoFixture.Create(id: Guid.Parse(request.Id));
BookDetailsDto expectedBook = _bookDetailsDtoFixture.Create(id: Guid.Parse(request.BookId));
_mockApiHttpClient.GetAsync<BookDetailsDto>(Arg.Any<string>(), Arg.Any<CancellationToken>())
.Returns(expectedBook);
@@ -63,8 +63,7 @@ public class GetLibraryItemsEndpointTests
// Assert
await _mockApiHttpClient.Received(1).GetAsync<PaginatedBookLiteDto>(
Arg.Is<string>(endpoint =>
endpoint.StartsWith(ApiRoutes.Books.GET_BOOKS_LITE, StringComparison.OrdinalIgnoreCase) &&
endpoint.Contains($"libraryId={request.LibraryId}") &&
endpoint.StartsWith(ApiRoutes.Books.GET_BOOKS_LITE.Replace("{libraryId}", request.LibraryId.ToString()), StringComparison.OrdinalIgnoreCase) &&
endpoint.Contains("currentPage=2") &&
endpoint.Contains("perPage=48") &&
endpoint.Contains("searchTerm=the%20hobbit") &&
@@ -89,8 +88,8 @@ public class GetLibraryItemsEndpointTests
// Assert
await _mockApiHttpClient.Received(1).GetAsync<PaginatedBookLiteDto>(
Arg.Is<string>(endpoint =>
endpoint.StartsWith(ApiRoutes.Books.GET_BOOKS_LITE, StringComparison.OrdinalIgnoreCase) &&
endpoint.EndsWith($"libraryId={request.LibraryId}&shouldIgnoreThePrefixForAlphaPicker=False", StringComparison.OrdinalIgnoreCase) &&
endpoint.StartsWith(ApiRoutes.Books.GET_BOOKS_LITE.Replace("{libraryId}", request.LibraryId.ToString()), StringComparison.OrdinalIgnoreCase) &&
endpoint.EndsWith("?shouldIgnoreThePrefixForAlphaPicker=False", StringComparison.OrdinalIgnoreCase) &&
!endpoint.Contains("currentPage=") &&
!endpoint.Contains("searchTerm=") &&
!endpoint.Contains("sortBy=")),
@@ -45,7 +45,7 @@ public class GetReadingAvailabilityEndpointTests
// Arrange
GetBookReadingAvailabilityRequest request = _requestFixture.Create();
ReadingAvailabilityDto availability = _readingAvailabilityDtoFixture.Create(bookId: request.BookId, isAvailable: true);
_mockApiHttpClient.GetAsync<ReadingAvailabilityDto>(ApiRoutes.Books.GET_BOOK_READING_AVAILABILITY.Replace("{bookId}", request.BookId.ToString()), Arg.Any<CancellationToken>())
_mockApiHttpClient.GetAsync<ReadingAvailabilityDto>(ApiRoutes.Books.GET_BOOK_READING_AVAILABILITY.Replace("{libraryId}", request.LibraryId.ToString()).Replace("{bookId}", request.BookId.ToString()), Arg.Any<CancellationToken>())
.Returns(availability);
// Act
@@ -64,7 +64,7 @@ public class GetReadingAvailabilityEndpointTests
// Arrange
GetBookReadingAvailabilityRequest request = _requestFixture.Create();
ReadingAvailabilityDto availability = _readingAvailabilityDtoFixture.Create(bookId: request.BookId, isAvailable: false, errorCode: "ReaderDisabled");
_mockApiHttpClient.GetAsync<ReadingAvailabilityDto>(ApiRoutes.Books.GET_BOOK_READING_AVAILABILITY.Replace("{bookId}", request.BookId.ToString()), Arg.Any<CancellationToken>())
_mockApiHttpClient.GetAsync<ReadingAvailabilityDto>(ApiRoutes.Books.GET_BOOK_READING_AVAILABILITY.Replace("{libraryId}", request.LibraryId.ToString()).Replace("{bookId}", request.BookId.ToString()), Arg.Any<CancellationToken>())
.Returns(availability);
// Act
@@ -81,15 +81,15 @@ public class GetReadingAvailabilityEndpointTests
public async Task ExecuteAsync_WhenCalled_ShouldRequestReadingAvailabilityFromApi()
{
// Arrange
GetBookReadingAvailabilityRequest request = new(BookId: Guid.NewGuid());
GetBookReadingAvailabilityRequest request = _requestFixture.Create();
ReadingAvailabilityDto availability = _readingAvailabilityDtoFixture.Create(bookId: request.BookId, isAvailable: true);
_mockApiHttpClient.GetAsync<ReadingAvailabilityDto>(ApiRoutes.Books.GET_BOOK_READING_AVAILABILITY.Replace("{bookId}", request.BookId.ToString()), Arg.Any<CancellationToken>())
_mockApiHttpClient.GetAsync<ReadingAvailabilityDto>(ApiRoutes.Books.GET_BOOK_READING_AVAILABILITY.Replace("{libraryId}", request.LibraryId.ToString()).Replace("{bookId}", request.BookId.ToString()), Arg.Any<CancellationToken>())
.Returns(availability);
// Act
await _sut.ExecuteAsync(request, CancellationToken.None);
// Assert
await _mockApiHttpClient.Received(1).GetAsync<ReadingAvailabilityDto>(ApiRoutes.Books.GET_BOOK_READING_AVAILABILITY.Replace("{bookId}", request.BookId.ToString()), Arg.Any<CancellationToken>());
await _mockApiHttpClient.Received(1).GetAsync<ReadingAvailabilityDto>(ApiRoutes.Books.GET_BOOK_READING_AVAILABILITY.Replace("{libraryId}", request.LibraryId.ToString()).Replace("{bookId}", request.BookId.ToString()), Arg.Any<CancellationToken>());
}
}
@@ -49,7 +49,7 @@ public class GetReadingManifestEndpointTests
// Arrange
GetBookReadingManifestRequest request = _requestFixture.Create();
ReadingManifestDto manifest = _readingManifestDtoFixture.Create();
_mockApiHttpClient.GetAsync<ReadingManifestDto>(ApiRoutes.Books.GET_BOOK_READING_MANIFEST.Replace("{bookId}", request.BookId.ToString()), Arg.Any<CancellationToken>())
_mockApiHttpClient.GetAsync<ReadingManifestDto>(ApiRoutes.Books.GET_BOOK_READING_MANIFEST.Replace("{libraryId}", request.LibraryId.ToString()).Replace("{bookId}", request.BookId.ToString()), Arg.Any<CancellationToken>())
.Returns(manifest);
// Act
@@ -119,13 +119,13 @@ public class GetReadingManifestEndpointTests
// Arrange
GetBookReadingManifestRequest request = _requestFixture.Create();
ReadingManifestDto manifest = _readingManifestDtoFixture.Create();
_mockApiHttpClient.GetAsync<ReadingManifestDto>(ApiRoutes.Books.GET_BOOK_READING_MANIFEST.Replace("{bookId}", request.BookId.ToString()), Arg.Any<CancellationToken>())
_mockApiHttpClient.GetAsync<ReadingManifestDto>(ApiRoutes.Books.GET_BOOK_READING_MANIFEST.Replace("{libraryId}", request.LibraryId.ToString()).Replace("{bookId}", request.BookId.ToString()), Arg.Any<CancellationToken>())
.Returns(manifest);
// Act
await _sut.ExecuteAsync(request, CancellationToken.None);
// Assert
await _mockApiHttpClient.Received(1).GetAsync<ReadingManifestDto>(ApiRoutes.Books.GET_BOOK_READING_MANIFEST.Replace("{bookId}", request.BookId.ToString()), Arg.Any<CancellationToken>());
await _mockApiHttpClient.Received(1).GetAsync<ReadingManifestDto>(ApiRoutes.Books.GET_BOOK_READING_MANIFEST.Replace("{libraryId}", request.LibraryId.ToString()).Replace("{bookId}", request.BookId.ToString()), Arg.Any<CancellationToken>());
}
}
@@ -65,6 +65,7 @@ public class GetReadingResourceEndpointTests
_mockApiHttpClient.GetBlobAsync(Arg.Any<string>(), Arg.Any<CancellationToken>())
.Returns(blob);
string expectedEndpoint = ApiRoutes.Books.GET_BOOK_READING_RESOURCE
.Replace("{libraryId}", request.LibraryId.ToString())
.Replace("{bookId}", request.BookId.ToString())
.Replace("{resourceKey}", Uri.EscapeDataString(request.ResourceKey));
@@ -67,6 +67,7 @@ public class GetReadingSectionEndpointTests
_mockApiHttpClient.GetAsync<ReadingSectionDto>(Arg.Any<string>(), Arg.Any<CancellationToken>())
.Returns(section);
string expectedEndpoint = ApiRoutes.Books.GET_BOOK_READING_SECTION
.Replace("{libraryId}", request.LibraryId.ToString())
.Replace("{bookId}", request.BookId.ToString())
.Replace("{locationRef}", Uri.EscapeDataString(request.LocationRef));
@@ -1,8 +1,10 @@
#region ========================================================================= USING =====================================================================================
#region ========================================================================= USING =====================================================================================
using FastEndpoints;
using Lumina.Presentation.Web.Common.Api;
using Lumina.Presentation.Web.Common.DTO.WrittenContentLibrary.BookLibrary;
using Lumina.Presentation.Web.Common.Routes;
using Lumina.Presentation.Web.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.Books.UpdateBookCover;
using Lumina.Presentation.Web.Fixtures.Common.DTO.WrittenContentLibrary.BookLibrary;
using Lumina.Presentation.Web.Fixtures.Common.TestHelpers;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Http.Features;
@@ -26,6 +28,8 @@ public class UpdateBookCoverEndpointTests
{
private readonly IApiHttpClient _mockApiHttpClient;
private readonly UpdateBookCoverEndpoint _sut;
private readonly UpdateBookCoverDtoFixture _updateBookCoverDtoFixture = new();
private static readonly Guid s_libraryId = Guid.NewGuid();
/// <summary>
/// Initializes a new instance of the <see cref="UpdateBookCoverEndpointTests"/> class.
@@ -41,16 +45,16 @@ public class UpdateBookCoverEndpointTests
{
// Arrange
Guid bookId = Guid.NewGuid();
_mockApiHttpClient.PutMultipartAsync<string>(Arg.Any<string>(), Arg.Any<Stream>(), Arg.Any<string>(), Arg.Any<string>(), Arg.Any<CancellationToken>())
.Returns("/media/books/cover.jpg");
_mockApiHttpClient.PutMultipartAsync<UpdateBookCoverDto>(Arg.Any<string>(), Arg.Any<Stream>(), Arg.Any<string>(), Arg.Any<string>(), Arg.Any<CancellationToken>())
.Returns(_updateBookCoverDtoFixture.Create(coverPath: "/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<string>(
Arg.Is<string>(endpoint => endpoint == ApiRoutes.Books.UPDATE_BOOK_COVER.Replace("{id}", bookId.ToString())),
await _mockApiHttpClient.Received(1).PutMultipartAsync<UpdateBookCoverDto>(
Arg.Is<string>(endpoint => endpoint == ApiRoutes.Books.UPDATE_BOOK_COVER.Replace("{libraryId}", s_libraryId.ToString()).Replace("{bookId}", bookId.ToString())),
Arg.Any<Stream>(),
Arg.Is<string>(fileName => fileName == "cover.jpg"),
Arg.Is<string>(fieldName => fieldName == "cover"),
@@ -61,16 +65,16 @@ public class UpdateBookCoverEndpointTests
public async Task ExecuteAsync_WhenRouteIdIsNotParseable_ShouldUploadCoverWithEmptyBookId()
{
// Arrange
_mockApiHttpClient.PutMultipartAsync<string>(Arg.Any<string>(), Arg.Any<Stream>(), Arg.Any<string>(), Arg.Any<string>(), Arg.Any<CancellationToken>())
.Returns("/media/books/cover.jpg");
_mockApiHttpClient.PutMultipartAsync<UpdateBookCoverDto>(Arg.Any<string>(), Arg.Any<Stream>(), Arg.Any<string>(), Arg.Any<string>(), Arg.Any<CancellationToken>())
.Returns(_updateBookCoverDtoFixture.Create(coverPath: "/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<string>(
Arg.Is<string>(endpoint => endpoint == ApiRoutes.Books.UPDATE_BOOK_COVER.Replace("{id}", Guid.Empty.ToString())),
await _mockApiHttpClient.Received(1).PutMultipartAsync<UpdateBookCoverDto>(
Arg.Is<string>(endpoint => endpoint == ApiRoutes.Books.UPDATE_BOOK_COVER.Replace("{libraryId}", s_libraryId.ToString()).Replace("{bookId}", Guid.Empty.ToString())),
Arg.Any<Stream>(),
Arg.Any<string>(),
Arg.Any<string>(),
@@ -83,8 +87,8 @@ public class UpdateBookCoverEndpointTests
// Arrange
Guid bookId = Guid.NewGuid();
string expectedPath = "/media/books/cover.jpg";
_mockApiHttpClient.PutMultipartAsync<string>(Arg.Any<string>(), Arg.Any<Stream>(), Arg.Any<string>(), Arg.Any<string>(), Arg.Any<CancellationToken>())
.Returns(expectedPath);
_mockApiHttpClient.PutMultipartAsync<UpdateBookCoverDto>(Arg.Any<string>(), Arg.Any<Stream>(), Arg.Any<string>(), Arg.Any<string>(), Arg.Any<CancellationToken>())
.Returns(_updateBookCoverDtoFixture.Create(coverPath: expectedPath));
ConfigureRequest(bookId, [1, 2, 3], "cover.jpg");
// Act
@@ -98,20 +102,57 @@ public class UpdateBookCoverEndpointTests
}
[Fact]
public async Task ExecuteAsync_WhenFormHasNoFile_ShouldReturnBadRequestProblem()
public async Task ExecuteAsync_WhenFormHasNoFile_ShouldForwardRequestWithoutFileToApi()
{
// Arrange
Guid bookId = Guid.NewGuid();
string expectedPath = "/media/books/cover.jpg";
_mockApiHttpClient.PutMultipartAsync<UpdateBookCoverDto>(Arg.Any<string>(), Arg.Any<Stream?>(), Arg.Any<string?>(), Arg.Any<string>(), Arg.Any<CancellationToken>())
.Returns(_updateBookCoverDtoFixture.Create(coverPath: expectedPath));
ConfigureRequestWithoutFiles(bookId);
// Act
IResult result = await _sut.ExecuteAsync(EmptyRequest.Instance, CancellationToken.None);
string body = await JsonResultTestHelper.GetResponseBodyAsync(result);
// Assert
ProblemHttpResult problemDetails = Assert.IsType<ProblemHttpResult>(result);
Assert.Equal(StatusCodes.Status400BadRequest, problemDetails.StatusCode);
Assert.Equal("The uploaded cover image is missing.", problemDetails.ProblemDetails.Detail);
await _mockApiHttpClient.DidNotReceive().PutMultipartAsync<string>(Arg.Any<string>(), Arg.Any<Stream>(), Arg.Any<string>(), Arg.Any<string>(), Arg.Any<CancellationToken>());
await _mockApiHttpClient.Received(1).PutMultipartAsync<UpdateBookCoverDto>(
Arg.Is<string>(endpoint => endpoint == ApiRoutes.Books.UPDATE_BOOK_COVER.Replace("{libraryId}", s_libraryId.ToString()).Replace("{bookId}", bookId.ToString())),
Arg.Is<Stream?>(stream => stream == null),
Arg.Is<string?>(fileName => fileName == null),
Arg.Is<string>(fieldName => fieldName == "cover"),
Arg.Any<CancellationToken>());
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_WhenRequestIsNotMultipart_ShouldForwardRequestWithoutFileToApi()
{
// Arrange
Guid bookId = Guid.NewGuid();
string expectedPath = "/media/books/cover.jpg";
_mockApiHttpClient.PutMultipartAsync<UpdateBookCoverDto>(Arg.Any<string>(), Arg.Any<Stream?>(), Arg.Any<string?>(), Arg.Any<string>(), Arg.Any<CancellationToken>())
.Returns(_updateBookCoverDtoFixture.Create(coverPath: expectedPath));
_sut.HttpContext.Request.RouteValues["bookId"] = bookId.ToString();
_sut.HttpContext.Request.QueryString = new QueryString($"?libraryId={s_libraryId}");
_sut.HttpContext.Request.ContentType = "application/json";
// Act
IResult result = await _sut.ExecuteAsync(EmptyRequest.Instance, CancellationToken.None);
string body = await JsonResultTestHelper.GetResponseBodyAsync(result);
// Assert
await _mockApiHttpClient.Received(1).PutMultipartAsync<UpdateBookCoverDto>(
Arg.Is<string>(endpoint => endpoint == ApiRoutes.Books.UPDATE_BOOK_COVER.Replace("{libraryId}", s_libraryId.ToString()).Replace("{bookId}", bookId.ToString())),
Arg.Is<Stream?>(stream => stream == null),
Arg.Is<string?>(fileName => fileName == null),
Arg.Is<string>(fieldName => fieldName == "cover"),
Arg.Any<CancellationToken>());
using JsonDocument jsonDocument = JsonDocument.Parse(body);
Assert.True(jsonDocument.RootElement.GetProperty("success").GetBoolean());
Assert.Equal(expectedPath, jsonDocument.RootElement.GetProperty("data").GetString());
}
private void ConfigureRequest(Guid bookId, byte[] content, string fileName)
@@ -121,7 +162,8 @@ public class UpdateBookCoverEndpointTests
private void ConfigureRequest(string bookId, byte[] content, string fileName)
{
_sut.HttpContext.Request.RouteValues["id"] = bookId;
_sut.HttpContext.Request.RouteValues["bookId"] = bookId;
_sut.HttpContext.Request.QueryString = new QueryString($"?libraryId={s_libraryId}");
MemoryStream coverStream = new(content);
IFormFile formFile = new FormFile(coverStream, 0, content.Length, "cover", fileName);
FormFileCollection files = [formFile];
@@ -132,7 +174,8 @@ public class UpdateBookCoverEndpointTests
private void ConfigureRequestWithoutFiles(Guid bookId)
{
_sut.HttpContext.Request.RouteValues["id"] = bookId.ToString();
_sut.HttpContext.Request.RouteValues["bookId"] = bookId.ToString();
_sut.HttpContext.Request.QueryString = new QueryString($"?libraryId={s_libraryId}");
IFormCollection form = new FormCollection([]);
_sut.HttpContext.Request.ContentType = "multipart/form-data; boundary=----test";
_sut.HttpContext.Features.Set<IFormFeature>(new FormFeature(form));