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

@@ -51,7 +51,7 @@ public class BookRepositoryTests
anchorConnection.Open();
using LuminaDbContext context = new(new DbContextOptionsBuilder<LuminaDbContext>().UseSqlite(anchorConnection.ConnectionString).Options);
context.Database.EnsureCreated();
BookRepository sut = new(context);
BookRepository sut = new(context, Substitute.For<IDateTimeProvider>());
Guid libraryId = Guid.NewGuid();
BookEntity changedBook = _bookEntityFixture.Create();
@@ -91,7 +91,7 @@ public class BookRepositoryTests
anchorConnection.Open();
using LuminaDbContext context = new(new DbContextOptionsBuilder<LuminaDbContext>().UseSqlite(anchorConnection.ConnectionString).Options);
context.Database.EnsureCreated();
BookRepository sut = new(context);
BookRepository sut = new(context, Substitute.For<IDateTimeProvider>());
Guid libraryId = Guid.NewGuid();
BookEntity book = _bookEntityFixture.Create();
@@ -120,7 +120,7 @@ public class BookRepositoryTests
anchorConnection.Open();
using LuminaDbContext context = new(new DbContextOptionsBuilder<LuminaDbContext>().UseSqlite(anchorConnection.ConnectionString).Options);
context.Database.EnsureCreated();
BookRepository sut = new(context);
BookRepository sut = new(context, Substitute.For<IDateTimeProvider>());
Guid libraryId = Guid.NewGuid();
BookEntity enrichedBook = _bookEntityFixture.Create();
@@ -155,7 +155,7 @@ public class BookRepositoryTests
anchorConnection.Open();
using LuminaDbContext context = new(new DbContextOptionsBuilder<LuminaDbContext>().UseSqlite(anchorConnection.ConnectionString).Options);
context.Database.EnsureCreated();
BookRepository sut = new(context);
BookRepository sut = new(context, Substitute.For<IDateTimeProvider>());
Guid libraryId = Guid.NewGuid();
BookEntity book = _bookEntityFixture.Create();
@@ -189,7 +189,7 @@ public class BookRepositoryTests
anchorConnection.Open();
using LuminaDbContext context = new(new DbContextOptionsBuilder<LuminaDbContext>().UseSqlite(anchorConnection.ConnectionString).Options);
context.Database.EnsureCreated();
BookRepository sut = new(context);
BookRepository sut = new(context, Substitute.For<IDateTimeProvider>());
BookEntity book = _bookEntityFixture.Create();
@@ -214,7 +214,7 @@ public class BookRepositoryTests
anchorConnection.Open();
using LuminaDbContext context = new(new DbContextOptionsBuilder<LuminaDbContext>().UseSqlite(anchorConnection.ConnectionString).Options);
context.Database.EnsureCreated();
BookRepository sut = new(context);
BookRepository sut = new(context, Substitute.For<IDateTimeProvider>());
Guid libraryId = Guid.NewGuid();
BookEntity existingBook = _bookEntityFixture.Create();
@@ -244,7 +244,7 @@ public class BookRepositoryTests
Guid userId = Guid.NewGuid();
DateTime utcNow = new(2025, 1, 1, 12, 0, 0, DateTimeKind.Utc);
using LuminaDbContext context = CreateAuditedContext(anchorConnection, userId, utcNow);
BookRepository sut = new(context);
BookRepository sut = new(context, Substitute.For<IDateTimeProvider>());
BookEntity book = _bookEntityFixture.Create(includeMetadata: false);
book.Contributors = [_bookContributorEntityFixture.Create(bookId: book.Id)];
book.Ratings = [_bookRatingEntityFixture.Create(source: BookRatingSource.GoogleBooks)];
@@ -278,7 +278,7 @@ public class BookRepositoryTests
Guid userId = Guid.NewGuid();
DateTime utcNow = new(2025, 1, 1, 12, 0, 0, DateTimeKind.Utc);
using LuminaDbContext context = CreateAuditedContext(anchorConnection, userId, utcNow);
BookRepository sut = new(context);
BookRepository sut = new(context, Substitute.For<IDateTimeProvider>());
BookEntity book = _bookEntityFixture.Create(includeMetadata: false);
book.Contributors = [_bookContributorEntityFixture.Create(bookId: book.Id)];
book.Ratings = [_bookRatingEntityFixture.Create(source: BookRatingSource.GoogleBooks)];
@@ -315,7 +315,7 @@ public class BookRepositoryTests
Guid userId = Guid.NewGuid();
DateTime utcNow = new(2025, 1, 1, 12, 0, 0, DateTimeKind.Utc);
using LuminaDbContext context = CreateAuditedContext(anchorConnection, userId, utcNow);
BookRepository sut = new(context);
BookRepository sut = new(context, Substitute.For<IDateTimeProvider>());
BookEntity book = _bookEntityFixture.Create(includeMetadata: false);
Guid keptMediaContributorId = Guid.NewGuid();
BookContributorEntity keptContributor = _bookContributorEntityFixture.Create(bookId: book.Id, mediaContributorId: keptMediaContributorId);
@@ -348,7 +348,7 @@ public class BookRepositoryTests
Guid userId = Guid.NewGuid();
DateTime utcNow = new(2025, 1, 1, 12, 0, 0, DateTimeKind.Utc);
using LuminaDbContext context = CreateAuditedContext(anchorConnection, userId, utcNow);
BookRepository sut = new(context);
BookRepository sut = new(context, Substitute.For<IDateTimeProvider>());
BookEntity book = _bookEntityFixture.Create(includeMetadata: false);
Guid keptMediaContributorId = Guid.NewGuid();
BookContributorEntity keptContributor = _bookContributorEntityFixture.Create(bookId: book.Id, mediaContributorId: keptMediaContributorId);
@@ -380,7 +380,7 @@ public class BookRepositoryTests
anchorConnection.Open();
using LuminaDbContext context = new(new DbContextOptionsBuilder<LuminaDbContext>().UseSqlite(anchorConnection.ConnectionString).Options);
context.Database.EnsureCreated();
BookRepository sut = new(context);
BookRepository sut = new(context, Substitute.For<IDateTimeProvider>());
BookEntity book = _bookEntityFixture.Create(includeMetadata: false);
book.Tags = [_tagEntityFixture.Create(name: $"noop-book-tag-{Guid.NewGuid():N}"), _tagEntityFixture.Create(name: $"noop-book-tag-two-{Guid.NewGuid():N}")];
@@ -429,7 +429,7 @@ public class BookRepositoryTests
anchorConnection.Open();
using LuminaDbContext context = new(new DbContextOptionsBuilder<LuminaDbContext>().UseSqlite(anchorConnection.ConnectionString).Options);
context.Database.EnsureCreated();
BookRepository sut = new(context);
BookRepository sut = new(context, Substitute.For<IDateTimeProvider>());
string keptTagName = $"remove-book-tag-{Guid.NewGuid():N}";
string keptGenreName = $"remove-book-genre-{Guid.NewGuid():N}";
@@ -483,7 +483,7 @@ public class BookRepositoryTests
anchorConnection.Open();
using LuminaDbContext context = new(new DbContextOptionsBuilder<LuminaDbContext>().UseSqlite(anchorConnection.ConnectionString).Options);
context.Database.EnsureCreated();
BookRepository sut = new(context);
BookRepository sut = new(context, Substitute.For<IDateTimeProvider>());
Guid libraryId = Guid.NewGuid();
BookEntity bookOfLibrary = _bookEntityFixture.Create();
@@ -513,7 +513,7 @@ public class BookRepositoryTests
using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-bookrepo-getbyids-empty-{Guid.NewGuid()};Mode=Memory;Cache=Shared");
anchorConnection.Open();
using LuminaDbContext context = CreateContext(anchorConnection);
BookRepository sut = new(context);
BookRepository sut = new(context, Substitute.For<IDateTimeProvider>());
context.Books.Add(_bookEntityFixture.Create(includeMetadata: false));
await context.SaveChangesAsync();
@@ -533,7 +533,7 @@ public class BookRepositoryTests
using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-bookrepo-getbyids-{Guid.NewGuid()};Mode=Memory;Cache=Shared");
anchorConnection.Open();
using LuminaDbContext context = CreateContext(anchorConnection);
BookRepository sut = new(context);
BookRepository sut = new(context, Substitute.For<IDateTimeProvider>());
BookEntity firstBook = _bookEntityFixture.Create(includeMetadata: false);
BookEntity secondBook = _bookEntityFixture.Create(includeMetadata: false);
BookEntity thirdBook = _bookEntityFixture.Create(includeMetadata: false);
@@ -559,7 +559,7 @@ public class BookRepositoryTests
using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-bookrepo-getbyids-notracking-{Guid.NewGuid()};Mode=Memory;Cache=Shared");
anchorConnection.Open();
using LuminaDbContext context = CreateContext(anchorConnection);
BookRepository sut = new(context);
BookRepository sut = new(context, Substitute.For<IDateTimeProvider>());
MediaContributorEntity author = _mediaContributorEntityFixture.Create(displayName: "Frank Herbert");
BookEntity book = _bookEntityFixture.Create(includeMetadata: false);
book.Tags = [_tagEntityFixture.Create(name: "HiddenTag")];
@@ -600,7 +600,7 @@ public class BookRepositoryTests
using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-bookrepo-getbyids-include-{Guid.NewGuid()};Mode=Memory;Cache=Shared");
anchorConnection.Open();
using LuminaDbContext context = CreateContext(anchorConnection);
BookRepository sut = new(context);
BookRepository sut = new(context, Substitute.For<IDateTimeProvider>());
MediaContributorEntity author = _mediaContributorEntityFixture.Create(displayName: "Frank Herbert");
BookEntity book = _bookEntityFixture.Create(includeMetadata: false);
book.Tags = [_tagEntityFixture.Create(name: "LoadedTag"), _tagEntityFixture.Create(name: "SecondLoadedTag")];
@@ -635,7 +635,7 @@ public class BookRepositoryTests
using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-bookrepo-getbyids-boundary-{Guid.NewGuid()};Mode=Memory;Cache=Shared");
anchorConnection.Open();
using LuminaDbContext context = CreateContext(anchorConnection);
BookRepository sut = new(context);
BookRepository sut = new(context, Substitute.For<IDateTimeProvider>());
const int BOOK_COUNT = 500;
List<BookEntity> books = CreateBooks(BOOK_COUNT);
context.Books.AddRange(books);
@@ -661,7 +661,7 @@ public class BookRepositoryTests
using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-bookrepo-getbyids-chunks-{Guid.NewGuid()};Mode=Memory;Cache=Shared");
anchorConnection.Open();
using LuminaDbContext context = CreateContext(anchorConnection);
BookRepository sut = new(context);
BookRepository sut = new(context, Substitute.For<IDateTimeProvider>());
const int BOOK_COUNT = 501;
List<BookEntity> books = CreateBooks(BOOK_COUNT);
context.Books.AddRange(books);
@@ -687,7 +687,7 @@ public class BookRepositoryTests
using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-bookrepo-authors-min-{Guid.NewGuid()};Mode=Memory;Cache=Shared");
anchorConnection.Open();
using LuminaDbContext context = CreateContext(anchorConnection);
BookRepository sut = new(context);
BookRepository sut = new(context, Substitute.For<IDateTimeProvider>());
BookEntity book = _bookEntityFixture.Create(includeMetadata: false);
MediaContributorEntity firstAuthor = _mediaContributorEntityFixture.Create(displayName: "Zoe Author");
MediaContributorEntity secondAuthor = _mediaContributorEntityFixture.Create(displayName: "Alice Author");
@@ -717,7 +717,7 @@ public class BookRepositoryTests
using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-bookrepo-authors-requested-{Guid.NewGuid()};Mode=Memory;Cache=Shared");
anchorConnection.Open();
using LuminaDbContext context = CreateContext(anchorConnection);
BookRepository sut = new(context);
BookRepository sut = new(context, Substitute.For<IDateTimeProvider>());
BookEntity requestedBook = _bookEntityFixture.Create(includeMetadata: false);
BookEntity bookNotRequested = _bookEntityFixture.Create(includeMetadata: false);
MediaContributorEntity requestedAuthor = _mediaContributorEntityFixture.Create(displayName: "Requested Author");
@@ -746,7 +746,7 @@ public class BookRepositoryTests
using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-bookrepo-authors-empty-{Guid.NewGuid()};Mode=Memory;Cache=Shared");
anchorConnection.Open();
using LuminaDbContext context = CreateContext(anchorConnection);
BookRepository sut = new(context);
BookRepository sut = new(context, Substitute.For<IDateTimeProvider>());
BookEntity book = _bookEntityFixture.Create(includeMetadata: false);
MediaContributorEntity author = _mediaContributorEntityFixture.Create();
context.Books.Add(book);
@@ -772,7 +772,7 @@ public class BookRepositoryTests
using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-bookrepo-authors-chunks-{Guid.NewGuid()};Mode=Memory;Cache=Shared");
anchorConnection.Open();
using LuminaDbContext context = CreateContext(anchorConnection);
BookRepository sut = new(context);
BookRepository sut = new(context, Substitute.For<IDateTimeProvider>());
const int BOOK_COUNT = 501;
List<BookEntity> books = CreateBooks(BOOK_COUNT);
MediaContributorEntity author = _mediaContributorEntityFixture.Create(displayName: "Shared Author");
@@ -348,6 +348,30 @@ public class FavoriteRepositoryTests
Assert.Equal((Guid?)expectedLibraryId, result.Value);
}
[Fact]
public async Task GetMediaItemLibraryIdAsync_WhenTheBookIsSoftDeleted_ShouldReturnSuccessWithNull()
{
// Arrange
using SqliteConnection anchorConnection = CreateAnchorConnection("library-id-deleted-book");
using LuminaDbContext context = CreateContext(anchorConnection);
FavoriteRepository sut = new(context);
BookEntity deletedBook = _bookEntityFixture.Create(
libraryId: Guid.NewGuid(),
path: $"/books/{Guid.NewGuid()}.epub",
isDeleted: true,
includeMetadata: false);
context.Books.Add(deletedBook);
await context.SaveChangesAsync();
// Act
Result<Guid?> result = await sut.GetMediaItemLibraryIdAsync(FavoriteMediaKind.Book, deletedBook.Id, CancellationToken.None);
// Assert
// A deleted book is hidden from the catalogue, so adding it to favorites is rejected as if the book did not exist.
Assert.False(result.IsFailure);
Assert.Null(result.Value);
}
[Fact]
public async Task GetMediaItemLibraryIdAsync_WhenTheMediaItemDoesNotExist_ShouldReturnSuccessWithNull()
{
@@ -853,6 +877,38 @@ public class FavoriteRepositoryTests
Assert.Null(item.Display);
}
[Fact]
public async Task GetAllForUserAsync_WhenTheFavoritedBookIsDeleted_ShouldKeepTheFavoriteWithoutDisplayData()
{
// Arrange
using SqliteConnection anchorConnection = CreateAnchorConnection("list-deleted-book");
using LuminaDbContext context = CreateContext(anchorConnection);
FavoriteRepository sut = new(context);
Guid userId = Guid.NewGuid();
Guid libraryId = Guid.NewGuid();
context.Users.Add(_userEntityFixture.Create(id: userId));
BookEntity deletedBook = _bookEntityFixture.Create(
libraryId: libraryId,
path: $"/books/{Guid.NewGuid()}.epub",
title: "Deleted Book",
isDeleted: true,
includeMetadata: false);
FavoriteEntity favorite = CreateFavorite(userId, FavoriteMediaKind.Book, deletedBook.Id);
context.Books.Add(deletedBook);
context.Favorites.Add(favorite);
await context.SaveChangesAsync();
// Act
Result<PaginatedResultDto<FavoriteItemDto>> result = await sut.GetAllForUserAsync(userId, FavoriteMediaKind.Book, paginationData: null, cancellationToken: CancellationToken.None);
// Assert
// A deleted book is hidden from the catalogue, so its favorite must fall back to the unavailable state instead of exposing its display data.
Assert.False(result.IsFailure);
FavoriteItemDto item = Assert.Single(result.Value.Data);
Assert.Equal(favorite.Id, item.Favorite.Id);
Assert.Null(item.Display);
}
[Theory]
[InlineData(FavoriteMediaKind.Video)] // planned kind, so no display data can be resolved yet
[InlineData(FavoriteMediaKind.Photo)] // planned kind, so no display data can be resolved yet
@@ -47,7 +47,7 @@ public class UnitOfWorkTests
{
using (dbContext)
{
UnitOfWork sut = new(dbContext);
UnitOfWork sut = new(dbContext, Substitute.For<IDateTimeProvider>());
// Act
await sut.BeginTransactionAsync(CancellationToken.None);
@@ -67,7 +67,7 @@ public class UnitOfWorkTests
{
using (dbContext)
{
UnitOfWork sut = new(dbContext);
UnitOfWork sut = new(dbContext, Substitute.For<IDateTimeProvider>());
RoleEntity role = _roleEntityFixture.Create(roleName: "Admin");
// Act
@@ -95,7 +95,7 @@ public class UnitOfWorkTests
{
using (dbContext)
{
UnitOfWork sut = new(dbContext);
UnitOfWork sut = new(dbContext, Substitute.For<IDateTimeProvider>());
// Act
await sut.CommitTransactionAsync(CancellationToken.None);
@@ -115,7 +115,7 @@ public class UnitOfWorkTests
{
using (dbContext)
{
UnitOfWork sut = new(dbContext);
UnitOfWork sut = new(dbContext, Substitute.For<IDateTimeProvider>());
RoleEntity role = _roleEntityFixture.Create(roleName: "Admin");
// Act
@@ -142,7 +142,7 @@ public class UnitOfWorkTests
{
using (dbContext)
{
UnitOfWork sut = new(dbContext);
UnitOfWork sut = new(dbContext, Substitute.For<IDateTimeProvider>());
// Act
await sut.RollbackTransactionAsync(CancellationToken.None);
@@ -162,7 +162,7 @@ public class UnitOfWorkTests
{
using (dbContext)
{
UnitOfWork sut = new(dbContext);
UnitOfWork sut = new(dbContext, Substitute.For<IDateTimeProvider>());
// Act
await sut.BeginTransactionAsync(CancellationToken.None);
@@ -183,7 +183,7 @@ public class UnitOfWorkTests
{
using (dbContext)
{
UnitOfWork sut = new(dbContext);
UnitOfWork sut = new(dbContext, Substitute.For<IDateTimeProvider>());
// Act
sut.Dispose();
@@ -203,7 +203,7 @@ public class UnitOfWorkTests
{
using (dbContext)
{
UnitOfWork sut = new(dbContext);
UnitOfWork sut = new(dbContext, Substitute.For<IDateTimeProvider>());
Guid libraryId = Guid.NewGuid();
BookEntity firstBook = _bookEntityFixture.Create();
firstBook.LibraryId = libraryId;
@@ -237,7 +237,7 @@ public class UnitOfWorkTests
{
using (dbContext)
{
UnitOfWork sut = new(dbContext);
UnitOfWork sut = new(dbContext, Substitute.For<IDateTimeProvider>());
// Act
IFavoriteRepository firstRepository = sut.FavoriteRepository;
@@ -259,7 +259,7 @@ public class UnitOfWorkTests
{
using (dbContext)
{
UnitOfWork sut = new(dbContext);
UnitOfWork sut = new(dbContext, Substitute.For<IDateTimeProvider>());
Guid userId = Guid.NewGuid();
dbContext.Users.Add(_userEntityFixture.Create(id: userId));
Result<Success> userSaveResult = await sut.SaveChangesAsync(CancellationToken.None);
@@ -303,7 +303,7 @@ public class UnitOfWorkTests
{
using (dbContext)
{
UnitOfWork sut = new(dbContext);
UnitOfWork sut = new(dbContext, Substitute.For<IDateTimeProvider>());
Guid userId = Guid.NewGuid();
UserEntity user = _userEntityFixture.Create(id: userId);
FavoriteEntity favorite = _favoriteEntityFixture.Create(
@@ -337,7 +337,7 @@ public class UnitOfWorkTests
{
using (dbContext)
{
UnitOfWork sut = new(dbContext);
UnitOfWork sut = new(dbContext, Substitute.For<IDateTimeProvider>());
dbContext.Users.Add(_userEntityFixture.Create(id: userId));
Guid mediaItemId = Guid.NewGuid();
// The fixture populates the update audit columns, so the test also proves the interceptor owns them on insert.
@@ -6,9 +6,10 @@ using Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Art
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management;
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary;
using Lumina.Application.Fixtures.Common.DataAccess.Entities.UsersManagement;
using Lumina.Contracts.Responses.Common;
using Lumina.Contracts.Responses.MediaLibrary.WrittenContentLibrary.BookLibrary.Books;
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;
@@ -21,6 +22,7 @@ using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Json;
using System.Text.Json;
using System.Threading;
using System.Threading.Tasks;
@@ -64,7 +66,7 @@ public class DeleteBookEndpointTests : IClassFixture<AuthenticatedLuminaApiFacto
}
[Fact]
public async Task DeleteBook_WhenBookBelongsToAnOwnedLibrary_ShouldDeleteTheBook()
public async Task DeleteBook_WhenBookBelongsToAnOwnedLibrary_ShouldSoftDeleteTheBook()
{
// Arrange
Guid userId = GetCurrentUserId();
@@ -78,11 +80,13 @@ public class DeleteBookEndpointTests : IClassFixture<AuthenticatedLuminaApiFacto
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
Assert.Null(await dbContext.Books.FirstOrDefaultAsync(book => book.Id == bookId));
BookEntity? book = await dbContext.Books.FirstOrDefaultAsync(book => book.Id == bookId);
Assert.NotNull(book);
Assert.True(book!.IsDeleted);
}
[Fact]
public async Task DeleteBook_WhenBookHasStoredArtwork_ShouldRemoveTheArtworkAndTheStoredCoverFile()
public async Task DeleteBook_WhenBookHasStoredArtwork_ShouldKeepTheArtworkAndTheStoredCoverFileForRestore()
{
// Arrange
Guid userId = GetCurrentUserId();
@@ -98,9 +102,45 @@ public class DeleteBookEndpointTests : IClassFixture<AuthenticatedLuminaApiFacto
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));
BookEntity? book = await dbContext.Books.FirstOrDefaultAsync(book => book.Id == bookId);
Assert.NotNull(book);
Assert.True(book!.IsDeleted);
Assert.NotNull(await dbContext.Books.SelectMany(book => book.Artwork).FirstOrDefaultAsync(artwork => artwork.BookId == bookId));
Assert.True(File.Exists(fullCoverPath));
}
[Fact]
public async Task DeleteBook_WhenBookIsSoftDeleted_ShouldHideItFromTheCatalogueAndReadingEndpoints()
{
// Arrange
Guid userId = GetCurrentUserId();
(Guid libraryId, Guid bookId) = await SeedLibraryAndBookAsync(userId);
HttpResponseMessage deleteResponse = await _client.DeleteAsync($"/api/v1/libraries/{libraryId}/books/{bookId}");
deleteResponse.EnsureSuccessStatusCode();
// Act
HttpResponseMessage booksResponse = await _client.GetAsync($"/api/v1/libraries/{libraryId}/books");
HttpResponseMessage booksLiteResponse = await _client.GetAsync($"/api/v1/libraries/{libraryId}/books/lite");
HttpResponseMessage bookResponse = await _client.GetAsync($"/api/v1/libraries/{libraryId}/books/{bookId}");
HttpResponseMessage availabilityResponse = await _client.GetAsync($"/api/v1/libraries/{libraryId}/books/{bookId}/reading/availability");
HttpResponseMessage manifestResponse = await _client.GetAsync($"/api/v1/libraries/{libraryId}/books/{bookId}/reading/manifest");
HttpResponseMessage sectionResponse = await _client.GetAsync($"/api/v1/libraries/{libraryId}/books/{bookId}/reading/sections/section-1");
HttpResponseMessage resourceResponse = await _client.GetAsync($"/api/v1/libraries/{libraryId}/books/{bookId}/reading/resources/resource-1");
// Assert
PaginatedResponse<BookResponse>? books = await booksResponse.Content.ReadFromJsonAsync<PaginatedResponse<BookResponse>>(_jsonOptions);
Assert.NotNull(books);
Assert.Equal(0, books!.Count);
Assert.Empty(books.Data);
PaginatedResponse<BookLiteResponse>? booksLite = await booksLiteResponse.Content.ReadFromJsonAsync<PaginatedResponse<BookLiteResponse>>(_jsonOptions);
Assert.NotNull(booksLite);
Assert.Equal(0, booksLite!.Count);
Assert.Empty(booksLite.Data);
await AssertNotFoundAsync(bookResponse, "BookNotFound", $"/api/v1/libraries/{libraryId}/books/{bookId}");
await AssertNotFoundAsync(availabilityResponse, "BookNotFound", $"/api/v1/libraries/{libraryId}/books/{bookId}/reading/availability");
await AssertNotFoundAsync(manifestResponse, "BookNotFound", $"/api/v1/libraries/{libraryId}/books/{bookId}/reading/manifest");
await AssertNotFoundAsync(sectionResponse, "BookNotFound", $"/api/v1/libraries/{libraryId}/books/{bookId}/reading/sections/section-1");
await AssertNotFoundAsync(resourceResponse, "BookNotFound", $"/api/v1/libraries/{libraryId}/books/{bookId}/reading/resources/resource-1");
}
[Fact]
@@ -0,0 +1,179 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary;
using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management;
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary;
using Lumina.Application.Fixtures.Common.DataAccess.Entities.UsersManagement;
using Lumina.Contracts.Responses.MediaLibrary.WrittenContentLibrary.BookLibrary.Books;
using Lumina.DataAccess.Core.UoW;
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
using Lumina.Presentation.Api.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.Books.GetDeletedBooks;
using Lumina.Presentation.Api.IntegrationTests.Common.Setup;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Json;
using System.Text.Json;
using System.Threading.Tasks;
#endregion
namespace Lumina.Presentation.Api.IntegrationTests.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.Books.GetDeletedBooks;
/// <summary>
/// Contains integration tests for the <see cref="GetDeletedBooksEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetDeletedBooksEndpointTests : 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 UserEntityFixture _userEntityFixture = new();
/// <summary>
/// Initializes a new instance of the <see cref="GetDeletedBooksEndpointTests"/> class.
/// </summary>
/// <param name="apiFactory">Injected in-memory API factory.</param>
public GetDeletedBooksEndpointTests(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 GetDeletedBooks_WhenLibraryHasDeletedBooks_ShouldReturnOnlyTheDeletedBooks()
{
// Arrange
Guid userId = GetCurrentUserId();
Guid libraryId = await SeedLibraryAsync(userId);
BookEntity deletedBook = await SeedBookAsync(libraryId, isDeleted: true, title: "Deleted Book");
await SeedBookAsync(libraryId, isDeleted: false, title: "Active Book");
// Act
HttpResponseMessage response = await _client.GetAsync($"/api/v1/libraries/{libraryId}/books/deleted-items");
// Assert
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
DeletedBookResponse[]? books = await response.Content.ReadFromJsonAsync<DeletedBookResponse[]>(_jsonOptions);
Assert.NotNull(books);
Assert.Single(books);
Assert.Equal(deletedBook.Id, books![0].Id);
Assert.Equal("Deleted Book", books[0].Title);
}
[Fact]
public async Task GetDeletedBooks_WhenLibraryBelongsToAnotherUser_ShouldReturnForbidden()
{
// Arrange
Guid otherUserId = await SeedOtherUserAsync();
Guid otherLibraryId = await SeedLibraryAsync(otherUserId);
// Act
HttpResponseMessage response = await _client.GetAsync($"/api/v1/libraries/{otherLibraryId}/books/deleted-items");
// Assert
Assert.Equal(HttpStatusCode.Forbidden, response.StatusCode);
}
[Fact]
public async Task GetDeletedBooks_WhenUnauthorized_ShouldReturnUnauthorizedResult()
{
// Arrange
HttpClient unauthenticatedClient = _apiFactory.CreateClient();
// Act
HttpResponseMessage response = await unauthenticatedClient.GetAsync($"/api/v1/libraries/{Guid.NewGuid()}/books/deleted-items");
// Assert
Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode);
}
[Fact]
public async Task GetDeletedBooks_WhenLibraryIdIsNotParseable_ShouldReturnUnprocessableEntity()
{
// Act
HttpResponseMessage response = await _client.GetAsync("/api/v1/libraries/not-a-guid/books/deleted-items");
// Assert
Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode);
}
/// <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 a book in the provided library.
/// </summary>
/// <param name="libraryId">The Id of the library that owns the book.</param>
/// <param name="isDeleted">Whether the book is soft deleted.</param>
/// <param name="title">The title of the book.</param>
/// <returns>The seeded book.</returns>
private async Task<BookEntity> SeedBookAsync(Guid libraryId, bool isDeleted, string title)
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
BookEntity book = _bookEntityFixture.Create(libraryId: libraryId, path: $"/books/{Guid.NewGuid():N}.epub", title: title, isDeleted: isDeleted, includeMetadata: false);
dbContext.Books.Add(book);
await dbContext.SaveChangesAsync();
return book;
}
/// <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>
/// Disposes API factory resources.
/// </summary>
public async Task DisposeAsync()
{
await _apiFactory.RemoveTestUserAsync();
}
}
@@ -0,0 +1,188 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary;
using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management;
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary;
using Lumina.Application.Fixtures.Common.DataAccess.Entities.UsersManagement;
using Lumina.DataAccess.Core.UoW;
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
using Lumina.Presentation.Api.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.Books.RestoreBook;
using Lumina.Presentation.Api.IntegrationTests.Common.Setup;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
#endregion
namespace Lumina.Presentation.Api.IntegrationTests.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.Books.RestoreBook;
/// <summary>
/// Contains integration tests for the <see cref="RestoreBookEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class RestoreBookEndpointTests : IClassFixture<AuthenticatedLuminaApiFactory>, IAsyncLifetime
{
private HttpClient _client;
private readonly AuthenticatedLuminaApiFactory _apiFactory;
private readonly LibraryEntityFixture _libraryEntityFixture = new();
private readonly BookEntityFixture _bookEntityFixture = new();
private readonly UserEntityFixture _userEntityFixture = new();
/// <summary>
/// Initializes a new instance of the <see cref="RestoreBookEndpointTests"/> class.
/// </summary>
/// <param name="apiFactory">Injected in-memory API factory.</param>
public RestoreBookEndpointTests(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 RestoreBook_WhenDeletedBookBelongsToAnOwnedLibrary_ShouldRestoreTheBook()
{
// Arrange
Guid userId = GetCurrentUserId();
(Guid libraryId, Guid bookId) = await SeedLibraryAndBookAsync(userId, isDeleted: true);
// Act
HttpResponseMessage response = await _client.PostAsync($"/api/v1/libraries/{libraryId}/books/{bookId}/restore", null);
// Assert
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
BookEntity? book = await dbContext.Books.FirstOrDefaultAsync(book => book.Id == bookId);
Assert.NotNull(book);
Assert.False(book!.IsDeleted);
}
[Fact]
public async Task RestoreBook_WhenBookIsNotDeleted_ShouldReturnBookNotFoundProblem()
{
// Arrange
Guid userId = GetCurrentUserId();
(Guid libraryId, Guid bookId) = await SeedLibraryAndBookAsync(userId, isDeleted: false);
// Act
HttpResponseMessage response = await _client.PostAsync($"/api/v1/libraries/{libraryId}/books/{bookId}/restore", null);
// Assert
Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);
}
[Fact]
public async Task RestoreBook_WhenBookIsRestoredThroughDifferentLibrary_ShouldReturnBookNotFoundProblem()
{
// Arrange
Guid userId = GetCurrentUserId();
(_, Guid bookId) = await SeedLibraryAndBookAsync(userId, isDeleted: true);
// Act
HttpResponseMessage response = await _client.PostAsync($"/api/v1/libraries/{Guid.NewGuid()}/books/{bookId}/restore", null);
// Assert
Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);
}
[Fact]
public async Task RestoreBook_WhenBookBelongsToAnotherUserLibrary_ShouldReturnForbiddenProblem()
{
// Arrange
Guid otherUserId = await SeedOtherUserAsync();
(Guid otherLibraryId, Guid otherBookId) = await SeedLibraryAndBookAsync(otherUserId, isDeleted: true);
// Act
HttpResponseMessage response = await _client.PostAsync($"/api/v1/libraries/{otherLibraryId}/books/{otherBookId}/restore", null);
// Assert
Assert.Equal(HttpStatusCode.Forbidden, response.StatusCode);
}
[Fact]
public async Task RestoreBook_WhenUnauthorized_ShouldReturnUnauthorizedResult()
{
// Arrange
HttpClient unauthenticatedClient = _apiFactory.CreateClient();
// Act
HttpResponseMessage response = await unauthenticatedClient.PostAsync($"/api/v1/libraries/{Guid.NewGuid()}/books/{Guid.NewGuid()}/restore", null);
// Assert
Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode);
}
[Fact]
public async Task RestoreBook_WhenIdsAreNotParseable_ShouldReturnUnprocessableEntity()
{
// Act
HttpResponseMessage response = await _client.PostAsync($"/api/v1/libraries/not-a-guid/books/not-a-guid/restore", null);
// Assert
Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode);
}
/// <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>
/// <param name="isDeleted">Whether the seeded book is soft deleted.</param>
/// <returns>The Ids of the seeded library and book.</returns>
private async Task<(Guid libraryId, Guid bookId)> SeedLibraryAndBookAsync(Guid userId, bool isDeleted)
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
Guid libraryId = Guid.NewGuid();
BookEntity book = _bookEntityFixture.Create(libraryId: libraryId, path: $"/books/{Guid.NewGuid():N}.epub", isDeleted: isDeleted, includeMetadata: false);
dbContext.Libraries.Add(_libraryEntityFixture.Create(id: libraryId, userId: userId, title: "Test Library", libraryType: LibraryType.EBook, contentLocations: []));
dbContext.Books.Add(book);
await dbContext.SaveChangesAsync();
return (libraryId, book.Id);
}
/// <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>
/// Disposes API factory resources.
/// </summary>
public async Task DisposeAsync()
{
await _apiFactory.RemoveTestUserAsync();
}
}
@@ -66,6 +66,27 @@ public class GetThemeTemplateEndpointTests : IClassFixture<AuthenticatedLuminaAp
Assert.False(string.IsNullOrWhiteSpace(result.Template));
}
[Theory]
[InlineData("lumina-default")]
[InlineData("editorial-paper")]
public async Task GetThemeTemplate_WhenCalledForTheDeletedItemsPage_ShouldReturnTheBundledTemplate(string themeId)
{
// Arrange
await ThemeTestHelpers.WaitForBundledThemeAsync(_apiFactory);
HttpClient anonymousClient = _apiFactory.CreateClient();
// Act
HttpResponseMessage response = await anonymousClient.GetAsync($"/api/v1/themes/{themeId}/templates/library/written-content-library/book-library/books/deleted-items");
// Assert
response.EnsureSuccessStatusCode();
ThemeTemplateResponse? result = await response.Content.ReadFromJsonAsync<ThemeTemplateResponse>(_jsonOptions);
Assert.NotNull(result);
Assert.Equal(themeId, result!.Theme.ThemeId);
Assert.Contains("btn-back-to-library", result.Template);
Assert.Contains("restoreUrlTemplate", result.Template);
}
[Fact]
public async Task GetThemeTemplate_WhenThemeDoesNotExist_ShouldReturnNotFound()
{
@@ -0,0 +1,110 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Presentation.Web.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.Books.DeleteBook;
using Lumina.Presentation.Web.Fixtures.Common.TestHelpers;
using Lumina.Presentation.Web.IntegrationTests.Common.Setup;
using System;
using System.Diagnostics.CodeAnalysis;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Text.Json;
using System.Threading.Tasks;
#endregion
namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.Books.DeleteBook;
/// <summary>
/// Contains integration tests for the <see cref="DeleteBookEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class DeleteBookEndpointTests : IClassFixture<LuminaWebFactory>
{
private readonly LuminaWebFactory _apiFactory;
/// <summary>
/// Initializes a new instance of the <see cref="DeleteBookEndpointTests"/> class.
/// </summary>
/// <param name="apiFactory">Injected Web application factory.</param>
public DeleteBookEndpointTests(LuminaWebFactory apiFactory)
{
_apiFactory = apiFactory;
}
[Fact]
public async Task DeleteBook_WhenCalledByAuthenticatedUserWithAntiforgeryToken_ShouldForwardDeleteAndReturnSuccess()
{
// Arrange
_apiFactory.ApiClientStub.Reset();
Guid libraryId = Guid.NewGuid();
Guid bookId = Guid.NewGuid();
_apiFactory.ApiClientStub.RegisterDeleteSuccess($"libraries/{libraryId}/books/{bookId}");
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
HttpRequestMessage deleteRequest = CreateDeleteRequest(bookId, libraryId);
deleteRequest.Headers.Add("RequestVerificationToken", webClient.AntiforgeryToken);
// Act
HttpResponseMessage response = await webClient.Client.SendAsync(deleteRequest);
string content = await response.Content.ReadAsStringAsync();
// Assert
response.EnsureSuccessStatusCode();
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
using JsonDocument json = JsonDocument.Parse(content);
Assert.True(json.RootElement.GetProperty("success").GetBoolean());
Assert.Contains($"libraries/{libraryId}/books/{bookId}", _apiFactory.ApiClientStub.DeleteEndpointsCalled);
}
[Fact]
public async Task DeleteBook_WhenCalledWithoutAntiforgeryToken_ShouldRejectRequest()
{
// Arrange
_apiFactory.ApiClientStub.Reset();
Guid libraryId = Guid.NewGuid();
Guid bookId = Guid.NewGuid();
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
HttpRequestMessage deleteRequest = CreateDeleteRequest(bookId, libraryId);
// Act
HttpResponseMessage response = await webClient.Client.SendAsync(deleteRequest);
// Assert
Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode);
Assert.DoesNotContain($"libraries/{libraryId}/books/{bookId}", _apiFactory.ApiClientStub.DeleteEndpointsCalled);
}
[Fact]
public async Task DeleteBook_WhenNotAuthenticated_ShouldRedirectToLogin()
{
// Arrange
_apiFactory.ApiClientStub.Reset();
HttpClient anonymousClient = WebTestHelpers.CreateAnonymousClient(_apiFactory);
HttpRequestMessage deleteRequest = CreateDeleteRequest(Guid.NewGuid(), Guid.NewGuid());
// Act
HttpResponseMessage response = await anonymousClient.SendAsync(deleteRequest);
// Assert
Assert.Equal(HttpStatusCode.Redirect, response.StatusCode);
Assert.Empty(_apiFactory.ApiClientStub.DeleteEndpointsCalled);
}
/// <summary>
/// Builds the delete request for the book identified by the route, with the owning library passed through the query string.
/// </summary>
/// <param name="bookId">The route Id of the book to delete.</param>
/// <param name="libraryId">The Id of the media library the book belongs to.</param>
/// <returns>The configured delete request.</returns>
private static HttpRequestMessage CreateDeleteRequest(Guid bookId, Guid libraryId)
{
HttpRequestMessage deleteRequest = new(HttpMethod.Delete, $"/en-us/library/written-content-library/books-library/books/{bookId}/api-delete-book?libraryId={libraryId}")
{
// The front-end sends the JSON content type even for DELETE requests, which triggers the antiforgery validation.
Content = new StringContent("{}", Encoding.UTF8, "application/json")
};
// The antiforgery middleware matches the content type exactly, so the charset suffix must be omitted.
deleteRequest.Content!.Headers.ContentType = new MediaTypeHeaderValue("application/json");
deleteRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
return deleteRequest;
}
}
@@ -0,0 +1,128 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Presentation.Web.Common.DTO.Libraries;
using Lumina.Presentation.Web.Common.DTO.WrittenContentLibrary.BookLibrary;
using Lumina.Presentation.Web.Common.Exceptions;
using Lumina.Presentation.Web.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.Books.DeletedBooks;
using Lumina.Presentation.Web.Fixtures.Common.DTO.Common;
using Lumina.Presentation.Web.Fixtures.Common.DTO.Libraries;
using Lumina.Presentation.Web.Fixtures.Common.DTO.WrittenContentLibrary.BookLibrary;
using Lumina.Presentation.Web.Fixtures.Common.TestHelpers;
using Lumina.Presentation.Web.IntegrationTests.Common.Setup;
using System;
using System.Diagnostics.CodeAnalysis;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
#endregion
namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.Books.DeletedBooks;
/// <summary>
/// Contains integration tests for the <see cref="DeletedBooksViewEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class DeletedBooksViewEndpointTests : IClassFixture<LuminaWebFactory>
{
private readonly LuminaWebFactory _apiFactory;
private readonly LibraryDtoFixture _libraryDtoFixture = new();
private readonly DeletedBookDtoFixture _deletedBookDtoFixture = new();
private readonly ProblemDetailsDtoFixture _problemDetailsDtoFixture = new();
/// <summary>
/// Initializes a new instance of the <see cref="DeletedBooksViewEndpointTests"/> class.
/// </summary>
/// <param name="apiFactory">Injected Web application factory.</param>
public DeletedBooksViewEndpointTests(LuminaWebFactory apiFactory)
{
_apiFactory = apiFactory;
}
[Fact]
public async Task DeletedBooksView_WhenCalledByAuthenticatedUserWithLibraryId_ShouldRenderDeletedBooksPage()
{
// Arrange
_apiFactory.ApiClientStub.Reset();
Guid libraryId = Guid.NewGuid();
LibraryDto library = _libraryDtoFixture.Create(id: libraryId, title: "Books");
DeletedBookDto deletedBook = _deletedBookDtoFixture.Create(libraryId: libraryId, title: "Deleted Book");
_apiFactory.ApiClientStub.RegisterGetResponse($"libraries/{libraryId}", library);
_apiFactory.ApiClientStub.RegisterGetResponse($"libraries/{libraryId}/books/deleted-items", new[] { deletedBook });
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
// Act
HttpResponseMessage response = await webClient.Client.GetAsync($"/en-us/library/written-content-library/books-library/books/deleted-items?libraryId={libraryId}");
string content = await response.Content.ReadAsStringAsync();
// Assert
response.EnsureSuccessStatusCode();
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
Assert.Equal("text/html", response.Content.Headers.ContentType!.MediaType);
Assert.Contains("Deleted Book", content);
Assert.Contains("deleted-books-table", content);
Assert.Contains($"libraries/{libraryId}/books/deleted-items", _apiFactory.ApiClientStub.GetEndpointsCalled);
}
[Fact]
public async Task DeletedBooksView_WhenDeletedBookTitleContainsMarkup_ShouldEncodeIt()
{
// Arrange
_apiFactory.ApiClientStub.Reset();
Guid libraryId = Guid.NewGuid();
LibraryDto library = _libraryDtoFixture.Create(id: libraryId, title: "Books");
DeletedBookDto deletedBook = _deletedBookDtoFixture.Create(libraryId: libraryId, title: "<script>alert('x')</script>");
_apiFactory.ApiClientStub.RegisterGetResponse($"libraries/{libraryId}", library);
_apiFactory.ApiClientStub.RegisterGetResponse($"libraries/{libraryId}/books/deleted-items", new[] { deletedBook });
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
// Act
HttpResponseMessage response = await webClient.Client.GetAsync($"/en-us/library/written-content-library/books-library/books/deleted-items?libraryId={libraryId}");
string content = await response.Content.ReadAsStringAsync();
// Assert
response.EnsureSuccessStatusCode();
Assert.Contains("&lt;script&gt;alert", content);
Assert.DoesNotContain("<script>alert('x')</script>", content);
}
[Fact]
public async Task DeletedBooksView_WhenTheApiReturnsForbidden_ShouldRedirectWithoutLeakingDetails()
{
// Arrange
_apiFactory.ApiClientStub.Reset();
Guid libraryId = Guid.NewGuid();
LibraryDto library = _libraryDtoFixture.Create(id: libraryId, title: "Books");
_apiFactory.ApiClientStub.RegisterGetResponse($"libraries/{libraryId}", library);
string endpoint = $"libraries/{libraryId}/books/deleted-items";
_apiFactory.ApiClientStub.RegisterGetException(endpoint, new ApiException(
_problemDetailsDtoFixture.Create(title: "General.Unauthorized", detail: "NotAuthorized"),
HttpStatusCode.Forbidden,
endpoint));
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
// Act
HttpResponseMessage response = await webClient.Client.GetAsync($"/en-us/library/written-content-library/books-library/books/deleted-items?libraryId={libraryId}");
string content = await response.Content.ReadAsStringAsync();
// Assert
// A browser navigation that the API forbids is redirected to the access denied page, without rendering any of the forbidden data.
Assert.Equal(HttpStatusCode.Found, response.StatusCode);
Assert.NotNull(response.Headers.Location);
Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase);
}
[Fact]
public async Task DeletedBooksView_WhenCalledWithoutLibraryId_ShouldRedirectToHome()
{
// Arrange
_apiFactory.ApiClientStub.Reset();
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
// Act
HttpResponseMessage response = await webClient.Client.GetAsync("/en-us/library/written-content-library/books-library/books/deleted-items");
// Assert
Assert.Equal(HttpStatusCode.Redirect, response.StatusCode);
Assert.Contains("/en-us", response.Headers.Location!.ToString());
}
}
@@ -4,7 +4,6 @@ using Lumina.Presentation.Web.Core.Endpoints.Library.WrittenContentLibrary.BookL
using Lumina.Presentation.Web.Fixtures.Common.DTO.WrittenContentLibrary.BookLibrary;
using Lumina.Presentation.Web.Fixtures.Common.TestHelpers;
using Lumina.Presentation.Web.IntegrationTests.Common.Setup;
using System;
using System.Diagnostics.CodeAnalysis;
using System.Net;
using System.Net.Http;
@@ -50,5 +49,6 @@ public class EditBookViewEndpointTests : IClassFixture<LuminaWebFactory>
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
Assert.Equal("text/html", response.Content.Headers.ContentType!.MediaType);
Assert.Contains("A book", content);
Assert.Contains("btn-delete-book", content);
}
}
@@ -50,9 +50,33 @@ public class BooksIndexViewEndpointTests : IClassFixture<LuminaWebFactory>
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
Assert.Equal("text/html", response.Content.Headers.ContentType!.MediaType);
Assert.Contains("search-input", content);
Assert.Contains("card-action-delete", content);
Assert.Contains($"libraries/{libraryId}", _apiFactory.ApiClientStub.GetEndpointsCalled);
}
[Fact]
public async Task BooksIndex_WhenTheCultureUsesApostrophes_ShouldSerializeTheLocalizedStringsAsJson()
{
// Arrange
_apiFactory.ApiClientStub.Reset();
Guid libraryId = Guid.NewGuid();
LibraryDto expectedLibrary = _libraryDtoFixture.Create(id: libraryId, title: "Livres");
_apiFactory.ApiClientStub.RegisterGetResponse($"libraries/{libraryId}", expectedLibrary);
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
// Act
HttpResponseMessage response = await webClient.Client.GetAsync($"/fr-fr/library/written-content-library/books-library/books?libraryId={libraryId}");
string content = await response.Content.ReadAsStringAsync();
// Assert
response.EnsureSuccessStatusCode();
// The apostrophes and accents are JSON-escaped, so the translations stay valid JavaScript string literals.
Assert.Contains("deleteFailed: \"L", content);
Assert.Contains("deleteConfirm: \"", content);
Assert.DoesNotContain("deleteFailed: '", content);
Assert.DoesNotContain("deleteConfirm: '", content);
}
[Fact]
public async Task BooksIndex_WhenCalledByAuthenticatedUserWithoutLibraryId_ShouldRedirectToHome()
{
@@ -0,0 +1,113 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Presentation.Web.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.Books.RestoreBook;
using Lumina.Presentation.Web.Fixtures.Common.TestHelpers;
using Lumina.Presentation.Web.IntegrationTests.Common.Setup;
using System;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Text.Json;
using System.Threading.Tasks;
#endregion
namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.Books.RestoreBook;
/// <summary>
/// Contains integration tests for the <see cref="RestoreBookEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class RestoreBookEndpointTests : IClassFixture<LuminaWebFactory>
{
private readonly LuminaWebFactory _apiFactory;
/// <summary>
/// Initializes a new instance of the <see cref="RestoreBookEndpointTests"/> class.
/// </summary>
/// <param name="apiFactory">Injected Web application factory.</param>
public RestoreBookEndpointTests(LuminaWebFactory apiFactory)
{
_apiFactory = apiFactory;
}
[Fact]
public async Task RestoreBook_WhenCalledByAuthenticatedUserWithAntiforgeryToken_ShouldForwardPostAndReturnSuccess()
{
// Arrange
_apiFactory.ApiClientStub.Reset();
Guid libraryId = Guid.NewGuid();
Guid bookId = Guid.NewGuid();
_apiFactory.ApiClientStub.RegisterPostResponse<object>($"libraries/{libraryId}/books/{bookId}/restore", new Lumina.Presentation.Web.Common.Requests.Common.EmptyRequest());
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
HttpRequestMessage restoreRequest = CreateRestoreRequest(bookId, libraryId);
restoreRequest.Headers.Add("RequestVerificationToken", webClient.AntiforgeryToken);
// Act
HttpResponseMessage response = await webClient.Client.SendAsync(restoreRequest);
string content = await response.Content.ReadAsStringAsync();
// Assert
response.EnsureSuccessStatusCode();
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
using JsonDocument json = JsonDocument.Parse(content);
Assert.True(json.RootElement.GetProperty("success").GetBoolean());
Assert.True(json.RootElement.GetProperty("data").GetProperty("isRestored").GetBoolean());
Assert.Contains($"libraries/{libraryId}/books/{bookId}/restore", _apiFactory.ApiClientStub.PostRequests.Select(request => request.Endpoint));
}
[Fact]
public async Task RestoreBook_WhenCalledWithoutAntiforgeryToken_ShouldRejectRequest()
{
// Arrange
_apiFactory.ApiClientStub.Reset();
Guid libraryId = Guid.NewGuid();
Guid bookId = Guid.NewGuid();
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
_apiFactory.ApiClientStub.Reset();
HttpRequestMessage restoreRequest = CreateRestoreRequest(bookId, libraryId);
// Act
HttpResponseMessage response = await webClient.Client.SendAsync(restoreRequest);
// Assert
Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode);
Assert.Empty(_apiFactory.ApiClientStub.PostRequests);
}
[Fact]
public async Task RestoreBook_WhenNotAuthenticated_ShouldRedirectToLogin()
{
// Arrange
_apiFactory.ApiClientStub.Reset();
HttpClient anonymousClient = WebTestHelpers.CreateAnonymousClient(_apiFactory);
HttpRequestMessage restoreRequest = CreateRestoreRequest(Guid.NewGuid(), Guid.NewGuid());
// Act
HttpResponseMessage response = await anonymousClient.SendAsync(restoreRequest);
// Assert
Assert.Equal(HttpStatusCode.Redirect, response.StatusCode);
Assert.Empty(_apiFactory.ApiClientStub.PostRequests);
}
/// <summary>
/// Builds the restore request for the book identified by the route, with the owning library passed through the query string.
/// </summary>
/// <param name="bookId">The route Id of the book to restore.</param>
/// <param name="libraryId">The Id of the media library the book belongs to.</param>
/// <returns>The configured restore request.</returns>
private static HttpRequestMessage CreateRestoreRequest(Guid bookId, Guid libraryId)
{
HttpRequestMessage restoreRequest = new(HttpMethod.Post, $"/en-us/library/written-content-library/books-library/books/{bookId}/api-restore-book?libraryId={libraryId}")
{
// The front-end sends the JSON content type even for bodyless POST requests, which triggers the antiforgery validation.
Content = new StringContent("{}", Encoding.UTF8, "application/json")
};
// The antiforgery middleware matches the content type exactly, so the charset suffix must be omitted.
restoreRequest.Content!.Headers.ContentType = new MediaTypeHeaderValue("application/json");
restoreRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
return restoreRequest;
}
}