Merge pull request #280 from BinaryAlley/feature/add-delete-book-api-endpoint

Adds a Delete Book API endpoint
This commit is contained in:
BinaryAlley authored and GitHub committed 2026-11-12 13:07:04 +02:00
commit ef5ede6325
15 files changed
+1752

No files matched your search

@@ -32,6 +32,7 @@
- [Get Reading Section](#get-reading-section)
- [Get Reading Section Request](#get-reading-section-request)
- [Get Reading Section Response](#get-reading-section-response)
- [Delete Book](#delete-book)
## Book
@@ -870,3 +871,15 @@ Returns the binary resource identified by `resourceKey` of the book identified b
```
The response is the raw bytes of the resource, served with the `Content-Type` of the resource and with `X-Content-Type-Options: nosniff`. A resource whose declared media type could be rendered as an active document (for example an SVG) is served as an opaque binary download instead.
### Delete Book
```js
DELETE api/v1/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/books/{bookId}
```
```js
200 Ok
```
Deletes the book identified by the route, together with its stored artwork.
@@ -0,0 +1,2 @@
DELETE {{host}}/api/v1/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/books/{{$guid}}
Authorization: Bearer {{ACCESS_TOKEN}}
@@ -0,0 +1,17 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.CQRS;
using System.Diagnostics;
#endregion
namespace Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Commands.DeleteBook;
/// <summary>
/// Command for deleting a book by its Id.
/// </summary>
/// <param name="LibraryId">The unique identifier of the media library this book belongs to, taken from the route.</param>
/// <param name="BookId">The unique identifier of the book to delete, taken from the route.</param>
[DebuggerDisplay("BookId: {BookId}")]
public record DeleteBookCommand(
string? LibraryId,
string? BookId
) : ICommand;
@@ -0,0 +1,133 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.CQRS;
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management;
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary;
using Lumina.Application.Common.DataAccess.UoW;
using Lumina.Application.Common.Infrastructure.Authentication;
using Lumina.Application.Common.Infrastructure.Authorization;
using Lumina.Application.Common.Infrastructure.Authorization.Policies.LibraryOwnership;
using Lumina.Application.Common.Infrastructure.Validation;
using Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Artwork;
using Lumina.Domain.Common.Primitives;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using ApplicationErrors = Lumina.Application.Common.Errors.Errors;
using DomainErrors = Lumina.Domain.Common.Errors.Errors;
#endregion
namespace Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Commands.DeleteBook;
/// <summary>
/// Handler for the command to delete a book by its Id.
/// </summary>
public class DeleteBookCommandHandler : ICommandHandler<DeleteBookCommand, Result<Deleted>>
{
private readonly IUnitOfWork _unitOfWork;
private readonly IBookArtworkService _bookArtworkService;
private readonly ILogger<DeleteBookCommandHandler> _logger;
private readonly IAuthorizationService _authorizationService;
private readonly ICurrentUserService _currentUserService;
private readonly IValidator<DeleteBookCommand> _validator;
/// <summary>
/// Initializes a new instance of the <see cref="DeleteBookCommandHandler"/> class.
/// </summary>
/// <param name="unitOfWork">Injected unit of work for interacting with the data access layer repositories.</param>
/// <param name="bookArtworkService">Injected service for removing the artwork of a book.</param>
/// <param name="logger">Injected logger used to report the issues encountered while removing the stored artwork.</param>
/// <param name="authorizationService">Injected service for authorization related functionality.</param>
/// <param name="currentUserService">Injected service to retrieve the current user information.</param>
/// <param name="validator">Injected validator for application validation rules.</param>
public DeleteBookCommandHandler(
IUnitOfWork unitOfWork,
IBookArtworkService bookArtworkService,
ILogger<DeleteBookCommandHandler> logger,
IAuthorizationService authorizationService,
ICurrentUserService currentUserService,
IValidator<DeleteBookCommand> validator)
{
_unitOfWork = unitOfWork;
_bookArtworkService = bookArtworkService;
_logger = logger;
_authorizationService = authorizationService;
_currentUserService = currentUserService;
_validator = validator;
}
/// <summary>
/// Handles the command to delete a book by its Id.
/// </summary>
/// <param name="command">The command to be handled.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>An <see cref="Result{TValue}"/> representing either a successful operation, or an error.</returns>
public async Task<Result<Deleted>> HandleAsync(DeleteBookCommand command, CancellationToken cancellationToken)
{
List<Error> validationResult = _validator.Validate(command);
if (validationResult.Count > 0)
return validationResult;
// An authenticated request must always carry a user identity.
Guid? currentUserId = _currentUserService.UserId;
if (currentUserId is null)
return ApplicationErrors.Authorization.NotAuthorized;
Guid userId = currentUserId.Value;
// The validator guarantees that the route identifiers are non-empty Guids before this point.
Guid libraryId = Guid.Parse(command.LibraryId!);
Guid bookId = Guid.Parse(command.BookId!);
// Only the library of the book is needed to scope the delete, so the book row is read without its aggregate graph and without tracking.
Result<BookEntity?> getBookResult = await _unitOfWork.BookRepository
.GetByIdAsync(bookId, shouldIncludeNavigationProperties: false, shouldTrackEntities: false, cancellationToken: cancellationToken).ConfigureAwait(false);
if (getBookResult.IsFailure)
return getBookResult.Errors;
if (getBookResult.Value is null)
return DomainErrors.WrittenContent.BookNotFound;
BookEntity existingBook = getBookResult.Value;
// Resource scoping: the book must belong to the library named by the route, so that a book can never be deleted through another
// library's route; the mismatch is reported as not found, without disclosing that the book exists in another library.
if (existingBook.LibraryId != libraryId)
return DomainErrors.WrittenContent.BookNotFound;
// Admins can delete the books of all libraries; for everyone else, only the books of the libraries they own.
bool canAccessLibrary = await _authorizationService.EvaluatePolicyAsync<ILibraryOwnershipPolicy>(
userId, new LibraryOwnershipPolicyContext(existingBook.LibraryId), cancellationToken).ConfigureAwait(false);
if (!canAccessLibrary)
return ApplicationErrors.Authorization.NotAuthorized;
// A book can only belong to a library that exists, so a client can never delete a book of a library of the host that is not there.
Result<LibraryEntity?> getLibraryResult = await _unitOfWork.LibraryRepository.GetByIdAsync(libraryId, shouldTrackEntities: false, cancellationToken: cancellationToken).ConfigureAwait(false);
if (getLibraryResult.IsFailure)
return getLibraryResult.Errors;
if (getLibraryResult.Value is null)
return DomainErrors.Library.LibraryNotFound;
LibraryEntity library = getLibraryResult.Value;
// The artwork is stored under the library and author segments, so the author is resolved before the book is removed.
Result<IReadOnlyDictionary<Guid, string?>> getAuthorsResult = await _unitOfWork.BookRepository
.GetAuthorsDisplayNamesByBookIdsAsync([existingBook.Id], cancellationToken).ConfigureAwait(false);
if (getAuthorsResult.IsFailure)
return getAuthorsResult.Errors;
string authorName = getAuthorsResult.Value.TryGetValue(existingBook.Id, out string? authorDisplayName) && authorDisplayName is not null ? authorDisplayName : string.Empty;
// Delete the stored artwork of the book, best-effort, since a stale cover must not prevent the book from being removed.
Result<Deleted> deleteArtworkResult = _bookArtworkService.DeleteBookArtwork(libraryId, existingBook.Id, library.Title, authorName, existingBook.Title);
if (deleteArtworkResult.IsFailure)
_logger.LogWarning("Failed to delete the stored artwork of the book with Id '{BookId}' at path '{BookPath}', the artwork might remain orphaned.", existingBook.Id, existingBook.Path);
// Delete the book, whose stored artwork rows and participations are removed by the database cascade.
Result<Deleted> deleteBookResult = await _unitOfWork.BookRepository.DeleteByIdAsync(existingBook.Id, cancellationToken).ConfigureAwait(false);
if (deleteBookResult.IsFailure)
return deleteBookResult.Errors;
Result<Success> saveChangesResult = await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
if (saveChangesResult.IsFailure)
return saveChangesResult.Errors;
return Result.Deleted;
}
}
@@ -0,0 +1,40 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.Infrastructure.Validation;
using Lumina.Application.Common.Utilities;
using Lumina.Domain.Common.Errors;
using System;
#endregion
namespace Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Commands.DeleteBook;
/// <summary>
/// Validates the needed validation rules for <see cref="DeleteBookCommand"/>.
/// </summary>
public class DeleteBookCommandValidator : AbstractValidator<DeleteBookCommand>
{
/// <summary>
/// Initializes a new instance of the <see cref="DeleteBookCommandValidator"/> class.
/// </summary>
public DeleteBookCommandValidator()
{
// Validates the identifier of the media library that owns the book, taken from the route.
RuleFor(command => command.LibraryId)
.NotEmpty()
.WithError(Errors.Library.LibraryIdCannotBeEmpty);
RuleFor(command => command.LibraryId)
.Must(libraryId => Guid.TryParse(libraryId, out Guid parsedLibraryId) && parsedLibraryId != Guid.Empty)
.When(command => command.LibraryId is not null && command.LibraryId.Length > 0)
.WithError(Errors.Library.LibraryIdCannotBeEmpty);
// Validates the identifier of the book, taken from the route.
RuleFor(command => command.BookId)
.NotEmpty()
.WithError(Errors.WrittenContent.BookIdCannotBeEmpty);
RuleFor(command => command.BookId)
.Must(bookId => Guid.TryParse(bookId, out Guid parsedBookId) && parsedBookId != Guid.Empty)
.When(command => command.BookId is not null && command.BookId.Length > 0)
.WithError(Errors.WrittenContent.BookIdCannotBeEmpty);
}
}
@@ -15,6 +15,7 @@ public static partial class ApiRoutes
public const string GET_BOOKS_LITE = "/libraries/{libraryId}/books/lite";
public const string ADD_BOOK = "/libraries/{libraryId}/books";
public const string UPDATE_BOOK = "/libraries/{libraryId}/books/{bookId}";
public const string DELETE_BOOK = "/libraries/{libraryId}/books/{bookId}";
public const string UPDATE_BOOK_COVER = "/libraries/{libraryId}/books/{bookId}/cover";
public const string GET_BOOK_READING_MANIFEST = "/libraries/{libraryId}/books/{bookId}/reading/manifest";
public const string GET_BOOK_READING_AVAILABILITY = "/libraries/{libraryId}/books/{bookId}/reading/availability";
@@ -0,0 +1,54 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.CQRS;
using Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Commands.DeleteBook;
using Lumina.Domain.Common.Primitives;
using Lumina.Presentation.Api.Common.Routes.Library.WrittenContentLibrary.BookLibrary;
using Lumina.Presentation.Api.Core.Endpoints.Common;
using Microsoft.AspNetCore.Http;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Presentation.Api.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.Books.DeleteBook;
/// <summary>
/// API endpoint for the <c>/libraries/{libraryId}/books/{bookId}</c> route.
/// </summary>
public class DeleteBookEndpoint : BaseEndpoint<FastEndpoints.EmptyRequest, IResult>
{
private readonly ICommandHandler<DeleteBookCommand, Result<Deleted>> _deleteBookCommandHandler;
/// <summary>
/// Initializes a new instance of the <see cref="DeleteBookEndpoint"/> class.
/// </summary>
/// <param name="deleteBookCommandHandler">Injected service for handling delete book commands.</param>
public DeleteBookEndpoint(ICommandHandler<DeleteBookCommand, Result<Deleted>> deleteBookCommandHandler)
{
_deleteBookCommandHandler = deleteBookCommandHandler;
}
/// <summary>
/// Configures the API endpoint.
/// </summary>
public override void Configure()
{
Verbs(FastEndpoints.Http.DELETE);
Routes(ApiRoutes.Books.DELETE_BOOK);
Version(1);
DontCatchExceptions();
}
/// <summary>
/// Deletes a book by Id.
/// </summary>
/// <param name="request">The request object.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
public override async Task<IResult> ExecuteAsync(FastEndpoints.EmptyRequest request, CancellationToken cancellationToken)
{
// Take unique identifiers from the route.
string? libraryId = HttpContext.Request.RouteValues["libraryId"]?.ToString();
string? bookId = HttpContext.Request.RouteValues["bookId"]?.ToString();
Result<Deleted> result = await _deleteBookCommandHandler.HandleAsync(new DeleteBookCommand(libraryId, bookId), cancellationToken).ConfigureAwait(false);
return result.Match(success => TypedResults.Ok(success), Problem);
}
}
@@ -0,0 +1,114 @@
#region ========================================================================= USING =====================================================================================
using FastEndpoints;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
#endregion
namespace Lumina.Presentation.Api.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.Books.DeleteBook;
/// <summary>
/// Class used for providing a textual description for the <see cref="DeleteBookEndpoint"/> API endpoint, for OpenAPI.
/// </summary>
[ExcludeFromCodeCoverage]
public class DeleteBookEndpointSummary : Summary<DeleteBookEndpoint, EmptyRequest>
{
/// <summary>
/// Initializes a new instance of the <see cref="DeleteBookEndpointSummary"/> class.
/// </summary>
public DeleteBookEndpointSummary()
{
Summary = "Deletes an existing book.";
Description = "Deletes the book identified by the route, together with its stored artwork. The book is deleted by an Admin, who can delete the books of all libraries, or by the owner of the library of the book.";
Response(200, "The book was successfully deleted.");
Response(401, "Authentication required.", "application/problem+json",
example: new[]
{
new
{
type = "https://tools.ietf.org/html/rfc7235#section-3.1",
status = 401,
title = "Unauthorized",
detail = "Authentication failed",
instance = $"/api/v1/libraries/{Guid.NewGuid()}/books/{Guid.NewGuid()}"
},
new
{
type = "https://tools.ietf.org/html/rfc7235#section-3.1",
status = 401,
title = "Unauthorized",
detail = "The token has expired",
instance = $"/api/v1/libraries/{Guid.NewGuid()}/books/{Guid.NewGuid()}"
},
new
{
type = "https://tools.ietf.org/html/rfc7235#section-3.1",
status = 401,
title = "Unauthorized",
detail = "The token is invalid",
instance = $"/api/v1/libraries/{Guid.NewGuid()}/books/{Guid.NewGuid()}"
}
}
);
Response(403, "The request failed because the user making the request is not an Admin, or the owner of the media library.", "application/problem+json",
example: new
{
type = "https://tools.ietf.org/html/rfc9110#section-15.5.4",
title = "General.Unauthorized",
status = 403,
detail = "NotAuthorized",
instance = $"/api/v1/libraries/{Guid.NewGuid()}/books/{Guid.NewGuid()}",
traceId = "00-a712bbf99ca8ab485f86a762ae5ae74d-b3a2eb78813b0a5d-00"
}
);
Response(404, "The request failed because the requested book or its media library does not exist.", "application/problem+json",
example: new[]
{
new
{
type = "https://tools.ietf.org/html/rfc9110#section-15.5.5",
title = "General.NotFound",
status = 404,
detail = "BookNotFound",
instance = $"/api/v1/libraries/{Guid.NewGuid()}/books/{Guid.NewGuid()}",
traceId = "00-57d15dadd702dbd4aeb5dc9b7cee68ee-9330237dbb2ce0e5-00"
},
new
{
type = "https://tools.ietf.org/html/rfc9110#section-15.5.5",
title = "General.NotFound",
status = 404,
detail = "LibraryNotFound",
instance = $"/api/v1/libraries/{Guid.NewGuid()}/books/{Guid.NewGuid()}",
traceId = "00-57d15dadd702dbd4aeb5dc9b7cee68ee-9330237dbb2ce0e5-00"
}
}
);
Response(422, "The request did not pass validation checks.", "application/problem+json",
example: new
{
type = "https://tools.ietf.org/html/rfc4918#section-11.2",
title = "General.Validation",
status = 422,
detail = "OneOrMoreValidationErrorsOccurred",
instance = $"/api/v1/libraries/{Guid.NewGuid()}/books/{Guid.NewGuid()}",
errors = new Dictionary<string, string[]>
{
{
"General.Validation", new[]
{
"LibraryIdCannotBeEmpty",
"BookIdCannotBeEmpty"
}
}
},
traceId = "00-2470be4248a2a5a0c6f70579975a6954-b9c3ba9544a03500-00"
}
);
}
}
+1
View File
@@ -245,6 +245,7 @@
<Folder Name="/docs/technical/requests/library/written-content-library/book-library/" />
<Folder Name="/docs/technical/requests/library/written-content-library/book-library/books/">
<File Path="../docs/technical/requests/library/written-content-library/book-library/books/AddBook.http" />
<File Path="../docs/technical/requests/library/written-content-library/book-library/books/DeleteBook.http" />
<File Path="../docs/technical/requests/library/written-content-library/book-library/books/GetBook.http" />
<File Path="../docs/technical/requests/library/written-content-library/book-library/books/GetBooks.http" />
<File Path="../docs/technical/requests/library/written-content-library/book-library/books/GetBooksLite.http" />
@@ -0,0 +1,45 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Commands.DeleteBook;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
#endregion
namespace Lumina.Application.Fixtures.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Commands.DeleteBook;
/// <summary>
/// Fixture class for the <see cref="DeleteBookCommand"/> record.
/// </summary>
[ExcludeFromCodeCoverage]
public class DeleteBookCommandFixture
{
/// <summary>
/// Creates a random valid <see cref="DeleteBookCommand"/>.
/// </summary>
/// <param name="libraryId">Optional. The Id of the media library the book belongs to, taken from the route.</param>
/// <param name="bookId">Optional. The Id of the book to delete, taken from the route.</param>
/// <param name="includeLibraryId">Whether the library Id should be included, or forced to <see langword="null"/>.</param>
/// <param name="includeBookId">Whether the book Id should be included, or forced to <see langword="null"/>.</param>
/// <returns>The created <see cref="DeleteBookCommand"/>.</returns>
public DeleteBookCommand Create(
string? libraryId = null,
string? bookId = null,
bool includeLibraryId = true,
bool includeBookId = true)
{
return new DeleteBookCommand(
includeLibraryId ? (libraryId ?? Guid.NewGuid().ToString()) : null,
includeBookId ? (bookId ?? Guid.NewGuid().ToString()) : null);
}
/// <summary>
/// Creates a list of <see cref="DeleteBookCommand"/>.
/// </summary>
/// <param name="count">Number of instances to create.</param>
/// <returns>List of configured <see cref="DeleteBookCommand"/> instances.</returns>
public List<DeleteBookCommand> CreateMany(int count = 3)
{
return [.. Enumerable.Range(0, count).Select(_ => Create())];
}
}
@@ -0,0 +1,380 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management;
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary;
using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
using Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Artwork;
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management;
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary;
using Lumina.Application.Fixtures.Common.DataAccess.Entities.UsersManagement;
using Lumina.DataAccess.Core.UoW;
using Lumina.Domain.Common.Primitives;
using Lumina.Domain.SharedKernel.Common.Enums.BookLibrary;
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
using Lumina.Presentation.Api.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.Books.DeleteBook;
using Lumina.Presentation.Api.IntegrationTests.Common.Setup;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Text.Json;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Presentation.Api.IntegrationTests.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.Books.DeleteBook;
/// <summary>
/// Contains integration tests for the <see cref="DeleteBookEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class DeleteBookEndpointTests : IClassFixture<AuthenticatedLuminaApiFactory>, IAsyncLifetime
{
private HttpClient _client;
private readonly AuthenticatedLuminaApiFactory _apiFactory;
private readonly JsonSerializerOptions _jsonOptions = new()
{
PropertyNameCaseInsensitive = true
};
private readonly LibraryEntityFixture _libraryEntityFixture = new();
private readonly BookEntityFixture _bookEntityFixture = new();
private readonly BookArtworkEntityFixture _bookArtworkEntityFixture = new();
private readonly UserEntityFixture _userEntityFixture = new();
/// <summary>
/// Initializes a new instance of the <see cref="DeleteBookEndpointTests"/> class.
/// </summary>
/// <param name="apiFactory">Injected in-memory API factory.</param>
public DeleteBookEndpointTests(AuthenticatedLuminaApiFactory apiFactory)
{
_client = apiFactory.CreateClient();
_apiFactory = apiFactory;
}
/// <summary>
/// Initializes authenticated API client.
/// </summary>
public async Task InitializeAsync()
{
_client = await _apiFactory.CreateAuthenticatedClientAsync();
}
[Fact]
public async Task DeleteBook_WhenBookBelongsToAnOwnedLibrary_ShouldDeleteTheBook()
{
// Arrange
Guid userId = GetCurrentUserId();
(Guid libraryId, Guid bookId) = await SeedLibraryAndBookAsync(userId);
// Act
HttpResponseMessage response = await _client.DeleteAsync($"/api/v1/libraries/{libraryId}/books/{bookId}");
// Assert
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
Assert.Null(await dbContext.Books.FirstOrDefaultAsync(book => book.Id == bookId));
}
[Fact]
public async Task DeleteBook_WhenBookHasStoredArtwork_ShouldRemoveTheArtworkAndTheStoredCoverFile()
{
// Arrange
Guid userId = GetCurrentUserId();
(Guid libraryId, Guid bookId, string storedCoverPath) = await SeedLibraryBookAndCoverAsync(userId);
string fullCoverPath = Path.Combine(AppContext.BaseDirectory, storedCoverPath.TrimStart(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar));
Assert.True(File.Exists(fullCoverPath));
// Act
HttpResponseMessage response = await _client.DeleteAsync($"/api/v1/libraries/{libraryId}/books/{bookId}");
// Assert
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
Assert.Null(await dbContext.Books.FirstOrDefaultAsync(book => book.Id == bookId));
Assert.Null(await dbContext.Books.SelectMany(book => book.Artwork).FirstOrDefaultAsync(artwork => artwork.BookId == bookId));
Assert.False(File.Exists(fullCoverPath));
}
[Fact]
public async Task DeleteBook_WhenBookDoesNotExist_ShouldReturnBookNotFoundProblem()
{
// Arrange
Guid userId = GetCurrentUserId();
Guid libraryId = await SeedLibraryAsync(userId);
string url = $"/api/v1/libraries/{libraryId}/books/{Guid.NewGuid()}";
// Act
HttpResponseMessage response = await _client.DeleteAsync(url);
// Assert
await AssertNotFoundAsync(response, "BookNotFound", url);
}
[Fact]
public async Task DeleteBook_WhenBookRequestedThroughDifferentLibrary_ShouldReturnBookNotFoundProblem()
{
// Arrange
Guid userId = GetCurrentUserId();
(_, Guid bookId) = await SeedLibraryAndBookAsync(userId);
string url = $"/api/v1/libraries/{Guid.NewGuid()}/books/{bookId}";
// Act
HttpResponseMessage response = await _client.DeleteAsync(url);
// Assert
// The route library id is enforced, so a book can never be deleted through another library's route, and the mismatch is
// reported as not found, without disclosing that the book exists in another library.
await AssertNotFoundAsync(response, "BookNotFound", url);
}
[Fact]
public async Task DeleteBook_WhenBookBelongsToAnotherUserLibrary_ShouldReturnForbiddenProblem()
{
// Arrange
Guid otherUserId = await SeedOtherUserAsync();
(Guid otherLibraryId, Guid otherBookId) = await SeedLibraryAndBookAsync(otherUserId);
string url = $"/api/v1/libraries/{otherLibraryId}/books/{otherBookId}";
// Act
HttpResponseMessage response = await _client.DeleteAsync(url);
// Assert
await AssertProblemDetails(response, HttpStatusCode.Forbidden, "General.Unauthorized", "NotAuthorized", url, "https://tools.ietf.org/html/rfc9110#section-15.5.4");
}
[Fact]
public async Task DeleteBook_WhenUnauthorized_ShouldReturnUnauthorizedResult()
{
// Arrange
HttpClient unauthenticatedClient = _apiFactory.CreateClient();
string url = $"/api/v1/libraries/{Guid.NewGuid()}/books/{Guid.NewGuid()}";
// Act
HttpResponseMessage response = await unauthenticatedClient.DeleteAsync(url);
// Assert
await AssertUnauthorizedAsync(response, url);
}
[Fact]
public async Task DeleteBook_WhenLibraryIdIsNotParseable_ShouldReturnUnprocessableEntity()
{
// Arrange
string url = $"/api/v1/libraries/not-a-guid/books/{Guid.NewGuid()}";
// Act
HttpResponseMessage response = await _client.DeleteAsync(url);
// Assert
await AssertUnprocessableEntityWithValidationErrors(response, url, "LibraryIdCannotBeEmpty");
}
[Fact]
public async Task DeleteBook_WhenBookIdIsNotParseable_ShouldReturnUnprocessableEntity()
{
// Arrange
string url = $"/api/v1/libraries/{Guid.NewGuid()}/books/not-a-guid";
// Act
HttpResponseMessage response = await _client.DeleteAsync(url);
// Assert
await AssertUnprocessableEntityWithValidationErrors(response, url, "BookIdCannotBeEmpty");
}
/// <summary>
/// Seeds an ebook library owned by <paramref name="userId"/>.
/// </summary>
/// <param name="userId">The Id of the user that owns the library.</param>
/// <returns>The Id of the seeded library.</returns>
private async Task<Guid> SeedLibraryAsync(Guid userId)
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
Guid libraryId = Guid.NewGuid();
dbContext.Libraries.Add(_libraryEntityFixture.Create(id: libraryId, userId: userId, title: "Test Library", libraryType: LibraryType.EBook, contentLocations: []));
await dbContext.SaveChangesAsync();
return libraryId;
}
/// <summary>
/// Seeds an ebook library owned by <paramref name="userId"/> and a book belonging to it.
/// </summary>
/// <param name="userId">The Id of the user that owns the library.</param>
/// <returns>The Ids of the seeded library and book.</returns>
private async Task<(Guid libraryId, Guid bookId)> SeedLibraryAndBookAsync(Guid userId)
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
Guid libraryId = Guid.NewGuid();
Guid bookId = Guid.NewGuid();
LibraryEntity library = _libraryEntityFixture.Create(id: libraryId, userId: userId, title: "Test Library", libraryType: LibraryType.EBook, contentLocations: []);
BookEntity book = _bookEntityFixture.Create(id: bookId, libraryId: libraryId, path: $"/books/{bookId:N}.epub", title: "Test Book", includeMetadata: false);
dbContext.Libraries.Add(library);
dbContext.Books.Add(book);
await dbContext.SaveChangesAsync();
return (libraryId, bookId);
}
/// <summary>
/// Seeds an ebook library owned by <paramref name="userId"/>, a book belonging to it, and a stored cover file of that book together with its artwork row.
/// </summary>
/// <param name="userId">The Id of the user that owns the library.</param>
/// <returns>The Ids of the seeded library and book, and the relative path of the stored cover file.</returns>
private async Task<(Guid libraryId, Guid bookId, string storedCoverPath)> SeedLibraryBookAndCoverAsync(Guid userId)
{
(Guid libraryId, Guid bookId) = await SeedLibraryAndBookAsync(userId);
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
LibraryEntity library = await dbContext.Libraries.SingleAsync(library => library.Id == libraryId);
BookEntity book = await dbContext.Books.Include(book => book.Artwork).SingleAsync(book => book.Id == bookId);
IBookArtworkService bookArtworkService = scope.ServiceProvider.GetRequiredService<IBookArtworkService>();
// Store a minimal PNG-like payload through the same artwork service that the API uses, so that the stored path matches the one the deletion resolves.
byte[] payload = new byte[100];
payload[0] = 137;
payload[1] = 80;
payload[2] = 78;
payload[3] = 71;
payload[4] = 13;
payload[5] = 10;
payload[6] = 26;
payload[7] = 10;
Result<string> saveArtworkResult;
using (MemoryStream artworkStream = new(payload))
saveArtworkResult = await bookArtworkService.SaveBookArtworkAsync(libraryId, bookId, library.Title, string.Empty, book.Title, artworkStream, "cover.png", CancellationToken.None);
Assert.False(saveArtworkResult.IsFailure);
book.Artwork.Add(_bookArtworkEntityFixture.Create(bookId: bookId, fileName: saveArtworkResult.Value));
await dbContext.SaveChangesAsync();
return (libraryId, bookId, saveArtworkResult.Value);
}
/// <summary>
/// Seeds a user distinct from the authenticated test user and returns its Id.
/// </summary>
/// <returns>The Id of the seeded user.</returns>
private async Task<Guid> SeedOtherUserAsync()
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
Guid userId = Guid.NewGuid();
dbContext.Users.Add(_userEntityFixture.Create(id: userId, username: $"otheruser_{Guid.NewGuid()}", password: "TestPass123!"));
await dbContext.SaveChangesAsync();
return userId;
}
/// <summary>
/// Gets the Id of the currently authenticated test user.
/// </summary>
/// <returns>The Id of the authenticated test user.</returns>
private Guid GetCurrentUserId()
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
UserEntity user = dbContext.Users.First(user => user.Username == _apiFactory.TestUsername);
return user.Id;
}
/// <summary>
/// Asserts that the response is a not found problem details carrying the expected detail and request instance path.
/// </summary>
/// <param name="response">The HTTP response to assert on.</param>
/// <param name="expectedDetail">The expected problem detail.</param>
/// <param name="expectedInstance">The expected request instance path.</param>
private async Task AssertNotFoundAsync(HttpResponseMessage response, string expectedDetail, string expectedInstance)
{
await AssertProblemDetails(response, HttpStatusCode.NotFound, "General.NotFound", expectedDetail, expectedInstance, "https://tools.ietf.org/html/rfc9110#section-15.5.5");
}
/// <summary>
/// Asserts the shape of a problem details response with the provided status, title, detail, instance and type.
/// </summary>
/// <param name="response">The HTTP response to assert on.</param>
/// <param name="statusCode">The expected HTTP status code.</param>
/// <param name="expectedTitle">The expected problem title.</param>
/// <param name="expectedDetail">The expected problem detail.</param>
/// <param name="expectedInstance">The expected request instance path.</param>
/// <param name="expectedType">The expected problem type URI.</param>
private async Task AssertProblemDetails(HttpResponseMessage response, HttpStatusCode statusCode, string expectedTitle, string expectedDetail, string expectedInstance, string expectedType)
{
Assert.Equal(statusCode, response.StatusCode);
Assert.Equal("application/problem+json", response.Content.Headers.ContentType?.MediaType);
string content = await response.Content.ReadAsStringAsync();
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
Assert.NotNull(problemDetails);
Assert.Equal((int)statusCode, problemDetails!["status"].GetInt32());
Assert.Equal(expectedType, problemDetails["type"].GetString());
Assert.Equal(expectedTitle, problemDetails["title"].GetString());
Assert.Equal(expectedDetail, problemDetails["detail"].GetString());
Assert.Equal(expectedInstance, problemDetails["instance"].GetString());
Assert.NotNull(problemDetails["traceId"].GetString());
Assert.NotEmpty(problemDetails["traceId"].GetString()!);
}
/// <summary>
/// Asserts that the response is an unauthorized problem details carrying the expected request instance path.
/// </summary>
/// <param name="response">The HTTP response to assert on.</param>
/// <param name="expectedInstance">The expected request instance path.</param>
private async Task AssertUnauthorizedAsync(HttpResponseMessage response, string expectedInstance)
{
Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode);
Assert.Equal("application/json", response.Content.Headers.ContentType?.MediaType);
string content = await response.Content.ReadAsStringAsync();
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
Assert.NotNull(problemDetails);
Assert.Equal((int)HttpStatusCode.Unauthorized, problemDetails!["status"].GetInt32());
Assert.Equal("https://tools.ietf.org/html/rfc7235#section-3.1", problemDetails["type"].GetString());
Assert.Equal("Unauthorized", problemDetails["title"].GetString());
Assert.Equal("Authentication failed", problemDetails["detail"].GetString());
Assert.Equal(expectedInstance, problemDetails["instance"].GetProperty("value").GetString());
}
/// <summary>
/// Asserts that the response is an unprocessable entity problem details carrying the expected validation error codes.
/// </summary>
/// <param name="response">The HTTP response to assert on.</param>
/// <param name="expectedInstance">The expected request instance path.</param>
/// <param name="expectedErrorCodes">The validation error codes that must all be present.</param>
private async Task AssertUnprocessableEntityWithValidationErrors(HttpResponseMessage response, string expectedInstance, params string[] expectedErrorCodes)
{
Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode);
Assert.Equal("application/problem+json", response.Content.Headers.ContentType?.MediaType);
string content = await response.Content.ReadAsStringAsync();
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
Assert.NotNull(problemDetails);
Assert.Equal((int)HttpStatusCode.UnprocessableEntity, problemDetails!["status"].GetInt32());
Assert.Equal("General.Validation", problemDetails["title"].GetString());
Assert.Equal("OneOrMoreValidationErrorsOccurred", problemDetails["detail"].GetString());
Assert.Equal("https://tools.ietf.org/html/rfc4918#section-11.2", problemDetails["type"].GetString());
Assert.Equal(expectedInstance, problemDetails["instance"].GetString());
Assert.NotNull(problemDetails["traceId"].GetString());
Assert.NotEmpty(problemDetails["traceId"].GetString()!);
Dictionary<string, string[]>? errors = problemDetails["errors"].Deserialize<Dictionary<string, string[]>>(_jsonOptions);
Assert.NotNull(errors);
Assert.Contains("General.Validation", errors.Keys);
Assert.All(expectedErrorCodes, code => Assert.Contains(code, errors["General.Validation"]));
}
/// <summary>
/// Disposes API factory resources.
/// </summary>
public async Task DisposeAsync()
{
await _apiFactory.RemoveTestUserAsync();
}
}
@@ -0,0 +1,225 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary;
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management;
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary;
using Lumina.Application.Fixtures.Common.DataAccess.Entities.UsersManagement;
using Lumina.DataAccess.Core.UoW;
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
using Lumina.Presentation.Api.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.Books.DeleteBook;
using Lumina.Presentation.Api.SecurityTests.Common.Setup;
using Microsoft.AspNetCore.Http;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Net;
using System.Net.Http;
using System.Text.Json;
using System.Threading.Tasks;
#endregion
namespace Lumina.Presentation.Api.SecurityTests.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.Books.DeleteBook;
/// <summary>
/// Contains security tests for the <see cref="DeleteBookEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class DeleteBookEndpointTests : IClassFixture<LuminaApiFactory>, IDisposable
{
private readonly LuminaApiFactory _apiFactory;
private readonly HttpClient _client;
private readonly JsonSerializerOptions _jsonOptions = new()
{
PropertyNameCaseInsensitive = true
};
private readonly LibraryEntityFixture _libraryEntityFixture = new();
private readonly BookEntityFixture _bookEntityFixture = new();
private readonly UserEntityFixture _userEntityFixture = new();
private readonly List<string> _seededUsernames = [];
/// <summary>
/// Initializes a new instance of the <see cref="DeleteBookEndpointTests"/> class.
/// </summary>
/// <param name="apiFactory">Injected in-memory API factory.</param>
public DeleteBookEndpointTests(LuminaApiFactory apiFactory)
{
_apiFactory = apiFactory;
_client = apiFactory.CreateClient();
// A unique X-Forwarded-For isolates rate limiting state per test.
_client.DefaultRequestHeaders.Add("X-Forwarded-For", LuminaApiFactory.GetUniqueTestIp());
}
[Fact]
public async Task DeleteBook_WhenUnauthorized_ShouldReturnUnauthorizedResult()
{
// Arrange
string url = $"/api/v1/libraries/{Guid.NewGuid()}/books/{Guid.NewGuid()}";
// Act
HttpResponseMessage response = await _client.DeleteAsync(url);
// Assert
Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode);
string content = await response.Content.ReadAsStringAsync();
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
Assert.NotNull(problemDetails);
Assert.Equal(StatusCodes.Status401Unauthorized, problemDetails!["status"].GetInt32());
Assert.Equal("https://tools.ietf.org/html/rfc7235#section-3.1", problemDetails["type"].GetString());
Assert.Equal("Unauthorized", problemDetails["title"].GetString());
Assert.Equal("Authentication failed", problemDetails["detail"].GetString());
Assert.Equal(url, problemDetails["instance"].GetProperty("value").GetString());
}
[Theory]
[InlineData("'; DROP TABLE Books; --")] // destructive injection
[InlineData("' OR '1'='1")] // boolean-based injection
[InlineData("'; EXEC xp_cmdshell('dir'); --")] // command execution attempt
public async Task DeleteBook_WithSQLInjectionInLibraryId_ShouldNotCorruptOrLeakData(string maliciousLibraryId)
{
// Arrange
HttpClient client = _apiFactory.CreateClient();
(_, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(client);
_seededUsernames.Add(username);
// Act
HttpResponseMessage response = await client.DeleteAsync($"/api/v1/libraries/{Uri.EscapeDataString(maliciousLibraryId)}/books/{Guid.NewGuid()}");
// Assert
Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode);
string content = await response.Content.ReadAsStringAsync();
Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
using JsonDocument problemDetails = JsonDocument.Parse(content);
Assert.Equal("General.Validation", problemDetails.RootElement.GetProperty("title").GetString());
}
[Theory]
[InlineData("'; DROP TABLE Books; --")] // destructive injection
[InlineData("' OR '1'='1")] // boolean-based injection
[InlineData("'; EXEC xp_cmdshell('dir'); --")] // command execution attempt
public async Task DeleteBook_WithSQLInjectionInBookId_ShouldNotCorruptOrLeakData(string maliciousBookId)
{
// Arrange
HttpClient client = _apiFactory.CreateClient();
(_, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(client);
_seededUsernames.Add(username);
// Act
HttpResponseMessage response = await client.DeleteAsync($"/api/v1/libraries/{Guid.NewGuid()}/books/{Uri.EscapeDataString(maliciousBookId)}");
// Assert
Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode);
string content = await response.Content.ReadAsStringAsync();
Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
using JsonDocument problemDetails = JsonDocument.Parse(content);
Assert.Equal("General.Validation", problemDetails.RootElement.GetProperty("title").GetString());
}
[Fact]
public async Task DeleteBook_WhenBookBelongsToAnotherUserLibrary_ShouldReturnForbiddenResult()
{
// Arrange
HttpClient client = _apiFactory.CreateClient();
(_, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(client);
_seededUsernames.Add(username);
Guid otherUserId = await SeedOtherUserAsync();
(Guid libraryId, Guid bookId) = await SeedLibraryAndBookAsync(otherUserId);
// Act
HttpResponseMessage response = await client.DeleteAsync($"/api/v1/libraries/{libraryId}/books/{bookId}");
string content = await response.Content.ReadAsStringAsync();
// Assert
Assert.Equal(HttpStatusCode.Forbidden, response.StatusCode);
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
Assert.NotNull(problemDetails);
Assert.Equal(StatusCodes.Status403Forbidden, problemDetails!["status"].GetInt32());
Assert.Equal("https://tools.ietf.org/html/rfc9110#section-15.5.4", problemDetails["type"].GetString());
Assert.Equal("General.Unauthorized", problemDetails["title"].GetString());
Assert.Equal("NotAuthorized", problemDetails["detail"].GetString());
Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("password", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("hash", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("salt", content, StringComparison.OrdinalIgnoreCase);
}
[Fact]
public async Task DeleteBook_WhenBookBelongsToAnotherUsersLibrary_ShouldReturnNotFoundWithoutDeletingIt()
{
// Arrange
HttpClient client = _apiFactory.CreateClient();
(Guid actingUserId, string actingUsername) = await _apiFactory.CreateAndAuthenticateUserAsync(client);
_seededUsernames.Add(actingUsername);
(Guid ownLibraryId, _) = await SeedLibraryAndBookAsync(actingUserId);
// The book lives in a library owned by another user, and is referenced through the acting user's own library route.
HttpClient victimClient = _apiFactory.CreateClient();
(Guid victimUserId, string victimUsername) = await _apiFactory.CreateAndAuthenticateUserAsync(victimClient);
_seededUsernames.Add(victimUsername);
(_, Guid victimBookId) = await SeedLibraryAndBookAsync(victimUserId);
// Act
HttpResponseMessage response = await client.DeleteAsync($"/api/v1/libraries/{ownLibraryId}/books/{victimBookId}");
// Assert
Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);
string content = await response.Content.ReadAsStringAsync();
Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("password", content, StringComparison.OrdinalIgnoreCase);
using JsonDocument problemDetails = JsonDocument.Parse(content);
Assert.Equal("General.NotFound", problemDetails.RootElement.GetProperty("title").GetString());
Assert.Equal("BookNotFound", problemDetails.RootElement.GetProperty("detail").GetString());
// The other user's book is untouched.
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
Assert.NotNull(await dbContext.Books.FirstOrDefaultAsync(book => book.Id == victimBookId));
}
/// <summary>
/// Seeds a user distinct from the authenticated test user and returns its Id.
/// </summary>
/// <returns>The Id of the seeded other user.</returns>
private async Task<Guid> SeedOtherUserAsync()
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
Guid userId = Guid.NewGuid();
string username = $"otheruser_{Guid.NewGuid()}";
dbContext.Users.Add(_userEntityFixture.Create(id: userId, username: username, password: "TestPass123!"));
await dbContext.SaveChangesAsync();
_seededUsernames.Add(username);
return userId;
}
/// <summary>
/// Seeds an ebook library owned by <paramref name="userId"/>, together with a book of that library.
/// </summary>
/// <param name="userId">The Id of the user that owns the library.</param>
/// <returns>The Ids of the seeded library and book.</returns>
private async Task<(Guid libraryId, Guid bookId)> SeedLibraryAndBookAsync(Guid userId)
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
Guid libraryId = Guid.NewGuid();
Guid bookId = Guid.NewGuid();
dbContext.Libraries.Add(_libraryEntityFixture.Create(id: libraryId, userId: userId, title: "Test Library", libraryType: LibraryType.EBook, contentLocations: []));
dbContext.Books.Add(_bookEntityFixture.Create(id: bookId, libraryId: libraryId, path: $"/books/{bookId:N}.epub", title: "Test Book", includeMetadata: false));
await dbContext.SaveChangesAsync();
return (libraryId, bookId);
}
/// <summary>
/// Disposes the API factory resources.
/// </summary>
public void Dispose()
{
_client.Dispose();
foreach (string username in _seededUsernames)
_apiFactory.RemoveTestUser(username);
}
}
@@ -0,0 +1,398 @@
#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;
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.DeleteBook;
/// <summary>
/// Contains unit tests for the <see cref="DeleteBookCommandHandler"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
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;
private readonly DeleteBookCommandHandler _sut;
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.
/// </summary>
public 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.
_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);
_mockUnitOfWork.SaveChangesAsync(Arg.Any<CancellationToken>())
.Returns(Result.Success);
_sut = new DeleteBookCommandHandler(_mockUnitOfWork, _mockBookArtworkService, _mockLogger, _mockAuthorizationService, _mockCurrentUserService, _mockValidator);
}
[Fact]
public async Task HandleAsync_WhenBookExists_ShouldDeleteBookAndReturnDeleted()
{
// 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));
// Act
Result<Deleted> result = await _sut.HandleAsync(command, CancellationToken.None);
// 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 _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()
{
// Arrange
DeleteBookCommand command = _deleteBookCommandFixture.Create();
_mockValidator.Validate(Arg.Any<DeleteBookCommand>())
.Returns([DomainErrors.WrittenContent.BookIdCannotBeEmpty]);
// Act
Result<Deleted> result = await _sut.HandleAsync(command, CancellationToken.None);
// Assert
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 _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenUserIsNotAuthenticated_ShouldReturnNotAuthorizedError()
{
// Arrange
DeleteBookCommand command = _deleteBookCommandFixture.Create();
_mockCurrentUserService.UserId.Returns((Guid?)null);
// Act
Result<Deleted> result = await _sut.HandleAsync(command, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(ApplicationErrors.Authorization.NotAuthorized, result.FirstError);
await _mockBookRepository.DidNotReceive().GetByIdAsync(Arg.Any<Guid>(), Arg.Any<bool>(), Arg.Any<bool>(), Arg.Any<CancellationToken>());
await _mockAuthorizationService.DidNotReceive().EvaluatePolicyAsync<ILibraryOwnershipPolicy>(Arg.Any<Guid>(), Arg.Any<LibraryOwnershipPolicyContext>(), Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenBookRepositoryFails_ShouldReturnFailureResultWithoutDeleting()
{
// Arrange
DeleteBookCommand command = _deleteBookCommandFixture.Create();
_mockBookRepository.GetByIdAsync(Arg.Any<Guid>(), Arg.Any<bool>(), Arg.Any<bool>(), 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.DidNotReceive().DeleteByIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenBookDoesNotExist_ShouldReturnBookNotFoundError()
{
// Arrange
DeleteBookCommand command = _deleteBookCommandFixture.Create();
_mockBookRepository.GetByIdAsync(Arg.Any<Guid>(), Arg.Any<bool>(), Arg.Any<bool>(), Arg.Any<CancellationToken>())
.Returns(_ => Result.From<BookEntity?>(null));
// Act
Result<Deleted> 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
DeleteBookCommand command = _deleteBookCommandFixture.Create();
Guid bookId = Guid.Parse(command.BookId!);
BookEntity book = _bookEntityFixture.Create(id: bookId, libraryId: Guid.NewGuid(), includeMetadata: false);
_mockBookRepository.GetByIdAsync(bookId, shouldIncludeNavigationProperties: false, shouldTrackEntities: false, cancellationToken: Arg.Any<CancellationToken>())
.Returns(Result.From<BookEntity?>(book));
// Act
Result<Deleted> result = await _sut.HandleAsync(command, CancellationToken.None);
// Assert
// Resource scoping is enforced before authorization, and the mismatch is reported as not found, without disclosing that the book exists in another library.
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
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));
_mockAuthorizationService.EvaluatePolicyAsync<ILibraryOwnershipPolicy>(_userId, Arg.Any<LibraryOwnershipPolicyContext>(), Arg.Any<CancellationToken>())
.Returns(false);
// Act
Result<Deleted> 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 _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 _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenLibraryRepositoryFails_ShouldReturnFailureResultWithoutDeleting()
{
// 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(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_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 _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenSaveChangesFails_ShouldReturnError()
{
// 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));
_mockUnitOfWork.SaveChangesAsync(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>());
}
}
@@ -0,0 +1,97 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Commands.DeleteBook;
using Lumina.Application.Fixtures.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Commands.DeleteBook;
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.DeleteBook;
/// <summary>
/// Contains unit tests for the <see cref="DeleteBookCommandValidator"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class DeleteBookCommandValidatorTests
{
private readonly DeleteBookCommandFixture _deleteBookCommandFixture = new();
private readonly DeleteBookCommandValidator _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
DeleteBookCommand command = _deleteBookCommandFixture.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
DeleteBookCommand command = _deleteBookCommandFixture.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
DeleteBookCommand command = _deleteBookCommandFixture.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
DeleteBookCommand command = _deleteBookCommandFixture.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
DeleteBookCommand command = _deleteBookCommandFixture.Create();
// Act
List<Error> result = _validator.TestValidate(command);
// Assert
result.ShouldNotHaveAnyValidationErrors();
}
}
@@ -0,0 +1,232 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.CQRS;
using Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Commands.DeleteBook;
using Lumina.Domain.Common.Primitives;
using Lumina.Presentation.Api.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.Books.DeleteBook;
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.DeleteBook;
/// <summary>
/// Contains unit tests for the <see cref="DeleteBookEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class DeleteBookEndpointTests
{
private readonly ICommandHandler<DeleteBookCommand, Result<Deleted>> _mockHandler;
private readonly DeleteBookEndpoint _sut;
/// <summary>
/// Initializes a new instance of the <see cref="DeleteBookEndpointTests"/> class.
/// </summary>
public DeleteBookEndpointTests()
{
_mockHandler = Substitute.For<ICommandHandler<DeleteBookCommand, Result<Deleted>>>();
_sut = FastEndpoints.Factory.Create<DeleteBookEndpoint>(_mockHandler);
}
[Fact]
public async Task ExecuteAsync_WhenSuccessful_ShouldReturnOkResultWithDeleted()
{
// Arrange
CancellationToken cancellationToken = CancellationToken.None;
_mockHandler.HandleAsync(Arg.Any<DeleteBookCommand>(), Arg.Any<CancellationToken>())
.Returns(Result.From(Result.Deleted));
ConfigureRouteValues();
// Act
IResult result = await _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, cancellationToken);
// Assert
Ok<Deleted> okResult = Assert.IsType<Ok<Deleted>>(result);
Assert.Equal(Result.Deleted, okResult.Value);
}
[Fact]
public async Task ExecuteAsync_WhenHandlerReturnsNotFoundError_ShouldReturnProblemResult()
{
// Arrange
CancellationToken cancellationToken = CancellationToken.None;
Error expectedError = DomainErrors.WrittenContent.BookNotFound;
_mockHandler.HandleAsync(Arg.Any<DeleteBookCommand>(), Arg.Any<CancellationToken>())
.Returns(expectedError);
ConfigureRouteValues();
// Act
IResult result = await _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, cancellationToken);
// 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
CancellationToken cancellationToken = CancellationToken.None;
Error expectedError = ApplicationErrors.Authorization.NotAuthorized;
_mockHandler.HandleAsync(Arg.Any<DeleteBookCommand>(), Arg.Any<CancellationToken>())
.Returns(expectedError);
ConfigureRouteValues();
// Act
IResult result = await _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, cancellationToken);
// 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
CancellationToken cancellationToken = CancellationToken.None;
Error validationError = DomainErrors.WrittenContent.BookIdCannotBeEmpty;
_mockHandler.HandleAsync(Arg.Any<DeleteBookCommand>(), Arg.Any<CancellationToken>())
.Returns(validationError);
ConfigureRouteValues();
// Act
IResult result = await _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, cancellationToken);
// Assert
ProblemHttpResult problemDetails = Assert.IsType<ProblemHttpResult>(result);
Assert.Equal(StatusCodes.Status422UnprocessableEntity, problemDetails.StatusCode);
Assert.Equal("application/problem+json", problemDetails.ContentType);
HttpValidationProblemDetails validationProblemDetails = Assert.IsType<HttpValidationProblemDetails>(problemDetails.ProblemDetails);
Assert.Equal(StatusCodes.Status422UnprocessableEntity, validationProblemDetails.Status);
Assert.Equal("General.Validation", validationProblemDetails.Title);
Assert.Equal("OneOrMoreValidationErrorsOccurred", validationProblemDetails.Detail);
Assert.Equal("https://tools.ietf.org/html/rfc4918#section-11.2", validationProblemDetails.Type);
Assert.Single(validationProblemDetails.Errors);
Assert.Equal(new[] { "BookIdCannotBeEmpty" }, validationProblemDetails.Errors["General.Validation"]);
}
[Fact]
public async Task ExecuteAsync_WhenCalled_ShouldSendDeleteBookCommandToSender()
{
// Arrange
Guid libraryId = Guid.NewGuid();
Guid bookId = Guid.NewGuid();
CancellationToken cancellationToken = CancellationToken.None;
_mockHandler.HandleAsync(Arg.Any<DeleteBookCommand>(), Arg.Any<CancellationToken>())
.Returns(Result.From(Result.Deleted));
_sut.HttpContext.Request.RouteValues["libraryId"] = libraryId.ToString();
_sut.HttpContext.Request.RouteValues["bookId"] = bookId.ToString();
// Act
await _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, cancellationToken);
// Assert
await _mockHandler.Received(1).HandleAsync(
Arg.Is<DeleteBookCommand>(command =>
command.LibraryId == libraryId.ToString() &&
command.BookId == bookId.ToString()),
Arg.Is(cancellationToken));
}
[Fact]
public async Task ExecuteAsync_WhenRouteValuesAreNotParseable_ShouldSendCommandWithRawRouteValues()
{
// Arrange
CancellationToken cancellationToken = CancellationToken.None;
_mockHandler.HandleAsync(Arg.Any<DeleteBookCommand>(), Arg.Any<CancellationToken>())
.Returns(Result.From(Result.Deleted));
_sut.HttpContext.Request.RouteValues["libraryId"] = "not-a-library-guid";
_sut.HttpContext.Request.RouteValues["bookId"] = "not-a-book-guid";
// Act
await _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, cancellationToken);
// Assert
await _mockHandler.Received(1).HandleAsync(
Arg.Is<DeleteBookCommand>(command =>
command.LibraryId == "not-a-library-guid" &&
command.BookId == "not-a-book-guid"),
Arg.Is(cancellationToken));
}
[Fact]
public async Task ExecuteAsync_WhenRouteValuesAreMissing_ShouldSendCommandWithNullIds()
{
// Arrange
CancellationToken cancellationToken = CancellationToken.None;
_mockHandler.HandleAsync(Arg.Any<DeleteBookCommand>(), Arg.Any<CancellationToken>())
.Returns(Result.From(Result.Deleted));
_sut.HttpContext.Request.RouteValues.Remove("libraryId");
_sut.HttpContext.Request.RouteValues.Remove("bookId");
// Act
await _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, cancellationToken);
// Assert
await _mockHandler.Received(1).HandleAsync(
Arg.Is<DeleteBookCommand>(command =>
command.LibraryId == null &&
command.BookId == null),
Arg.Is(cancellationToken));
}
[Fact]
public async Task ExecuteAsync_WhenCancellationRequested_ShouldCancelOperation()
{
// Arrange
CancellationTokenSource cts = new();
TaskCompletionSource<bool> operationStarted = new();
TaskCompletionSource<bool> cancellationRequested = new();
_mockHandler.HandleAsync(Arg.Any<DeleteBookCommand>(), Arg.Any<CancellationToken>())
.Returns(callInfo => Task.Run(async () =>
{
operationStarted.SetResult(true);
await cancellationRequested.Task;
callInfo.Arg<CancellationToken>().ThrowIfCancellationRequested();
return Result.From(Result.Deleted);
}, 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>
/// Populates the route values read by the endpoint.
/// </summary>
private void ConfigureRouteValues()
{
_sut.HttpContext.Request.RouteValues["libraryId"] = Guid.NewGuid().ToString();
_sut.HttpContext.Request.RouteValues["bookId"] = Guid.NewGuid().ToString();
}
}