Adds book deletion and restore to the web client.

Soft deletes books so the scan keeps their paths reserved, lists the deleted books on a themed page, and lets the user restore them. Updates the API, bundled themes, localization, documentation and tests.

Closes #213
This commit is contained in:
BinaryAlley committed 2026-11-13 18:00:00 +02:00
1 parent ef5ede6325
commit f26b07d4ff
125 files changed
+9856 -378

No files matched your search

@@ -1,23 +1,17 @@
#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.BookLibrary;
using Lumina.Application.Common.DataAccess.Repositories.MediaLibrary;
using Lumina.Application.Common.DataAccess.UoW;
using Lumina.Application.Common.Infrastructure.Authentication;
using Lumina.Application.Common.Infrastructure.Authorization;
using Lumina.Application.Common.Infrastructure.Authorization.Policies.LibraryOwnership;
using Lumina.Application.Common.Infrastructure.Validation;
using Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Artwork;
using Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Commands.DeleteBook;
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.DeleteBook;
using Lumina.Domain.Common.Primitives;
using Microsoft.Extensions.Logging;
using NSubstitute;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Threading;
using System.Threading.Tasks;
@@ -35,9 +29,6 @@ public class DeleteBookCommandHandlerTests
{
private readonly IUnitOfWork _mockUnitOfWork;
private readonly IBookRepository _mockBookRepository;
private readonly ILibraryRepository _mockLibraryRepository;
private readonly IBookArtworkService _mockBookArtworkService;
private readonly ILogger<DeleteBookCommandHandler> _mockLogger;
private readonly IAuthorizationService _mockAuthorizationService;
private readonly ICurrentUserService _mockCurrentUserService;
private readonly IValidator<DeleteBookCommand> _mockValidator;
@@ -45,7 +36,6 @@ public class DeleteBookCommandHandlerTests
private readonly Guid _userId;
private readonly DeleteBookCommandFixture _deleteBookCommandFixture = new();
private readonly BookEntityFixture _bookEntityFixture = new();
private readonly LibraryEntityFixture _libraryEntityFixture = new();
/// <summary>
/// Initializes a new instance of the <see cref="DeleteBookCommandHandlerTests"/> class.
@@ -54,37 +44,30 @@ public class DeleteBookCommandHandlerTests
{
_mockUnitOfWork = Substitute.For<IUnitOfWork>();
_mockBookRepository = Substitute.For<IBookRepository>();
_mockLibraryRepository = Substitute.For<ILibraryRepository>();
_mockUnitOfWork.BookRepository.Returns(_mockBookRepository);
_mockUnitOfWork.LibraryRepository.Returns(_mockLibraryRepository);
_mockBookArtworkService = Substitute.For<IBookArtworkService>();
_mockLogger = Substitute.For<ILogger<DeleteBookCommandHandler>>();
_mockAuthorizationService = Substitute.For<IAuthorizationService>();
_mockCurrentUserService = Substitute.For<ICurrentUserService>();
_mockValidator = Substitute.For<IValidator<DeleteBookCommand>>();
_userId = Guid.NewGuid();
// Default stubs: the command is valid, the current user is authenticated, the ownership policy allows the deletion, the book has no author, the library exists, the artwork deletion succeeds, the book deletion succeeds and saving changes succeeds.
// Default stubs: the command is valid, the current user is authenticated, the ownership policy allows the deletion, the book exists,
// marking it as deleted succeeds, and saving changes succeeds.
_mockValidator.Validate(Arg.Any<DeleteBookCommand>()).Returns([]);
_mockCurrentUserService.UserId.Returns(_userId);
_mockAuthorizationService.EvaluatePolicyAsync<ILibraryOwnershipPolicy>(_userId, Arg.Any<LibraryOwnershipPolicyContext>(), Arg.Any<CancellationToken>())
.Returns(true);
_mockLibraryRepository.GetByIdAsync(Arg.Any<Guid>(), Arg.Any<bool>(), Arg.Any<bool>(), Arg.Any<CancellationToken>())
.Returns(_ => Result.From<LibraryEntity?>(_libraryEntityFixture.Create()));
_mockBookRepository.GetAuthorsDisplayNamesByBookIdsAsync(Arg.Any<IReadOnlyCollection<Guid>>(), Arg.Any<CancellationToken>())
.Returns(Result.From<IReadOnlyDictionary<Guid, string?>>(new Dictionary<Guid, string?>()));
_mockBookArtworkService.DeleteBookArtwork(Arg.Any<Guid>(), Arg.Any<Guid>(), Arg.Any<string>(), Arg.Any<string>(), Arg.Any<string>())
.Returns(Result.Deleted);
_mockBookRepository.DeleteByIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>())
.Returns(Result.Deleted);
_mockBookRepository.GetByIdAsync(Arg.Any<Guid>(), Arg.Any<bool>(), Arg.Any<bool>(), Arg.Any<CancellationToken>())
.Returns(_ => Result.From<BookEntity?>(_bookEntityFixture.Create(includeMetadata: false)));
_mockBookRepository.SoftDeleteByIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>())
.Returns(Result.Updated);
_mockUnitOfWork.SaveChangesAsync(Arg.Any<CancellationToken>())
.Returns(Result.Success);
_sut = new DeleteBookCommandHandler(_mockUnitOfWork, _mockBookArtworkService, _mockLogger, _mockAuthorizationService, _mockCurrentUserService, _mockValidator);
_sut = new DeleteBookCommandHandler(_mockUnitOfWork, _mockAuthorizationService, _mockCurrentUserService, _mockValidator);
}
[Fact]
public async Task HandleAsync_WhenBookExists_ShouldDeleteBookAndReturnDeleted()
public async Task HandleAsync_WhenBookExists_ShouldSoftDeleteBookAndReturnDeleted()
{
// Arrange
DeleteBookCommand command = _deleteBookCommandFixture.Create();
@@ -100,42 +83,12 @@ public class DeleteBookCommandHandlerTests
// Assert
Assert.False(result.IsFailure);
Assert.Equal(Result.Deleted, result.Value);
// The stored artwork of the book is removed before the book row, so that no artwork file is orphaned.
Received.InOrder(() =>
{
_mockBookArtworkService.DeleteBookArtwork(libraryId, bookId, Arg.Any<string>(), Arg.Any<string>(), book.Title);
_mockBookRepository.DeleteByIdAsync(bookId, Arg.Any<CancellationToken>());
});
await _mockBookRepository.Received(1).DeleteByIdAsync(bookId, Arg.Any<CancellationToken>());
await _mockBookRepository.Received(1).SoftDeleteByIdAsync(bookId, Arg.Any<CancellationToken>());
await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any<CancellationToken>());
await _mockAuthorizationService.Received(1).EvaluatePolicyAsync<ILibraryOwnershipPolicy>(
_userId, Arg.Is<LibraryOwnershipPolicyContext>(context => context.LibraryId == libraryId), Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenBookHasAnAuthor_ShouldDeleteTheArtworkUnderTheAuthorSegments()
{
// Arrange
DeleteBookCommand command = _deleteBookCommandFixture.Create();
Guid libraryId = Guid.Parse(command.LibraryId!);
Guid bookId = Guid.Parse(command.BookId!);
BookEntity book = _bookEntityFixture.Create(id: bookId, libraryId: libraryId, includeMetadata: false);
LibraryEntity library = _libraryEntityFixture.Create(id: libraryId);
_mockBookRepository.GetByIdAsync(bookId, shouldIncludeNavigationProperties: false, shouldTrackEntities: false, cancellationToken: Arg.Any<CancellationToken>())
.Returns(Result.From<BookEntity?>(book));
_mockLibraryRepository.GetByIdAsync(libraryId, shouldTrackEntities: false, cancellationToken: Arg.Any<CancellationToken>())
.Returns(Result.From<LibraryEntity?>(library));
_mockBookRepository.GetAuthorsDisplayNamesByBookIdsAsync(Arg.Any<IReadOnlyCollection<Guid>>(), Arg.Any<CancellationToken>())
.Returns(Result.From<IReadOnlyDictionary<Guid, string?>>(new Dictionary<Guid, string?> { [bookId] = "J.R.R. Tolkien" }));
// Act
Result<Deleted> result = await _sut.HandleAsync(command, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
_mockBookArtworkService.Received(1).DeleteBookArtwork(libraryId, bookId, library.Title, "J.R.R. Tolkien", book.Title);
}
[Fact]
public async Task HandleAsync_WhenValidationFails_ShouldReturnValidationErrorsWithoutTouchingAnyRepository()
{
@@ -151,8 +104,7 @@ public class DeleteBookCommandHandlerTests
Assert.True(result.IsFailure);
Assert.Equal(DomainErrors.WrittenContent.BookIdCannotBeEmpty, result.FirstError);
await _mockBookRepository.DidNotReceive().GetByIdAsync(Arg.Any<Guid>(), Arg.Any<bool>(), Arg.Any<bool>(), Arg.Any<CancellationToken>());
_mockBookArtworkService.DidNotReceive().DeleteBookArtwork(Arg.Any<Guid>(), Arg.Any<Guid>(), Arg.Any<string>(), Arg.Any<string>(), Arg.Any<string>());
await _mockBookRepository.DidNotReceive().DeleteByIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
await _mockBookRepository.DidNotReceive().SoftDeleteByIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
}
@@ -187,7 +139,7 @@ public class DeleteBookCommandHandlerTests
// Assert
Assert.True(result.IsFailure);
Assert.Equal(ApplicationErrors.Persistence.UniqueConstraintViolation, result.FirstError);
await _mockBookRepository.DidNotReceive().DeleteByIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
await _mockBookRepository.DidNotReceive().SoftDeleteByIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
}
@@ -251,14 +203,12 @@ public class DeleteBookCommandHandlerTests
Assert.Equal(ApplicationErrors.Authorization.NotAuthorized, result.FirstError);
await _mockAuthorizationService.Received(1).EvaluatePolicyAsync<ILibraryOwnershipPolicy>(
_userId, Arg.Is<LibraryOwnershipPolicyContext>(context => context.LibraryId == libraryId), Arg.Any<CancellationToken>());
await _mockLibraryRepository.DidNotReceive().GetByIdAsync(Arg.Any<Guid>(), Arg.Any<bool>(), Arg.Any<bool>(), Arg.Any<CancellationToken>());
_mockBookArtworkService.DidNotReceive().DeleteBookArtwork(Arg.Any<Guid>(), Arg.Any<Guid>(), Arg.Any<string>(), Arg.Any<string>(), Arg.Any<string>());
await _mockBookRepository.DidNotReceive().DeleteByIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
await _mockBookRepository.DidNotReceive().SoftDeleteByIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenLibraryRepositoryFails_ShouldReturnFailureResultWithoutDeleting()
public async Task HandleAsync_WhenSoftDeleteFails_ShouldReturnErrorWithoutSaving()
{
// Arrange
DeleteBookCommand command = _deleteBookCommandFixture.Create();
@@ -267,7 +217,7 @@ public class DeleteBookCommandHandlerTests
BookEntity book = _bookEntityFixture.Create(id: bookId, libraryId: libraryId, includeMetadata: false);
_mockBookRepository.GetByIdAsync(bookId, shouldIncludeNavigationProperties: false, shouldTrackEntities: false, cancellationToken: Arg.Any<CancellationToken>())
.Returns(Result.From<BookEntity?>(book));
_mockLibraryRepository.GetByIdAsync(Arg.Any<Guid>(), Arg.Any<bool>(), Arg.Any<bool>(), Arg.Any<CancellationToken>())
_mockBookRepository.SoftDeleteByIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>())
.Returns(ApplicationErrors.Persistence.UniqueConstraintViolation);
// Act
@@ -276,101 +226,7 @@ public class DeleteBookCommandHandlerTests
// Assert
Assert.True(result.IsFailure);
Assert.Equal(ApplicationErrors.Persistence.UniqueConstraintViolation, result.FirstError);
_mockBookArtworkService.DidNotReceive().DeleteBookArtwork(Arg.Any<Guid>(), Arg.Any<Guid>(), Arg.Any<string>(), Arg.Any<string>(), Arg.Any<string>());
await _mockBookRepository.DidNotReceive().DeleteByIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenLibraryDoesNotExist_ShouldReturnLibraryNotFoundError()
{
// Arrange
DeleteBookCommand command = _deleteBookCommandFixture.Create();
Guid libraryId = Guid.Parse(command.LibraryId!);
Guid bookId = Guid.Parse(command.BookId!);
BookEntity book = _bookEntityFixture.Create(id: bookId, libraryId: libraryId, includeMetadata: false);
_mockBookRepository.GetByIdAsync(bookId, shouldIncludeNavigationProperties: false, shouldTrackEntities: false, cancellationToken: Arg.Any<CancellationToken>())
.Returns(Result.From<BookEntity?>(book));
_mockLibraryRepository.GetByIdAsync(Arg.Any<Guid>(), Arg.Any<bool>(), Arg.Any<bool>(), Arg.Any<CancellationToken>())
.Returns(_ => Result.From<LibraryEntity?>(null));
// Act
Result<Deleted> result = await _sut.HandleAsync(command, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(DomainErrors.Library.LibraryNotFound, result.FirstError);
_mockBookArtworkService.DidNotReceive().DeleteBookArtwork(Arg.Any<Guid>(), Arg.Any<Guid>(), Arg.Any<string>(), Arg.Any<string>(), Arg.Any<string>());
await _mockBookRepository.DidNotReceive().DeleteByIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenAuthorLookupFails_ShouldReturnErrorWithoutDeleting()
{
// Arrange
DeleteBookCommand command = _deleteBookCommandFixture.Create();
Guid libraryId = Guid.Parse(command.LibraryId!);
Guid bookId = Guid.Parse(command.BookId!);
BookEntity book = _bookEntityFixture.Create(id: bookId, libraryId: libraryId, includeMetadata: false);
_mockBookRepository.GetByIdAsync(bookId, shouldIncludeNavigationProperties: false, shouldTrackEntities: false, cancellationToken: Arg.Any<CancellationToken>())
.Returns(Result.From<BookEntity?>(book));
_mockBookRepository.GetAuthorsDisplayNamesByBookIdsAsync(Arg.Any<IReadOnlyCollection<Guid>>(), Arg.Any<CancellationToken>())
.Returns(ApplicationErrors.Persistence.UniqueConstraintViolation);
// Act
Result<Deleted> result = await _sut.HandleAsync(command, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(ApplicationErrors.Persistence.UniqueConstraintViolation, result.FirstError);
_mockBookArtworkService.DidNotReceive().DeleteBookArtwork(Arg.Any<Guid>(), Arg.Any<Guid>(), Arg.Any<string>(), Arg.Any<string>(), Arg.Any<string>());
await _mockBookRepository.DidNotReceive().DeleteByIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenArtworkDeletionFails_ShouldStillDeleteTheBook()
{
// Arrange
DeleteBookCommand command = _deleteBookCommandFixture.Create();
Guid libraryId = Guid.Parse(command.LibraryId!);
Guid bookId = Guid.Parse(command.BookId!);
BookEntity book = _bookEntityFixture.Create(id: bookId, libraryId: libraryId, includeMetadata: false);
_mockBookRepository.GetByIdAsync(bookId, shouldIncludeNavigationProperties: false, shouldTrackEntities: false, cancellationToken: Arg.Any<CancellationToken>())
.Returns(Result.From<BookEntity?>(book));
_mockBookArtworkService.DeleteBookArtwork(Arg.Any<Guid>(), Arg.Any<Guid>(), Arg.Any<string>(), Arg.Any<string>(), Arg.Any<string>())
.Returns(Error.Failure(description: "Failed to delete the artwork"));
// Act
Result<Deleted> result = await _sut.HandleAsync(command, CancellationToken.None);
// Assert
// A stale cover file must not prevent the book from being removed.
Assert.False(result.IsFailure);
Assert.Equal(Result.Deleted, result.Value);
await _mockBookRepository.Received(1).DeleteByIdAsync(bookId, Arg.Any<CancellationToken>());
await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenDeleteBookFails_ShouldReturnErrorWithoutSaving()
{
// Arrange
DeleteBookCommand command = _deleteBookCommandFixture.Create();
Guid libraryId = Guid.Parse(command.LibraryId!);
Guid bookId = Guid.Parse(command.BookId!);
BookEntity book = _bookEntityFixture.Create(id: bookId, libraryId: libraryId, includeMetadata: false);
_mockBookRepository.GetByIdAsync(bookId, shouldIncludeNavigationProperties: false, shouldTrackEntities: false, cancellationToken: Arg.Any<CancellationToken>())
.Returns(Result.From<BookEntity?>(book));
_mockBookRepository.DeleteByIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>())
.Returns(ApplicationErrors.Persistence.UniqueConstraintViolation);
// Act
Result<Deleted> result = await _sut.HandleAsync(command, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(ApplicationErrors.Persistence.UniqueConstraintViolation, result.FirstError);
await _mockBookRepository.Received(1).DeleteByIdAsync(bookId, Arg.Any<CancellationToken>());
await _mockBookRepository.Received(1).SoftDeleteByIdAsync(bookId, Arg.Any<CancellationToken>());
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
}
@@ -393,6 +249,6 @@ public class DeleteBookCommandHandlerTests
// Assert
Assert.True(result.IsFailure);
Assert.Equal(ApplicationErrors.Persistence.UniqueConstraintViolation, result.FirstError);
await _mockBookRepository.Received(1).DeleteByIdAsync(bookId, Arg.Any<CancellationToken>());
await _mockBookRepository.Received(1).SoftDeleteByIdAsync(bookId, Arg.Any<CancellationToken>());
}
}
@@ -0,0 +1,253 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary;
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;
using Lumina.Application.Common.Infrastructure.Authorization.Policies.LibraryOwnership;
using Lumina.Application.Common.Infrastructure.Validation;
using Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Commands.RestoreBook;
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary;
using Lumina.Application.Fixtures.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Commands.RestoreBook;
using Lumina.Domain.Common.Primitives;
using NSubstitute;
using System;
using System.Diagnostics.CodeAnalysis;
using System.Threading;
using System.Threading.Tasks;
using ApplicationErrors = Lumina.Application.Common.Errors.Errors;
using DomainErrors = Lumina.Domain.Common.Errors.Errors;
#endregion
namespace Lumina.Application.UnitTests.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Commands.RestoreBook;
/// <summary>
/// Contains unit tests for the <see cref="RestoreBookCommandHandler"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class RestoreBookCommandHandlerTests
{
private readonly IUnitOfWork _mockUnitOfWork;
private readonly IBookRepository _mockBookRepository;
private readonly IAuthorizationService _mockAuthorizationService;
private readonly ICurrentUserService _mockCurrentUserService;
private readonly IValidator<RestoreBookCommand> _mockValidator;
private readonly RestoreBookCommandHandler _sut;
private readonly Guid _userId;
private readonly RestoreBookCommandFixture _restoreBookCommandFixture = new();
private readonly BookEntityFixture _bookEntityFixture = new();
/// <summary>
/// Initializes a new instance of the <see cref="RestoreBookCommandHandlerTests"/> class.
/// </summary>
public RestoreBookCommandHandlerTests()
{
_mockUnitOfWork = Substitute.For<IUnitOfWork>();
_mockBookRepository = Substitute.For<IBookRepository>();
_mockUnitOfWork.BookRepository.Returns(_mockBookRepository);
_mockAuthorizationService = Substitute.For<IAuthorizationService>();
_mockCurrentUserService = Substitute.For<ICurrentUserService>();
_mockValidator = Substitute.For<IValidator<RestoreBookCommand>>();
_userId = Guid.NewGuid();
// Default stubs: the command is valid, the current user is authenticated, the ownership policy allows the restoration, the deleted
// book exists, restoring it succeeds, and saving changes succeeds.
_mockValidator.Validate(Arg.Any<RestoreBookCommand>()).Returns([]);
_mockCurrentUserService.UserId.Returns(_userId);
_mockAuthorizationService.EvaluatePolicyAsync<ILibraryOwnershipPolicy>(_userId, Arg.Any<LibraryOwnershipPolicyContext>(), Arg.Any<CancellationToken>())
.Returns(true);
_mockBookRepository.GetSoftDeletedByIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>())
.Returns(_ => Result.From<BookEntity?>(_bookEntityFixture.Create(isDeleted: true, includeMetadata: false)));
_mockBookRepository.RestoreSoftDeletedByIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>())
.Returns(Result.Updated);
_mockUnitOfWork.SaveChangesAsync(Arg.Any<CancellationToken>())
.Returns(Result.Success);
_sut = new RestoreBookCommandHandler(_mockUnitOfWork, _mockAuthorizationService, _mockCurrentUserService, _mockValidator);
}
[Fact]
public async Task HandleAsync_WhenDeletedBookExists_ShouldRestoreBookAndReturnUpdated()
{
// Arrange
RestoreBookCommand command = _restoreBookCommandFixture.Create();
Guid libraryId = Guid.Parse(command.LibraryId!);
Guid bookId = Guid.Parse(command.BookId!);
BookEntity book = _bookEntityFixture.Create(id: bookId, libraryId: libraryId, isDeleted: true, includeMetadata: false);
_mockBookRepository.GetSoftDeletedByIdAsync(bookId, Arg.Any<CancellationToken>())
.Returns(Result.From<BookEntity?>(book));
// Act
Result<Updated> result = await _sut.HandleAsync(command, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
Assert.Equal(Result.Updated, result.Value);
await _mockBookRepository.Received(1).RestoreSoftDeletedByIdAsync(bookId, Arg.Any<CancellationToken>());
await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any<CancellationToken>());
await _mockAuthorizationService.Received(1).EvaluatePolicyAsync<ILibraryOwnershipPolicy>(
_userId, Arg.Is<LibraryOwnershipPolicyContext>(context => context.LibraryId == libraryId), Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenValidationFails_ShouldReturnValidationErrorsWithoutTouchingAnyRepository()
{
// Arrange
RestoreBookCommand command = _restoreBookCommandFixture.Create();
_mockValidator.Validate(Arg.Any<RestoreBookCommand>())
.Returns([DomainErrors.WrittenContent.BookIdCannotBeEmpty]);
// Act
Result<Updated> result = await _sut.HandleAsync(command, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(DomainErrors.WrittenContent.BookIdCannotBeEmpty, result.FirstError);
await _mockBookRepository.DidNotReceive().GetSoftDeletedByIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
await _mockBookRepository.DidNotReceive().RestoreSoftDeletedByIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenUserIsNotAuthenticated_ShouldReturnNotAuthorizedError()
{
// Arrange
RestoreBookCommand command = _restoreBookCommandFixture.Create();
_mockCurrentUserService.UserId.Returns((Guid?)null);
// Act
Result<Updated> result = await _sut.HandleAsync(command, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(ApplicationErrors.Authorization.NotAuthorized, result.FirstError);
await _mockBookRepository.DidNotReceive().GetSoftDeletedByIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
await _mockAuthorizationService.DidNotReceive().EvaluatePolicyAsync<ILibraryOwnershipPolicy>(Arg.Any<Guid>(), Arg.Any<LibraryOwnershipPolicyContext>(), Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenBookRepositoryFails_ShouldReturnFailureResultWithoutRestoring()
{
// Arrange
RestoreBookCommand command = _restoreBookCommandFixture.Create();
_mockBookRepository.GetSoftDeletedByIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>())
.Returns(ApplicationErrors.Persistence.UniqueConstraintViolation);
// Act
Result<Updated> result = await _sut.HandleAsync(command, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(ApplicationErrors.Persistence.UniqueConstraintViolation, result.FirstError);
await _mockBookRepository.DidNotReceive().RestoreSoftDeletedByIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenDeletedBookDoesNotExist_ShouldReturnBookNotFoundError()
{
// Arrange
RestoreBookCommand command = _restoreBookCommandFixture.Create();
_mockBookRepository.GetSoftDeletedByIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>())
.Returns(_ => Result.From<BookEntity?>(null));
// Act
Result<Updated> result = await _sut.HandleAsync(command, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(DomainErrors.WrittenContent.BookNotFound, result.FirstError);
await _mockAuthorizationService.DidNotReceive().EvaluatePolicyAsync<ILibraryOwnershipPolicy>(Arg.Any<Guid>(), Arg.Any<LibraryOwnershipPolicyContext>(), Arg.Any<CancellationToken>());
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenBookBelongsToAnotherLibrary_ShouldReturnBookNotFoundWithoutEvaluatingThePolicy()
{
// Arrange
RestoreBookCommand command = _restoreBookCommandFixture.Create();
Guid bookId = Guid.Parse(command.BookId!);
BookEntity book = _bookEntityFixture.Create(id: bookId, libraryId: Guid.NewGuid(), isDeleted: true, includeMetadata: false);
_mockBookRepository.GetSoftDeletedByIdAsync(bookId, Arg.Any<CancellationToken>())
.Returns(Result.From<BookEntity?>(book));
// Act
Result<Updated> result = await _sut.HandleAsync(command, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(DomainErrors.WrittenContent.BookNotFound, result.FirstError);
await _mockAuthorizationService.DidNotReceive().EvaluatePolicyAsync<ILibraryOwnershipPolicy>(Arg.Any<Guid>(), Arg.Any<LibraryOwnershipPolicyContext>(), Arg.Any<CancellationToken>());
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenPolicyDeniesAccess_ShouldReturnNotAuthorizedError()
{
// Arrange
RestoreBookCommand command = _restoreBookCommandFixture.Create();
Guid libraryId = Guid.Parse(command.LibraryId!);
Guid bookId = Guid.Parse(command.BookId!);
BookEntity book = _bookEntityFixture.Create(id: bookId, libraryId: libraryId, isDeleted: true, includeMetadata: false);
_mockBookRepository.GetSoftDeletedByIdAsync(bookId, Arg.Any<CancellationToken>())
.Returns(Result.From<BookEntity?>(book));
_mockAuthorizationService.EvaluatePolicyAsync<ILibraryOwnershipPolicy>(_userId, Arg.Any<LibraryOwnershipPolicyContext>(), Arg.Any<CancellationToken>())
.Returns(false);
// Act
Result<Updated> result = await _sut.HandleAsync(command, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(ApplicationErrors.Authorization.NotAuthorized, result.FirstError);
await _mockAuthorizationService.Received(1).EvaluatePolicyAsync<ILibraryOwnershipPolicy>(
_userId, Arg.Is<LibraryOwnershipPolicyContext>(context => context.LibraryId == libraryId), Arg.Any<CancellationToken>());
await _mockBookRepository.DidNotReceive().RestoreSoftDeletedByIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenRestoreFails_ShouldReturnErrorWithoutSaving()
{
// Arrange
RestoreBookCommand command = _restoreBookCommandFixture.Create();
Guid libraryId = Guid.Parse(command.LibraryId!);
Guid bookId = Guid.Parse(command.BookId!);
BookEntity book = _bookEntityFixture.Create(id: bookId, libraryId: libraryId, isDeleted: true, includeMetadata: false);
_mockBookRepository.GetSoftDeletedByIdAsync(bookId, Arg.Any<CancellationToken>())
.Returns(Result.From<BookEntity?>(book));
_mockBookRepository.RestoreSoftDeletedByIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>())
.Returns(ApplicationErrors.Persistence.UniqueConstraintViolation);
// Act
Result<Updated> result = await _sut.HandleAsync(command, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(ApplicationErrors.Persistence.UniqueConstraintViolation, result.FirstError);
await _mockBookRepository.Received(1).RestoreSoftDeletedByIdAsync(bookId, Arg.Any<CancellationToken>());
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenSaveChangesFails_ShouldReturnError()
{
// Arrange
RestoreBookCommand command = _restoreBookCommandFixture.Create();
Guid libraryId = Guid.Parse(command.LibraryId!);
Guid bookId = Guid.Parse(command.BookId!);
BookEntity book = _bookEntityFixture.Create(id: bookId, libraryId: libraryId, isDeleted: true, includeMetadata: false);
_mockBookRepository.GetSoftDeletedByIdAsync(bookId, Arg.Any<CancellationToken>())
.Returns(Result.From<BookEntity?>(book));
_mockUnitOfWork.SaveChangesAsync(Arg.Any<CancellationToken>())
.Returns(ApplicationErrors.Persistence.UniqueConstraintViolation);
// Act
Result<Updated> result = await _sut.HandleAsync(command, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(ApplicationErrors.Persistence.UniqueConstraintViolation, result.FirstError);
await _mockBookRepository.Received(1).RestoreSoftDeletedByIdAsync(bookId, Arg.Any<CancellationToken>());
}
}
@@ -0,0 +1,97 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Commands.RestoreBook;
using Lumina.Application.Fixtures.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Commands.RestoreBook;
using Lumina.Application.UnitTests.Common.Setup;
using Lumina.Domain.Common.Errors;
using Lumina.Domain.Common.Primitives;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
#endregion
namespace Lumina.Application.UnitTests.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Commands.RestoreBook;
/// <summary>
/// Contains unit tests for the <see cref="RestoreBookCommandValidator"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class RestoreBookCommandValidatorTests
{
private readonly RestoreBookCommandFixture _restoreBookCommandFixture = new();
private readonly RestoreBookCommandValidator _validator = new();
[Theory]
[InlineData(null)] // missing route value
[InlineData("")] // empty route value
[InlineData(" ")] // whitespace route value, which both the not empty rule and the format rule reject
[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
RestoreBookCommand command = _restoreBookCommandFixture.Create(libraryId: libraryId, includeLibraryId: libraryId is not null);
// Act
List<Error> result = _validator.TestValidate(command);
// Assert
result.ShouldHaveValidationError(Errors.Library.LibraryIdCannotBeEmpty);
}
[Theory]
[InlineData(null)] // missing route value
[InlineData("")] // empty route value
[InlineData(" ")] // whitespace route value, which both the not empty rule and the format rule reject
[InlineData("not-a-book-guid")] // non-Guid route value
[InlineData("00000000-0000-0000-0000-000000000000")] // empty Guid route value
public void Validate_WhenBookIdIsEmptyOrInvalid_ShouldHaveValidationError(string? bookId)
{
// Arrange
RestoreBookCommand command = _restoreBookCommandFixture.Create(bookId: bookId, includeBookId: bookId is not null);
// Act
List<Error> result = _validator.TestValidate(command);
// Assert
result.ShouldHaveValidationError(Errors.WrittenContent.BookIdCannotBeEmpty);
}
[Fact]
public void Validate_WhenLibraryIdIsValid_ShouldNotHaveValidationError()
{
// Arrange
RestoreBookCommand command = _restoreBookCommandFixture.Create(libraryId: Guid.NewGuid().ToString());
// Act
List<Error> result = _validator.TestValidate(command);
// Assert
result.ShouldNotHaveValidationError(Errors.Library.LibraryIdCannotBeEmpty);
}
[Fact]
public void Validate_WhenBookIdIsValid_ShouldNotHaveValidationError()
{
// Arrange
RestoreBookCommand command = _restoreBookCommandFixture.Create(bookId: Guid.NewGuid().ToString());
// Act
List<Error> result = _validator.TestValidate(command);
// Assert
result.ShouldNotHaveValidationError(Errors.WrittenContent.BookIdCannotBeEmpty);
}
[Fact]
public void Validate_WhenCommandIsValid_ShouldNotHaveAnyValidationErrors()
{
// Arrange
RestoreBookCommand command = _restoreBookCommandFixture.Create();
// Act
List<Error> result = _validator.TestValidate(command);
// Assert
result.ShouldNotHaveAnyValidationErrors();
}
}
@@ -0,0 +1,179 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary;
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;
using Lumina.Application.Common.Infrastructure.Authorization.Policies.LibraryOwnership;
using Lumina.Application.Common.Infrastructure.Validation;
using Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Queries.GetDeletedBooks;
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary;
using Lumina.Application.Fixtures.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Queries.GetDeletedBooks;
using Lumina.Contracts.Responses.MediaLibrary.WrittenContentLibrary.BookLibrary.Books;
using Lumina.Domain.Common.Primitives;
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
using NSubstitute;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Threading;
using System.Threading.Tasks;
using ApplicationErrors = Lumina.Application.Common.Errors.Errors;
using DomainErrors = Lumina.Domain.Common.Errors.Errors;
#endregion
namespace Lumina.Application.UnitTests.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Queries.GetDeletedBooks;
/// <summary>
/// Contains unit tests for the <see cref="GetDeletedBooksQueryHandler"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetDeletedBooksQueryHandlerTests
{
private readonly IUnitOfWork _mockUnitOfWork;
private readonly IBookRepository _mockBookRepository;
private readonly IAuthorizationService _mockAuthorizationService;
private readonly ICurrentUserService _mockCurrentUserService;
private readonly IValidator<GetDeletedBooksQuery> _mockValidator;
private readonly GetDeletedBooksQueryHandler _sut;
private readonly Guid _userId;
private readonly BookEntityFixture _bookEntityFixture = new();
private readonly BookArtworkEntityFixture _bookArtworkEntityFixture = new();
private readonly GetDeletedBooksQueryFixture _getDeletedBooksQueryFixture = new();
/// <summary>
/// Initializes a new instance of the <see cref="GetDeletedBooksQueryHandlerTests"/> class.
/// </summary>
public GetDeletedBooksQueryHandlerTests()
{
_mockUnitOfWork = Substitute.For<IUnitOfWork>();
_mockBookRepository = Substitute.For<IBookRepository>();
_mockUnitOfWork.BookRepository.Returns(_mockBookRepository);
_mockAuthorizationService = Substitute.For<IAuthorizationService>();
_mockCurrentUserService = Substitute.For<ICurrentUserService>();
_mockValidator = Substitute.For<IValidator<GetDeletedBooksQuery>>();
_userId = Guid.NewGuid();
// Default stubs: the query is valid, the current user is authenticated and the library ownership policy allows access.
_mockValidator.Validate(Arg.Any<GetDeletedBooksQuery>()).Returns([]);
_mockCurrentUserService.UserId.Returns(_userId);
_mockAuthorizationService.EvaluatePolicyAsync<ILibraryOwnershipPolicy>(_userId, Arg.Any<LibraryOwnershipPolicyContext>(), Arg.Any<CancellationToken>())
.Returns(true);
_mockBookRepository.GetSoftDeletedByLibraryIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>())
.Returns(Result.From<IReadOnlyList<BookEntity>>([]));
_sut = new GetDeletedBooksQueryHandler(_mockUnitOfWork, _mockAuthorizationService, _mockCurrentUserService, _mockValidator);
}
[Fact]
public async Task HandleAsync_WhenDeletedBooksExist_ShouldReturnTheirMappedResponses()
{
// Arrange
GetDeletedBooksQuery query = _getDeletedBooksQueryFixture.Create();
Guid libraryId = Guid.Parse(query.LibraryId!);
string coverFileName = $"covers/{Guid.NewGuid()}.jpg";
BookEntity firstBook = _bookEntityFixture.Create(libraryId: libraryId, isDeleted: true, includeMetadata: false);
firstBook.Artwork = [_bookArtworkEntityFixture.Create(bookId: firstBook.Id, artworkType: ArtworkType.Cover, ordinal: 0, fileName: coverFileName)];
BookEntity secondBook = _bookEntityFixture.Create(libraryId: libraryId, isDeleted: true, includeMetadata: false);
_mockBookRepository.GetSoftDeletedByLibraryIdAsync(libraryId, Arg.Any<CancellationToken>())
.Returns(Result.From<IReadOnlyList<BookEntity>>([firstBook, secondBook]));
// Act
Result<IReadOnlyList<DeletedBookResponse>> result = await _sut.HandleAsync(query, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
Assert.Equal(2, result.Value.Count);
Assert.Equal(firstBook.Id, result.Value[0].Id);
Assert.Equal(firstBook.LibraryId, result.Value[0].LibraryId);
Assert.Equal(firstBook.Title, result.Value[0].Title);
Assert.Equal(firstBook.OriginalTitle, result.Value[0].OriginalTitle);
Assert.Equal(firstBook.Path, result.Value[0].Path);
Assert.Equal(firstBook.DeletedOnUtc ?? firstBook.CreatedOnUtc, result.Value[0].DeletedOnUtc);
Assert.Equal(coverFileName, result.Value[0].CoverPath);
Assert.Equal(secondBook.Id, result.Value[1].Id);
}
[Fact]
public async Task HandleAsync_WhenThereAreNoDeletedBooks_ShouldReturnAnEmptyCollection()
{
// Arrange
GetDeletedBooksQuery query = _getDeletedBooksQueryFixture.Create();
// Act
Result<IReadOnlyList<DeletedBookResponse>> result = await _sut.HandleAsync(query, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
Assert.Empty(result.Value);
}
[Fact]
public async Task HandleAsync_WhenValidationFails_ShouldReturnValidationErrorsWithoutTouchingAnyRepository()
{
// Arrange
GetDeletedBooksQuery query = _getDeletedBooksQueryFixture.Create();
_mockValidator.Validate(Arg.Any<GetDeletedBooksQuery>())
.Returns([DomainErrors.Library.LibraryIdCannotBeEmpty]);
// Act
Result<IReadOnlyList<DeletedBookResponse>> result = await _sut.HandleAsync(query, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(DomainErrors.Library.LibraryIdCannotBeEmpty, result.FirstError);
await _mockBookRepository.DidNotReceive().GetSoftDeletedByLibraryIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenUserIsNotAuthenticated_ShouldReturnNotAuthorizedError()
{
// Arrange
GetDeletedBooksQuery query = _getDeletedBooksQueryFixture.Create();
_mockCurrentUserService.UserId.Returns((Guid?)null);
// Act
Result<IReadOnlyList<DeletedBookResponse>> result = await _sut.HandleAsync(query, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(ApplicationErrors.Authorization.NotAuthorized, result.FirstError);
await _mockBookRepository.DidNotReceive().GetSoftDeletedByLibraryIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenPolicyDeniesAccess_ShouldReturnNotAuthorizedError()
{
// Arrange
GetDeletedBooksQuery query = _getDeletedBooksQueryFixture.Create();
Guid libraryId = Guid.Parse(query.LibraryId!);
_mockAuthorizationService.EvaluatePolicyAsync<ILibraryOwnershipPolicy>(_userId, Arg.Any<LibraryOwnershipPolicyContext>(), Arg.Any<CancellationToken>())
.Returns(false);
// Act
Result<IReadOnlyList<DeletedBookResponse>> result = await _sut.HandleAsync(query, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(ApplicationErrors.Authorization.NotAuthorized, result.FirstError);
await _mockAuthorizationService.Received(1).EvaluatePolicyAsync<ILibraryOwnershipPolicy>(
_userId, Arg.Is<LibraryOwnershipPolicyContext>(context => context.LibraryId == libraryId), Arg.Any<CancellationToken>());
await _mockBookRepository.DidNotReceive().GetSoftDeletedByLibraryIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenBookRepositoryFails_ShouldReturnFailureResult()
{
// Arrange
GetDeletedBooksQuery query = _getDeletedBooksQueryFixture.Create();
_mockBookRepository.GetSoftDeletedByLibraryIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>())
.Returns(ApplicationErrors.Persistence.UniqueConstraintViolation);
// Act
Result<IReadOnlyList<DeletedBookResponse>> result = await _sut.HandleAsync(query, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(ApplicationErrors.Persistence.UniqueConstraintViolation, result.FirstError);
}
}
@@ -0,0 +1,66 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Queries.GetDeletedBooks;
using Lumina.Application.Fixtures.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Queries.GetDeletedBooks;
using Lumina.Application.UnitTests.Common.Setup;
using Lumina.Domain.Common.Errors;
using Lumina.Domain.Common.Primitives;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
#endregion
namespace Lumina.Application.UnitTests.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Queries.GetDeletedBooks;
/// <summary>
/// Contains unit tests for the <see cref="GetDeletedBooksQueryValidator"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetDeletedBooksQueryValidatorTests
{
private readonly GetDeletedBooksQueryFixture _getDeletedBooksQueryFixture = new();
private readonly GetDeletedBooksQueryValidator _validator = new();
[Theory]
[InlineData(null)] // missing route value
[InlineData("")] // empty route value
[InlineData(" ")] // whitespace route value, which both the not empty rule and the format rule reject
[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
GetDeletedBooksQuery query = _getDeletedBooksQueryFixture.Create(libraryId: libraryId, includeLibraryId: libraryId is not null);
// Act
List<Error> result = _validator.TestValidate(query);
// Assert
result.ShouldHaveValidationError(Errors.Library.LibraryIdCannotBeEmpty);
}
[Fact]
public void Validate_WhenLibraryIdIsValid_ShouldNotHaveValidationError()
{
// Arrange
GetDeletedBooksQuery query = _getDeletedBooksQueryFixture.Create(libraryId: Guid.NewGuid().ToString());
// Act
List<Error> result = _validator.TestValidate(query);
// Assert
result.ShouldNotHaveValidationError(Errors.Library.LibraryIdCannotBeEmpty);
}
[Fact]
public void Validate_WhenQueryIsValid_ShouldNotHaveAnyValidationErrors()
{
// Arrange
GetDeletedBooksQuery query = _getDeletedBooksQueryFixture.Create();
// Act
List<Error> result = _validator.TestValidate(query);
// Assert
result.ShouldNotHaveAnyValidationErrors();
}
}
@@ -6,6 +6,7 @@ using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentL
using Lumina.Application.Common.DTO.Filtering;
using Lumina.Application.Common.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary;
using Lumina.Application.Common.DTO.Pagination;
using Lumina.Application.Common.Infrastructure.Time;
using Lumina.Application.Fixtures.Common.DataAccess.Entities.Common;
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaContributors;
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary;
@@ -21,6 +22,7 @@ using Lumina.Domain.SharedKernel.Common.Enums.MediaContributors;
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.ChangeTracking;
using NSubstitute;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
@@ -38,6 +40,7 @@ namespace Lumina.DataAccess.UnitTests.Core.Repositories.BookLibrary;
public class BookRepositoryTests
{
private readonly LuminaDbContext _mockContext;
private readonly IDateTimeProvider _mockDateTimeProvider;
private readonly BookRepository _sut;
private readonly BookEntityFixture _bookEntityFixture = new();
private readonly BookRatingEntityFixture _bookRatingEntityFixture = new();
@@ -57,7 +60,9 @@ public class BookRepositoryTests
public BookRepositoryTests()
{
_mockContext = Create.MockedDbContextFor<LuminaDbContext>();
_sut = new BookRepository(_mockContext);
_mockDateTimeProvider = Substitute.For<IDateTimeProvider>();
_mockDateTimeProvider.UtcNow.Returns(new DateTime(2026, 1, 1, 12, 0, 0, DateTimeKind.Utc));
_sut = new BookRepository(_mockContext, _mockDateTimeProvider);
}
[Fact]
@@ -120,6 +125,25 @@ public class BookRepositoryTests
Assert.Equal(Errors.WrittenContent.BookAlreadyExists, result.FirstError);
}
[Fact]
public async Task InsertAsync_WhenADeletedBookHasTheSamePath_ShouldReturnError()
{
// Arrange
Guid libraryId = Guid.NewGuid();
BookEntity deletedBook = _bookEntityFixture.Create(libraryId: libraryId, path: "/books/deleted.epub", isDeleted: true);
_mockContext.Books.Add(deletedBook);
await _mockContext.SaveChangesAsync();
BookEntity bookModel = _bookEntityFixture.Create(libraryId: libraryId, path: "/books/deleted.epub");
// Act
Result<Created> result = await _sut.InsertAsync(bookModel, CancellationToken.None);
// Assert
// The deleted book keeps its path as a tombstone, so a scan can never insert it again.
Assert.True(result.IsFailure);
Assert.Equal(Errors.WrittenContent.BookAlreadyExists, result.FirstError);
}
[Fact]
public async Task InsertAsync_WhenAnotherLibraryHasABookWithTheSamePath_ShouldAddBookToContextAndReturnCreated()
{
@@ -299,6 +323,24 @@ public class BookRepositoryTests
Assert.Equal(book.Id, result.Value!.Id);
}
[Fact]
public async Task GetByPathAsync_WhenBookIsDeleted_ShouldReturnIt()
{
// Arrange
BookEntity deletedBook = _bookEntityFixture.Create(isDeleted: true);
_mockContext.Books.Add(deletedBook);
await _mockContext.SaveChangesAsync();
// Act
Result<BookEntity?> result = await _sut.GetByPathAsync(deletedBook.LibraryId, deletedBook.Path, CancellationToken.None);
// Assert
// The scan deletion strategy must find the deleted row when its file disappears, so that it can remove it permanently.
Assert.False(result.IsFailure);
Assert.NotNull(result.Value);
Assert.Equal(deletedBook.Id, result.Value!.Id);
}
[Fact]
public async Task GetByPathAsync_WhenBookDoesNotExist_ShouldReturnNull()
{
@@ -383,6 +425,198 @@ public class BookRepositoryTests
Assert.Empty(result.Value);
}
[Fact]
public async Task GetAllAsync_WhenBooksAreDeleted_ShouldExcludeThem()
{
// Arrange
Guid libraryId = Guid.NewGuid();
BookEntity activeBook = _bookEntityFixture.Create(libraryId: libraryId, path: "/books/active.epub");
BookEntity deletedBook = _bookEntityFixture.Create(libraryId: libraryId, path: "/books/deleted.epub", isDeleted: true);
_mockContext.Books.AddRange(activeBook, deletedBook);
await _mockContext.SaveChangesAsync();
LibraryFilterDto filter = _libraryFilterDtoFixture.Create(libraryId: libraryId);
// Act
Result<PaginatedResultDto<BookEntity>> result = await _sut.GetAllAsync<LibraryFilterDto>(filterModel: filter, cancellationToken: CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
Assert.Single(result.Value.Data);
Assert.Equal(activeBook.Id, result.Value.Data[0].Id);
}
[Fact]
public async Task GetByIdAsync_WhenBookIsDeleted_ShouldReturnNull()
{
// Arrange
BookEntity deletedBook = _bookEntityFixture.Create(isDeleted: true);
_mockContext.Books.Add(deletedBook);
await _mockContext.SaveChangesAsync();
// Act
Result<BookEntity?> result = await _sut.GetByIdAsync(deletedBook.Id, cancellationToken: CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
Assert.Null(result.Value);
}
[Fact]
public async Task GetExistingPathsAsync_WhenBookIsDeleted_ShouldStillReportItsPathAsExisting()
{
// Arrange
Guid libraryId = Guid.NewGuid();
BookEntity deletedBook = _bookEntityFixture.Create(libraryId: libraryId, path: "/books/deleted.epub", isDeleted: true);
_mockContext.Books.Add(deletedBook);
await _mockContext.SaveChangesAsync();
// Act
Result<IReadOnlyCollection<string>> result = await _sut.GetExistingPathsAsync(libraryId, ["/books/deleted.epub"], CancellationToken.None);
// Assert
// The path must keep counting as taken, so that a scan never materializes the deleted book back into the catalogue.
Assert.False(result.IsFailure);
Assert.Equal(["/books/deleted.epub"], result.Value);
}
[Fact]
public async Task GetSoftDeletedByLibraryIdAsync_WhenCalled_ShouldReturnOnlyTheDeletedBooksOfTheLibrary()
{
// Arrange
Guid libraryId = Guid.NewGuid();
BookEntity activeBook = _bookEntityFixture.Create(libraryId: libraryId, path: "/books/active.epub");
BookEntity deletedBook = _bookEntityFixture.Create(libraryId: libraryId, path: "/books/deleted.epub", isDeleted: true);
BookEntity otherLibraryDeletedBook = _bookEntityFixture.Create(libraryId: Guid.NewGuid(), path: "/books/other.epub", isDeleted: true);
_mockContext.Books.AddRange(activeBook, deletedBook, otherLibraryDeletedBook);
await _mockContext.SaveChangesAsync();
// Act
Result<IReadOnlyList<BookEntity>> result = await _sut.GetSoftDeletedByLibraryIdAsync(libraryId, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
Assert.Single(result.Value);
Assert.Equal(deletedBook.Id, result.Value[0].Id);
}
[Fact]
public async Task GetSoftDeletedByLibraryIdAsync_WhenCalled_ShouldOrderByTheStoredDeletionTime()
{
// Arrange
Guid libraryId = Guid.NewGuid();
BookEntity olderDeletion = _bookEntityFixture.Create(libraryId: libraryId, isDeleted: true, deletedOnUtc: DateTime.UtcNow.AddHours(-2));
olderDeletion.UpdatedOnUtc = DateTime.UtcNow;
BookEntity newerDeletion = _bookEntityFixture.Create(libraryId: libraryId, isDeleted: true, deletedOnUtc: DateTime.UtcNow.AddHours(-1));
newerDeletion.UpdatedOnUtc = DateTime.UtcNow.AddHours(-3);
_mockContext.Books.AddRange(olderDeletion, newerDeletion);
await _mockContext.SaveChangesAsync();
// Act
Result<IReadOnlyList<BookEntity>> result = await _sut.GetSoftDeletedByLibraryIdAsync(libraryId, CancellationToken.None);
// Assert
// A later write to a deleted row may change its update time, but it must not change the order of the deleted items.
Assert.False(result.IsFailure);
Assert.Equal(2, result.Value.Count);
Assert.Equal(newerDeletion.Id, result.Value[0].Id);
Assert.Equal(olderDeletion.Id, result.Value[1].Id);
}
[Fact]
public async Task GetSoftDeletedByIdAsync_WhenBookIsNotDeleted_ShouldReturnNull()
{
// Arrange
BookEntity activeBook = _bookEntityFixture.Create();
_mockContext.Books.Add(activeBook);
await _mockContext.SaveChangesAsync();
// Act
Result<BookEntity?> result = await _sut.GetSoftDeletedByIdAsync(activeBook.Id, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
Assert.Null(result.Value);
}
[Fact]
public async Task SoftDeleteByIdAsync_WhenCalled_ShouldSetTheDeletionStateAndTime()
{
// Arrange
BookEntity book = _bookEntityFixture.Create();
_mockContext.Books.Add(book);
await _mockContext.SaveChangesAsync();
// Act
Result<Updated> result = await _sut.SoftDeleteByIdAsync(book.Id, CancellationToken.None);
await _mockContext.SaveChangesAsync();
// Assert
Assert.False(result.IsFailure);
Assert.True(book.IsDeleted);
Assert.Equal(_mockDateTimeProvider.UtcNow, book.DeletedOnUtc);
}
[Fact]
public async Task SoftDeleteByIdAsync_WhenBookIsAlreadyDeleted_ShouldReturnBookNotFoundError()
{
// Arrange
BookEntity book = _bookEntityFixture.Create(isDeleted: true);
_mockContext.Books.Add(book);
await _mockContext.SaveChangesAsync();
// Act
Result<Updated> result = await _sut.SoftDeleteByIdAsync(book.Id, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(Errors.WrittenContent.BookNotFound, result.FirstError);
}
[Fact]
public async Task RestoreSoftDeletedByIdAsync_WhenCalled_ShouldClearTheDeletionStateAndTime()
{
// Arrange
BookEntity book = _bookEntityFixture.Create(isDeleted: true, deletedOnUtc: DateTime.UtcNow.AddHours(-1));
_mockContext.Books.Add(book);
await _mockContext.SaveChangesAsync();
// Act
Result<Updated> result = await _sut.RestoreSoftDeletedByIdAsync(book.Id, CancellationToken.None);
await _mockContext.SaveChangesAsync();
// Assert
Assert.False(result.IsFailure);
Assert.False(book.IsDeleted);
Assert.Null(book.DeletedOnUtc);
}
[Fact]
public async Task RestoreSoftDeletedByIdAsync_WhenBookIsNotDeleted_ShouldReturnBookNotFoundError()
{
// Arrange
BookEntity book = _bookEntityFixture.Create();
_mockContext.Books.Add(book);
await _mockContext.SaveChangesAsync();
// Act
Result<Updated> result = await _sut.RestoreSoftDeletedByIdAsync(book.Id, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(Errors.WrittenContent.BookNotFound, result.FirstError);
}
[Fact]
public async Task SoftDeleteByIdAsync_WhenBookDoesNotExist_ShouldReturnBookNotFoundError()
{
// Act
Result<Updated> result = await _sut.SoftDeleteByIdAsync(Guid.NewGuid(), CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(Errors.WrittenContent.BookNotFound, result.FirstError);
}
[Fact]
public async Task GetBooksNeedingMetadataAsync_WhenCalled_ShouldReturnOnlyBooksWhoseMetadataIsNotEnriched()
{
@@ -403,7 +637,11 @@ public class BookRepositoryTests
BookEntity bookOfAnotherLibrary = _bookEntityFixture.Create();
bookOfAnotherLibrary.LibraryId = Guid.NewGuid();
bookOfAnotherLibrary.MetadataStatus = MetadataStatus.Pending;
_mockContext.Books.AddRange(pendingBook, enrichedBook, failedBook, bookOfAnotherLibrary);
BookEntity deletedPendingBook = _bookEntityFixture.Create(isDeleted: true);
deletedPendingBook.LibraryId = libraryId;
deletedPendingBook.Path = "/books/d.epub";
deletedPendingBook.MetadataStatus = MetadataStatus.Pending;
_mockContext.Books.AddRange(pendingBook, enrichedBook, failedBook, bookOfAnotherLibrary, deletedPendingBook);
await _mockContext.SaveChangesAsync();
// Act
@@ -414,6 +652,7 @@ public class BookRepositoryTests
Assert.Equal(2, result.Value.Count);
Assert.Contains(result.Value, book => book.Id == pendingBook.Id);
Assert.Contains(result.Value, book => book.Id == failedBook.Id);
Assert.DoesNotContain(result.Value, book => book.Id == deletedPendingBook.Id);
}
[Fact]
@@ -483,6 +722,8 @@ public class BookRepositoryTests
Guid storedLibraryId = storedBook.LibraryId;
string storedPath = storedBook.Path;
bool storedIsDeleted = storedBook.IsDeleted;
DateTime? storedDeletedOnUtc = storedBook.DeletedOnUtc;
MetadataStatus storedMetadataStatus = storedBook.MetadataStatus;
DateTime? storedLastMetadataUpdateUtc = storedBook.LastMetadataUpdateUtc;
string? storedMetadataProvider = storedBook.MetadataProvider;
@@ -493,6 +734,8 @@ public class BookRepositoryTests
data.Title = "Updated Title";
data.LibraryId = Guid.NewGuid();
data.Path = "/books/updated.epub";
data.IsDeleted = true;
data.DeletedOnUtc = DateTime.UtcNow;
data.MetadataStatus = MetadataStatus.Enriched;
data.LastMetadataUpdateUtc = DateTime.UtcNow;
data.MetadataProvider = "UpdatedProvider";
@@ -501,10 +744,14 @@ public class BookRepositoryTests
// Act
Result<Updated> result = await _sut.UpdateAsync(data, CancellationToken.None);
bool isDeletionStateModified = _mockContext.Entry(storedBook).Property(book => book.IsDeleted).IsModified;
bool isDeletionTimeModified = _mockContext.Entry(storedBook).Property(book => book.DeletedOnUtc).IsModified;
await _mockContext.SaveChangesAsync();
// Assert
Assert.False(result.IsFailure);
Assert.False(isDeletionStateModified);
Assert.False(isDeletionTimeModified);
BookEntity? retrievedBook = await _mockContext.Books
.Include(book => book.Tags)
.Include(book => book.Genres)
@@ -517,6 +764,8 @@ public class BookRepositoryTests
// The identity, enrichment and audit columns of the stored book are never overwritten by an edit.
Assert.Equal(storedLibraryId, retrievedBook.LibraryId);
Assert.Equal(storedPath, retrievedBook.Path);
Assert.Equal(storedIsDeleted, retrievedBook.IsDeleted);
Assert.Equal(storedDeletedOnUtc, retrievedBook.DeletedOnUtc);
Assert.Equal(storedMetadataStatus, retrievedBook.MetadataStatus);
Assert.Equal(storedLastMetadataUpdateUtc, retrievedBook.LastMetadataUpdateUtc);
Assert.Equal(storedMetadataProvider, retrievedBook.MetadataProvider);
@@ -524,6 +773,27 @@ public class BookRepositoryTests
Assert.Equal(storedCreatedBy, retrievedBook.CreatedBy);
}
[Fact]
public async Task UpdateAsync_WhenBookIsDeleted_ShouldReturnBookNotFoundWithoutUpdatingIt()
{
// Arrange
BookEntity storedBook = _bookEntityFixture.Create(isDeleted: true);
_mockContext.Books.Add(storedBook);
await _mockContext.SaveChangesAsync();
string storedTitle = storedBook.Title;
BookEntity data = _bookEntityFixture.Create(id: storedBook.Id);
data.Title = "Updated Title";
// Act
Result<Updated> result = await _sut.UpdateAsync(data, CancellationToken.None);
// Assert
// A soft deleted book can only be brought back by the explicit restore operation, never by an edit.
Assert.True(result.IsFailure);
Assert.Equal(Errors.WrittenContent.BookNotFound, result.FirstError);
Assert.Equal(storedTitle, storedBook.Title);
}
[Fact]
public async Task UpdateAsync_WhenStoredBookHasArtwork_ShouldPreserveTheStoredArtwork()
{
@@ -832,7 +1102,11 @@ public class BookRepositoryTests
BookEntity bookOfAnotherLibrary = _bookEntityFixture.Create();
bookOfAnotherLibrary.LibraryId = Guid.NewGuid();
bookOfAnotherLibrary.Artwork = [];
_mockContext.Books.AddRange(bookWithoutCover, bookWithEnrichedCover, bookWithFailedCover, bookOfAnotherLibrary);
BookEntity deletedBookWithoutCover = _bookEntityFixture.Create(isDeleted: true);
deletedBookWithoutCover.LibraryId = libraryId;
deletedBookWithoutCover.Path = "/books/d.epub";
deletedBookWithoutCover.Artwork = [];
_mockContext.Books.AddRange(bookWithoutCover, bookWithEnrichedCover, bookWithFailedCover, bookOfAnotherLibrary, deletedBookWithoutCover);
await _mockContext.SaveChangesAsync();
// Act
@@ -843,6 +1117,7 @@ public class BookRepositoryTests
Assert.Equal(2, result.Value.Count);
Assert.Contains(result.Value, book => book.Id == bookWithoutCover.Id);
Assert.Contains(result.Value, book => book.Id == bookWithFailedCover.Id);
Assert.DoesNotContain(result.Value, book => book.Id == deletedBookWithoutCover.Id);
}
[Fact]
@@ -859,7 +1134,10 @@ public class BookRepositoryTests
BookEntity bookOfAnotherLibrary = _bookEntityFixture.Create();
bookOfAnotherLibrary.LibraryId = Guid.NewGuid();
bookOfAnotherLibrary.Artwork = [];
_mockContext.Books.AddRange(bookWithoutCover, bookWithEnrichedCover, bookOfAnotherLibrary);
BookEntity deletedBookWithoutCover = _bookEntityFixture.Create(isDeleted: true);
deletedBookWithoutCover.LibraryId = libraryId;
deletedBookWithoutCover.Artwork = [];
_mockContext.Books.AddRange(bookWithoutCover, bookWithEnrichedCover, bookOfAnotherLibrary, deletedBookWithoutCover);
await _mockContext.SaveChangesAsync();
// Act
@@ -998,7 +1276,10 @@ public class BookRepositoryTests
BookEntity bookOfAnotherLibrary = _bookEntityFixture.Create();
bookOfAnotherLibrary.LibraryId = Guid.NewGuid();
bookOfAnotherLibrary.MetadataStatus = MetadataStatus.Pending;
_mockContext.Books.AddRange(pendingBook, enrichedBook, failedBook, bookOfAnotherLibrary);
BookEntity deletedPendingBook = _bookEntityFixture.Create(isDeleted: true);
deletedPendingBook.LibraryId = libraryId;
deletedPendingBook.MetadataStatus = MetadataStatus.Pending;
_mockContext.Books.AddRange(pendingBook, enrichedBook, failedBook, bookOfAnotherLibrary, deletedPendingBook);
await _mockContext.SaveChangesAsync();
// Act
@@ -1191,7 +1472,9 @@ public class BookRepositoryTests
List<BookEntity> books = _bookEntityFixture.CreateMany(3);
foreach (BookEntity book in books)
book.LibraryId = libraryId;
BookEntity deletedBook = _bookEntityFixture.Create(libraryId: libraryId, isDeleted: true);
_mockContext.Books.AddRange(books);
_mockContext.Books.Add(deletedBook);
await _mockContext.SaveChangesAsync();
PaginationDataDto paginationData = _paginationDataDtoFixture.Create(currentPage: 1, perPage: 10);
@@ -1204,6 +1487,7 @@ public class BookRepositoryTests
Assert.False(result.IsFailure);
Assert.Equal(3, result.Value.Count);
Assert.Equal(3, result.Value.Data.Count);
Assert.DoesNotContain(result.Value.Data, row => row.Id == deletedBook.Id);
Assert.Equal(1, result.Value.CurrentPage);
Assert.Equal(10, result.Value.PerPage);
Assert.Equal(1, result.Value.NumberOfPages);
@@ -1492,6 +1776,24 @@ public class BookRepositoryTests
Assert.DoesNotContain(result.Value, book => book.Id == secondBook.Id);
}
[Fact]
public async Task GetByIdsAsync_WhenABookIsDeleted_ShouldExcludeIt()
{
// Arrange
BookEntity activeBook = _bookEntityFixture.Create(includeMetadata: false);
BookEntity deletedBook = _bookEntityFixture.Create(isDeleted: true, includeMetadata: false);
_mockContext.Books.AddRange(activeBook, deletedBook);
await _mockContext.SaveChangesAsync();
// Act
Result<IReadOnlyList<BookEntity>> result = await _sut.GetByIdsAsync([activeBook.Id, deletedBook.Id], false, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
Assert.Single(result.Value);
Assert.Equal(activeBook.Id, result.Value[0].Id);
}
[Fact]
public async Task GetByIdsAsync_WhenNavigationPropertiesShouldNotBeIncluded_ShouldReturnTheRequestedBooks()
{
@@ -101,7 +101,7 @@ public class UnitOfWorkTests
{
// Arrange
LuminaDbContext dbContext = _fixture.Create<LuminaDbContext>();
UnitOfWork unitOfWork = new(dbContext);
UnitOfWork unitOfWork = new(dbContext, Substitute.For<IDateTimeProvider>());
CancellationToken cancellationToken = new();
// Act
@@ -121,7 +121,7 @@ public class UnitOfWorkTests
.UseInMemoryDatabase(databaseName: Guid.NewGuid().ToString())
.Options;
LuminaDbContext dbContext = new(options);
UnitOfWork unitOfWork = new(dbContext);
UnitOfWork unitOfWork = new(dbContext, Substitute.For<IDateTimeProvider>());
dbContext.Roles.Add(_roleEntityFixture.Create(id: Guid.NewGuid(), roleName: "TestRole"));
await dbContext.SaveChangesAsync(CancellationToken.None);
Assert.NotEmpty(dbContext.ChangeTracker.Entries());
@@ -154,6 +154,6 @@ public class UnitOfWorkTests
private UnitOfWork CreateUnitOfWork()
{
return new(_fixture.Create<LuminaDbContext>());
return new(_fixture.Create<LuminaDbContext>(), Substitute.For<IDateTimeProvider>());
}
}
@@ -107,6 +107,25 @@ public class BooksMediaLibraryScanItemMaterializerTests
_mockPathTemplateService.Received(1).Parse(Arg.Any<LibraryType>(), Arg.Any<LibraryPathTemplate>(), "Artist\\track.epub", '\\');
}
[Fact]
public async Task MaterializeItemsAsync_WhenPathIsAlreadyUsedByADeletedBook_ShouldNotInsertItAgain()
{
// Arrange
LibraryEntity library = _libraryEntityFixture.Create(id: _libraryId, libraryType: LibraryType.Book, contentLocations: ["C:\\Music"]);
_mockLibraryRepository.GetByIdAsync(_libraryId, cancellationToken: Arg.Any<CancellationToken>())
.Returns(Result.From<LibraryEntity?>(library));
_mockBookRepository.GetExistingPathsAsync(_libraryId, Arg.Any<IReadOnlyCollection<string>>(), Arg.Any<CancellationToken>())
.Returns(Result.From<IReadOnlyCollection<string>>(["C:\\Music\\deleted.epub"]));
// Act
Result<Success> result = await _sut.MaterializeItemsAsync(_mockUnitOfWork, _libraryId, _scanId, CreatePathSet("C:\\Music\\deleted.epub"), CancellationToken.None);
// Assert
// A deleted book keeps its stored path, so the scan treats the file as already catalogued and never materializes it again.
Assert.False(result.IsFailure);
await _mockBookRepository.DidNotReceive().InsertAsync(Arg.Any<BookEntity>(), Arg.Any<CancellationToken>());
}
/// <summary>
/// Creates the set of media library scan snapshot paths that the media library scan produces.
/// </summary>
@@ -1,6 +1,7 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DataAccess.UoW;
using Lumina.Application.Common.DomainEvents;
using Lumina.Application.Common.Infrastructure.Time;
using Lumina.DataAccess.Core.UoW;
using Lumina.Domain.Common.Events;
using Lumina.Presentation.Api.Common.Http;
@@ -72,7 +73,7 @@ public class EventualConsistencyMiddlewareTests
using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-eventual-consistency-abort-{Guid.NewGuid()};Mode=Memory;Cache=Shared");
anchorConnection.Open();
using LuminaDbContext dbContext = CreateContext(anchorConnection);
using UnitOfWork unitOfWork = new(dbContext);
using UnitOfWork unitOfWork = new(dbContext, Substitute.For<IDateTimeProvider>());
await dbContext.Database.ExecuteSqlRawAsync("CREATE TABLE CommitProbe (Id INTEGER NOT NULL PRIMARY KEY);");
CapturingHttpResponseFeature responseFeature = new();
DefaultHttpContext httpContext = new();
@@ -112,7 +113,7 @@ public class EventualConsistencyMiddlewareTests
using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-eventual-consistency-rollback-{Guid.NewGuid()};Mode=Memory;Cache=Shared");
anchorConnection.Open();
using LuminaDbContext dbContext = CreateContext(anchorConnection);
using UnitOfWork unitOfWork = new(dbContext);
using UnitOfWork unitOfWork = new(dbContext, Substitute.For<IDateTimeProvider>());
await dbContext.Database.ExecuteSqlRawAsync("CREATE TABLE CommitProbe (Id INTEGER NOT NULL PRIMARY KEY);");
CapturingHttpResponseFeature responseFeature = new();
DefaultHttpContext httpContext = new();
@@ -0,0 +1,161 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.CQRS;
using Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Queries.GetDeletedBooks;
using Lumina.Application.Fixtures.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Queries.GetDeletedBooks;
using Lumina.Contracts.Fixtures.Responses.MediaLibrary.WrittenContentLibrary.BookLibrary.Books;
using Lumina.Contracts.Responses.MediaLibrary.WrittenContentLibrary.BookLibrary.Books;
using Lumina.Domain.Common.Primitives;
using Lumina.Presentation.Api.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.Books.GetDeletedBooks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Http.HttpResults;
using Microsoft.AspNetCore.Mvc;
using NSubstitute;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Threading;
using System.Threading.Tasks;
using ApplicationErrors = Lumina.Application.Common.Errors.Errors;
using DomainErrors = Lumina.Domain.Common.Errors.Errors;
#endregion
namespace Lumina.Presentation.Api.UnitTests.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.Books.GetDeletedBooks;
/// <summary>
/// Contains unit tests for the <see cref="GetDeletedBooksEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetDeletedBooksEndpointTests
{
private readonly IQueryHandler<GetDeletedBooksQuery, Result<IReadOnlyList<DeletedBookResponse>>> _mockHandler;
private readonly GetDeletedBooksEndpoint _sut;
private readonly DeletedBookResponseFixture _deletedBookResponseFixture = new();
private readonly GetDeletedBooksQueryFixture _getDeletedBooksQueryFixture = new();
/// <summary>
/// Initializes a new instance of the <see cref="GetDeletedBooksEndpointTests"/> class.
/// </summary>
public GetDeletedBooksEndpointTests()
{
_mockHandler = Substitute.For<IQueryHandler<GetDeletedBooksQuery, Result<IReadOnlyList<DeletedBookResponse>>>>();
_sut = FastEndpoints.Factory.Create<GetDeletedBooksEndpoint>(_mockHandler);
}
[Fact]
public async Task ExecuteAsync_WhenSuccessful_ShouldReturnOkResultWithDeletedBooks()
{
// Arrange
Guid libraryId = Guid.NewGuid();
IReadOnlyList<DeletedBookResponse> expectedBooks =
[
_deletedBookResponseFixture.Create(
libraryId: libraryId,
title: "The Hobbit",
includeOriginalTitle: false,
includeCoverPath: false)
];
_mockHandler.HandleAsync(Arg.Any<GetDeletedBooksQuery>(), Arg.Any<CancellationToken>())
.Returns(Result.From(expectedBooks));
_sut.HttpContext.Request.RouteValues["libraryId"] = libraryId.ToString();
// Act
IResult result = await _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, CancellationToken.None);
// Assert
Ok<IReadOnlyList<DeletedBookResponse>> okResult = Assert.IsType<Ok<IReadOnlyList<DeletedBookResponse>>>(result);
Assert.Equal(expectedBooks, okResult.Value);
}
[Fact]
public async Task ExecuteAsync_WhenHandlerReturnsNotAuthorizedError_ShouldReturnProblemResult()
{
// Arrange
Error expectedError = ApplicationErrors.Authorization.NotAuthorized;
_mockHandler.HandleAsync(Arg.Any<GetDeletedBooksQuery>(), Arg.Any<CancellationToken>())
.Returns(expectedError);
_sut.HttpContext.Request.RouteValues["libraryId"] = Guid.NewGuid().ToString();
// Act
IResult result = await _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, CancellationToken.None);
// Assert
ProblemHttpResult problemDetails = Assert.IsType<ProblemHttpResult>(result);
Assert.Equal(StatusCodes.Status403Forbidden, problemDetails.StatusCode);
Assert.Equal("application/problem+json", problemDetails.ContentType);
ProblemDetails problemDetailsBody = Assert.IsType<ProblemDetails>(problemDetails.ProblemDetails);
Assert.Equal(StatusCodes.Status403Forbidden, problemDetailsBody.Status);
Assert.Equal("General.Unauthorized", problemDetailsBody.Title);
Assert.Equal("NotAuthorized", problemDetailsBody.Detail);
Assert.Equal("https://tools.ietf.org/html/rfc9110#section-15.5.4", problemDetailsBody.Type);
Assert.NotNull(problemDetailsBody.Extensions["traceId"]);
}
[Fact]
public async Task ExecuteAsync_WhenHandlerReturnsValidationErrors_ShouldReturnValidationProblemResult()
{
// Arrange
Error validationError = DomainErrors.Library.LibraryIdCannotBeEmpty;
_mockHandler.HandleAsync(Arg.Any<GetDeletedBooksQuery>(), Arg.Any<CancellationToken>())
.Returns(validationError);
_sut.HttpContext.Request.RouteValues["libraryId"] = Guid.NewGuid().ToString();
// Act
IResult result = await _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, CancellationToken.None);
// 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[] { "LibraryIdCannotBeEmpty" }, validationProblemDetails.Errors["General.Validation"]);
}
[Fact]
public async Task ExecuteAsync_WhenCalled_ShouldSendTheRouteLibraryIdToTheHandler()
{
// Arrange
Guid libraryId = Guid.NewGuid();
_mockHandler.HandleAsync(Arg.Any<GetDeletedBooksQuery>(), Arg.Any<CancellationToken>())
.Returns(Result.From<IReadOnlyList<DeletedBookResponse>>([]));
_sut.HttpContext.Request.RouteValues["libraryId"] = libraryId.ToString();
// Act
await _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, CancellationToken.None);
// Assert
GetDeletedBooksQuery expectedQuery = _getDeletedBooksQueryFixture.Create(libraryId: libraryId.ToString());
await _mockHandler.Received(1).HandleAsync(expectedQuery, Arg.Any<CancellationToken>());
}
[Fact]
public async Task ExecuteAsync_WhenCancellationRequested_ShouldCancelOperation()
{
// Arrange
CancellationTokenSource cts = new();
TaskCompletionSource<bool> operationStarted = new();
TaskCompletionSource<bool> cancellationRequested = new();
_mockHandler.HandleAsync(Arg.Any<GetDeletedBooksQuery>(), Arg.Any<CancellationToken>())
.Returns(callInfo => Task.Run(async () =>
{
operationStarted.SetResult(true);
await cancellationRequested.Task;
callInfo.Arg<CancellationToken>().ThrowIfCancellationRequested();
return Result.From<IReadOnlyList<DeletedBookResponse>>([]);
}, callInfo.Arg<CancellationToken>()));
_sut.HttpContext.Request.RouteValues["libraryId"] = Guid.NewGuid().ToString();
// Act
Task<IResult> operationTask = _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, cts.Token);
await operationStarted.Task;
cts.Cancel();
cancellationRequested.SetResult(true);
// Assert
await Assert.ThrowsAnyAsync<OperationCanceledException>(() => operationTask);
}
}
@@ -0,0 +1,185 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.CQRS;
using Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Commands.RestoreBook;
using Lumina.Application.Fixtures.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Commands.RestoreBook;
using Lumina.Domain.Common.Primitives;
using Lumina.Presentation.Api.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.Books.RestoreBook;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Http.HttpResults;
using Microsoft.AspNetCore.Mvc;
using NSubstitute;
using System;
using System.Diagnostics.CodeAnalysis;
using System.Threading;
using System.Threading.Tasks;
using ApplicationErrors = Lumina.Application.Common.Errors.Errors;
using DomainErrors = Lumina.Domain.Common.Errors.Errors;
#endregion
namespace Lumina.Presentation.Api.UnitTests.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.Books.RestoreBook;
/// <summary>
/// Contains unit tests for the <see cref="RestoreBookEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class RestoreBookEndpointTests
{
private readonly ICommandHandler<RestoreBookCommand, Result<Updated>> _mockHandler;
private readonly RestoreBookEndpoint _sut;
private readonly RestoreBookCommandFixture _restoreBookCommandFixture = new();
/// <summary>
/// Initializes a new instance of the <see cref="RestoreBookEndpointTests"/> class.
/// </summary>
public RestoreBookEndpointTests()
{
_mockHandler = Substitute.For<ICommandHandler<RestoreBookCommand, Result<Updated>>>();
_sut = FastEndpoints.Factory.Create<RestoreBookEndpoint>(_mockHandler);
}
[Fact]
public async Task ExecuteAsync_WhenSuccessful_ShouldReturnOkResultWithUpdated()
{
// Arrange
_mockHandler.HandleAsync(Arg.Any<RestoreBookCommand>(), Arg.Any<CancellationToken>())
.Returns(Result.From(Result.Updated));
ConfigureRouteValues();
// Act
IResult result = await _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, CancellationToken.None);
// Assert
Ok<Updated> okResult = Assert.IsType<Ok<Updated>>(result);
Assert.Equal(Result.Updated, okResult.Value);
}
[Fact]
public async Task ExecuteAsync_WhenHandlerReturnsNotFoundError_ShouldReturnProblemResult()
{
// Arrange
Error expectedError = DomainErrors.WrittenContent.BookNotFound;
_mockHandler.HandleAsync(Arg.Any<RestoreBookCommand>(), Arg.Any<CancellationToken>())
.Returns(expectedError);
ConfigureRouteValues();
// Act
IResult result = await _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, CancellationToken.None);
// Assert
ProblemHttpResult problemDetails = Assert.IsType<ProblemHttpResult>(result);
Assert.Equal(StatusCodes.Status404NotFound, problemDetails.StatusCode);
Assert.Equal("application/problem+json", problemDetails.ContentType);
ProblemDetails problemDetailsBody = Assert.IsType<ProblemDetails>(problemDetails.ProblemDetails);
Assert.Equal(StatusCodes.Status404NotFound, problemDetailsBody.Status);
Assert.Equal("General.NotFound", problemDetailsBody.Title);
Assert.Equal("BookNotFound", problemDetailsBody.Detail);
Assert.Equal("https://tools.ietf.org/html/rfc9110#section-15.5.5", problemDetailsBody.Type);
Assert.NotNull(problemDetailsBody.Extensions["traceId"]);
}
[Fact]
public async Task ExecuteAsync_WhenHandlerReturnsNotAuthorizedError_ShouldReturnProblemResult()
{
// Arrange
Error expectedError = ApplicationErrors.Authorization.NotAuthorized;
_mockHandler.HandleAsync(Arg.Any<RestoreBookCommand>(), Arg.Any<CancellationToken>())
.Returns(expectedError);
ConfigureRouteValues();
// Act
IResult result = await _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, CancellationToken.None);
// Assert
ProblemHttpResult problemDetails = Assert.IsType<ProblemHttpResult>(result);
Assert.Equal(StatusCodes.Status403Forbidden, problemDetails.StatusCode);
Assert.Equal("application/problem+json", problemDetails.ContentType);
ProblemDetails problemDetailsBody = Assert.IsType<ProblemDetails>(problemDetails.ProblemDetails);
Assert.Equal(StatusCodes.Status403Forbidden, problemDetailsBody.Status);
Assert.Equal("General.Unauthorized", problemDetailsBody.Title);
Assert.Equal("NotAuthorized", problemDetailsBody.Detail);
Assert.Equal("https://tools.ietf.org/html/rfc9110#section-15.5.4", problemDetailsBody.Type);
Assert.NotNull(problemDetailsBody.Extensions["traceId"]);
}
[Fact]
public async Task ExecuteAsync_WhenHandlerReturnsValidationErrors_ShouldReturnValidationProblemResult()
{
// Arrange
Error validationError = DomainErrors.WrittenContent.BookIdCannotBeEmpty;
_mockHandler.HandleAsync(Arg.Any<RestoreBookCommand>(), Arg.Any<CancellationToken>())
.Returns(validationError);
ConfigureRouteValues();
// Act
IResult result = await _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, CancellationToken.None);
// 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_ShouldSendTheRouteIdsToTheHandler()
{
// Arrange
Guid libraryId = Guid.NewGuid();
Guid bookId = Guid.NewGuid();
_mockHandler.HandleAsync(Arg.Any<RestoreBookCommand>(), Arg.Any<CancellationToken>())
.Returns(Result.From(Result.Updated));
_sut.HttpContext.Request.RouteValues["libraryId"] = libraryId.ToString();
_sut.HttpContext.Request.RouteValues["bookId"] = bookId.ToString();
// Act
await _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, CancellationToken.None);
// Assert
RestoreBookCommand expectedCommand = _restoreBookCommandFixture.Create(
libraryId: libraryId.ToString(),
bookId: bookId.ToString());
await _mockHandler.Received(1).HandleAsync(expectedCommand, Arg.Any<CancellationToken>());
}
[Fact]
public async Task ExecuteAsync_WhenCancellationRequested_ShouldCancelOperation()
{
// Arrange
CancellationTokenSource cts = new();
TaskCompletionSource<bool> operationStarted = new();
TaskCompletionSource<bool> cancellationRequested = new();
_mockHandler.HandleAsync(Arg.Any<RestoreBookCommand>(), Arg.Any<CancellationToken>())
.Returns(callInfo => Task.Run(async () =>
{
operationStarted.SetResult(true);
await cancellationRequested.Task;
callInfo.Arg<CancellationToken>().ThrowIfCancellationRequested();
return Result.From(Result.Updated);
}, callInfo.Arg<CancellationToken>()));
ConfigureRouteValues();
// Act
Task<IResult> operationTask = _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, cts.Token);
await operationStarted.Task;
cts.Cancel();
cancellationRequested.SetResult(true);
// Assert
await Assert.ThrowsAnyAsync<OperationCanceledException>(() => operationTask);
}
/// <summary>
/// Configures the route values of a valid restore request.
/// </summary>
private void ConfigureRouteValues()
{
_sut.HttpContext.Request.RouteValues["libraryId"] = Guid.NewGuid().ToString();
_sut.HttpContext.Request.RouteValues["bookId"] = Guid.NewGuid().ToString();
}
}
@@ -0,0 +1,138 @@
#region ========================================================================= USING =====================================================================================
using FastEndpoints;
using Lumina.Presentation.Web.Common.Api;
using Lumina.Presentation.Web.Common.Routes;
using Lumina.Presentation.Web.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.Books.DeleteBook;
using Lumina.Presentation.Web.Fixtures.Common.TestHelpers;
using Microsoft.AspNetCore.Http;
using NSubstitute;
using System;
using System.Diagnostics.CodeAnalysis;
using System.Text.Json;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Presentation.Web.UnitTests.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.Books.DeleteBook;
/// <summary>
/// Contains unit tests for the <see cref="DeleteBookEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class DeleteBookEndpointTests
{
private readonly IApiHttpClient _mockApiHttpClient;
private readonly DeleteBookEndpoint _sut;
/// <summary>
/// Initializes a new instance of the <see cref="DeleteBookEndpointTests"/> class.
/// </summary>
public DeleteBookEndpointTests()
{
_mockApiHttpClient = Substitute.For<IApiHttpClient>();
_sut = Factory.Create<DeleteBookEndpoint>(_mockApiHttpClient);
}
[Fact]
public async Task ExecuteAsync_WhenCalled_ShouldDeleteBookViaApiAndReturnSuccessWithoutData()
{
// Arrange
Guid bookId = Guid.NewGuid();
Guid libraryId = Guid.NewGuid();
ConfigureRequest(bookId.ToString(), libraryId);
// Act
IResult result = await _sut.ExecuteAsync(EmptyRequest.Instance, CancellationToken.None);
string body = await JsonResultTestHelper.GetResponseBodyAsync(result);
// Assert
await _mockApiHttpClient.Received(1).DeleteAsync(
BuildExpectedEndpoint(libraryId, bookId),
Arg.Any<CancellationToken>());
using JsonDocument jsonDocument = JsonDocument.Parse(body);
Assert.True(jsonDocument.RootElement.GetProperty("success").GetBoolean());
Assert.False(jsonDocument.RootElement.TryGetProperty("data", out JsonElement _));
}
[Fact]
public async Task ExecuteAsync_WhenBookIdIsNotParseable_ShouldForwardGuidEmptyBookIdToApi()
{
// Arrange
Guid libraryId = Guid.NewGuid();
ConfigureRequest("not-a-guid", libraryId);
// Act
await _sut.ExecuteAsync(EmptyRequest.Instance, CancellationToken.None);
// Assert
await _mockApiHttpClient.Received(1).DeleteAsync(
BuildExpectedEndpoint(libraryId, Guid.Empty),
Arg.Any<CancellationToken>());
}
[Fact]
public async Task ExecuteAsync_WhenBookIdIsMissing_ShouldForwardGuidEmptyBookIdToApi()
{
// Arrange
Guid libraryId = Guid.NewGuid();
_sut.HttpContext.Request.QueryString = new QueryString($"?libraryId={libraryId}");
// Act
await _sut.ExecuteAsync(EmptyRequest.Instance, CancellationToken.None);
// Assert
await _mockApiHttpClient.Received(1).DeleteAsync(
BuildExpectedEndpoint(libraryId, Guid.Empty),
Arg.Any<CancellationToken>());
}
[Fact]
public async Task ExecuteAsync_WhenLibraryQueryIdIsNotParseable_ShouldForwardGuidEmptyLibraryIdToApi()
{
// Arrange
Guid bookId = Guid.NewGuid();
ConfigureRequest(bookId.ToString(), "not-a-guid");
// Act
await _sut.ExecuteAsync(EmptyRequest.Instance, CancellationToken.None);
// Assert
await _mockApiHttpClient.Received(1).DeleteAsync(
BuildExpectedEndpoint(Guid.Empty, bookId),
Arg.Any<CancellationToken>());
}
/// <summary>
/// Sets the route and query values the endpoint reads the book identity from.
/// </summary>
/// <param name="bookId">The raw route value of the book Id.</param>
/// <param name="libraryId">The raw query value of the library Id.</param>
private void ConfigureRequest(string bookId, Guid libraryId)
{
ConfigureRequest(bookId, libraryId.ToString());
}
/// <summary>
/// Sets the route and query values the endpoint reads the book identity from.
/// </summary>
/// <param name="bookId">The raw route value of the book Id.</param>
/// <param name="libraryId">The raw query value of the library Id.</param>
private void ConfigureRequest(string bookId, string libraryId)
{
_sut.HttpContext.Request.RouteValues["bookId"] = bookId;
_sut.HttpContext.Request.QueryString = new QueryString($"?libraryId={libraryId}");
}
/// <summary>
/// Builds the upstream endpoint the book deletion is expected to be sent to.
/// </summary>
/// <param name="libraryId">The normalized Id of the media library.</param>
/// <param name="bookId">The normalized Id of the book.</param>
/// <returns>The expected upstream endpoint.</returns>
private static string BuildExpectedEndpoint(Guid libraryId, Guid bookId)
{
return ApiRoutes.Books.DELETE_BOOK
.Replace("{libraryId}", libraryId.ToString())
.Replace("{bookId}", bookId.ToString());
}
}
@@ -0,0 +1,183 @@
#region ========================================================================= USING =====================================================================================
using FastEndpoints;
using Lumina.Presentation.Web.Common.Api;
using Lumina.Presentation.Web.Common.DTO.Libraries;
using Lumina.Presentation.Web.Common.DTO.Themes;
using Lumina.Presentation.Web.Common.DTO.WrittenContentLibrary.BookLibrary;
using Lumina.Presentation.Web.Common.Http;
using Lumina.Presentation.Web.Common.Primitives;
using Lumina.Presentation.Web.Common.Routes;
using Lumina.Presentation.Web.Common.Services;
using Lumina.Presentation.Web.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.Books.DeletedBooks;
using Lumina.Presentation.Web.Core.Themes;
using Lumina.Presentation.Web.Fixtures.Common.DTO.Libraries;
using Lumina.Presentation.Web.Fixtures.Common.DTO.Themes;
using Lumina.Presentation.Web.Fixtures.Common.DTO.WrittenContentLibrary.BookLibrary;
using Lumina.Presentation.Web.Fixtures.Common.Requests.Library.WrittenContentLibrary.BookLibrary.Books;
using Lumina.Presentation.Web.Fixtures.Common.TestHelpers;
using Microsoft.AspNetCore.Antiforgery;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Http.HttpResults;
using Microsoft.Extensions.Localization;
using NSubstitute;
using System;
using System.Diagnostics.CodeAnalysis;
using System.Reflection;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Presentation.Web.UnitTests.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.Books.DeletedBooks;
/// <summary>
/// Contains unit tests for the <see cref="DeletedBooksViewEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class DeletedBooksViewEndpointTests
{
private readonly IApiHttpClient _mockApiHttpClient;
private readonly IUrlService _mockUrlService;
private readonly ThemePageRenderer _mockThemePageRenderer;
private readonly IAntiforgery _mockAntiforgery;
private readonly IStringLocalizerFactory _mockStringLocalizerFactory;
private readonly IStringLocalizer _mockStringLocalizer;
private readonly DeletedBooksViewEndpoint _sut;
private readonly LibraryDtoFixture _libraryDtoFixture = new();
private readonly DeletedBookDtoFixture _deletedBookDtoFixture = new();
private readonly GetBooksViewRequestFixture _getBooksViewRequestFixture = new();
private readonly ThemePageRenderResultDtoFixture _themePageRenderResultDtoFixture = new();
/// <summary>
/// Initializes a new instance of the <see cref="DeletedBooksViewEndpointTests"/> class.
/// </summary>
public DeletedBooksViewEndpointTests()
{
_mockApiHttpClient = Substitute.For<IApiHttpClient>();
_mockUrlService = Substitute.For<IUrlService>();
_mockThemePageRenderer = Substitute.For<ThemePageRenderer>(new ThemeService(_mockApiHttpClient), new ThemeTemplateEngine());
_mockAntiforgery = Substitute.For<IAntiforgery>();
_mockAntiforgery.GetAndStoreTokens(Arg.Any<HttpContext>())
.Returns(new AntiforgeryTokenSet("request-token", "cookie-token", "__RequestVerificationToken", "RequestVerificationToken"));
_mockStringLocalizer = Substitute.For<IStringLocalizer>();
_mockStringLocalizer[Arg.Any<string>()].Returns(callInfo => new LocalizedString(
callInfo.Arg<string>(),
callInfo.Arg<string>() == "Title" ? "Deleted items" : $"Localized-{callInfo.Arg<string>()}"));
_mockStringLocalizer.GetAllStrings(Arg.Any<bool>()).Returns(new LocalizedString[]
{
new("Title", "Deleted items"),
new("NoDeletedItems", "There are no deleted items in this library.")
});
_mockStringLocalizerFactory = Substitute.For<IStringLocalizerFactory>();
_mockStringLocalizerFactory.Create(Arg.Any<string>(), Arg.Any<string>()).Returns(_mockStringLocalizer);
_sut = Factory.Create<DeletedBooksViewEndpoint>(_mockApiHttpClient, _mockUrlService, _mockThemePageRenderer, _mockAntiforgery, _mockStringLocalizerFactory);
TestHttpContextFactory.ConfigureSession(_sut.HttpContext, TestHttpContextFactory.CreateSession());
_sut.HttpContext.Request.Path = "/en-us/library/written-content-library/books-library/books/deleted-items";
StubUrls();
}
[Fact]
public async Task ExecuteAsync_WhenThemeRenderingSucceeds_ShouldRenderThemedViewWithDocumentedPageData()
{
// Arrange
LibraryDto library = _libraryDtoFixture.Create(title: "Books");
DeletedBookDto[] deletedBooks = [.. _deletedBookDtoFixture.CreateMany(2)];
_mockApiHttpClient.GetAsync<LibraryDto>(Arg.Any<string>(), Arg.Any<CancellationToken>()).Returns(library);
_mockApiHttpClient.GetAsync<DeletedBookDto[]>(Arg.Any<string>(), Arg.Any<CancellationToken>()).Returns(deletedBooks);
_mockThemePageRenderer.RenderAsync(Arg.Any<ThemePageDto>(), Arg.Any<string?>(), Arg.Any<CancellationToken>())
.Returns(Result.From(_themePageRenderResultDtoFixture.Create(content: "<section>deleted</section>", script: "<script>deleted</script>")));
// Act
IResult result = await _sut.ExecuteAsync(_getBooksViewRequestFixture.Create(libraryId: library.Id), CancellationToken.None);
// Assert
Assert.Equal("/Core/Views/Shared/_ThemedView.cshtml", GetRenderedViewName(result));
await _mockThemePageRenderer.Received(1).RenderAsync(
Arg.Is<ThemePageDto>(page =>
page.PageKey == "library/written-content-library/book-library/books/deleted-items" &&
page.Title == "Deleted items" &&
string.Equals(page.PageData["libraryId"] as string, library.Id!.Value.ToString(), StringComparison.Ordinal) &&
string.Equals(page.PageData["libraryTitle"] as string, "Books", StringComparison.Ordinal) &&
string.Equals(page.PageData["restoreUrl"] as string, "http://localhost/en-us/library/written-content-library/books-library/books/00000000-0000-0000-0000-000000000000/api-restore-book", StringComparison.Ordinal) &&
string.Equals(page.PageData["backUrl"] as string, $"http://localhost/en-us/library/written-content-library/books-library/books?libraryId={library.Id}", StringComparison.Ordinal) &&
string.Equals(page.PageData["antiforgeryToken"] as string, "request-token", StringComparison.Ordinal) &&
page.PageData.ContainsKey("deletedBooksJson") &&
page.PageData.ContainsKey("strings") &&
page.PageData.ContainsKey("stringsJson")),
Arg.Is<string?>(requestedThemeId => requestedThemeId == null),
Arg.Any<CancellationToken>());
}
[Fact]
public async Task ExecuteAsync_WhenLibraryIdIsNull_ShouldRedirectToHome()
{
// Arrange
_mockUrlService.GetAbsoluteUrl(WebRoutes.Home.INDEX_CULTURED).Returns("http://localhost/en-us");
// Act
IResult result = await _sut.ExecuteAsync(_getBooksViewRequestFixture.Create(libraryId: null), CancellationToken.None);
// Assert
RedirectHttpResult redirectResult = Assert.IsType<RedirectHttpResult>(result);
Assert.Equal("http://localhost/en-us", redirectResult.Url);
await _mockApiHttpClient.DidNotReceive().GetAsync<LibraryDto>(Arg.Any<string>(), Arg.Any<CancellationToken>());
await _mockThemePageRenderer.DidNotReceive().RenderAsync(Arg.Any<ThemePageDto>(), Arg.Any<string?>(), Arg.Any<CancellationToken>());
}
[Fact]
public async Task ExecuteAsync_WhenThemeRenderingFails_ShouldFallBackToTheRazorViewWithTheDeletedBooks()
{
// Arrange
LibraryDto library = _libraryDtoFixture.Create(title: "Books");
DeletedBookDto[] deletedBooks = [.. _deletedBookDtoFixture.CreateMany(2)];
_mockApiHttpClient.GetAsync<LibraryDto>(Arg.Any<string>(), Arg.Any<CancellationToken>()).Returns(library);
_mockApiHttpClient.GetAsync<DeletedBookDto[]>(Arg.Any<string>(), Arg.Any<CancellationToken>()).Returns(deletedBooks);
_mockThemePageRenderer.RenderAsync(Arg.Any<ThemePageDto>(), Arg.Any<string?>(), Arg.Any<CancellationToken>())
.Returns(Result<ThemePageRenderResultDto>.Failure(Error.Failure("Theme.Render", "The page could not be rendered.")));
// Act
IResult result = await _sut.ExecuteAsync(_getBooksViewRequestFixture.Create(libraryId: library.Id), CancellationToken.None);
// Assert
Assert.Equal("/Core/Views/Library/WrittenContentLibrary/BookLibrary/Books/DeletedItems.cshtml", GetRenderedViewName(result));
DeletedBooksPageDto model = Assert.IsType<DeletedBooksPageDto>(GetRenderedModel(result));
Assert.Equal(library.Id, model.Library.Id);
Assert.Equal(deletedBooks, model.DeletedBooks);
}
/// <summary>
/// Stubs the absolute URLs that the endpoint resolves for the deleted items page.
/// </summary>
private void StubUrls()
{
_mockUrlService.GetAbsoluteUrl(WebRoutes.Books.INDEX).Returns("http://localhost/en-us/library/written-content-library/books-library/books");
_mockUrlService.GetAbsoluteUrl(WebRoutes.Books.RESTORE_BOOK, Arg.Any<object?>())
.Returns("http://localhost/en-us/library/written-content-library/books-library/books/00000000-0000-0000-0000-000000000000/api-restore-book");
}
/// <summary>
/// Reads the private view name of the rendered <see cref="RazorViewResult"/>, which the result does not expose publicly.
/// </summary>
/// <param name="result">The result returned by the endpoint under test.</param>
/// <returns>The name or path of the rendered view.</returns>
private static string GetRenderedViewName(IResult result)
{
RazorViewResult viewResult = Assert.IsType<RazorViewResult>(result);
FieldInfo? viewNameField = typeof(RazorViewResult).GetField("_viewName", BindingFlags.Instance | BindingFlags.NonPublic);
Assert.NotNull(viewNameField);
return (string)viewNameField.GetValue(viewResult)!;
}
/// <summary>
/// Reads the private model of the rendered <see cref="RazorViewResult"/>, which the result does not expose publicly.
/// </summary>
/// <param name="result">The result returned by the endpoint under test.</param>
/// <returns>The model passed to the rendered view.</returns>
private static object? GetRenderedModel(IResult result)
{
RazorViewResult viewResult = Assert.IsType<RazorViewResult>(result);
FieldInfo? modelField = typeof(RazorViewResult).GetField("_model", BindingFlags.Instance | BindingFlags.NonPublic);
Assert.NotNull(modelField);
return modelField.GetValue(viewResult);
}
}
@@ -84,6 +84,8 @@ public class BooksIndexViewEndpointTests
_mockUrlService.GetAbsoluteUrl(WebRoutes.Books.GET_LIBRARY_ITEMS).Returns("http://localhost/en-us/library/written-content-library/books-library/books/api-get-library-items");
_mockUrlService.GetAbsoluteUrl(WebRoutes.Settings.GET_USER_SETTINGS).Returns("http://localhost/en-us/tools/settings/api-get-user-settings");
_mockUrlService.GetAbsoluteUrl(WebRoutes.Books.READ, Arg.Any<object>()).Returns("http://localhost/en-us/library/written-content-library/books-library/books/00000000-0000-0000-0000-000000000000/read");
_mockUrlService.GetAbsoluteUrl(WebRoutes.Books.DELETE_BOOK, Arg.Any<object>()).Returns("http://localhost/en-us/library/written-content-library/books-library/books/00000000-0000-0000-0000-000000000000/api-delete-book");
_mockUrlService.GetAbsoluteUrl(WebRoutes.Books.DELETED_BOOKS).Returns("http://localhost/en-us/library/written-content-library/books-library/books/deleted-items");
_mockThemePageRenderer.RenderAsync(Arg.Any<ThemePageDto>(), Arg.Any<string?>(), Arg.Any<CancellationToken>())
.Returns(Result.From(_themePageRenderResultDtoFixture.Create(content: "<section>content</section>", script: "<script>script</script>")));
@@ -99,6 +101,7 @@ public class BooksIndexViewEndpointTests
page.PageData.ContainsKey("libraryId") &&
page.PageData.ContainsKey("settingsUrl") &&
page.PageData.ContainsKey("strings") &&
page.PageData.ContainsKey("stringsJson") &&
string.Equals(
page.PageData["itemsUrl"] as string,
"http://localhost/en-us/library/written-content-library/books-library/books/api-get-library-items",
@@ -106,6 +109,14 @@ public class BooksIndexViewEndpointTests
string.Equals(
page.PageData["readUrl"] as string,
"http://localhost/en-us/library/written-content-library/books-library/books/00000000-0000-0000-0000-000000000000/read",
StringComparison.Ordinal) &&
string.Equals(
page.PageData["deleteUrl"] as string,
"http://localhost/en-us/library/written-content-library/books-library/books/00000000-0000-0000-0000-000000000000/api-delete-book",
StringComparison.Ordinal) &&
string.Equals(
page.PageData["deletedBooksUrl"] as string,
"http://localhost/en-us/library/written-content-library/books-library/books/deleted-items",
StringComparison.Ordinal)),
Arg.Is<string?>(requestedThemeId => requestedThemeId == null),
Arg.Any<CancellationToken>());
@@ -0,0 +1,134 @@
#region ========================================================================= USING =====================================================================================
using FastEndpoints;
using Lumina.Presentation.Web.Common.Api;
using Lumina.Presentation.Web.Common.Routes;
using Lumina.Presentation.Web.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.Books.RestoreBook;
using Lumina.Presentation.Web.Fixtures.Common.TestHelpers;
using Microsoft.AspNetCore.Http;
using NSubstitute;
using System;
using System.Diagnostics.CodeAnalysis;
using System.Text.Json;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Presentation.Web.UnitTests.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.Books.RestoreBook;
/// <summary>
/// Contains unit tests for the <see cref="RestoreBookEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class RestoreBookEndpointTests
{
private readonly IApiHttpClient _mockApiHttpClient;
private readonly RestoreBookEndpoint _sut;
/// <summary>
/// Initializes a new instance of the <see cref="RestoreBookEndpointTests"/> class.
/// </summary>
public RestoreBookEndpointTests()
{
_mockApiHttpClient = Substitute.For<IApiHttpClient>();
_sut = Factory.Create<RestoreBookEndpoint>(_mockApiHttpClient);
}
[Fact]
public async Task ExecuteAsync_WhenCalled_ShouldRestoreBookViaApiAndReturnSuccessPayload()
{
// Arrange
Guid bookId = Guid.NewGuid();
Guid libraryId = Guid.NewGuid();
ConfigureRequest(bookId.ToString(), libraryId);
_mockApiHttpClient.PostAsync<Web.Common.Requests.Common.EmptyRequest, Web.Common.Requests.Common.EmptyRequest>(
Arg.Any<string>(), Arg.Any<Web.Common.Requests.Common.EmptyRequest>(), Arg.Any<CancellationToken>())
.Returns(new Web.Common.Requests.Common.EmptyRequest());
// Act
IResult result = await _sut.ExecuteAsync(EmptyRequest.Instance, CancellationToken.None);
string body = await JsonResultTestHelper.GetResponseBodyAsync(result);
// Assert
await _mockApiHttpClient.Received(1).PostAsync<Web.Common.Requests.Common.EmptyRequest, Web.Common.Requests.Common.EmptyRequest>(
BuildExpectedEndpoint(libraryId, bookId),
Arg.Any<Web.Common.Requests.Common.EmptyRequest>(),
Arg.Any<CancellationToken>());
using JsonDocument jsonDocument = JsonDocument.Parse(body);
Assert.True(jsonDocument.RootElement.GetProperty("success").GetBoolean());
Assert.True(jsonDocument.RootElement.GetProperty("data").GetProperty("isRestored").GetBoolean());
}
[Fact]
public async Task ExecuteAsync_WhenBookIdIsNotParseable_ShouldForwardGuidEmptyBookIdToApi()
{
// Arrange
Guid libraryId = Guid.NewGuid();
ConfigureRequest("not-a-guid", libraryId);
_mockApiHttpClient.PostAsync<Web.Common.Requests.Common.EmptyRequest, Web.Common.Requests.Common.EmptyRequest>(
Arg.Any<string>(), Arg.Any<Web.Common.Requests.Common.EmptyRequest>(), Arg.Any<CancellationToken>())
.Returns(new Web.Common.Requests.Common.EmptyRequest());
// Act
await _sut.ExecuteAsync(EmptyRequest.Instance, CancellationToken.None);
// Assert
await _mockApiHttpClient.Received(1).PostAsync<Web.Common.Requests.Common.EmptyRequest, Web.Common.Requests.Common.EmptyRequest>(
BuildExpectedEndpoint(libraryId, Guid.Empty),
Arg.Any<Web.Common.Requests.Common.EmptyRequest>(),
Arg.Any<CancellationToken>());
}
[Fact]
public async Task ExecuteAsync_WhenLibraryQueryIdIsNotParseable_ShouldForwardGuidEmptyLibraryIdToApi()
{
// Arrange
Guid bookId = Guid.NewGuid();
ConfigureRequest(bookId.ToString(), "not-a-guid");
_mockApiHttpClient.PostAsync<Web.Common.Requests.Common.EmptyRequest, Web.Common.Requests.Common.EmptyRequest>(
Arg.Any<string>(), Arg.Any<Web.Common.Requests.Common.EmptyRequest>(), Arg.Any<CancellationToken>())
.Returns(new Web.Common.Requests.Common.EmptyRequest());
// Act
await _sut.ExecuteAsync(EmptyRequest.Instance, CancellationToken.None);
// Assert
await _mockApiHttpClient.Received(1).PostAsync<Web.Common.Requests.Common.EmptyRequest, Web.Common.Requests.Common.EmptyRequest>(
BuildExpectedEndpoint(Guid.Empty, bookId),
Arg.Any<Web.Common.Requests.Common.EmptyRequest>(),
Arg.Any<CancellationToken>());
}
/// <summary>
/// Sets the route and query values the endpoint reads the book identity from.
/// </summary>
/// <param name="bookId">The raw route value of the book Id.</param>
/// <param name="libraryId">The raw query value of the library Id.</param>
private void ConfigureRequest(string bookId, Guid libraryId)
{
ConfigureRequest(bookId, libraryId.ToString());
}
/// <summary>
/// Sets the route and query values the endpoint reads the book identity from.
/// </summary>
/// <param name="bookId">The raw route value of the book Id.</param>
/// <param name="libraryId">The raw query value of the library Id.</param>
private void ConfigureRequest(string bookId, string libraryId)
{
_sut.HttpContext.Request.RouteValues["bookId"] = bookId;
_sut.HttpContext.Request.QueryString = new QueryString($"?libraryId={libraryId}");
}
/// <summary>
/// Builds the upstream endpoint the book restoration is expected to be sent to.
/// </summary>
/// <param name="libraryId">The normalized Id of the media library.</param>
/// <param name="bookId">The normalized Id of the book.</param>
/// <returns>The expected upstream endpoint.</returns>
private static string BuildExpectedEndpoint(Guid libraryId, Guid bookId)
{
return ApiRoutes.Books.RESTORE_BOOK
.Replace("{libraryId}", libraryId.ToString())
.Replace("{bookId}", bookId.ToString());
}
}