mirror of
https://github.com/BinaryAlley/Nemera.git
synced 2026-12-01 18:57:24 +00:00
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:
1 parent
ef5ede6325
commit
f26b07d4ff
125 files changed
+9856
-378
No files matched your search
+6
@@ -33,6 +33,8 @@ public class BookEntityFixture
|
||||
/// <param name="path">Optional. The file system path of the book.</param>
|
||||
/// <param name="title">Optional. The title of the book.</param>
|
||||
/// <param name="originalTitle">Optional. The original title of the book.</param>
|
||||
/// <param name="deletedOnUtc">Optional. The date and time when the book was deleted. Only used when the book is marked as deleted.</param>
|
||||
/// <param name="isDeleted">Optional. Whether the book is marked as deleted.</param>
|
||||
/// <param name="includeMetadata">Whether the owned metadata collections (Tags, Genres, ISBNs, Ratings) should be included, or forced to empty collections.</param>
|
||||
/// <returns>The created <see cref="BookEntity"/>.</returns>
|
||||
public BookEntity Create(
|
||||
@@ -41,6 +43,8 @@ public class BookEntityFixture
|
||||
string? path = null,
|
||||
string? title = null,
|
||||
string? originalTitle = null,
|
||||
DateTime? deletedOnUtc = null,
|
||||
bool isDeleted = false,
|
||||
bool includeMetadata = true)
|
||||
{
|
||||
int releaseYear = Random.Shared.Next(2000, 2010);
|
||||
@@ -83,6 +87,8 @@ public class BookEntityFixture
|
||||
.RuleFor(x => x.AppleBooksId, f => $"id{f.Random.Number(1, 999999)}")
|
||||
.RuleFor(x => x.ISBNs, f => includeMetadata ? _isbnEntityFixture.CreateMany(f.Random.Number(1, 5)) : [])
|
||||
.RuleFor(x => x.Ratings, f => includeMetadata ? _bookRatingEntityFixture.CreateMany(f.Random.Number(1, 5)) : [])
|
||||
.RuleFor(x => x.IsDeleted, isDeleted)
|
||||
.RuleFor(x => x.DeletedOnUtc, f => isDeleted ? (deletedOnUtc ?? f.Date.Recent()) : null)
|
||||
.RuleFor(x => x.CreatedOnUtc, f => f.Date.Past())
|
||||
.RuleFor(x => x.UpdatedOnUtc, f => f.Date.Recent())
|
||||
.Generate();
|
||||
|
||||
+45
@@ -0,0 +1,45 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Commands.RestoreBook;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.Fixtures.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Commands.RestoreBook;
|
||||
|
||||
/// <summary>
|
||||
/// Fixture class for the <see cref="RestoreBookCommand"/> record.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class RestoreBookCommandFixture
|
||||
{
|
||||
/// <summary>
|
||||
/// Creates a random valid <see cref="RestoreBookCommand"/>.
|
||||
/// </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 deleted book to restore, 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="RestoreBookCommand"/>.</returns>
|
||||
public RestoreBookCommand Create(
|
||||
string? libraryId = null,
|
||||
string? bookId = null,
|
||||
bool includeLibraryId = true,
|
||||
bool includeBookId = true)
|
||||
{
|
||||
return new RestoreBookCommand(
|
||||
includeLibraryId ? (libraryId ?? Guid.NewGuid().ToString()) : null,
|
||||
includeBookId ? (bookId ?? Guid.NewGuid().ToString()) : null);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a list of <see cref="RestoreBookCommand"/>.
|
||||
/// </summary>
|
||||
/// <param name="count">Number of instances to create.</param>
|
||||
/// <returns>List of configured <see cref="RestoreBookCommand"/> instances.</returns>
|
||||
public List<RestoreBookCommand> CreateMany(int count = 3)
|
||||
{
|
||||
return [.. Enumerable.Range(0, count).Select(_ => Create())];
|
||||
}
|
||||
}
|
||||
+40
@@ -0,0 +1,40 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Queries.GetDeletedBooks;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.Fixtures.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Queries.GetDeletedBooks;
|
||||
|
||||
/// <summary>
|
||||
/// Fixture class for the <see cref="GetDeletedBooksQuery"/> record.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class GetDeletedBooksQueryFixture
|
||||
{
|
||||
/// <summary>
|
||||
/// Creates a random valid <see cref="GetDeletedBooksQuery"/>.
|
||||
/// </summary>
|
||||
/// <param name="libraryId">Optional. The Id of the media library whose deleted books are retrieved, taken from the route.</param>
|
||||
/// <param name="includeLibraryId">Whether the library Id should be included, or forced to <see langword="null"/>.</param>
|
||||
/// <returns>The created <see cref="GetDeletedBooksQuery"/>.</returns>
|
||||
public GetDeletedBooksQuery Create(
|
||||
string? libraryId = null,
|
||||
bool includeLibraryId = true)
|
||||
{
|
||||
return new GetDeletedBooksQuery(
|
||||
includeLibraryId ? (libraryId ?? Guid.NewGuid().ToString()) : null);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a list of <see cref="GetDeletedBooksQuery"/>.
|
||||
/// </summary>
|
||||
/// <param name="count">Number of instances to create.</param>
|
||||
/// <returns>List of configured <see cref="GetDeletedBooksQuery"/> instances.</returns>
|
||||
public List<GetDeletedBooksQuery> CreateMany(int count = 3)
|
||||
{
|
||||
return [.. Enumerable.Range(0, count).Select(_ => Create())];
|
||||
}
|
||||
}
|
||||
+64
@@ -0,0 +1,64 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Bogus;
|
||||
using Lumina.Contracts.Responses.MediaLibrary.WrittenContentLibrary.BookLibrary.Books;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Contracts.Fixtures.Responses.MediaLibrary.WrittenContentLibrary.BookLibrary.Books;
|
||||
|
||||
/// <summary>
|
||||
/// Fixture class for the <see cref="DeletedBookResponse"/> record.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class DeletedBookResponseFixture
|
||||
{
|
||||
private readonly Faker _faker = new();
|
||||
|
||||
/// <summary>
|
||||
/// Creates a random valid <see cref="DeletedBookResponse"/>.
|
||||
/// </summary>
|
||||
/// <param name="id">Optional. The Id of the deleted book.</param>
|
||||
/// <param name="libraryId">Optional. The Id of the media library the deleted book belongs to.</param>
|
||||
/// <param name="title">Optional. The title of the deleted book.</param>
|
||||
/// <param name="originalTitle">Optional. The original title of the deleted book.</param>
|
||||
/// <param name="path">Optional. The file system path of the deleted book.</param>
|
||||
/// <param name="deletedOnUtc">Optional. The date and time when the book was deleted.</param>
|
||||
/// <param name="coverPath">Optional. The path of the cover image of the deleted book.</param>
|
||||
/// <param name="includeOriginalTitle">Whether the original title should be included, or forced to <see langword="null"/>.</param>
|
||||
/// <param name="includeCoverPath">Whether the cover path should be included, or forced to <see langword="null"/>.</param>
|
||||
/// <returns>The created <see cref="DeletedBookResponse"/>.</returns>
|
||||
public DeletedBookResponse Create(
|
||||
Guid? id = null,
|
||||
Guid? libraryId = null,
|
||||
string? title = null,
|
||||
string? originalTitle = null,
|
||||
string? path = null,
|
||||
DateTime? deletedOnUtc = null,
|
||||
string? coverPath = null,
|
||||
bool includeOriginalTitle = true,
|
||||
bool includeCoverPath = true)
|
||||
{
|
||||
return new DeletedBookResponse(
|
||||
id ?? _faker.Random.Guid(),
|
||||
libraryId ?? _faker.Random.Guid(),
|
||||
title ?? _faker.Lorem.Sentence(3),
|
||||
includeOriginalTitle ? (originalTitle ?? _faker.Lorem.Sentence(3)) : null,
|
||||
path ?? _faker.System.FilePath(),
|
||||
deletedOnUtc ?? _faker.Date.Recent(),
|
||||
includeCoverPath ? (coverPath ?? $"/covers/{_faker.Random.Guid()}.jpg") : null
|
||||
);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a list of <see cref="DeletedBookResponse"/> instances with randomized test data.
|
||||
/// </summary>
|
||||
/// <param name="count">Number of instances to create.</param>
|
||||
/// <returns>List of configured <see cref="DeletedBookResponse"/> instances.</returns>
|
||||
public List<DeletedBookResponse> CreateMany(int count = 3)
|
||||
{
|
||||
return [.. Enumerable.Range(0, count).Select(_ => Create())];
|
||||
}
|
||||
}
|
||||
+64
@@ -0,0 +1,64 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Bogus;
|
||||
using Lumina.Presentation.Web.Common.DTO.WrittenContentLibrary.BookLibrary;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.Fixtures.Common.DTO.WrittenContentLibrary.BookLibrary;
|
||||
|
||||
/// <summary>
|
||||
/// Fixture class for the <see cref="DeletedBookDto"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class DeletedBookDtoFixture
|
||||
{
|
||||
private readonly Faker _faker = new();
|
||||
|
||||
/// <summary>
|
||||
/// Creates a new <see cref="DeletedBookDto"/> instance with randomized test data.
|
||||
/// </summary>
|
||||
/// <param name="id">Optional. The Id of the deleted book.</param>
|
||||
/// <param name="libraryId">Optional. The Id of the media library the deleted book belongs to.</param>
|
||||
/// <param name="title">Optional. The title of the deleted book.</param>
|
||||
/// <param name="originalTitle">Optional. The original title of the deleted book.</param>
|
||||
/// <param name="path">Optional. The file system path of the deleted book.</param>
|
||||
/// <param name="deletedOnUtc">Optional. The date and time when the book was deleted.</param>
|
||||
/// <param name="coverPath">Optional. The relative path of the stored cover image of the deleted book.</param>
|
||||
/// <param name="includeOriginalTitle">Whether the original title should be included, or forced to <see langword="null"/>.</param>
|
||||
/// <param name="includeCoverPath">Whether the cover path should be included, or forced to <see langword="null"/>.</param>
|
||||
/// <returns>The created <see cref="DeletedBookDto"/>.</returns>
|
||||
public DeletedBookDto Create(
|
||||
Guid? id = null,
|
||||
Guid? libraryId = null,
|
||||
string? title = null,
|
||||
string? originalTitle = null,
|
||||
string? path = null,
|
||||
DateTime? deletedOnUtc = null,
|
||||
string? coverPath = null,
|
||||
bool includeOriginalTitle = true,
|
||||
bool includeCoverPath = true)
|
||||
{
|
||||
return new DeletedBookDto(
|
||||
Id: id ?? _faker.Random.Guid(),
|
||||
LibraryId: libraryId ?? _faker.Random.Guid(),
|
||||
Title: title ?? _faker.Lorem.Sentence(),
|
||||
OriginalTitle: includeOriginalTitle ? (originalTitle ?? _faker.Lorem.Sentence()) : null,
|
||||
Path: path ?? _faker.System.FilePath(),
|
||||
DeletedOnUtc: deletedOnUtc ?? _faker.Date.Recent(),
|
||||
CoverPath: includeCoverPath ? (coverPath ?? _faker.System.FilePath()) : null
|
||||
);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates multiple <see cref="DeletedBookDto"/> instances with randomized test data.
|
||||
/// </summary>
|
||||
/// <param name="count">Number of instances to create.</param>
|
||||
/// <returns>List of configured <see cref="DeletedBookDto"/> instances.</returns>
|
||||
public List<DeletedBookDto> CreateMany(int count = 3)
|
||||
{
|
||||
return [.. Enumerable.Range(0, count).Select(_ => Create())];
|
||||
}
|
||||
}
|
||||
+23
-23
@@ -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");
|
||||
|
||||
+56
@@ -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
|
||||
|
||||
+12
-12
@@ -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.
|
||||
|
||||
+47
-7
@@ -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]
|
||||
|
||||
+179
@@ -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();
|
||||
}
|
||||
}
|
||||
+188
@@ -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();
|
||||
}
|
||||
}
|
||||
+21
@@ -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()
|
||||
{
|
||||
|
||||
+110
@@ -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;
|
||||
}
|
||||
}
|
||||
+128
@@ -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("<script>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());
|
||||
}
|
||||
}
|
||||
+1
-1
@@ -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);
|
||||
}
|
||||
}
|
||||
+24
@@ -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()
|
||||
{
|
||||
|
||||
+113
@@ -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;
|
||||
}
|
||||
}
|
||||
+142
@@ -0,0 +1,142 @@
|
||||
#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.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.SecurityTests.Common.Setup;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Net;
|
||||
using System.Text.Json;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Api.SecurityTests.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.Books.GetDeletedBooks;
|
||||
|
||||
/// <summary>
|
||||
/// Contains security tests for the <see cref="GetDeletedBooksEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class GetDeletedBooksEndpointTests : IClassFixture<LuminaApiFactory>, IDisposable
|
||||
{
|
||||
private readonly LuminaApiFactory _apiFactory;
|
||||
private readonly HttpClient _client;
|
||||
private readonly JsonSerializerOptions _jsonOptions = new() { PropertyNameCaseInsensitive = true };
|
||||
private readonly List<string> _seededUsernames = [];
|
||||
private readonly LibraryEntityFixture _libraryEntityFixture = new();
|
||||
private readonly BookEntityFixture _bookEntityFixture = new();
|
||||
private readonly BookArtworkEntityFixture _bookArtworkEntityFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="GetDeletedBooksEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected in-memory API factory.</param>
|
||||
public GetDeletedBooksEndpointTests(LuminaApiFactory apiFactory)
|
||||
{
|
||||
_apiFactory = apiFactory;
|
||||
_client = apiFactory.CreateClient();
|
||||
_client.DefaultRequestHeaders.Add("X-Forwarded-For", LuminaApiFactory.GetUniqueTestIp());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetDeletedBooks_WhenUnauthorized_ShouldReturnUnauthorizedResult()
|
||||
{
|
||||
// Arrange
|
||||
string url = $"/api/v1/libraries/{Guid.NewGuid()}/books/deleted-items";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync(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("Unauthorized", problemDetails["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 GetDeletedBooks_WithSQLInjectionInLibraryId_ShouldNotCorruptOrLeakData(string maliciousLibraryId)
|
||||
{
|
||||
// Arrange
|
||||
HttpClient client = _apiFactory.CreateClient();
|
||||
(_, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(client);
|
||||
_seededUsernames.Add(username);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await client.GetAsync($"/api/v1/libraries/{Uri.EscapeDataString(maliciousLibraryId)}/books/deleted-items");
|
||||
|
||||
// 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 GetDeletedBooks_WhenLibraryBelongsToAnotherUser_ShouldReturnForbiddenAndNotLeakTheDeletedBook()
|
||||
{
|
||||
// Arrange
|
||||
HttpClient client = _apiFactory.CreateClient();
|
||||
(_, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(client);
|
||||
_seededUsernames.Add(username);
|
||||
HttpClient victimClient = _apiFactory.CreateClient();
|
||||
(Guid victimUserId, string victimUsername) = await _apiFactory.CreateAndAuthenticateUserAsync(victimClient);
|
||||
_seededUsernames.Add(victimUsername);
|
||||
const string TITLE = "Secret Deleted Book";
|
||||
const string PATH = "/private/deleted-book.epub";
|
||||
const string COVER_PATH = "/private/deleted-book-cover.jpg";
|
||||
(Guid libraryId, _) = await SeedLibraryAndDeletedBookAsync(victimUserId, TITLE, PATH, COVER_PATH);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await client.GetAsync($"/api/v1/libraries/{libraryId}/books/deleted-items");
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.Forbidden, response.StatusCode);
|
||||
Assert.DoesNotContain(TITLE, content, StringComparison.Ordinal);
|
||||
Assert.DoesNotContain(PATH, content, StringComparison.Ordinal);
|
||||
Assert.DoesNotContain(COVER_PATH, content, StringComparison.Ordinal);
|
||||
Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds an ebook library owned by <paramref name="userId"/>, together with a deleted book and its cover.
|
||||
/// </summary>
|
||||
/// <param name="userId">The Id of the user that owns the library.</param>
|
||||
/// <param name="title">The title of the deleted book.</param>
|
||||
/// <param name="path">The file system path of the deleted book.</param>
|
||||
/// <param name="coverPath">The stored cover path of the deleted book.</param>
|
||||
/// <returns>The Id of the seeded library and the seeded book.</returns>
|
||||
private async Task<(Guid libraryId, BookEntity book)> SeedLibraryAndDeletedBookAsync(Guid userId, string title, string path, string coverPath)
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
BookEntity book = _bookEntityFixture.Create(libraryId: libraryId, path: path, title: title, isDeleted: true, includeMetadata: false);
|
||||
book.Artwork = [_bookArtworkEntityFixture.Create(bookId: book.Id, artworkType: ArtworkType.Cover, ordinal: 0, fileName: coverPath)];
|
||||
dbContext.Libraries.Add(_libraryEntityFixture.Create(id: libraryId, userId: userId, title: "Victim Library", libraryType: LibraryType.EBook, contentLocations: []));
|
||||
dbContext.Books.Add(book);
|
||||
await dbContext.SaveChangesAsync();
|
||||
return (libraryId, book);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Removes the users created by the tests.
|
||||
/// </summary>
|
||||
public void Dispose()
|
||||
{
|
||||
_client.Dispose();
|
||||
foreach (string username in _seededUsernames)
|
||||
_apiFactory.RemoveTestUser(username);
|
||||
}
|
||||
}
|
||||
+165
@@ -0,0 +1,165 @@
|
||||
#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.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.SecurityTests.Common.Setup;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Net;
|
||||
using System.Text.Json;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Api.SecurityTests.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.Books.RestoreBook;
|
||||
|
||||
/// <summary>
|
||||
/// Contains security tests for the <see cref="RestoreBookEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class RestoreBookEndpointTests : IClassFixture<LuminaApiFactory>, IDisposable
|
||||
{
|
||||
private readonly LuminaApiFactory _apiFactory;
|
||||
private readonly HttpClient _client;
|
||||
private readonly JsonSerializerOptions _jsonOptions = new() { PropertyNameCaseInsensitive = true };
|
||||
private readonly List<string> _seededUsernames = [];
|
||||
private readonly LibraryEntityFixture _libraryEntityFixture = new();
|
||||
private readonly BookEntityFixture _bookEntityFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="RestoreBookEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected in-memory API factory.</param>
|
||||
public RestoreBookEndpointTests(LuminaApiFactory apiFactory)
|
||||
{
|
||||
_apiFactory = apiFactory;
|
||||
_client = apiFactory.CreateClient();
|
||||
_client.DefaultRequestHeaders.Add("X-Forwarded-For", LuminaApiFactory.GetUniqueTestIp());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task RestoreBook_WhenUnauthorized_ShouldReturnUnauthorizedResult()
|
||||
{
|
||||
// Arrange
|
||||
string url = $"/api/v1/libraries/{Guid.NewGuid()}/books/{Guid.NewGuid()}/restore";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.PostAsync(url, null);
|
||||
|
||||
// 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("Unauthorized", problemDetails["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 RestoreBook_WithSQLInjectionInRouteIds_ShouldNotCorruptOrLeakData(string maliciousId)
|
||||
{
|
||||
// Arrange
|
||||
HttpClient client = _apiFactory.CreateClient();
|
||||
(_, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(client);
|
||||
_seededUsernames.Add(username);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await client.PostAsync($"/api/v1/libraries/{Uri.EscapeDataString(maliciousId)}/books/{Uri.EscapeDataString(maliciousId)}/restore", null);
|
||||
|
||||
// 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 RestoreBook_WhenBookBelongsToAnotherUser_ShouldReturnForbiddenAndKeepItDeleted()
|
||||
{
|
||||
// Arrange
|
||||
HttpClient client = _apiFactory.CreateClient();
|
||||
(_, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(client);
|
||||
_seededUsernames.Add(username);
|
||||
HttpClient victimClient = _apiFactory.CreateClient();
|
||||
(Guid victimUserId, string victimUsername) = await _apiFactory.CreateAndAuthenticateUserAsync(victimClient);
|
||||
_seededUsernames.Add(victimUsername);
|
||||
(Guid libraryId, Guid bookId) = await SeedLibraryAndDeletedBookAsync(victimUserId);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await client.PostAsync($"/api/v1/libraries/{libraryId}/books/{bookId}/restore", null);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.Forbidden, response.StatusCode);
|
||||
Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase);
|
||||
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.True(book!.IsDeleted);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task RestoreBook_WhenBookIsRestoredThroughAnotherLibrary_ShouldReturnNotFoundAndKeepItDeleted()
|
||||
{
|
||||
// Arrange
|
||||
HttpClient client = _apiFactory.CreateClient();
|
||||
(Guid actingUserId, string actingUsername) = await _apiFactory.CreateAndAuthenticateUserAsync(client);
|
||||
_seededUsernames.Add(actingUsername);
|
||||
(Guid ownLibraryId, _) = await SeedLibraryAndDeletedBookAsync(actingUserId, isDeleted: false);
|
||||
HttpClient victimClient = _apiFactory.CreateClient();
|
||||
(Guid victimUserId, string victimUsername) = await _apiFactory.CreateAndAuthenticateUserAsync(victimClient);
|
||||
_seededUsernames.Add(victimUsername);
|
||||
(_, Guid victimBookId) = await SeedLibraryAndDeletedBookAsync(victimUserId);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await client.PostAsync($"/api/v1/libraries/{ownLibraryId}/books/{victimBookId}/restore", null);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);
|
||||
Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
BookEntity? victimBook = await dbContext.Books.FirstOrDefaultAsync(book => book.Id == victimBookId);
|
||||
Assert.NotNull(victimBook);
|
||||
Assert.True(victimBook!.IsDeleted);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds an ebook library owned by <paramref name="userId"/>, together with a book in the requested deletion state.
|
||||
/// </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)> SeedLibraryAndDeletedBookAsync(Guid userId, bool isDeleted = true)
|
||||
{
|
||||
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: "Victim Library", libraryType: LibraryType.EBook, contentLocations: []));
|
||||
dbContext.Books.Add(book);
|
||||
await dbContext.SaveChangesAsync();
|
||||
return (libraryId, book.Id);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Removes the users created by the tests.
|
||||
/// </summary>
|
||||
public void Dispose()
|
||||
{
|
||||
_client.Dispose();
|
||||
foreach (string username in _seededUsernames)
|
||||
_apiFactory.RemoveTestUser(username);
|
||||
}
|
||||
}
|
||||
+133
@@ -0,0 +1,133 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Presentation.Web.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.Books.DeleteBook;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.TestHelpers;
|
||||
using Lumina.Presentation.Web.SecurityTests.Common.Setup;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Net;
|
||||
using System.Net.Http.Headers;
|
||||
using System.Text;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.SecurityTests.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.Books.DeleteBook;
|
||||
|
||||
/// <summary>
|
||||
/// Contains security 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;
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("'; DROP TABLE Books; --")] // destructive injection
|
||||
[InlineData("' OR '1'='1")] // boolean-based injection
|
||||
public async Task DeleteBook_WithSQLInjectionInRouteId_ShouldNormalizeTheIdAndNeverDeleteAnotherBook(string maliciousId)
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
string normalizedId = Guid.Empty.ToString();
|
||||
_apiFactory.ApiClientStub.RegisterDeleteSuccess($"libraries/{libraryId}/books/{normalizedId}");
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
HttpRequestMessage deleteRequest = CreateDeleteRequest(maliciousId, libraryId.ToString());
|
||||
deleteRequest.Headers.Add("RequestVerificationToken", webClient.AntiforgeryToken);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.SendAsync(deleteRequest);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("at Lumina", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.Contains($"libraries/{libraryId}/books/{normalizedId}", _apiFactory.ApiClientStub.DeleteEndpointsCalled);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("'; DROP TABLE Books; --")] // destructive injection
|
||||
[InlineData("' OR '1'='1")] // boolean-based injection
|
||||
public async Task DeleteBook_WithSQLInjectionInLibraryQueryId_ShouldNormalizeTheLibraryId(string maliciousLibraryId)
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
Guid bookId = Guid.NewGuid();
|
||||
string normalizedId = Guid.Empty.ToString();
|
||||
_apiFactory.ApiClientStub.RegisterDeleteSuccess($"libraries/{normalizedId}/books/{bookId}");
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
HttpRequestMessage deleteRequest = CreateDeleteRequest(bookId.ToString(), maliciousLibraryId);
|
||||
deleteRequest.Headers.Add("RequestVerificationToken", webClient.AntiforgeryToken);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.SendAsync(deleteRequest);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.Contains($"libraries/{normalizedId}/books/{bookId}", _apiFactory.ApiClientStub.DeleteEndpointsCalled);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task DeleteBook_WhenCalledWithoutAntiforgeryToken_ShouldRejectRequestAndNotCallApi()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
Guid bookId = Guid.NewGuid();
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
HttpRequestMessage deleteRequest = CreateDeleteRequest(bookId.ToString(), libraryId.ToString());
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.SendAsync(deleteRequest);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode);
|
||||
Assert.Empty(_apiFactory.ApiClientStub.DeleteEndpointsCalled);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task DeleteBook_WhenCalledWithoutAuthentication_ShouldRedirectToLogin()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
HttpClient anonymousClient = WebTestHelpers.CreateAnonymousClient(_apiFactory);
|
||||
HttpRequestMessage deleteRequest = CreateDeleteRequest(Guid.NewGuid().ToString(), Guid.NewGuid().ToString());
|
||||
|
||||
// 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 raw route value of the book Id.</param>
|
||||
/// <param name="libraryId">The raw query value of the library Id.</param>
|
||||
/// <returns>The configured delete request.</returns>
|
||||
private static HttpRequestMessage CreateDeleteRequest(string bookId, string libraryId)
|
||||
{
|
||||
HttpRequestMessage deleteRequest = new(HttpMethod.Delete, $"/en-us/library/written-content-library/books-library/books/{Uri.EscapeDataString(bookId)}/api-delete-book?libraryId={Uri.EscapeDataString(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;
|
||||
}
|
||||
}
|
||||
+42
@@ -0,0 +1,42 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Presentation.Web.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.Books.DeletedBooks;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.TestHelpers;
|
||||
using Lumina.Presentation.Web.SecurityTests.Common.Setup;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Net;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.SecurityTests.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.Books.DeletedBooks;
|
||||
|
||||
/// <summary>
|
||||
/// Contains security tests for the <see cref="DeletedBooksViewEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class DeletedBooksViewEndpointTests : IClassFixture<LuminaWebFactory>
|
||||
{
|
||||
private readonly LuminaWebFactory _apiFactory;
|
||||
|
||||
/// <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_WhenNotAuthenticated_ShouldRedirectToLogin()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
HttpClient anonymousClient = WebTestHelpers.CreateAnonymousClient(_apiFactory);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await anonymousClient.GetAsync($"/en-us/library/written-content-library/books-library/books/deleted-items?libraryId={Guid.NewGuid()}");
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.Redirect, response.StatusCode);
|
||||
Assert.Empty(_apiFactory.ApiClientStub.GetEndpointsCalled);
|
||||
}
|
||||
}
|
||||
+133
@@ -0,0 +1,133 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Presentation.Web.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.Books.RestoreBook;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.TestHelpers;
|
||||
using Lumina.Presentation.Web.SecurityTests.Common.Setup;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Net;
|
||||
using System.Net.Http.Headers;
|
||||
using System.Text;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.SecurityTests.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.Books.RestoreBook;
|
||||
|
||||
/// <summary>
|
||||
/// Contains security 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;
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("'; DROP TABLE Books; --")] // destructive injection
|
||||
[InlineData("' OR '1'='1")] // boolean-based injection
|
||||
public async Task RestoreBook_WithSQLInjectionInRouteId_ShouldNormalizeTheIdAndNeverRestoreAnotherBook(string maliciousId)
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
string normalizedId = Guid.Empty.ToString();
|
||||
_apiFactory.ApiClientStub.RegisterPostResponse<object>($"libraries/{libraryId}/books/{normalizedId}/restore", new Lumina.Presentation.Web.Common.Requests.Common.EmptyRequest());
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
HttpRequestMessage restoreRequest = CreateRestoreRequest(maliciousId, libraryId.ToString());
|
||||
restoreRequest.Headers.Add("RequestVerificationToken", webClient.AntiforgeryToken);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.SendAsync(restoreRequest);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("at Lumina", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.Contains($"libraries/{libraryId}/books/{normalizedId}/restore", _apiFactory.ApiClientStub.PostRequests.Select(request => request.Endpoint));
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("'; DROP TABLE Books; --")] // destructive injection
|
||||
[InlineData("' OR '1'='1")] // boolean-based injection
|
||||
public async Task RestoreBook_WithSQLInjectionInLibraryQueryId_ShouldNormalizeTheLibraryId(string maliciousLibraryId)
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
Guid bookId = Guid.NewGuid();
|
||||
string normalizedId = Guid.Empty.ToString();
|
||||
_apiFactory.ApiClientStub.RegisterPostResponse<object>($"libraries/{normalizedId}/books/{bookId}/restore", new Lumina.Presentation.Web.Common.Requests.Common.EmptyRequest());
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
HttpRequestMessage restoreRequest = CreateRestoreRequest(bookId.ToString(), maliciousLibraryId);
|
||||
restoreRequest.Headers.Add("RequestVerificationToken", webClient.AntiforgeryToken);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.SendAsync(restoreRequest);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("at Lumina", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.Contains($"libraries/{normalizedId}/books/{bookId}/restore", _apiFactory.ApiClientStub.PostRequests.Select(request => request.Endpoint));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task RestoreBook_WhenCalledWithoutAntiforgeryToken_ShouldRejectRequestAndNotCallApi()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
HttpRequestMessage restoreRequest = CreateRestoreRequest(Guid.NewGuid().ToString(), Guid.NewGuid().ToString());
|
||||
|
||||
// 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_WhenCalledWithoutAuthentication_ShouldRedirectToLogin()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
HttpClient anonymousClient = WebTestHelpers.CreateAnonymousClient(_apiFactory);
|
||||
HttpRequestMessage restoreRequest = CreateRestoreRequest(Guid.NewGuid().ToString(), Guid.NewGuid().ToString());
|
||||
|
||||
// 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 raw route value of the book Id.</param>
|
||||
/// <param name="libraryId">The raw query value of the library Id.</param>
|
||||
/// <returns>The configured restore request.</returns>
|
||||
private static HttpRequestMessage CreateRestoreRequest(string bookId, string libraryId)
|
||||
{
|
||||
HttpRequestMessage restoreRequest = new(HttpMethod.Post, $"/en-us/library/written-content-library/books-library/books/{Uri.EscapeDataString(bookId)}/api-restore-book?libraryId={Uri.EscapeDataString(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;
|
||||
}
|
||||
}
|
||||
+16
-160
@@ -1,23 +1,17 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management;
|
||||
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary;
|
||||
using Lumina.Application.Common.DataAccess.Repositories.BookLibrary;
|
||||
using Lumina.Application.Common.DataAccess.Repositories.MediaLibrary;
|
||||
using Lumina.Application.Common.DataAccess.UoW;
|
||||
using Lumina.Application.Common.Infrastructure.Authentication;
|
||||
using Lumina.Application.Common.Infrastructure.Authorization;
|
||||
using Lumina.Application.Common.Infrastructure.Authorization.Policies.LibraryOwnership;
|
||||
using Lumina.Application.Common.Infrastructure.Validation;
|
||||
using Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Artwork;
|
||||
using Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Commands.DeleteBook;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary;
|
||||
using Lumina.Application.Fixtures.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Commands.DeleteBook;
|
||||
using Lumina.Domain.Common.Primitives;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using NSubstitute;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
@@ -35,9 +29,6 @@ public class DeleteBookCommandHandlerTests
|
||||
{
|
||||
private readonly IUnitOfWork _mockUnitOfWork;
|
||||
private readonly IBookRepository _mockBookRepository;
|
||||
private readonly ILibraryRepository _mockLibraryRepository;
|
||||
private readonly IBookArtworkService _mockBookArtworkService;
|
||||
private readonly ILogger<DeleteBookCommandHandler> _mockLogger;
|
||||
private readonly IAuthorizationService _mockAuthorizationService;
|
||||
private readonly ICurrentUserService _mockCurrentUserService;
|
||||
private readonly IValidator<DeleteBookCommand> _mockValidator;
|
||||
@@ -45,7 +36,6 @@ public class DeleteBookCommandHandlerTests
|
||||
private readonly Guid _userId;
|
||||
private readonly DeleteBookCommandFixture _deleteBookCommandFixture = new();
|
||||
private readonly BookEntityFixture _bookEntityFixture = new();
|
||||
private readonly LibraryEntityFixture _libraryEntityFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="DeleteBookCommandHandlerTests"/> class.
|
||||
@@ -54,37 +44,30 @@ public class DeleteBookCommandHandlerTests
|
||||
{
|
||||
_mockUnitOfWork = Substitute.For<IUnitOfWork>();
|
||||
_mockBookRepository = Substitute.For<IBookRepository>();
|
||||
_mockLibraryRepository = Substitute.For<ILibraryRepository>();
|
||||
_mockUnitOfWork.BookRepository.Returns(_mockBookRepository);
|
||||
_mockUnitOfWork.LibraryRepository.Returns(_mockLibraryRepository);
|
||||
_mockBookArtworkService = Substitute.For<IBookArtworkService>();
|
||||
_mockLogger = Substitute.For<ILogger<DeleteBookCommandHandler>>();
|
||||
_mockAuthorizationService = Substitute.For<IAuthorizationService>();
|
||||
_mockCurrentUserService = Substitute.For<ICurrentUserService>();
|
||||
_mockValidator = Substitute.For<IValidator<DeleteBookCommand>>();
|
||||
_userId = Guid.NewGuid();
|
||||
|
||||
// Default stubs: the command is valid, the current user is authenticated, the ownership policy allows the deletion, the book has no author, the library exists, the artwork deletion succeeds, the book deletion succeeds and saving changes succeeds.
|
||||
// Default stubs: the command is valid, the current user is authenticated, the ownership policy allows the deletion, the book exists,
|
||||
// marking it as deleted succeeds, and saving changes succeeds.
|
||||
_mockValidator.Validate(Arg.Any<DeleteBookCommand>()).Returns([]);
|
||||
_mockCurrentUserService.UserId.Returns(_userId);
|
||||
_mockAuthorizationService.EvaluatePolicyAsync<ILibraryOwnershipPolicy>(_userId, Arg.Any<LibraryOwnershipPolicyContext>(), Arg.Any<CancellationToken>())
|
||||
.Returns(true);
|
||||
_mockLibraryRepository.GetByIdAsync(Arg.Any<Guid>(), Arg.Any<bool>(), Arg.Any<bool>(), Arg.Any<CancellationToken>())
|
||||
.Returns(_ => Result.From<LibraryEntity?>(_libraryEntityFixture.Create()));
|
||||
_mockBookRepository.GetAuthorsDisplayNamesByBookIdsAsync(Arg.Any<IReadOnlyCollection<Guid>>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<IReadOnlyDictionary<Guid, string?>>(new Dictionary<Guid, string?>()));
|
||||
_mockBookArtworkService.DeleteBookArtwork(Arg.Any<Guid>(), Arg.Any<Guid>(), Arg.Any<string>(), Arg.Any<string>(), Arg.Any<string>())
|
||||
.Returns(Result.Deleted);
|
||||
_mockBookRepository.DeleteByIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.Deleted);
|
||||
_mockBookRepository.GetByIdAsync(Arg.Any<Guid>(), Arg.Any<bool>(), Arg.Any<bool>(), Arg.Any<CancellationToken>())
|
||||
.Returns(_ => Result.From<BookEntity?>(_bookEntityFixture.Create(includeMetadata: false)));
|
||||
_mockBookRepository.SoftDeleteByIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.Updated);
|
||||
_mockUnitOfWork.SaveChangesAsync(Arg.Any<CancellationToken>())
|
||||
.Returns(Result.Success);
|
||||
|
||||
_sut = new DeleteBookCommandHandler(_mockUnitOfWork, _mockBookArtworkService, _mockLogger, _mockAuthorizationService, _mockCurrentUserService, _mockValidator);
|
||||
_sut = new DeleteBookCommandHandler(_mockUnitOfWork, _mockAuthorizationService, _mockCurrentUserService, _mockValidator);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task HandleAsync_WhenBookExists_ShouldDeleteBookAndReturnDeleted()
|
||||
public async Task HandleAsync_WhenBookExists_ShouldSoftDeleteBookAndReturnDeleted()
|
||||
{
|
||||
// Arrange
|
||||
DeleteBookCommand command = _deleteBookCommandFixture.Create();
|
||||
@@ -100,42 +83,12 @@ public class DeleteBookCommandHandlerTests
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Equal(Result.Deleted, result.Value);
|
||||
// The stored artwork of the book is removed before the book row, so that no artwork file is orphaned.
|
||||
Received.InOrder(() =>
|
||||
{
|
||||
_mockBookArtworkService.DeleteBookArtwork(libraryId, bookId, Arg.Any<string>(), Arg.Any<string>(), book.Title);
|
||||
_mockBookRepository.DeleteByIdAsync(bookId, Arg.Any<CancellationToken>());
|
||||
});
|
||||
await _mockBookRepository.Received(1).DeleteByIdAsync(bookId, Arg.Any<CancellationToken>());
|
||||
await _mockBookRepository.Received(1).SoftDeleteByIdAsync(bookId, Arg.Any<CancellationToken>());
|
||||
await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any<CancellationToken>());
|
||||
await _mockAuthorizationService.Received(1).EvaluatePolicyAsync<ILibraryOwnershipPolicy>(
|
||||
_userId, Arg.Is<LibraryOwnershipPolicyContext>(context => context.LibraryId == libraryId), Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task HandleAsync_WhenBookHasAnAuthor_ShouldDeleteTheArtworkUnderTheAuthorSegments()
|
||||
{
|
||||
// Arrange
|
||||
DeleteBookCommand command = _deleteBookCommandFixture.Create();
|
||||
Guid libraryId = Guid.Parse(command.LibraryId!);
|
||||
Guid bookId = Guid.Parse(command.BookId!);
|
||||
BookEntity book = _bookEntityFixture.Create(id: bookId, libraryId: libraryId, includeMetadata: false);
|
||||
LibraryEntity library = _libraryEntityFixture.Create(id: libraryId);
|
||||
_mockBookRepository.GetByIdAsync(bookId, shouldIncludeNavigationProperties: false, shouldTrackEntities: false, cancellationToken: Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<BookEntity?>(book));
|
||||
_mockLibraryRepository.GetByIdAsync(libraryId, shouldTrackEntities: false, cancellationToken: Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<LibraryEntity?>(library));
|
||||
_mockBookRepository.GetAuthorsDisplayNamesByBookIdsAsync(Arg.Any<IReadOnlyCollection<Guid>>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<IReadOnlyDictionary<Guid, string?>>(new Dictionary<Guid, string?> { [bookId] = "J.R.R. Tolkien" }));
|
||||
|
||||
// Act
|
||||
Result<Deleted> result = await _sut.HandleAsync(command, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
_mockBookArtworkService.Received(1).DeleteBookArtwork(libraryId, bookId, library.Title, "J.R.R. Tolkien", book.Title);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task HandleAsync_WhenValidationFails_ShouldReturnValidationErrorsWithoutTouchingAnyRepository()
|
||||
{
|
||||
@@ -151,8 +104,7 @@ public class DeleteBookCommandHandlerTests
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(DomainErrors.WrittenContent.BookIdCannotBeEmpty, result.FirstError);
|
||||
await _mockBookRepository.DidNotReceive().GetByIdAsync(Arg.Any<Guid>(), Arg.Any<bool>(), Arg.Any<bool>(), Arg.Any<CancellationToken>());
|
||||
_mockBookArtworkService.DidNotReceive().DeleteBookArtwork(Arg.Any<Guid>(), Arg.Any<Guid>(), Arg.Any<string>(), Arg.Any<string>(), Arg.Any<string>());
|
||||
await _mockBookRepository.DidNotReceive().DeleteByIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
|
||||
await _mockBookRepository.DidNotReceive().SoftDeleteByIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
|
||||
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
@@ -187,7 +139,7 @@ public class DeleteBookCommandHandlerTests
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(ApplicationErrors.Persistence.UniqueConstraintViolation, result.FirstError);
|
||||
await _mockBookRepository.DidNotReceive().DeleteByIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
|
||||
await _mockBookRepository.DidNotReceive().SoftDeleteByIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
|
||||
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
@@ -251,14 +203,12 @@ public class DeleteBookCommandHandlerTests
|
||||
Assert.Equal(ApplicationErrors.Authorization.NotAuthorized, result.FirstError);
|
||||
await _mockAuthorizationService.Received(1).EvaluatePolicyAsync<ILibraryOwnershipPolicy>(
|
||||
_userId, Arg.Is<LibraryOwnershipPolicyContext>(context => context.LibraryId == libraryId), Arg.Any<CancellationToken>());
|
||||
await _mockLibraryRepository.DidNotReceive().GetByIdAsync(Arg.Any<Guid>(), Arg.Any<bool>(), Arg.Any<bool>(), Arg.Any<CancellationToken>());
|
||||
_mockBookArtworkService.DidNotReceive().DeleteBookArtwork(Arg.Any<Guid>(), Arg.Any<Guid>(), Arg.Any<string>(), Arg.Any<string>(), Arg.Any<string>());
|
||||
await _mockBookRepository.DidNotReceive().DeleteByIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
|
||||
await _mockBookRepository.DidNotReceive().SoftDeleteByIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
|
||||
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task HandleAsync_WhenLibraryRepositoryFails_ShouldReturnFailureResultWithoutDeleting()
|
||||
public async Task HandleAsync_WhenSoftDeleteFails_ShouldReturnErrorWithoutSaving()
|
||||
{
|
||||
// Arrange
|
||||
DeleteBookCommand command = _deleteBookCommandFixture.Create();
|
||||
@@ -267,7 +217,7 @@ public class DeleteBookCommandHandlerTests
|
||||
BookEntity book = _bookEntityFixture.Create(id: bookId, libraryId: libraryId, includeMetadata: false);
|
||||
_mockBookRepository.GetByIdAsync(bookId, shouldIncludeNavigationProperties: false, shouldTrackEntities: false, cancellationToken: Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<BookEntity?>(book));
|
||||
_mockLibraryRepository.GetByIdAsync(Arg.Any<Guid>(), Arg.Any<bool>(), Arg.Any<bool>(), Arg.Any<CancellationToken>())
|
||||
_mockBookRepository.SoftDeleteByIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>())
|
||||
.Returns(ApplicationErrors.Persistence.UniqueConstraintViolation);
|
||||
|
||||
// Act
|
||||
@@ -276,101 +226,7 @@ public class DeleteBookCommandHandlerTests
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(ApplicationErrors.Persistence.UniqueConstraintViolation, result.FirstError);
|
||||
_mockBookArtworkService.DidNotReceive().DeleteBookArtwork(Arg.Any<Guid>(), Arg.Any<Guid>(), Arg.Any<string>(), Arg.Any<string>(), Arg.Any<string>());
|
||||
await _mockBookRepository.DidNotReceive().DeleteByIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task HandleAsync_WhenLibraryDoesNotExist_ShouldReturnLibraryNotFoundError()
|
||||
{
|
||||
// Arrange
|
||||
DeleteBookCommand command = _deleteBookCommandFixture.Create();
|
||||
Guid libraryId = Guid.Parse(command.LibraryId!);
|
||||
Guid bookId = Guid.Parse(command.BookId!);
|
||||
BookEntity book = _bookEntityFixture.Create(id: bookId, libraryId: libraryId, includeMetadata: false);
|
||||
_mockBookRepository.GetByIdAsync(bookId, shouldIncludeNavigationProperties: false, shouldTrackEntities: false, cancellationToken: Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<BookEntity?>(book));
|
||||
_mockLibraryRepository.GetByIdAsync(Arg.Any<Guid>(), Arg.Any<bool>(), Arg.Any<bool>(), Arg.Any<CancellationToken>())
|
||||
.Returns(_ => Result.From<LibraryEntity?>(null));
|
||||
|
||||
// Act
|
||||
Result<Deleted> result = await _sut.HandleAsync(command, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(DomainErrors.Library.LibraryNotFound, result.FirstError);
|
||||
_mockBookArtworkService.DidNotReceive().DeleteBookArtwork(Arg.Any<Guid>(), Arg.Any<Guid>(), Arg.Any<string>(), Arg.Any<string>(), Arg.Any<string>());
|
||||
await _mockBookRepository.DidNotReceive().DeleteByIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
|
||||
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task HandleAsync_WhenAuthorLookupFails_ShouldReturnErrorWithoutDeleting()
|
||||
{
|
||||
// Arrange
|
||||
DeleteBookCommand command = _deleteBookCommandFixture.Create();
|
||||
Guid libraryId = Guid.Parse(command.LibraryId!);
|
||||
Guid bookId = Guid.Parse(command.BookId!);
|
||||
BookEntity book = _bookEntityFixture.Create(id: bookId, libraryId: libraryId, includeMetadata: false);
|
||||
_mockBookRepository.GetByIdAsync(bookId, shouldIncludeNavigationProperties: false, shouldTrackEntities: false, cancellationToken: Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<BookEntity?>(book));
|
||||
_mockBookRepository.GetAuthorsDisplayNamesByBookIdsAsync(Arg.Any<IReadOnlyCollection<Guid>>(), Arg.Any<CancellationToken>())
|
||||
.Returns(ApplicationErrors.Persistence.UniqueConstraintViolation);
|
||||
|
||||
// Act
|
||||
Result<Deleted> result = await _sut.HandleAsync(command, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(ApplicationErrors.Persistence.UniqueConstraintViolation, result.FirstError);
|
||||
_mockBookArtworkService.DidNotReceive().DeleteBookArtwork(Arg.Any<Guid>(), Arg.Any<Guid>(), Arg.Any<string>(), Arg.Any<string>(), Arg.Any<string>());
|
||||
await _mockBookRepository.DidNotReceive().DeleteByIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task HandleAsync_WhenArtworkDeletionFails_ShouldStillDeleteTheBook()
|
||||
{
|
||||
// Arrange
|
||||
DeleteBookCommand command = _deleteBookCommandFixture.Create();
|
||||
Guid libraryId = Guid.Parse(command.LibraryId!);
|
||||
Guid bookId = Guid.Parse(command.BookId!);
|
||||
BookEntity book = _bookEntityFixture.Create(id: bookId, libraryId: libraryId, includeMetadata: false);
|
||||
_mockBookRepository.GetByIdAsync(bookId, shouldIncludeNavigationProperties: false, shouldTrackEntities: false, cancellationToken: Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<BookEntity?>(book));
|
||||
_mockBookArtworkService.DeleteBookArtwork(Arg.Any<Guid>(), Arg.Any<Guid>(), Arg.Any<string>(), Arg.Any<string>(), Arg.Any<string>())
|
||||
.Returns(Error.Failure(description: "Failed to delete the artwork"));
|
||||
|
||||
// Act
|
||||
Result<Deleted> result = await _sut.HandleAsync(command, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
// A stale cover file must not prevent the book from being removed.
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Equal(Result.Deleted, result.Value);
|
||||
await _mockBookRepository.Received(1).DeleteByIdAsync(bookId, Arg.Any<CancellationToken>());
|
||||
await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task HandleAsync_WhenDeleteBookFails_ShouldReturnErrorWithoutSaving()
|
||||
{
|
||||
// Arrange
|
||||
DeleteBookCommand command = _deleteBookCommandFixture.Create();
|
||||
Guid libraryId = Guid.Parse(command.LibraryId!);
|
||||
Guid bookId = Guid.Parse(command.BookId!);
|
||||
BookEntity book = _bookEntityFixture.Create(id: bookId, libraryId: libraryId, includeMetadata: false);
|
||||
_mockBookRepository.GetByIdAsync(bookId, shouldIncludeNavigationProperties: false, shouldTrackEntities: false, cancellationToken: Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<BookEntity?>(book));
|
||||
_mockBookRepository.DeleteByIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>())
|
||||
.Returns(ApplicationErrors.Persistence.UniqueConstraintViolation);
|
||||
|
||||
// Act
|
||||
Result<Deleted> result = await _sut.HandleAsync(command, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(ApplicationErrors.Persistence.UniqueConstraintViolation, result.FirstError);
|
||||
await _mockBookRepository.Received(1).DeleteByIdAsync(bookId, Arg.Any<CancellationToken>());
|
||||
await _mockBookRepository.Received(1).SoftDeleteByIdAsync(bookId, Arg.Any<CancellationToken>());
|
||||
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
@@ -393,6 +249,6 @@ public class DeleteBookCommandHandlerTests
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(ApplicationErrors.Persistence.UniqueConstraintViolation, result.FirstError);
|
||||
await _mockBookRepository.Received(1).DeleteByIdAsync(bookId, Arg.Any<CancellationToken>());
|
||||
await _mockBookRepository.Received(1).SoftDeleteByIdAsync(bookId, Arg.Any<CancellationToken>());
|
||||
}
|
||||
}
|
||||
+253
@@ -0,0 +1,253 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary;
|
||||
using Lumina.Application.Common.DataAccess.Repositories.BookLibrary;
|
||||
using Lumina.Application.Common.DataAccess.UoW;
|
||||
using Lumina.Application.Common.Infrastructure.Authentication;
|
||||
using Lumina.Application.Common.Infrastructure.Authorization;
|
||||
using Lumina.Application.Common.Infrastructure.Authorization.Policies.LibraryOwnership;
|
||||
using Lumina.Application.Common.Infrastructure.Validation;
|
||||
using Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Commands.RestoreBook;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary;
|
||||
using Lumina.Application.Fixtures.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Commands.RestoreBook;
|
||||
using Lumina.Domain.Common.Primitives;
|
||||
using NSubstitute;
|
||||
using System;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using ApplicationErrors = Lumina.Application.Common.Errors.Errors;
|
||||
using DomainErrors = Lumina.Domain.Common.Errors.Errors;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.UnitTests.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Commands.RestoreBook;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="RestoreBookCommandHandler"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class RestoreBookCommandHandlerTests
|
||||
{
|
||||
private readonly IUnitOfWork _mockUnitOfWork;
|
||||
private readonly IBookRepository _mockBookRepository;
|
||||
private readonly IAuthorizationService _mockAuthorizationService;
|
||||
private readonly ICurrentUserService _mockCurrentUserService;
|
||||
private readonly IValidator<RestoreBookCommand> _mockValidator;
|
||||
private readonly RestoreBookCommandHandler _sut;
|
||||
private readonly Guid _userId;
|
||||
private readonly RestoreBookCommandFixture _restoreBookCommandFixture = new();
|
||||
private readonly BookEntityFixture _bookEntityFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="RestoreBookCommandHandlerTests"/> class.
|
||||
/// </summary>
|
||||
public RestoreBookCommandHandlerTests()
|
||||
{
|
||||
_mockUnitOfWork = Substitute.For<IUnitOfWork>();
|
||||
_mockBookRepository = Substitute.For<IBookRepository>();
|
||||
_mockUnitOfWork.BookRepository.Returns(_mockBookRepository);
|
||||
_mockAuthorizationService = Substitute.For<IAuthorizationService>();
|
||||
_mockCurrentUserService = Substitute.For<ICurrentUserService>();
|
||||
_mockValidator = Substitute.For<IValidator<RestoreBookCommand>>();
|
||||
_userId = Guid.NewGuid();
|
||||
|
||||
// Default stubs: the command is valid, the current user is authenticated, the ownership policy allows the restoration, the deleted
|
||||
// book exists, restoring it succeeds, and saving changes succeeds.
|
||||
_mockValidator.Validate(Arg.Any<RestoreBookCommand>()).Returns([]);
|
||||
_mockCurrentUserService.UserId.Returns(_userId);
|
||||
_mockAuthorizationService.EvaluatePolicyAsync<ILibraryOwnershipPolicy>(_userId, Arg.Any<LibraryOwnershipPolicyContext>(), Arg.Any<CancellationToken>())
|
||||
.Returns(true);
|
||||
_mockBookRepository.GetSoftDeletedByIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>())
|
||||
.Returns(_ => Result.From<BookEntity?>(_bookEntityFixture.Create(isDeleted: true, includeMetadata: false)));
|
||||
_mockBookRepository.RestoreSoftDeletedByIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.Updated);
|
||||
_mockUnitOfWork.SaveChangesAsync(Arg.Any<CancellationToken>())
|
||||
.Returns(Result.Success);
|
||||
|
||||
_sut = new RestoreBookCommandHandler(_mockUnitOfWork, _mockAuthorizationService, _mockCurrentUserService, _mockValidator);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task HandleAsync_WhenDeletedBookExists_ShouldRestoreBookAndReturnUpdated()
|
||||
{
|
||||
// Arrange
|
||||
RestoreBookCommand command = _restoreBookCommandFixture.Create();
|
||||
Guid libraryId = Guid.Parse(command.LibraryId!);
|
||||
Guid bookId = Guid.Parse(command.BookId!);
|
||||
BookEntity book = _bookEntityFixture.Create(id: bookId, libraryId: libraryId, isDeleted: true, includeMetadata: false);
|
||||
_mockBookRepository.GetSoftDeletedByIdAsync(bookId, Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<BookEntity?>(book));
|
||||
|
||||
// Act
|
||||
Result<Updated> result = await _sut.HandleAsync(command, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Equal(Result.Updated, result.Value);
|
||||
await _mockBookRepository.Received(1).RestoreSoftDeletedByIdAsync(bookId, Arg.Any<CancellationToken>());
|
||||
await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any<CancellationToken>());
|
||||
await _mockAuthorizationService.Received(1).EvaluatePolicyAsync<ILibraryOwnershipPolicy>(
|
||||
_userId, Arg.Is<LibraryOwnershipPolicyContext>(context => context.LibraryId == libraryId), Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task HandleAsync_WhenValidationFails_ShouldReturnValidationErrorsWithoutTouchingAnyRepository()
|
||||
{
|
||||
// Arrange
|
||||
RestoreBookCommand command = _restoreBookCommandFixture.Create();
|
||||
_mockValidator.Validate(Arg.Any<RestoreBookCommand>())
|
||||
.Returns([DomainErrors.WrittenContent.BookIdCannotBeEmpty]);
|
||||
|
||||
// Act
|
||||
Result<Updated> result = await _sut.HandleAsync(command, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(DomainErrors.WrittenContent.BookIdCannotBeEmpty, result.FirstError);
|
||||
await _mockBookRepository.DidNotReceive().GetSoftDeletedByIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
|
||||
await _mockBookRepository.DidNotReceive().RestoreSoftDeletedByIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
|
||||
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task HandleAsync_WhenUserIsNotAuthenticated_ShouldReturnNotAuthorizedError()
|
||||
{
|
||||
// Arrange
|
||||
RestoreBookCommand command = _restoreBookCommandFixture.Create();
|
||||
_mockCurrentUserService.UserId.Returns((Guid?)null);
|
||||
|
||||
// Act
|
||||
Result<Updated> result = await _sut.HandleAsync(command, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(ApplicationErrors.Authorization.NotAuthorized, result.FirstError);
|
||||
await _mockBookRepository.DidNotReceive().GetSoftDeletedByIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
|
||||
await _mockAuthorizationService.DidNotReceive().EvaluatePolicyAsync<ILibraryOwnershipPolicy>(Arg.Any<Guid>(), Arg.Any<LibraryOwnershipPolicyContext>(), Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task HandleAsync_WhenBookRepositoryFails_ShouldReturnFailureResultWithoutRestoring()
|
||||
{
|
||||
// Arrange
|
||||
RestoreBookCommand command = _restoreBookCommandFixture.Create();
|
||||
_mockBookRepository.GetSoftDeletedByIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>())
|
||||
.Returns(ApplicationErrors.Persistence.UniqueConstraintViolation);
|
||||
|
||||
// Act
|
||||
Result<Updated> result = await _sut.HandleAsync(command, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(ApplicationErrors.Persistence.UniqueConstraintViolation, result.FirstError);
|
||||
await _mockBookRepository.DidNotReceive().RestoreSoftDeletedByIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
|
||||
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task HandleAsync_WhenDeletedBookDoesNotExist_ShouldReturnBookNotFoundError()
|
||||
{
|
||||
// Arrange
|
||||
RestoreBookCommand command = _restoreBookCommandFixture.Create();
|
||||
_mockBookRepository.GetSoftDeletedByIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>())
|
||||
.Returns(_ => Result.From<BookEntity?>(null));
|
||||
|
||||
// Act
|
||||
Result<Updated> result = await _sut.HandleAsync(command, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(DomainErrors.WrittenContent.BookNotFound, result.FirstError);
|
||||
await _mockAuthorizationService.DidNotReceive().EvaluatePolicyAsync<ILibraryOwnershipPolicy>(Arg.Any<Guid>(), Arg.Any<LibraryOwnershipPolicyContext>(), Arg.Any<CancellationToken>());
|
||||
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task HandleAsync_WhenBookBelongsToAnotherLibrary_ShouldReturnBookNotFoundWithoutEvaluatingThePolicy()
|
||||
{
|
||||
// Arrange
|
||||
RestoreBookCommand command = _restoreBookCommandFixture.Create();
|
||||
Guid bookId = Guid.Parse(command.BookId!);
|
||||
BookEntity book = _bookEntityFixture.Create(id: bookId, libraryId: Guid.NewGuid(), isDeleted: true, includeMetadata: false);
|
||||
_mockBookRepository.GetSoftDeletedByIdAsync(bookId, Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<BookEntity?>(book));
|
||||
|
||||
// Act
|
||||
Result<Updated> result = await _sut.HandleAsync(command, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(DomainErrors.WrittenContent.BookNotFound, result.FirstError);
|
||||
await _mockAuthorizationService.DidNotReceive().EvaluatePolicyAsync<ILibraryOwnershipPolicy>(Arg.Any<Guid>(), Arg.Any<LibraryOwnershipPolicyContext>(), Arg.Any<CancellationToken>());
|
||||
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task HandleAsync_WhenPolicyDeniesAccess_ShouldReturnNotAuthorizedError()
|
||||
{
|
||||
// Arrange
|
||||
RestoreBookCommand command = _restoreBookCommandFixture.Create();
|
||||
Guid libraryId = Guid.Parse(command.LibraryId!);
|
||||
Guid bookId = Guid.Parse(command.BookId!);
|
||||
BookEntity book = _bookEntityFixture.Create(id: bookId, libraryId: libraryId, isDeleted: true, includeMetadata: false);
|
||||
_mockBookRepository.GetSoftDeletedByIdAsync(bookId, Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<BookEntity?>(book));
|
||||
_mockAuthorizationService.EvaluatePolicyAsync<ILibraryOwnershipPolicy>(_userId, Arg.Any<LibraryOwnershipPolicyContext>(), Arg.Any<CancellationToken>())
|
||||
.Returns(false);
|
||||
|
||||
// Act
|
||||
Result<Updated> result = await _sut.HandleAsync(command, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(ApplicationErrors.Authorization.NotAuthorized, result.FirstError);
|
||||
await _mockAuthorizationService.Received(1).EvaluatePolicyAsync<ILibraryOwnershipPolicy>(
|
||||
_userId, Arg.Is<LibraryOwnershipPolicyContext>(context => context.LibraryId == libraryId), Arg.Any<CancellationToken>());
|
||||
await _mockBookRepository.DidNotReceive().RestoreSoftDeletedByIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
|
||||
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task HandleAsync_WhenRestoreFails_ShouldReturnErrorWithoutSaving()
|
||||
{
|
||||
// Arrange
|
||||
RestoreBookCommand command = _restoreBookCommandFixture.Create();
|
||||
Guid libraryId = Guid.Parse(command.LibraryId!);
|
||||
Guid bookId = Guid.Parse(command.BookId!);
|
||||
BookEntity book = _bookEntityFixture.Create(id: bookId, libraryId: libraryId, isDeleted: true, includeMetadata: false);
|
||||
_mockBookRepository.GetSoftDeletedByIdAsync(bookId, Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<BookEntity?>(book));
|
||||
_mockBookRepository.RestoreSoftDeletedByIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>())
|
||||
.Returns(ApplicationErrors.Persistence.UniqueConstraintViolation);
|
||||
|
||||
// Act
|
||||
Result<Updated> result = await _sut.HandleAsync(command, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(ApplicationErrors.Persistence.UniqueConstraintViolation, result.FirstError);
|
||||
await _mockBookRepository.Received(1).RestoreSoftDeletedByIdAsync(bookId, Arg.Any<CancellationToken>());
|
||||
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task HandleAsync_WhenSaveChangesFails_ShouldReturnError()
|
||||
{
|
||||
// Arrange
|
||||
RestoreBookCommand command = _restoreBookCommandFixture.Create();
|
||||
Guid libraryId = Guid.Parse(command.LibraryId!);
|
||||
Guid bookId = Guid.Parse(command.BookId!);
|
||||
BookEntity book = _bookEntityFixture.Create(id: bookId, libraryId: libraryId, isDeleted: true, includeMetadata: false);
|
||||
_mockBookRepository.GetSoftDeletedByIdAsync(bookId, Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<BookEntity?>(book));
|
||||
_mockUnitOfWork.SaveChangesAsync(Arg.Any<CancellationToken>())
|
||||
.Returns(ApplicationErrors.Persistence.UniqueConstraintViolation);
|
||||
|
||||
// Act
|
||||
Result<Updated> result = await _sut.HandleAsync(command, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(ApplicationErrors.Persistence.UniqueConstraintViolation, result.FirstError);
|
||||
await _mockBookRepository.Received(1).RestoreSoftDeletedByIdAsync(bookId, Arg.Any<CancellationToken>());
|
||||
}
|
||||
}
|
||||
+97
@@ -0,0 +1,97 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Commands.RestoreBook;
|
||||
using Lumina.Application.Fixtures.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Commands.RestoreBook;
|
||||
using Lumina.Application.UnitTests.Common.Setup;
|
||||
using Lumina.Domain.Common.Errors;
|
||||
using Lumina.Domain.Common.Primitives;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.UnitTests.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Commands.RestoreBook;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="RestoreBookCommandValidator"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class RestoreBookCommandValidatorTests
|
||||
{
|
||||
private readonly RestoreBookCommandFixture _restoreBookCommandFixture = new();
|
||||
private readonly RestoreBookCommandValidator _validator = new();
|
||||
|
||||
[Theory]
|
||||
[InlineData(null)] // missing route value
|
||||
[InlineData("")] // empty route value
|
||||
[InlineData(" ")] // whitespace route value, which both the not empty rule and the format rule reject
|
||||
[InlineData("not-a-library-guid")] // non-Guid route value
|
||||
[InlineData("00000000-0000-0000-0000-000000000000")] // empty Guid route value
|
||||
public void Validate_WhenLibraryIdIsEmptyOrInvalid_ShouldHaveValidationError(string? libraryId)
|
||||
{
|
||||
// Arrange
|
||||
RestoreBookCommand command = _restoreBookCommandFixture.Create(libraryId: libraryId, includeLibraryId: libraryId is not null);
|
||||
|
||||
// Act
|
||||
List<Error> result = _validator.TestValidate(command);
|
||||
|
||||
// Assert
|
||||
result.ShouldHaveValidationError(Errors.Library.LibraryIdCannotBeEmpty);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(null)] // missing route value
|
||||
[InlineData("")] // empty route value
|
||||
[InlineData(" ")] // whitespace route value, which both the not empty rule and the format rule reject
|
||||
[InlineData("not-a-book-guid")] // non-Guid route value
|
||||
[InlineData("00000000-0000-0000-0000-000000000000")] // empty Guid route value
|
||||
public void Validate_WhenBookIdIsEmptyOrInvalid_ShouldHaveValidationError(string? bookId)
|
||||
{
|
||||
// Arrange
|
||||
RestoreBookCommand command = _restoreBookCommandFixture.Create(bookId: bookId, includeBookId: bookId is not null);
|
||||
|
||||
// Act
|
||||
List<Error> result = _validator.TestValidate(command);
|
||||
|
||||
// Assert
|
||||
result.ShouldHaveValidationError(Errors.WrittenContent.BookIdCannotBeEmpty);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Validate_WhenLibraryIdIsValid_ShouldNotHaveValidationError()
|
||||
{
|
||||
// Arrange
|
||||
RestoreBookCommand command = _restoreBookCommandFixture.Create(libraryId: Guid.NewGuid().ToString());
|
||||
|
||||
// Act
|
||||
List<Error> result = _validator.TestValidate(command);
|
||||
|
||||
// Assert
|
||||
result.ShouldNotHaveValidationError(Errors.Library.LibraryIdCannotBeEmpty);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Validate_WhenBookIdIsValid_ShouldNotHaveValidationError()
|
||||
{
|
||||
// Arrange
|
||||
RestoreBookCommand command = _restoreBookCommandFixture.Create(bookId: Guid.NewGuid().ToString());
|
||||
|
||||
// Act
|
||||
List<Error> result = _validator.TestValidate(command);
|
||||
|
||||
// Assert
|
||||
result.ShouldNotHaveValidationError(Errors.WrittenContent.BookIdCannotBeEmpty);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Validate_WhenCommandIsValid_ShouldNotHaveAnyValidationErrors()
|
||||
{
|
||||
// Arrange
|
||||
RestoreBookCommand command = _restoreBookCommandFixture.Create();
|
||||
|
||||
// Act
|
||||
List<Error> result = _validator.TestValidate(command);
|
||||
|
||||
// Assert
|
||||
result.ShouldNotHaveAnyValidationErrors();
|
||||
}
|
||||
}
|
||||
+179
@@ -0,0 +1,179 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary;
|
||||
using Lumina.Application.Common.DataAccess.Repositories.BookLibrary;
|
||||
using Lumina.Application.Common.DataAccess.UoW;
|
||||
using Lumina.Application.Common.Infrastructure.Authentication;
|
||||
using Lumina.Application.Common.Infrastructure.Authorization;
|
||||
using Lumina.Application.Common.Infrastructure.Authorization.Policies.LibraryOwnership;
|
||||
using Lumina.Application.Common.Infrastructure.Validation;
|
||||
using Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Queries.GetDeletedBooks;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary;
|
||||
using Lumina.Application.Fixtures.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Queries.GetDeletedBooks;
|
||||
using Lumina.Contracts.Responses.MediaLibrary.WrittenContentLibrary.BookLibrary.Books;
|
||||
using Lumina.Domain.Common.Primitives;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
|
||||
using NSubstitute;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using ApplicationErrors = Lumina.Application.Common.Errors.Errors;
|
||||
using DomainErrors = Lumina.Domain.Common.Errors.Errors;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.UnitTests.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Queries.GetDeletedBooks;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="GetDeletedBooksQueryHandler"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class GetDeletedBooksQueryHandlerTests
|
||||
{
|
||||
private readonly IUnitOfWork _mockUnitOfWork;
|
||||
private readonly IBookRepository _mockBookRepository;
|
||||
private readonly IAuthorizationService _mockAuthorizationService;
|
||||
private readonly ICurrentUserService _mockCurrentUserService;
|
||||
private readonly IValidator<GetDeletedBooksQuery> _mockValidator;
|
||||
private readonly GetDeletedBooksQueryHandler _sut;
|
||||
private readonly Guid _userId;
|
||||
private readonly BookEntityFixture _bookEntityFixture = new();
|
||||
private readonly BookArtworkEntityFixture _bookArtworkEntityFixture = new();
|
||||
private readonly GetDeletedBooksQueryFixture _getDeletedBooksQueryFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="GetDeletedBooksQueryHandlerTests"/> class.
|
||||
/// </summary>
|
||||
public GetDeletedBooksQueryHandlerTests()
|
||||
{
|
||||
_mockUnitOfWork = Substitute.For<IUnitOfWork>();
|
||||
_mockBookRepository = Substitute.For<IBookRepository>();
|
||||
_mockUnitOfWork.BookRepository.Returns(_mockBookRepository);
|
||||
_mockAuthorizationService = Substitute.For<IAuthorizationService>();
|
||||
_mockCurrentUserService = Substitute.For<ICurrentUserService>();
|
||||
_mockValidator = Substitute.For<IValidator<GetDeletedBooksQuery>>();
|
||||
_userId = Guid.NewGuid();
|
||||
|
||||
// Default stubs: the query is valid, the current user is authenticated and the library ownership policy allows access.
|
||||
_mockValidator.Validate(Arg.Any<GetDeletedBooksQuery>()).Returns([]);
|
||||
_mockCurrentUserService.UserId.Returns(_userId);
|
||||
_mockAuthorizationService.EvaluatePolicyAsync<ILibraryOwnershipPolicy>(_userId, Arg.Any<LibraryOwnershipPolicyContext>(), Arg.Any<CancellationToken>())
|
||||
.Returns(true);
|
||||
_mockBookRepository.GetSoftDeletedByLibraryIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<IReadOnlyList<BookEntity>>([]));
|
||||
|
||||
_sut = new GetDeletedBooksQueryHandler(_mockUnitOfWork, _mockAuthorizationService, _mockCurrentUserService, _mockValidator);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task HandleAsync_WhenDeletedBooksExist_ShouldReturnTheirMappedResponses()
|
||||
{
|
||||
// Arrange
|
||||
GetDeletedBooksQuery query = _getDeletedBooksQueryFixture.Create();
|
||||
Guid libraryId = Guid.Parse(query.LibraryId!);
|
||||
string coverFileName = $"covers/{Guid.NewGuid()}.jpg";
|
||||
BookEntity firstBook = _bookEntityFixture.Create(libraryId: libraryId, isDeleted: true, includeMetadata: false);
|
||||
firstBook.Artwork = [_bookArtworkEntityFixture.Create(bookId: firstBook.Id, artworkType: ArtworkType.Cover, ordinal: 0, fileName: coverFileName)];
|
||||
BookEntity secondBook = _bookEntityFixture.Create(libraryId: libraryId, isDeleted: true, includeMetadata: false);
|
||||
_mockBookRepository.GetSoftDeletedByLibraryIdAsync(libraryId, Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<IReadOnlyList<BookEntity>>([firstBook, secondBook]));
|
||||
|
||||
// Act
|
||||
Result<IReadOnlyList<DeletedBookResponse>> result = await _sut.HandleAsync(query, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Equal(2, result.Value.Count);
|
||||
Assert.Equal(firstBook.Id, result.Value[0].Id);
|
||||
Assert.Equal(firstBook.LibraryId, result.Value[0].LibraryId);
|
||||
Assert.Equal(firstBook.Title, result.Value[0].Title);
|
||||
Assert.Equal(firstBook.OriginalTitle, result.Value[0].OriginalTitle);
|
||||
Assert.Equal(firstBook.Path, result.Value[0].Path);
|
||||
Assert.Equal(firstBook.DeletedOnUtc ?? firstBook.CreatedOnUtc, result.Value[0].DeletedOnUtc);
|
||||
Assert.Equal(coverFileName, result.Value[0].CoverPath);
|
||||
Assert.Equal(secondBook.Id, result.Value[1].Id);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task HandleAsync_WhenThereAreNoDeletedBooks_ShouldReturnAnEmptyCollection()
|
||||
{
|
||||
// Arrange
|
||||
GetDeletedBooksQuery query = _getDeletedBooksQueryFixture.Create();
|
||||
|
||||
// Act
|
||||
Result<IReadOnlyList<DeletedBookResponse>> result = await _sut.HandleAsync(query, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Empty(result.Value);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task HandleAsync_WhenValidationFails_ShouldReturnValidationErrorsWithoutTouchingAnyRepository()
|
||||
{
|
||||
// Arrange
|
||||
GetDeletedBooksQuery query = _getDeletedBooksQueryFixture.Create();
|
||||
_mockValidator.Validate(Arg.Any<GetDeletedBooksQuery>())
|
||||
.Returns([DomainErrors.Library.LibraryIdCannotBeEmpty]);
|
||||
|
||||
// Act
|
||||
Result<IReadOnlyList<DeletedBookResponse>> result = await _sut.HandleAsync(query, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(DomainErrors.Library.LibraryIdCannotBeEmpty, result.FirstError);
|
||||
await _mockBookRepository.DidNotReceive().GetSoftDeletedByLibraryIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task HandleAsync_WhenUserIsNotAuthenticated_ShouldReturnNotAuthorizedError()
|
||||
{
|
||||
// Arrange
|
||||
GetDeletedBooksQuery query = _getDeletedBooksQueryFixture.Create();
|
||||
_mockCurrentUserService.UserId.Returns((Guid?)null);
|
||||
|
||||
// Act
|
||||
Result<IReadOnlyList<DeletedBookResponse>> result = await _sut.HandleAsync(query, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(ApplicationErrors.Authorization.NotAuthorized, result.FirstError);
|
||||
await _mockBookRepository.DidNotReceive().GetSoftDeletedByLibraryIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task HandleAsync_WhenPolicyDeniesAccess_ShouldReturnNotAuthorizedError()
|
||||
{
|
||||
// Arrange
|
||||
GetDeletedBooksQuery query = _getDeletedBooksQueryFixture.Create();
|
||||
Guid libraryId = Guid.Parse(query.LibraryId!);
|
||||
_mockAuthorizationService.EvaluatePolicyAsync<ILibraryOwnershipPolicy>(_userId, Arg.Any<LibraryOwnershipPolicyContext>(), Arg.Any<CancellationToken>())
|
||||
.Returns(false);
|
||||
|
||||
// Act
|
||||
Result<IReadOnlyList<DeletedBookResponse>> result = await _sut.HandleAsync(query, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(ApplicationErrors.Authorization.NotAuthorized, result.FirstError);
|
||||
await _mockAuthorizationService.Received(1).EvaluatePolicyAsync<ILibraryOwnershipPolicy>(
|
||||
_userId, Arg.Is<LibraryOwnershipPolicyContext>(context => context.LibraryId == libraryId), Arg.Any<CancellationToken>());
|
||||
await _mockBookRepository.DidNotReceive().GetSoftDeletedByLibraryIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task HandleAsync_WhenBookRepositoryFails_ShouldReturnFailureResult()
|
||||
{
|
||||
// Arrange
|
||||
GetDeletedBooksQuery query = _getDeletedBooksQueryFixture.Create();
|
||||
_mockBookRepository.GetSoftDeletedByLibraryIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>())
|
||||
.Returns(ApplicationErrors.Persistence.UniqueConstraintViolation);
|
||||
|
||||
// Act
|
||||
Result<IReadOnlyList<DeletedBookResponse>> result = await _sut.HandleAsync(query, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(ApplicationErrors.Persistence.UniqueConstraintViolation, result.FirstError);
|
||||
}
|
||||
}
|
||||
+66
@@ -0,0 +1,66 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Queries.GetDeletedBooks;
|
||||
using Lumina.Application.Fixtures.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Queries.GetDeletedBooks;
|
||||
using Lumina.Application.UnitTests.Common.Setup;
|
||||
using Lumina.Domain.Common.Errors;
|
||||
using Lumina.Domain.Common.Primitives;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.UnitTests.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Queries.GetDeletedBooks;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="GetDeletedBooksQueryValidator"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class GetDeletedBooksQueryValidatorTests
|
||||
{
|
||||
private readonly GetDeletedBooksQueryFixture _getDeletedBooksQueryFixture = new();
|
||||
private readonly GetDeletedBooksQueryValidator _validator = new();
|
||||
|
||||
[Theory]
|
||||
[InlineData(null)] // missing route value
|
||||
[InlineData("")] // empty route value
|
||||
[InlineData(" ")] // whitespace route value, which both the not empty rule and the format rule reject
|
||||
[InlineData("not-a-library-guid")] // non-Guid route value
|
||||
[InlineData("00000000-0000-0000-0000-000000000000")] // empty Guid route value
|
||||
public void Validate_WhenLibraryIdIsEmptyOrInvalid_ShouldHaveValidationError(string? libraryId)
|
||||
{
|
||||
// Arrange
|
||||
GetDeletedBooksQuery query = _getDeletedBooksQueryFixture.Create(libraryId: libraryId, includeLibraryId: libraryId is not null);
|
||||
|
||||
// Act
|
||||
List<Error> result = _validator.TestValidate(query);
|
||||
|
||||
// Assert
|
||||
result.ShouldHaveValidationError(Errors.Library.LibraryIdCannotBeEmpty);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Validate_WhenLibraryIdIsValid_ShouldNotHaveValidationError()
|
||||
{
|
||||
// Arrange
|
||||
GetDeletedBooksQuery query = _getDeletedBooksQueryFixture.Create(libraryId: Guid.NewGuid().ToString());
|
||||
|
||||
// Act
|
||||
List<Error> result = _validator.TestValidate(query);
|
||||
|
||||
// Assert
|
||||
result.ShouldNotHaveValidationError(Errors.Library.LibraryIdCannotBeEmpty);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Validate_WhenQueryIsValid_ShouldNotHaveAnyValidationErrors()
|
||||
{
|
||||
// Arrange
|
||||
GetDeletedBooksQuery query = _getDeletedBooksQueryFixture.Create();
|
||||
|
||||
// Act
|
||||
List<Error> result = _validator.TestValidate(query);
|
||||
|
||||
// Assert
|
||||
result.ShouldNotHaveAnyValidationErrors();
|
||||
}
|
||||
}
|
||||
+307
-5
@@ -6,6 +6,7 @@ using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentL
|
||||
using Lumina.Application.Common.DTO.Filtering;
|
||||
using Lumina.Application.Common.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary;
|
||||
using Lumina.Application.Common.DTO.Pagination;
|
||||
using Lumina.Application.Common.Infrastructure.Time;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.Common;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaContributors;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary;
|
||||
@@ -21,6 +22,7 @@ using Lumina.Domain.SharedKernel.Common.Enums.MediaContributors;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.EntityFrameworkCore.ChangeTracking;
|
||||
using NSubstitute;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
@@ -38,6 +40,7 @@ namespace Lumina.DataAccess.UnitTests.Core.Repositories.BookLibrary;
|
||||
public class BookRepositoryTests
|
||||
{
|
||||
private readonly LuminaDbContext _mockContext;
|
||||
private readonly IDateTimeProvider _mockDateTimeProvider;
|
||||
private readonly BookRepository _sut;
|
||||
private readonly BookEntityFixture _bookEntityFixture = new();
|
||||
private readonly BookRatingEntityFixture _bookRatingEntityFixture = new();
|
||||
@@ -57,7 +60,9 @@ public class BookRepositoryTests
|
||||
public BookRepositoryTests()
|
||||
{
|
||||
_mockContext = Create.MockedDbContextFor<LuminaDbContext>();
|
||||
_sut = new BookRepository(_mockContext);
|
||||
_mockDateTimeProvider = Substitute.For<IDateTimeProvider>();
|
||||
_mockDateTimeProvider.UtcNow.Returns(new DateTime(2026, 1, 1, 12, 0, 0, DateTimeKind.Utc));
|
||||
_sut = new BookRepository(_mockContext, _mockDateTimeProvider);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
@@ -120,6 +125,25 @@ public class BookRepositoryTests
|
||||
Assert.Equal(Errors.WrittenContent.BookAlreadyExists, result.FirstError);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task InsertAsync_WhenADeletedBookHasTheSamePath_ShouldReturnError()
|
||||
{
|
||||
// Arrange
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
BookEntity deletedBook = _bookEntityFixture.Create(libraryId: libraryId, path: "/books/deleted.epub", isDeleted: true);
|
||||
_mockContext.Books.Add(deletedBook);
|
||||
await _mockContext.SaveChangesAsync();
|
||||
BookEntity bookModel = _bookEntityFixture.Create(libraryId: libraryId, path: "/books/deleted.epub");
|
||||
|
||||
// Act
|
||||
Result<Created> result = await _sut.InsertAsync(bookModel, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
// The deleted book keeps its path as a tombstone, so a scan can never insert it again.
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(Errors.WrittenContent.BookAlreadyExists, result.FirstError);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task InsertAsync_WhenAnotherLibraryHasABookWithTheSamePath_ShouldAddBookToContextAndReturnCreated()
|
||||
{
|
||||
@@ -299,6 +323,24 @@ public class BookRepositoryTests
|
||||
Assert.Equal(book.Id, result.Value!.Id);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetByPathAsync_WhenBookIsDeleted_ShouldReturnIt()
|
||||
{
|
||||
// Arrange
|
||||
BookEntity deletedBook = _bookEntityFixture.Create(isDeleted: true);
|
||||
_mockContext.Books.Add(deletedBook);
|
||||
await _mockContext.SaveChangesAsync();
|
||||
|
||||
// Act
|
||||
Result<BookEntity?> result = await _sut.GetByPathAsync(deletedBook.LibraryId, deletedBook.Path, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
// The scan deletion strategy must find the deleted row when its file disappears, so that it can remove it permanently.
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.NotNull(result.Value);
|
||||
Assert.Equal(deletedBook.Id, result.Value!.Id);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetByPathAsync_WhenBookDoesNotExist_ShouldReturnNull()
|
||||
{
|
||||
@@ -383,6 +425,198 @@ public class BookRepositoryTests
|
||||
Assert.Empty(result.Value);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetAllAsync_WhenBooksAreDeleted_ShouldExcludeThem()
|
||||
{
|
||||
// Arrange
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
BookEntity activeBook = _bookEntityFixture.Create(libraryId: libraryId, path: "/books/active.epub");
|
||||
BookEntity deletedBook = _bookEntityFixture.Create(libraryId: libraryId, path: "/books/deleted.epub", isDeleted: true);
|
||||
_mockContext.Books.AddRange(activeBook, deletedBook);
|
||||
await _mockContext.SaveChangesAsync();
|
||||
LibraryFilterDto filter = _libraryFilterDtoFixture.Create(libraryId: libraryId);
|
||||
|
||||
// Act
|
||||
Result<PaginatedResultDto<BookEntity>> result = await _sut.GetAllAsync<LibraryFilterDto>(filterModel: filter, cancellationToken: CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Single(result.Value.Data);
|
||||
Assert.Equal(activeBook.Id, result.Value.Data[0].Id);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetByIdAsync_WhenBookIsDeleted_ShouldReturnNull()
|
||||
{
|
||||
// Arrange
|
||||
BookEntity deletedBook = _bookEntityFixture.Create(isDeleted: true);
|
||||
_mockContext.Books.Add(deletedBook);
|
||||
await _mockContext.SaveChangesAsync();
|
||||
|
||||
// Act
|
||||
Result<BookEntity?> result = await _sut.GetByIdAsync(deletedBook.Id, cancellationToken: CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Null(result.Value);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetExistingPathsAsync_WhenBookIsDeleted_ShouldStillReportItsPathAsExisting()
|
||||
{
|
||||
// Arrange
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
BookEntity deletedBook = _bookEntityFixture.Create(libraryId: libraryId, path: "/books/deleted.epub", isDeleted: true);
|
||||
_mockContext.Books.Add(deletedBook);
|
||||
await _mockContext.SaveChangesAsync();
|
||||
|
||||
// Act
|
||||
Result<IReadOnlyCollection<string>> result = await _sut.GetExistingPathsAsync(libraryId, ["/books/deleted.epub"], CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
// The path must keep counting as taken, so that a scan never materializes the deleted book back into the catalogue.
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Equal(["/books/deleted.epub"], result.Value);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetSoftDeletedByLibraryIdAsync_WhenCalled_ShouldReturnOnlyTheDeletedBooksOfTheLibrary()
|
||||
{
|
||||
// Arrange
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
BookEntity activeBook = _bookEntityFixture.Create(libraryId: libraryId, path: "/books/active.epub");
|
||||
BookEntity deletedBook = _bookEntityFixture.Create(libraryId: libraryId, path: "/books/deleted.epub", isDeleted: true);
|
||||
BookEntity otherLibraryDeletedBook = _bookEntityFixture.Create(libraryId: Guid.NewGuid(), path: "/books/other.epub", isDeleted: true);
|
||||
_mockContext.Books.AddRange(activeBook, deletedBook, otherLibraryDeletedBook);
|
||||
await _mockContext.SaveChangesAsync();
|
||||
|
||||
// Act
|
||||
Result<IReadOnlyList<BookEntity>> result = await _sut.GetSoftDeletedByLibraryIdAsync(libraryId, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Single(result.Value);
|
||||
Assert.Equal(deletedBook.Id, result.Value[0].Id);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetSoftDeletedByLibraryIdAsync_WhenCalled_ShouldOrderByTheStoredDeletionTime()
|
||||
{
|
||||
// Arrange
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
BookEntity olderDeletion = _bookEntityFixture.Create(libraryId: libraryId, isDeleted: true, deletedOnUtc: DateTime.UtcNow.AddHours(-2));
|
||||
olderDeletion.UpdatedOnUtc = DateTime.UtcNow;
|
||||
BookEntity newerDeletion = _bookEntityFixture.Create(libraryId: libraryId, isDeleted: true, deletedOnUtc: DateTime.UtcNow.AddHours(-1));
|
||||
newerDeletion.UpdatedOnUtc = DateTime.UtcNow.AddHours(-3);
|
||||
_mockContext.Books.AddRange(olderDeletion, newerDeletion);
|
||||
await _mockContext.SaveChangesAsync();
|
||||
|
||||
// Act
|
||||
Result<IReadOnlyList<BookEntity>> result = await _sut.GetSoftDeletedByLibraryIdAsync(libraryId, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
// A later write to a deleted row may change its update time, but it must not change the order of the deleted items.
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Equal(2, result.Value.Count);
|
||||
Assert.Equal(newerDeletion.Id, result.Value[0].Id);
|
||||
Assert.Equal(olderDeletion.Id, result.Value[1].Id);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetSoftDeletedByIdAsync_WhenBookIsNotDeleted_ShouldReturnNull()
|
||||
{
|
||||
// Arrange
|
||||
BookEntity activeBook = _bookEntityFixture.Create();
|
||||
_mockContext.Books.Add(activeBook);
|
||||
await _mockContext.SaveChangesAsync();
|
||||
|
||||
// Act
|
||||
Result<BookEntity?> result = await _sut.GetSoftDeletedByIdAsync(activeBook.Id, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Null(result.Value);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task SoftDeleteByIdAsync_WhenCalled_ShouldSetTheDeletionStateAndTime()
|
||||
{
|
||||
// Arrange
|
||||
BookEntity book = _bookEntityFixture.Create();
|
||||
_mockContext.Books.Add(book);
|
||||
await _mockContext.SaveChangesAsync();
|
||||
|
||||
// Act
|
||||
Result<Updated> result = await _sut.SoftDeleteByIdAsync(book.Id, CancellationToken.None);
|
||||
await _mockContext.SaveChangesAsync();
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.True(book.IsDeleted);
|
||||
Assert.Equal(_mockDateTimeProvider.UtcNow, book.DeletedOnUtc);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task SoftDeleteByIdAsync_WhenBookIsAlreadyDeleted_ShouldReturnBookNotFoundError()
|
||||
{
|
||||
// Arrange
|
||||
BookEntity book = _bookEntityFixture.Create(isDeleted: true);
|
||||
_mockContext.Books.Add(book);
|
||||
await _mockContext.SaveChangesAsync();
|
||||
|
||||
// Act
|
||||
Result<Updated> result = await _sut.SoftDeleteByIdAsync(book.Id, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(Errors.WrittenContent.BookNotFound, result.FirstError);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task RestoreSoftDeletedByIdAsync_WhenCalled_ShouldClearTheDeletionStateAndTime()
|
||||
{
|
||||
// Arrange
|
||||
BookEntity book = _bookEntityFixture.Create(isDeleted: true, deletedOnUtc: DateTime.UtcNow.AddHours(-1));
|
||||
_mockContext.Books.Add(book);
|
||||
await _mockContext.SaveChangesAsync();
|
||||
|
||||
// Act
|
||||
Result<Updated> result = await _sut.RestoreSoftDeletedByIdAsync(book.Id, CancellationToken.None);
|
||||
await _mockContext.SaveChangesAsync();
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.False(book.IsDeleted);
|
||||
Assert.Null(book.DeletedOnUtc);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task RestoreSoftDeletedByIdAsync_WhenBookIsNotDeleted_ShouldReturnBookNotFoundError()
|
||||
{
|
||||
// Arrange
|
||||
BookEntity book = _bookEntityFixture.Create();
|
||||
_mockContext.Books.Add(book);
|
||||
await _mockContext.SaveChangesAsync();
|
||||
|
||||
// Act
|
||||
Result<Updated> result = await _sut.RestoreSoftDeletedByIdAsync(book.Id, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(Errors.WrittenContent.BookNotFound, result.FirstError);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task SoftDeleteByIdAsync_WhenBookDoesNotExist_ShouldReturnBookNotFoundError()
|
||||
{
|
||||
// Act
|
||||
Result<Updated> result = await _sut.SoftDeleteByIdAsync(Guid.NewGuid(), CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(Errors.WrittenContent.BookNotFound, result.FirstError);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetBooksNeedingMetadataAsync_WhenCalled_ShouldReturnOnlyBooksWhoseMetadataIsNotEnriched()
|
||||
{
|
||||
@@ -403,7 +637,11 @@ public class BookRepositoryTests
|
||||
BookEntity bookOfAnotherLibrary = _bookEntityFixture.Create();
|
||||
bookOfAnotherLibrary.LibraryId = Guid.NewGuid();
|
||||
bookOfAnotherLibrary.MetadataStatus = MetadataStatus.Pending;
|
||||
_mockContext.Books.AddRange(pendingBook, enrichedBook, failedBook, bookOfAnotherLibrary);
|
||||
BookEntity deletedPendingBook = _bookEntityFixture.Create(isDeleted: true);
|
||||
deletedPendingBook.LibraryId = libraryId;
|
||||
deletedPendingBook.Path = "/books/d.epub";
|
||||
deletedPendingBook.MetadataStatus = MetadataStatus.Pending;
|
||||
_mockContext.Books.AddRange(pendingBook, enrichedBook, failedBook, bookOfAnotherLibrary, deletedPendingBook);
|
||||
await _mockContext.SaveChangesAsync();
|
||||
|
||||
// Act
|
||||
@@ -414,6 +652,7 @@ public class BookRepositoryTests
|
||||
Assert.Equal(2, result.Value.Count);
|
||||
Assert.Contains(result.Value, book => book.Id == pendingBook.Id);
|
||||
Assert.Contains(result.Value, book => book.Id == failedBook.Id);
|
||||
Assert.DoesNotContain(result.Value, book => book.Id == deletedPendingBook.Id);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
@@ -483,6 +722,8 @@ public class BookRepositoryTests
|
||||
|
||||
Guid storedLibraryId = storedBook.LibraryId;
|
||||
string storedPath = storedBook.Path;
|
||||
bool storedIsDeleted = storedBook.IsDeleted;
|
||||
DateTime? storedDeletedOnUtc = storedBook.DeletedOnUtc;
|
||||
MetadataStatus storedMetadataStatus = storedBook.MetadataStatus;
|
||||
DateTime? storedLastMetadataUpdateUtc = storedBook.LastMetadataUpdateUtc;
|
||||
string? storedMetadataProvider = storedBook.MetadataProvider;
|
||||
@@ -493,6 +734,8 @@ public class BookRepositoryTests
|
||||
data.Title = "Updated Title";
|
||||
data.LibraryId = Guid.NewGuid();
|
||||
data.Path = "/books/updated.epub";
|
||||
data.IsDeleted = true;
|
||||
data.DeletedOnUtc = DateTime.UtcNow;
|
||||
data.MetadataStatus = MetadataStatus.Enriched;
|
||||
data.LastMetadataUpdateUtc = DateTime.UtcNow;
|
||||
data.MetadataProvider = "UpdatedProvider";
|
||||
@@ -501,10 +744,14 @@ public class BookRepositoryTests
|
||||
|
||||
// Act
|
||||
Result<Updated> result = await _sut.UpdateAsync(data, CancellationToken.None);
|
||||
bool isDeletionStateModified = _mockContext.Entry(storedBook).Property(book => book.IsDeleted).IsModified;
|
||||
bool isDeletionTimeModified = _mockContext.Entry(storedBook).Property(book => book.DeletedOnUtc).IsModified;
|
||||
await _mockContext.SaveChangesAsync();
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.False(isDeletionStateModified);
|
||||
Assert.False(isDeletionTimeModified);
|
||||
BookEntity? retrievedBook = await _mockContext.Books
|
||||
.Include(book => book.Tags)
|
||||
.Include(book => book.Genres)
|
||||
@@ -517,6 +764,8 @@ public class BookRepositoryTests
|
||||
// The identity, enrichment and audit columns of the stored book are never overwritten by an edit.
|
||||
Assert.Equal(storedLibraryId, retrievedBook.LibraryId);
|
||||
Assert.Equal(storedPath, retrievedBook.Path);
|
||||
Assert.Equal(storedIsDeleted, retrievedBook.IsDeleted);
|
||||
Assert.Equal(storedDeletedOnUtc, retrievedBook.DeletedOnUtc);
|
||||
Assert.Equal(storedMetadataStatus, retrievedBook.MetadataStatus);
|
||||
Assert.Equal(storedLastMetadataUpdateUtc, retrievedBook.LastMetadataUpdateUtc);
|
||||
Assert.Equal(storedMetadataProvider, retrievedBook.MetadataProvider);
|
||||
@@ -524,6 +773,27 @@ public class BookRepositoryTests
|
||||
Assert.Equal(storedCreatedBy, retrievedBook.CreatedBy);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task UpdateAsync_WhenBookIsDeleted_ShouldReturnBookNotFoundWithoutUpdatingIt()
|
||||
{
|
||||
// Arrange
|
||||
BookEntity storedBook = _bookEntityFixture.Create(isDeleted: true);
|
||||
_mockContext.Books.Add(storedBook);
|
||||
await _mockContext.SaveChangesAsync();
|
||||
string storedTitle = storedBook.Title;
|
||||
BookEntity data = _bookEntityFixture.Create(id: storedBook.Id);
|
||||
data.Title = "Updated Title";
|
||||
|
||||
// Act
|
||||
Result<Updated> result = await _sut.UpdateAsync(data, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
// A soft deleted book can only be brought back by the explicit restore operation, never by an edit.
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(Errors.WrittenContent.BookNotFound, result.FirstError);
|
||||
Assert.Equal(storedTitle, storedBook.Title);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task UpdateAsync_WhenStoredBookHasArtwork_ShouldPreserveTheStoredArtwork()
|
||||
{
|
||||
@@ -832,7 +1102,11 @@ public class BookRepositoryTests
|
||||
BookEntity bookOfAnotherLibrary = _bookEntityFixture.Create();
|
||||
bookOfAnotherLibrary.LibraryId = Guid.NewGuid();
|
||||
bookOfAnotherLibrary.Artwork = [];
|
||||
_mockContext.Books.AddRange(bookWithoutCover, bookWithEnrichedCover, bookWithFailedCover, bookOfAnotherLibrary);
|
||||
BookEntity deletedBookWithoutCover = _bookEntityFixture.Create(isDeleted: true);
|
||||
deletedBookWithoutCover.LibraryId = libraryId;
|
||||
deletedBookWithoutCover.Path = "/books/d.epub";
|
||||
deletedBookWithoutCover.Artwork = [];
|
||||
_mockContext.Books.AddRange(bookWithoutCover, bookWithEnrichedCover, bookWithFailedCover, bookOfAnotherLibrary, deletedBookWithoutCover);
|
||||
await _mockContext.SaveChangesAsync();
|
||||
|
||||
// Act
|
||||
@@ -843,6 +1117,7 @@ public class BookRepositoryTests
|
||||
Assert.Equal(2, result.Value.Count);
|
||||
Assert.Contains(result.Value, book => book.Id == bookWithoutCover.Id);
|
||||
Assert.Contains(result.Value, book => book.Id == bookWithFailedCover.Id);
|
||||
Assert.DoesNotContain(result.Value, book => book.Id == deletedBookWithoutCover.Id);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
@@ -859,7 +1134,10 @@ public class BookRepositoryTests
|
||||
BookEntity bookOfAnotherLibrary = _bookEntityFixture.Create();
|
||||
bookOfAnotherLibrary.LibraryId = Guid.NewGuid();
|
||||
bookOfAnotherLibrary.Artwork = [];
|
||||
_mockContext.Books.AddRange(bookWithoutCover, bookWithEnrichedCover, bookOfAnotherLibrary);
|
||||
BookEntity deletedBookWithoutCover = _bookEntityFixture.Create(isDeleted: true);
|
||||
deletedBookWithoutCover.LibraryId = libraryId;
|
||||
deletedBookWithoutCover.Artwork = [];
|
||||
_mockContext.Books.AddRange(bookWithoutCover, bookWithEnrichedCover, bookOfAnotherLibrary, deletedBookWithoutCover);
|
||||
await _mockContext.SaveChangesAsync();
|
||||
|
||||
// Act
|
||||
@@ -998,7 +1276,10 @@ public class BookRepositoryTests
|
||||
BookEntity bookOfAnotherLibrary = _bookEntityFixture.Create();
|
||||
bookOfAnotherLibrary.LibraryId = Guid.NewGuid();
|
||||
bookOfAnotherLibrary.MetadataStatus = MetadataStatus.Pending;
|
||||
_mockContext.Books.AddRange(pendingBook, enrichedBook, failedBook, bookOfAnotherLibrary);
|
||||
BookEntity deletedPendingBook = _bookEntityFixture.Create(isDeleted: true);
|
||||
deletedPendingBook.LibraryId = libraryId;
|
||||
deletedPendingBook.MetadataStatus = MetadataStatus.Pending;
|
||||
_mockContext.Books.AddRange(pendingBook, enrichedBook, failedBook, bookOfAnotherLibrary, deletedPendingBook);
|
||||
await _mockContext.SaveChangesAsync();
|
||||
|
||||
// Act
|
||||
@@ -1191,7 +1472,9 @@ public class BookRepositoryTests
|
||||
List<BookEntity> books = _bookEntityFixture.CreateMany(3);
|
||||
foreach (BookEntity book in books)
|
||||
book.LibraryId = libraryId;
|
||||
BookEntity deletedBook = _bookEntityFixture.Create(libraryId: libraryId, isDeleted: true);
|
||||
_mockContext.Books.AddRange(books);
|
||||
_mockContext.Books.Add(deletedBook);
|
||||
await _mockContext.SaveChangesAsync();
|
||||
|
||||
PaginationDataDto paginationData = _paginationDataDtoFixture.Create(currentPage: 1, perPage: 10);
|
||||
@@ -1204,6 +1487,7 @@ public class BookRepositoryTests
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Equal(3, result.Value.Count);
|
||||
Assert.Equal(3, result.Value.Data.Count);
|
||||
Assert.DoesNotContain(result.Value.Data, row => row.Id == deletedBook.Id);
|
||||
Assert.Equal(1, result.Value.CurrentPage);
|
||||
Assert.Equal(10, result.Value.PerPage);
|
||||
Assert.Equal(1, result.Value.NumberOfPages);
|
||||
@@ -1492,6 +1776,24 @@ public class BookRepositoryTests
|
||||
Assert.DoesNotContain(result.Value, book => book.Id == secondBook.Id);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetByIdsAsync_WhenABookIsDeleted_ShouldExcludeIt()
|
||||
{
|
||||
// Arrange
|
||||
BookEntity activeBook = _bookEntityFixture.Create(includeMetadata: false);
|
||||
BookEntity deletedBook = _bookEntityFixture.Create(isDeleted: true, includeMetadata: false);
|
||||
_mockContext.Books.AddRange(activeBook, deletedBook);
|
||||
await _mockContext.SaveChangesAsync();
|
||||
|
||||
// Act
|
||||
Result<IReadOnlyList<BookEntity>> result = await _sut.GetByIdsAsync([activeBook.Id, deletedBook.Id], false, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Single(result.Value);
|
||||
Assert.Equal(activeBook.Id, result.Value[0].Id);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetByIdsAsync_WhenNavigationPropertiesShouldNotBeIncluded_ShouldReturnTheRequestedBooks()
|
||||
{
|
||||
|
||||
@@ -101,7 +101,7 @@ public class UnitOfWorkTests
|
||||
{
|
||||
// Arrange
|
||||
LuminaDbContext dbContext = _fixture.Create<LuminaDbContext>();
|
||||
UnitOfWork unitOfWork = new(dbContext);
|
||||
UnitOfWork unitOfWork = new(dbContext, Substitute.For<IDateTimeProvider>());
|
||||
CancellationToken cancellationToken = new();
|
||||
|
||||
// Act
|
||||
@@ -121,7 +121,7 @@ public class UnitOfWorkTests
|
||||
.UseInMemoryDatabase(databaseName: Guid.NewGuid().ToString())
|
||||
.Options;
|
||||
LuminaDbContext dbContext = new(options);
|
||||
UnitOfWork unitOfWork = new(dbContext);
|
||||
UnitOfWork unitOfWork = new(dbContext, Substitute.For<IDateTimeProvider>());
|
||||
dbContext.Roles.Add(_roleEntityFixture.Create(id: Guid.NewGuid(), roleName: "TestRole"));
|
||||
await dbContext.SaveChangesAsync(CancellationToken.None);
|
||||
Assert.NotEmpty(dbContext.ChangeTracker.Entries());
|
||||
@@ -154,6 +154,6 @@ public class UnitOfWorkTests
|
||||
|
||||
private UnitOfWork CreateUnitOfWork()
|
||||
{
|
||||
return new(_fixture.Create<LuminaDbContext>());
|
||||
return new(_fixture.Create<LuminaDbContext>(), Substitute.For<IDateTimeProvider>());
|
||||
}
|
||||
}
|
||||
+19
@@ -107,6 +107,25 @@ public class BooksMediaLibraryScanItemMaterializerTests
|
||||
_mockPathTemplateService.Received(1).Parse(Arg.Any<LibraryType>(), Arg.Any<LibraryPathTemplate>(), "Artist\\track.epub", '\\');
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task MaterializeItemsAsync_WhenPathIsAlreadyUsedByADeletedBook_ShouldNotInsertItAgain()
|
||||
{
|
||||
// Arrange
|
||||
LibraryEntity library = _libraryEntityFixture.Create(id: _libraryId, libraryType: LibraryType.Book, contentLocations: ["C:\\Music"]);
|
||||
_mockLibraryRepository.GetByIdAsync(_libraryId, cancellationToken: Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<LibraryEntity?>(library));
|
||||
_mockBookRepository.GetExistingPathsAsync(_libraryId, Arg.Any<IReadOnlyCollection<string>>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<IReadOnlyCollection<string>>(["C:\\Music\\deleted.epub"]));
|
||||
|
||||
// Act
|
||||
Result<Success> result = await _sut.MaterializeItemsAsync(_mockUnitOfWork, _libraryId, _scanId, CreatePathSet("C:\\Music\\deleted.epub"), CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
// A deleted book keeps its stored path, so the scan treats the file as already catalogued and never materializes it again.
|
||||
Assert.False(result.IsFailure);
|
||||
await _mockBookRepository.DidNotReceive().InsertAsync(Arg.Any<BookEntity>(), Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates the set of media library scan snapshot paths that the media library scan produces.
|
||||
/// </summary>
|
||||
|
||||
+3
-2
@@ -1,6 +1,7 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DataAccess.UoW;
|
||||
using Lumina.Application.Common.DomainEvents;
|
||||
using Lumina.Application.Common.Infrastructure.Time;
|
||||
using Lumina.DataAccess.Core.UoW;
|
||||
using Lumina.Domain.Common.Events;
|
||||
using Lumina.Presentation.Api.Common.Http;
|
||||
@@ -72,7 +73,7 @@ public class EventualConsistencyMiddlewareTests
|
||||
using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-eventual-consistency-abort-{Guid.NewGuid()};Mode=Memory;Cache=Shared");
|
||||
anchorConnection.Open();
|
||||
using LuminaDbContext dbContext = CreateContext(anchorConnection);
|
||||
using UnitOfWork unitOfWork = new(dbContext);
|
||||
using UnitOfWork unitOfWork = new(dbContext, Substitute.For<IDateTimeProvider>());
|
||||
await dbContext.Database.ExecuteSqlRawAsync("CREATE TABLE CommitProbe (Id INTEGER NOT NULL PRIMARY KEY);");
|
||||
CapturingHttpResponseFeature responseFeature = new();
|
||||
DefaultHttpContext httpContext = new();
|
||||
@@ -112,7 +113,7 @@ public class EventualConsistencyMiddlewareTests
|
||||
using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-eventual-consistency-rollback-{Guid.NewGuid()};Mode=Memory;Cache=Shared");
|
||||
anchorConnection.Open();
|
||||
using LuminaDbContext dbContext = CreateContext(anchorConnection);
|
||||
using UnitOfWork unitOfWork = new(dbContext);
|
||||
using UnitOfWork unitOfWork = new(dbContext, Substitute.For<IDateTimeProvider>());
|
||||
await dbContext.Database.ExecuteSqlRawAsync("CREATE TABLE CommitProbe (Id INTEGER NOT NULL PRIMARY KEY);");
|
||||
CapturingHttpResponseFeature responseFeature = new();
|
||||
DefaultHttpContext httpContext = new();
|
||||
|
||||
+161
@@ -0,0 +1,161 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.CQRS;
|
||||
using Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Queries.GetDeletedBooks;
|
||||
using Lumina.Application.Fixtures.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Queries.GetDeletedBooks;
|
||||
using Lumina.Contracts.Fixtures.Responses.MediaLibrary.WrittenContentLibrary.BookLibrary.Books;
|
||||
using Lumina.Contracts.Responses.MediaLibrary.WrittenContentLibrary.BookLibrary.Books;
|
||||
using Lumina.Domain.Common.Primitives;
|
||||
using Lumina.Presentation.Api.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.Books.GetDeletedBooks;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using Microsoft.AspNetCore.Http.HttpResults;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using NSubstitute;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using ApplicationErrors = Lumina.Application.Common.Errors.Errors;
|
||||
using DomainErrors = Lumina.Domain.Common.Errors.Errors;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Api.UnitTests.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.Books.GetDeletedBooks;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="GetDeletedBooksEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class GetDeletedBooksEndpointTests
|
||||
{
|
||||
private readonly IQueryHandler<GetDeletedBooksQuery, Result<IReadOnlyList<DeletedBookResponse>>> _mockHandler;
|
||||
private readonly GetDeletedBooksEndpoint _sut;
|
||||
private readonly DeletedBookResponseFixture _deletedBookResponseFixture = new();
|
||||
private readonly GetDeletedBooksQueryFixture _getDeletedBooksQueryFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="GetDeletedBooksEndpointTests"/> class.
|
||||
/// </summary>
|
||||
public GetDeletedBooksEndpointTests()
|
||||
{
|
||||
_mockHandler = Substitute.For<IQueryHandler<GetDeletedBooksQuery, Result<IReadOnlyList<DeletedBookResponse>>>>();
|
||||
_sut = FastEndpoints.Factory.Create<GetDeletedBooksEndpoint>(_mockHandler);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenSuccessful_ShouldReturnOkResultWithDeletedBooks()
|
||||
{
|
||||
// Arrange
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
IReadOnlyList<DeletedBookResponse> expectedBooks =
|
||||
[
|
||||
_deletedBookResponseFixture.Create(
|
||||
libraryId: libraryId,
|
||||
title: "The Hobbit",
|
||||
includeOriginalTitle: false,
|
||||
includeCoverPath: false)
|
||||
];
|
||||
_mockHandler.HandleAsync(Arg.Any<GetDeletedBooksQuery>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From(expectedBooks));
|
||||
_sut.HttpContext.Request.RouteValues["libraryId"] = libraryId.ToString();
|
||||
|
||||
// Act
|
||||
IResult result = await _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Ok<IReadOnlyList<DeletedBookResponse>> okResult = Assert.IsType<Ok<IReadOnlyList<DeletedBookResponse>>>(result);
|
||||
Assert.Equal(expectedBooks, okResult.Value);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenHandlerReturnsNotAuthorizedError_ShouldReturnProblemResult()
|
||||
{
|
||||
// Arrange
|
||||
Error expectedError = ApplicationErrors.Authorization.NotAuthorized;
|
||||
_mockHandler.HandleAsync(Arg.Any<GetDeletedBooksQuery>(), Arg.Any<CancellationToken>())
|
||||
.Returns(expectedError);
|
||||
_sut.HttpContext.Request.RouteValues["libraryId"] = Guid.NewGuid().ToString();
|
||||
|
||||
// Act
|
||||
IResult result = await _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
ProblemHttpResult problemDetails = Assert.IsType<ProblemHttpResult>(result);
|
||||
Assert.Equal(StatusCodes.Status403Forbidden, problemDetails.StatusCode);
|
||||
Assert.Equal("application/problem+json", problemDetails.ContentType);
|
||||
ProblemDetails problemDetailsBody = Assert.IsType<ProblemDetails>(problemDetails.ProblemDetails);
|
||||
Assert.Equal(StatusCodes.Status403Forbidden, problemDetailsBody.Status);
|
||||
Assert.Equal("General.Unauthorized", problemDetailsBody.Title);
|
||||
Assert.Equal("NotAuthorized", problemDetailsBody.Detail);
|
||||
Assert.Equal("https://tools.ietf.org/html/rfc9110#section-15.5.4", problemDetailsBody.Type);
|
||||
Assert.NotNull(problemDetailsBody.Extensions["traceId"]);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenHandlerReturnsValidationErrors_ShouldReturnValidationProblemResult()
|
||||
{
|
||||
// Arrange
|
||||
Error validationError = DomainErrors.Library.LibraryIdCannotBeEmpty;
|
||||
_mockHandler.HandleAsync(Arg.Any<GetDeletedBooksQuery>(), Arg.Any<CancellationToken>())
|
||||
.Returns(validationError);
|
||||
_sut.HttpContext.Request.RouteValues["libraryId"] = Guid.NewGuid().ToString();
|
||||
|
||||
// Act
|
||||
IResult result = await _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
ProblemHttpResult problemDetails = Assert.IsType<ProblemHttpResult>(result);
|
||||
Assert.Equal(StatusCodes.Status422UnprocessableEntity, problemDetails.StatusCode);
|
||||
Assert.Equal("application/problem+json", problemDetails.ContentType);
|
||||
HttpValidationProblemDetails validationProblemDetails = Assert.IsType<HttpValidationProblemDetails>(problemDetails.ProblemDetails);
|
||||
Assert.Equal(StatusCodes.Status422UnprocessableEntity, validationProblemDetails.Status);
|
||||
Assert.Equal("General.Validation", validationProblemDetails.Title);
|
||||
Assert.Equal("OneOrMoreValidationErrorsOccurred", validationProblemDetails.Detail);
|
||||
Assert.Equal("https://tools.ietf.org/html/rfc4918#section-11.2", validationProblemDetails.Type);
|
||||
Assert.Single(validationProblemDetails.Errors);
|
||||
Assert.Equal(new[] { "LibraryIdCannotBeEmpty" }, validationProblemDetails.Errors["General.Validation"]);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenCalled_ShouldSendTheRouteLibraryIdToTheHandler()
|
||||
{
|
||||
// Arrange
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
_mockHandler.HandleAsync(Arg.Any<GetDeletedBooksQuery>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<IReadOnlyList<DeletedBookResponse>>([]));
|
||||
_sut.HttpContext.Request.RouteValues["libraryId"] = libraryId.ToString();
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
GetDeletedBooksQuery expectedQuery = _getDeletedBooksQueryFixture.Create(libraryId: libraryId.ToString());
|
||||
await _mockHandler.Received(1).HandleAsync(expectedQuery, Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenCancellationRequested_ShouldCancelOperation()
|
||||
{
|
||||
// Arrange
|
||||
CancellationTokenSource cts = new();
|
||||
TaskCompletionSource<bool> operationStarted = new();
|
||||
TaskCompletionSource<bool> cancellationRequested = new();
|
||||
_mockHandler.HandleAsync(Arg.Any<GetDeletedBooksQuery>(), Arg.Any<CancellationToken>())
|
||||
.Returns(callInfo => Task.Run(async () =>
|
||||
{
|
||||
operationStarted.SetResult(true);
|
||||
await cancellationRequested.Task;
|
||||
callInfo.Arg<CancellationToken>().ThrowIfCancellationRequested();
|
||||
return Result.From<IReadOnlyList<DeletedBookResponse>>([]);
|
||||
}, callInfo.Arg<CancellationToken>()));
|
||||
_sut.HttpContext.Request.RouteValues["libraryId"] = Guid.NewGuid().ToString();
|
||||
|
||||
// Act
|
||||
Task<IResult> operationTask = _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, cts.Token);
|
||||
await operationStarted.Task;
|
||||
cts.Cancel();
|
||||
cancellationRequested.SetResult(true);
|
||||
|
||||
// Assert
|
||||
await Assert.ThrowsAnyAsync<OperationCanceledException>(() => operationTask);
|
||||
}
|
||||
}
|
||||
+185
@@ -0,0 +1,185 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.CQRS;
|
||||
using Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Commands.RestoreBook;
|
||||
using Lumina.Application.Fixtures.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Commands.RestoreBook;
|
||||
using Lumina.Domain.Common.Primitives;
|
||||
using Lumina.Presentation.Api.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.Books.RestoreBook;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using Microsoft.AspNetCore.Http.HttpResults;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using NSubstitute;
|
||||
using System;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using ApplicationErrors = Lumina.Application.Common.Errors.Errors;
|
||||
using DomainErrors = Lumina.Domain.Common.Errors.Errors;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Api.UnitTests.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.Books.RestoreBook;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="RestoreBookEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class RestoreBookEndpointTests
|
||||
{
|
||||
private readonly ICommandHandler<RestoreBookCommand, Result<Updated>> _mockHandler;
|
||||
private readonly RestoreBookEndpoint _sut;
|
||||
private readonly RestoreBookCommandFixture _restoreBookCommandFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="RestoreBookEndpointTests"/> class.
|
||||
/// </summary>
|
||||
public RestoreBookEndpointTests()
|
||||
{
|
||||
_mockHandler = Substitute.For<ICommandHandler<RestoreBookCommand, Result<Updated>>>();
|
||||
_sut = FastEndpoints.Factory.Create<RestoreBookEndpoint>(_mockHandler);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenSuccessful_ShouldReturnOkResultWithUpdated()
|
||||
{
|
||||
// Arrange
|
||||
_mockHandler.HandleAsync(Arg.Any<RestoreBookCommand>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From(Result.Updated));
|
||||
ConfigureRouteValues();
|
||||
|
||||
// Act
|
||||
IResult result = await _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Ok<Updated> okResult = Assert.IsType<Ok<Updated>>(result);
|
||||
Assert.Equal(Result.Updated, okResult.Value);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenHandlerReturnsNotFoundError_ShouldReturnProblemResult()
|
||||
{
|
||||
// Arrange
|
||||
Error expectedError = DomainErrors.WrittenContent.BookNotFound;
|
||||
_mockHandler.HandleAsync(Arg.Any<RestoreBookCommand>(), Arg.Any<CancellationToken>())
|
||||
.Returns(expectedError);
|
||||
ConfigureRouteValues();
|
||||
|
||||
// Act
|
||||
IResult result = await _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
ProblemHttpResult problemDetails = Assert.IsType<ProblemHttpResult>(result);
|
||||
Assert.Equal(StatusCodes.Status404NotFound, problemDetails.StatusCode);
|
||||
Assert.Equal("application/problem+json", problemDetails.ContentType);
|
||||
ProblemDetails problemDetailsBody = Assert.IsType<ProblemDetails>(problemDetails.ProblemDetails);
|
||||
Assert.Equal(StatusCodes.Status404NotFound, problemDetailsBody.Status);
|
||||
Assert.Equal("General.NotFound", problemDetailsBody.Title);
|
||||
Assert.Equal("BookNotFound", problemDetailsBody.Detail);
|
||||
Assert.Equal("https://tools.ietf.org/html/rfc9110#section-15.5.5", problemDetailsBody.Type);
|
||||
Assert.NotNull(problemDetailsBody.Extensions["traceId"]);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenHandlerReturnsNotAuthorizedError_ShouldReturnProblemResult()
|
||||
{
|
||||
// Arrange
|
||||
Error expectedError = ApplicationErrors.Authorization.NotAuthorized;
|
||||
_mockHandler.HandleAsync(Arg.Any<RestoreBookCommand>(), Arg.Any<CancellationToken>())
|
||||
.Returns(expectedError);
|
||||
ConfigureRouteValues();
|
||||
|
||||
// Act
|
||||
IResult result = await _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
ProblemHttpResult problemDetails = Assert.IsType<ProblemHttpResult>(result);
|
||||
Assert.Equal(StatusCodes.Status403Forbidden, problemDetails.StatusCode);
|
||||
Assert.Equal("application/problem+json", problemDetails.ContentType);
|
||||
ProblemDetails problemDetailsBody = Assert.IsType<ProblemDetails>(problemDetails.ProblemDetails);
|
||||
Assert.Equal(StatusCodes.Status403Forbidden, problemDetailsBody.Status);
|
||||
Assert.Equal("General.Unauthorized", problemDetailsBody.Title);
|
||||
Assert.Equal("NotAuthorized", problemDetailsBody.Detail);
|
||||
Assert.Equal("https://tools.ietf.org/html/rfc9110#section-15.5.4", problemDetailsBody.Type);
|
||||
Assert.NotNull(problemDetailsBody.Extensions["traceId"]);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenHandlerReturnsValidationErrors_ShouldReturnValidationProblemResult()
|
||||
{
|
||||
// Arrange
|
||||
Error validationError = DomainErrors.WrittenContent.BookIdCannotBeEmpty;
|
||||
_mockHandler.HandleAsync(Arg.Any<RestoreBookCommand>(), Arg.Any<CancellationToken>())
|
||||
.Returns(validationError);
|
||||
ConfigureRouteValues();
|
||||
|
||||
// Act
|
||||
IResult result = await _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
ProblemHttpResult problemDetails = Assert.IsType<ProblemHttpResult>(result);
|
||||
Assert.Equal(StatusCodes.Status422UnprocessableEntity, problemDetails.StatusCode);
|
||||
Assert.Equal("application/problem+json", problemDetails.ContentType);
|
||||
HttpValidationProblemDetails validationProblemDetails = Assert.IsType<HttpValidationProblemDetails>(problemDetails.ProblemDetails);
|
||||
Assert.Equal(StatusCodes.Status422UnprocessableEntity, validationProblemDetails.Status);
|
||||
Assert.Equal("General.Validation", validationProblemDetails.Title);
|
||||
Assert.Equal("OneOrMoreValidationErrorsOccurred", validationProblemDetails.Detail);
|
||||
Assert.Equal("https://tools.ietf.org/html/rfc4918#section-11.2", validationProblemDetails.Type);
|
||||
Assert.Single(validationProblemDetails.Errors);
|
||||
Assert.Equal(new[] { "BookIdCannotBeEmpty" }, validationProblemDetails.Errors["General.Validation"]);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenCalled_ShouldSendTheRouteIdsToTheHandler()
|
||||
{
|
||||
// Arrange
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
Guid bookId = Guid.NewGuid();
|
||||
_mockHandler.HandleAsync(Arg.Any<RestoreBookCommand>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From(Result.Updated));
|
||||
_sut.HttpContext.Request.RouteValues["libraryId"] = libraryId.ToString();
|
||||
_sut.HttpContext.Request.RouteValues["bookId"] = bookId.ToString();
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
RestoreBookCommand expectedCommand = _restoreBookCommandFixture.Create(
|
||||
libraryId: libraryId.ToString(),
|
||||
bookId: bookId.ToString());
|
||||
await _mockHandler.Received(1).HandleAsync(expectedCommand, Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenCancellationRequested_ShouldCancelOperation()
|
||||
{
|
||||
// Arrange
|
||||
CancellationTokenSource cts = new();
|
||||
TaskCompletionSource<bool> operationStarted = new();
|
||||
TaskCompletionSource<bool> cancellationRequested = new();
|
||||
_mockHandler.HandleAsync(Arg.Any<RestoreBookCommand>(), Arg.Any<CancellationToken>())
|
||||
.Returns(callInfo => Task.Run(async () =>
|
||||
{
|
||||
operationStarted.SetResult(true);
|
||||
await cancellationRequested.Task;
|
||||
callInfo.Arg<CancellationToken>().ThrowIfCancellationRequested();
|
||||
return Result.From(Result.Updated);
|
||||
}, callInfo.Arg<CancellationToken>()));
|
||||
ConfigureRouteValues();
|
||||
|
||||
// Act
|
||||
Task<IResult> operationTask = _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, cts.Token);
|
||||
await operationStarted.Task;
|
||||
cts.Cancel();
|
||||
cancellationRequested.SetResult(true);
|
||||
|
||||
// Assert
|
||||
await Assert.ThrowsAnyAsync<OperationCanceledException>(() => operationTask);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Configures the route values of a valid restore request.
|
||||
/// </summary>
|
||||
private void ConfigureRouteValues()
|
||||
{
|
||||
_sut.HttpContext.Request.RouteValues["libraryId"] = Guid.NewGuid().ToString();
|
||||
_sut.HttpContext.Request.RouteValues["bookId"] = Guid.NewGuid().ToString();
|
||||
}
|
||||
}
|
||||
+138
@@ -0,0 +1,138 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using FastEndpoints;
|
||||
using Lumina.Presentation.Web.Common.Api;
|
||||
using Lumina.Presentation.Web.Common.Routes;
|
||||
using Lumina.Presentation.Web.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.Books.DeleteBook;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.TestHelpers;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using NSubstitute;
|
||||
using System;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Text.Json;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.UnitTests.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.Books.DeleteBook;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="DeleteBookEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class DeleteBookEndpointTests
|
||||
{
|
||||
private readonly IApiHttpClient _mockApiHttpClient;
|
||||
private readonly DeleteBookEndpoint _sut;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="DeleteBookEndpointTests"/> class.
|
||||
/// </summary>
|
||||
public DeleteBookEndpointTests()
|
||||
{
|
||||
_mockApiHttpClient = Substitute.For<IApiHttpClient>();
|
||||
_sut = Factory.Create<DeleteBookEndpoint>(_mockApiHttpClient);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenCalled_ShouldDeleteBookViaApiAndReturnSuccessWithoutData()
|
||||
{
|
||||
// Arrange
|
||||
Guid bookId = Guid.NewGuid();
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
ConfigureRequest(bookId.ToString(), libraryId);
|
||||
|
||||
// Act
|
||||
IResult result = await _sut.ExecuteAsync(EmptyRequest.Instance, CancellationToken.None);
|
||||
string body = await JsonResultTestHelper.GetResponseBodyAsync(result);
|
||||
|
||||
// Assert
|
||||
await _mockApiHttpClient.Received(1).DeleteAsync(
|
||||
BuildExpectedEndpoint(libraryId, bookId),
|
||||
Arg.Any<CancellationToken>());
|
||||
using JsonDocument jsonDocument = JsonDocument.Parse(body);
|
||||
Assert.True(jsonDocument.RootElement.GetProperty("success").GetBoolean());
|
||||
Assert.False(jsonDocument.RootElement.TryGetProperty("data", out JsonElement _));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenBookIdIsNotParseable_ShouldForwardGuidEmptyBookIdToApi()
|
||||
{
|
||||
// Arrange
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
ConfigureRequest("not-a-guid", libraryId);
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(EmptyRequest.Instance, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
await _mockApiHttpClient.Received(1).DeleteAsync(
|
||||
BuildExpectedEndpoint(libraryId, Guid.Empty),
|
||||
Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenBookIdIsMissing_ShouldForwardGuidEmptyBookIdToApi()
|
||||
{
|
||||
// Arrange
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
_sut.HttpContext.Request.QueryString = new QueryString($"?libraryId={libraryId}");
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(EmptyRequest.Instance, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
await _mockApiHttpClient.Received(1).DeleteAsync(
|
||||
BuildExpectedEndpoint(libraryId, Guid.Empty),
|
||||
Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenLibraryQueryIdIsNotParseable_ShouldForwardGuidEmptyLibraryIdToApi()
|
||||
{
|
||||
// Arrange
|
||||
Guid bookId = Guid.NewGuid();
|
||||
ConfigureRequest(bookId.ToString(), "not-a-guid");
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(EmptyRequest.Instance, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
await _mockApiHttpClient.Received(1).DeleteAsync(
|
||||
BuildExpectedEndpoint(Guid.Empty, bookId),
|
||||
Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Sets the route and query values the endpoint reads the book identity from.
|
||||
/// </summary>
|
||||
/// <param name="bookId">The raw route value of the book Id.</param>
|
||||
/// <param name="libraryId">The raw query value of the library Id.</param>
|
||||
private void ConfigureRequest(string bookId, Guid libraryId)
|
||||
{
|
||||
ConfigureRequest(bookId, libraryId.ToString());
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Sets the route and query values the endpoint reads the book identity from.
|
||||
/// </summary>
|
||||
/// <param name="bookId">The raw route value of the book Id.</param>
|
||||
/// <param name="libraryId">The raw query value of the library Id.</param>
|
||||
private void ConfigureRequest(string bookId, string libraryId)
|
||||
{
|
||||
_sut.HttpContext.Request.RouteValues["bookId"] = bookId;
|
||||
_sut.HttpContext.Request.QueryString = new QueryString($"?libraryId={libraryId}");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Builds the upstream endpoint the book deletion is expected to be sent to.
|
||||
/// </summary>
|
||||
/// <param name="libraryId">The normalized Id of the media library.</param>
|
||||
/// <param name="bookId">The normalized Id of the book.</param>
|
||||
/// <returns>The expected upstream endpoint.</returns>
|
||||
private static string BuildExpectedEndpoint(Guid libraryId, Guid bookId)
|
||||
{
|
||||
return ApiRoutes.Books.DELETE_BOOK
|
||||
.Replace("{libraryId}", libraryId.ToString())
|
||||
.Replace("{bookId}", bookId.ToString());
|
||||
}
|
||||
}
|
||||
+183
@@ -0,0 +1,183 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using FastEndpoints;
|
||||
using Lumina.Presentation.Web.Common.Api;
|
||||
using Lumina.Presentation.Web.Common.DTO.Libraries;
|
||||
using Lumina.Presentation.Web.Common.DTO.Themes;
|
||||
using Lumina.Presentation.Web.Common.DTO.WrittenContentLibrary.BookLibrary;
|
||||
using Lumina.Presentation.Web.Common.Http;
|
||||
using Lumina.Presentation.Web.Common.Primitives;
|
||||
using Lumina.Presentation.Web.Common.Routes;
|
||||
using Lumina.Presentation.Web.Common.Services;
|
||||
using Lumina.Presentation.Web.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.Books.DeletedBooks;
|
||||
using Lumina.Presentation.Web.Core.Themes;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.DTO.Libraries;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.DTO.Themes;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.DTO.WrittenContentLibrary.BookLibrary;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.Requests.Library.WrittenContentLibrary.BookLibrary.Books;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.TestHelpers;
|
||||
using Microsoft.AspNetCore.Antiforgery;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using Microsoft.AspNetCore.Http.HttpResults;
|
||||
using Microsoft.Extensions.Localization;
|
||||
using NSubstitute;
|
||||
using System;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Reflection;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.UnitTests.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.Books.DeletedBooks;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="DeletedBooksViewEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class DeletedBooksViewEndpointTests
|
||||
{
|
||||
private readonly IApiHttpClient _mockApiHttpClient;
|
||||
private readonly IUrlService _mockUrlService;
|
||||
private readonly ThemePageRenderer _mockThemePageRenderer;
|
||||
private readonly IAntiforgery _mockAntiforgery;
|
||||
private readonly IStringLocalizerFactory _mockStringLocalizerFactory;
|
||||
private readonly IStringLocalizer _mockStringLocalizer;
|
||||
private readonly DeletedBooksViewEndpoint _sut;
|
||||
private readonly LibraryDtoFixture _libraryDtoFixture = new();
|
||||
private readonly DeletedBookDtoFixture _deletedBookDtoFixture = new();
|
||||
private readonly GetBooksViewRequestFixture _getBooksViewRequestFixture = new();
|
||||
private readonly ThemePageRenderResultDtoFixture _themePageRenderResultDtoFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="DeletedBooksViewEndpointTests"/> class.
|
||||
/// </summary>
|
||||
public DeletedBooksViewEndpointTests()
|
||||
{
|
||||
_mockApiHttpClient = Substitute.For<IApiHttpClient>();
|
||||
_mockUrlService = Substitute.For<IUrlService>();
|
||||
_mockThemePageRenderer = Substitute.For<ThemePageRenderer>(new ThemeService(_mockApiHttpClient), new ThemeTemplateEngine());
|
||||
_mockAntiforgery = Substitute.For<IAntiforgery>();
|
||||
_mockAntiforgery.GetAndStoreTokens(Arg.Any<HttpContext>())
|
||||
.Returns(new AntiforgeryTokenSet("request-token", "cookie-token", "__RequestVerificationToken", "RequestVerificationToken"));
|
||||
_mockStringLocalizer = Substitute.For<IStringLocalizer>();
|
||||
_mockStringLocalizer[Arg.Any<string>()].Returns(callInfo => new LocalizedString(
|
||||
callInfo.Arg<string>(),
|
||||
callInfo.Arg<string>() == "Title" ? "Deleted items" : $"Localized-{callInfo.Arg<string>()}"));
|
||||
_mockStringLocalizer.GetAllStrings(Arg.Any<bool>()).Returns(new LocalizedString[]
|
||||
{
|
||||
new("Title", "Deleted items"),
|
||||
new("NoDeletedItems", "There are no deleted items in this library.")
|
||||
});
|
||||
_mockStringLocalizerFactory = Substitute.For<IStringLocalizerFactory>();
|
||||
_mockStringLocalizerFactory.Create(Arg.Any<string>(), Arg.Any<string>()).Returns(_mockStringLocalizer);
|
||||
_sut = Factory.Create<DeletedBooksViewEndpoint>(_mockApiHttpClient, _mockUrlService, _mockThemePageRenderer, _mockAntiforgery, _mockStringLocalizerFactory);
|
||||
TestHttpContextFactory.ConfigureSession(_sut.HttpContext, TestHttpContextFactory.CreateSession());
|
||||
_sut.HttpContext.Request.Path = "/en-us/library/written-content-library/books-library/books/deleted-items";
|
||||
|
||||
StubUrls();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenThemeRenderingSucceeds_ShouldRenderThemedViewWithDocumentedPageData()
|
||||
{
|
||||
// Arrange
|
||||
LibraryDto library = _libraryDtoFixture.Create(title: "Books");
|
||||
DeletedBookDto[] deletedBooks = [.. _deletedBookDtoFixture.CreateMany(2)];
|
||||
_mockApiHttpClient.GetAsync<LibraryDto>(Arg.Any<string>(), Arg.Any<CancellationToken>()).Returns(library);
|
||||
_mockApiHttpClient.GetAsync<DeletedBookDto[]>(Arg.Any<string>(), Arg.Any<CancellationToken>()).Returns(deletedBooks);
|
||||
_mockThemePageRenderer.RenderAsync(Arg.Any<ThemePageDto>(), Arg.Any<string?>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From(_themePageRenderResultDtoFixture.Create(content: "<section>deleted</section>", script: "<script>deleted</script>")));
|
||||
|
||||
// Act
|
||||
IResult result = await _sut.ExecuteAsync(_getBooksViewRequestFixture.Create(libraryId: library.Id), CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.Equal("/Core/Views/Shared/_ThemedView.cshtml", GetRenderedViewName(result));
|
||||
await _mockThemePageRenderer.Received(1).RenderAsync(
|
||||
Arg.Is<ThemePageDto>(page =>
|
||||
page.PageKey == "library/written-content-library/book-library/books/deleted-items" &&
|
||||
page.Title == "Deleted items" &&
|
||||
string.Equals(page.PageData["libraryId"] as string, library.Id!.Value.ToString(), StringComparison.Ordinal) &&
|
||||
string.Equals(page.PageData["libraryTitle"] as string, "Books", StringComparison.Ordinal) &&
|
||||
string.Equals(page.PageData["restoreUrl"] as string, "http://localhost/en-us/library/written-content-library/books-library/books/00000000-0000-0000-0000-000000000000/api-restore-book", StringComparison.Ordinal) &&
|
||||
string.Equals(page.PageData["backUrl"] as string, $"http://localhost/en-us/library/written-content-library/books-library/books?libraryId={library.Id}", StringComparison.Ordinal) &&
|
||||
string.Equals(page.PageData["antiforgeryToken"] as string, "request-token", StringComparison.Ordinal) &&
|
||||
page.PageData.ContainsKey("deletedBooksJson") &&
|
||||
page.PageData.ContainsKey("strings") &&
|
||||
page.PageData.ContainsKey("stringsJson")),
|
||||
Arg.Is<string?>(requestedThemeId => requestedThemeId == null),
|
||||
Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenLibraryIdIsNull_ShouldRedirectToHome()
|
||||
{
|
||||
// Arrange
|
||||
_mockUrlService.GetAbsoluteUrl(WebRoutes.Home.INDEX_CULTURED).Returns("http://localhost/en-us");
|
||||
|
||||
// Act
|
||||
IResult result = await _sut.ExecuteAsync(_getBooksViewRequestFixture.Create(libraryId: null), CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
RedirectHttpResult redirectResult = Assert.IsType<RedirectHttpResult>(result);
|
||||
Assert.Equal("http://localhost/en-us", redirectResult.Url);
|
||||
await _mockApiHttpClient.DidNotReceive().GetAsync<LibraryDto>(Arg.Any<string>(), Arg.Any<CancellationToken>());
|
||||
await _mockThemePageRenderer.DidNotReceive().RenderAsync(Arg.Any<ThemePageDto>(), Arg.Any<string?>(), Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenThemeRenderingFails_ShouldFallBackToTheRazorViewWithTheDeletedBooks()
|
||||
{
|
||||
// Arrange
|
||||
LibraryDto library = _libraryDtoFixture.Create(title: "Books");
|
||||
DeletedBookDto[] deletedBooks = [.. _deletedBookDtoFixture.CreateMany(2)];
|
||||
_mockApiHttpClient.GetAsync<LibraryDto>(Arg.Any<string>(), Arg.Any<CancellationToken>()).Returns(library);
|
||||
_mockApiHttpClient.GetAsync<DeletedBookDto[]>(Arg.Any<string>(), Arg.Any<CancellationToken>()).Returns(deletedBooks);
|
||||
_mockThemePageRenderer.RenderAsync(Arg.Any<ThemePageDto>(), Arg.Any<string?>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result<ThemePageRenderResultDto>.Failure(Error.Failure("Theme.Render", "The page could not be rendered.")));
|
||||
|
||||
// Act
|
||||
IResult result = await _sut.ExecuteAsync(_getBooksViewRequestFixture.Create(libraryId: library.Id), CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.Equal("/Core/Views/Library/WrittenContentLibrary/BookLibrary/Books/DeletedItems.cshtml", GetRenderedViewName(result));
|
||||
DeletedBooksPageDto model = Assert.IsType<DeletedBooksPageDto>(GetRenderedModel(result));
|
||||
Assert.Equal(library.Id, model.Library.Id);
|
||||
Assert.Equal(deletedBooks, model.DeletedBooks);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Stubs the absolute URLs that the endpoint resolves for the deleted items page.
|
||||
/// </summary>
|
||||
private void StubUrls()
|
||||
{
|
||||
_mockUrlService.GetAbsoluteUrl(WebRoutes.Books.INDEX).Returns("http://localhost/en-us/library/written-content-library/books-library/books");
|
||||
_mockUrlService.GetAbsoluteUrl(WebRoutes.Books.RESTORE_BOOK, Arg.Any<object?>())
|
||||
.Returns("http://localhost/en-us/library/written-content-library/books-library/books/00000000-0000-0000-0000-000000000000/api-restore-book");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Reads the private view name of the rendered <see cref="RazorViewResult"/>, which the result does not expose publicly.
|
||||
/// </summary>
|
||||
/// <param name="result">The result returned by the endpoint under test.</param>
|
||||
/// <returns>The name or path of the rendered view.</returns>
|
||||
private static string GetRenderedViewName(IResult result)
|
||||
{
|
||||
RazorViewResult viewResult = Assert.IsType<RazorViewResult>(result);
|
||||
FieldInfo? viewNameField = typeof(RazorViewResult).GetField("_viewName", BindingFlags.Instance | BindingFlags.NonPublic);
|
||||
Assert.NotNull(viewNameField);
|
||||
return (string)viewNameField.GetValue(viewResult)!;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Reads the private model of the rendered <see cref="RazorViewResult"/>, which the result does not expose publicly.
|
||||
/// </summary>
|
||||
/// <param name="result">The result returned by the endpoint under test.</param>
|
||||
/// <returns>The model passed to the rendered view.</returns>
|
||||
private static object? GetRenderedModel(IResult result)
|
||||
{
|
||||
RazorViewResult viewResult = Assert.IsType<RazorViewResult>(result);
|
||||
FieldInfo? modelField = typeof(RazorViewResult).GetField("_model", BindingFlags.Instance | BindingFlags.NonPublic);
|
||||
Assert.NotNull(modelField);
|
||||
return modelField.GetValue(viewResult);
|
||||
}
|
||||
}
|
||||
+11
@@ -84,6 +84,8 @@ public class BooksIndexViewEndpointTests
|
||||
_mockUrlService.GetAbsoluteUrl(WebRoutes.Books.GET_LIBRARY_ITEMS).Returns("http://localhost/en-us/library/written-content-library/books-library/books/api-get-library-items");
|
||||
_mockUrlService.GetAbsoluteUrl(WebRoutes.Settings.GET_USER_SETTINGS).Returns("http://localhost/en-us/tools/settings/api-get-user-settings");
|
||||
_mockUrlService.GetAbsoluteUrl(WebRoutes.Books.READ, Arg.Any<object>()).Returns("http://localhost/en-us/library/written-content-library/books-library/books/00000000-0000-0000-0000-000000000000/read");
|
||||
_mockUrlService.GetAbsoluteUrl(WebRoutes.Books.DELETE_BOOK, Arg.Any<object>()).Returns("http://localhost/en-us/library/written-content-library/books-library/books/00000000-0000-0000-0000-000000000000/api-delete-book");
|
||||
_mockUrlService.GetAbsoluteUrl(WebRoutes.Books.DELETED_BOOKS).Returns("http://localhost/en-us/library/written-content-library/books-library/books/deleted-items");
|
||||
_mockThemePageRenderer.RenderAsync(Arg.Any<ThemePageDto>(), Arg.Any<string?>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From(_themePageRenderResultDtoFixture.Create(content: "<section>content</section>", script: "<script>script</script>")));
|
||||
|
||||
@@ -99,6 +101,7 @@ public class BooksIndexViewEndpointTests
|
||||
page.PageData.ContainsKey("libraryId") &&
|
||||
page.PageData.ContainsKey("settingsUrl") &&
|
||||
page.PageData.ContainsKey("strings") &&
|
||||
page.PageData.ContainsKey("stringsJson") &&
|
||||
string.Equals(
|
||||
page.PageData["itemsUrl"] as string,
|
||||
"http://localhost/en-us/library/written-content-library/books-library/books/api-get-library-items",
|
||||
@@ -106,6 +109,14 @@ public class BooksIndexViewEndpointTests
|
||||
string.Equals(
|
||||
page.PageData["readUrl"] as string,
|
||||
"http://localhost/en-us/library/written-content-library/books-library/books/00000000-0000-0000-0000-000000000000/read",
|
||||
StringComparison.Ordinal) &&
|
||||
string.Equals(
|
||||
page.PageData["deleteUrl"] as string,
|
||||
"http://localhost/en-us/library/written-content-library/books-library/books/00000000-0000-0000-0000-000000000000/api-delete-book",
|
||||
StringComparison.Ordinal) &&
|
||||
string.Equals(
|
||||
page.PageData["deletedBooksUrl"] as string,
|
||||
"http://localhost/en-us/library/written-content-library/books-library/books/deleted-items",
|
||||
StringComparison.Ordinal)),
|
||||
Arg.Is<string?>(requestedThemeId => requestedThemeId == null),
|
||||
Arg.Any<CancellationToken>());
|
||||
|
||||
+134
@@ -0,0 +1,134 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using FastEndpoints;
|
||||
using Lumina.Presentation.Web.Common.Api;
|
||||
using Lumina.Presentation.Web.Common.Routes;
|
||||
using Lumina.Presentation.Web.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.Books.RestoreBook;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.TestHelpers;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using NSubstitute;
|
||||
using System;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Text.Json;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.UnitTests.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.Books.RestoreBook;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="RestoreBookEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class RestoreBookEndpointTests
|
||||
{
|
||||
private readonly IApiHttpClient _mockApiHttpClient;
|
||||
private readonly RestoreBookEndpoint _sut;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="RestoreBookEndpointTests"/> class.
|
||||
/// </summary>
|
||||
public RestoreBookEndpointTests()
|
||||
{
|
||||
_mockApiHttpClient = Substitute.For<IApiHttpClient>();
|
||||
_sut = Factory.Create<RestoreBookEndpoint>(_mockApiHttpClient);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenCalled_ShouldRestoreBookViaApiAndReturnSuccessPayload()
|
||||
{
|
||||
// Arrange
|
||||
Guid bookId = Guid.NewGuid();
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
ConfigureRequest(bookId.ToString(), libraryId);
|
||||
_mockApiHttpClient.PostAsync<Web.Common.Requests.Common.EmptyRequest, Web.Common.Requests.Common.EmptyRequest>(
|
||||
Arg.Any<string>(), Arg.Any<Web.Common.Requests.Common.EmptyRequest>(), Arg.Any<CancellationToken>())
|
||||
.Returns(new Web.Common.Requests.Common.EmptyRequest());
|
||||
|
||||
// Act
|
||||
IResult result = await _sut.ExecuteAsync(EmptyRequest.Instance, CancellationToken.None);
|
||||
string body = await JsonResultTestHelper.GetResponseBodyAsync(result);
|
||||
|
||||
// Assert
|
||||
await _mockApiHttpClient.Received(1).PostAsync<Web.Common.Requests.Common.EmptyRequest, Web.Common.Requests.Common.EmptyRequest>(
|
||||
BuildExpectedEndpoint(libraryId, bookId),
|
||||
Arg.Any<Web.Common.Requests.Common.EmptyRequest>(),
|
||||
Arg.Any<CancellationToken>());
|
||||
using JsonDocument jsonDocument = JsonDocument.Parse(body);
|
||||
Assert.True(jsonDocument.RootElement.GetProperty("success").GetBoolean());
|
||||
Assert.True(jsonDocument.RootElement.GetProperty("data").GetProperty("isRestored").GetBoolean());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenBookIdIsNotParseable_ShouldForwardGuidEmptyBookIdToApi()
|
||||
{
|
||||
// Arrange
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
ConfigureRequest("not-a-guid", libraryId);
|
||||
_mockApiHttpClient.PostAsync<Web.Common.Requests.Common.EmptyRequest, Web.Common.Requests.Common.EmptyRequest>(
|
||||
Arg.Any<string>(), Arg.Any<Web.Common.Requests.Common.EmptyRequest>(), Arg.Any<CancellationToken>())
|
||||
.Returns(new Web.Common.Requests.Common.EmptyRequest());
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(EmptyRequest.Instance, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
await _mockApiHttpClient.Received(1).PostAsync<Web.Common.Requests.Common.EmptyRequest, Web.Common.Requests.Common.EmptyRequest>(
|
||||
BuildExpectedEndpoint(libraryId, Guid.Empty),
|
||||
Arg.Any<Web.Common.Requests.Common.EmptyRequest>(),
|
||||
Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenLibraryQueryIdIsNotParseable_ShouldForwardGuidEmptyLibraryIdToApi()
|
||||
{
|
||||
// Arrange
|
||||
Guid bookId = Guid.NewGuid();
|
||||
ConfigureRequest(bookId.ToString(), "not-a-guid");
|
||||
_mockApiHttpClient.PostAsync<Web.Common.Requests.Common.EmptyRequest, Web.Common.Requests.Common.EmptyRequest>(
|
||||
Arg.Any<string>(), Arg.Any<Web.Common.Requests.Common.EmptyRequest>(), Arg.Any<CancellationToken>())
|
||||
.Returns(new Web.Common.Requests.Common.EmptyRequest());
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(EmptyRequest.Instance, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
await _mockApiHttpClient.Received(1).PostAsync<Web.Common.Requests.Common.EmptyRequest, Web.Common.Requests.Common.EmptyRequest>(
|
||||
BuildExpectedEndpoint(Guid.Empty, bookId),
|
||||
Arg.Any<Web.Common.Requests.Common.EmptyRequest>(),
|
||||
Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Sets the route and query values the endpoint reads the book identity from.
|
||||
/// </summary>
|
||||
/// <param name="bookId">The raw route value of the book Id.</param>
|
||||
/// <param name="libraryId">The raw query value of the library Id.</param>
|
||||
private void ConfigureRequest(string bookId, Guid libraryId)
|
||||
{
|
||||
ConfigureRequest(bookId, libraryId.ToString());
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Sets the route and query values the endpoint reads the book identity from.
|
||||
/// </summary>
|
||||
/// <param name="bookId">The raw route value of the book Id.</param>
|
||||
/// <param name="libraryId">The raw query value of the library Id.</param>
|
||||
private void ConfigureRequest(string bookId, string libraryId)
|
||||
{
|
||||
_sut.HttpContext.Request.RouteValues["bookId"] = bookId;
|
||||
_sut.HttpContext.Request.QueryString = new QueryString($"?libraryId={libraryId}");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Builds the upstream endpoint the book restoration is expected to be sent to.
|
||||
/// </summary>
|
||||
/// <param name="libraryId">The normalized Id of the media library.</param>
|
||||
/// <param name="bookId">The normalized Id of the book.</param>
|
||||
/// <returns>The expected upstream endpoint.</returns>
|
||||
private static string BuildExpectedEndpoint(Guid libraryId, Guid bookId)
|
||||
{
|
||||
return ApiRoutes.Books.RESTORE_BOOK
|
||||
.Replace("{libraryId}", libraryId.ToString())
|
||||
.Replace("{bookId}", bookId.ToString());
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user