Adds pagination and filtering to the API

This commit is contained in:
BinaryAlley committed 2026-08-16 03:10:47 -07:00
1 parent ad984910a2
commit ce4ebf36bc
59 files changed
+4423 -242

No files matched your search

@@ -0,0 +1,25 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.Specifications;
using System;
using System.Diagnostics.CodeAnalysis;
using System.Linq.Expressions;
#endregion
namespace Lumina.Application.Fixtures.Common.Specifications;
/// <summary>
/// Fixture class for generating a <see cref="FilterSpecification{T}"/> instance that is never satisfied, regardless of the entity being evaluated.
/// </summary>
/// <typeparam name="T">The type of entity to which the specification applies.</typeparam>
[ExcludeFromCodeCoverage]
public sealed class AlwaysFalseFilterSpecificationFixture<T> : FilterSpecification<T>
{
/// <summary>
/// Creates a LINQ expression that always evaluates to <see langword="false"/>.
/// </summary>
/// <returns>An expression tree that always evaluates to <see langword="false"/>.</returns>
public override Expression<Func<T, bool>> ToExpression()
{
return entity => false;
}
}
@@ -0,0 +1,25 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.Specifications;
using System;
using System.Diagnostics.CodeAnalysis;
using System.Linq.Expressions;
#endregion
namespace Lumina.Application.Fixtures.Common.Specifications;
/// <summary>
/// Fixture class for generating a <see cref="FilterSpecification{T}"/> instance that is always satisfied, regardless of the entity being evaluated.
/// </summary>
/// <typeparam name="T">The type of entity to which the specification applies.</typeparam>
[ExcludeFromCodeCoverage]
public sealed class AlwaysTrueFilterSpecificationFixture<T> : FilterSpecification<T>
{
/// <summary>
/// Creates a LINQ expression that always evaluates to <see langword="true"/>.
/// </summary>
/// <returns>An expression tree that always evaluates to <see langword="true"/>.</returns>
public override Expression<Func<T, bool>> ToExpression()
{
return entity => true;
}
}
@@ -0,0 +1,36 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.Specifications;
using System;
using System.Diagnostics.CodeAnalysis;
using System.Linq.Expressions;
#endregion
namespace Lumina.Application.Fixtures.Common.Specifications;
/// <summary>
/// Fixture class for generating a <see cref="FilterSpecification{T}"/> instance that is satisfied when an integer value exceeds a configured threshold.
/// </summary>
[ExcludeFromCodeCoverage]
public sealed class GreaterThanFilterSpecificationFixture : FilterSpecification<int>
{
private readonly int _threshold;
/// <summary>
/// Initializes a new instance of the <see cref="GreaterThanFilterSpecificationFixture"/> class.
/// </summary>
/// <param name="threshold">The threshold value that an entity must exceed to satisfy the specification.</param>
public GreaterThanFilterSpecificationFixture(int threshold)
{
_threshold = threshold;
}
/// <summary>
/// Creates a LINQ expression that evaluates whether a value is greater than the configured threshold.
/// </summary>
/// <returns>An expression tree that evaluates to <see langword="true"/> when the value exceeds the threshold.</returns>
public override Expression<Func<int, bool>> ToExpression()
{
int threshold = _threshold;
return value => value > threshold;
}
}
@@ -0,0 +1,64 @@
#region ========================================================================= USING =====================================================================================
using Bogus;
using Lumina.Application.Common.DTO.Filtering;
using Lumina.Application.Common.DTO.Pagination;
using Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BooksLibrary.Books.Queries.GetBooks;
using Lumina.Domain.SharedKernel.Common.Enums.Common;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
#endregion
namespace Lumina.Application.Fixtures.Core.MediaLibrary.WrittenContentLibrary.BooksLibrary.Books.Queries.GetBooks;
/// <summary>
/// Fixture class for the <see cref="GetBooksQuery"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetBooksQueryFixture
{
private readonly Faker _faker = new();
/// <summary>
/// Creates a random valid query to get books.
/// </summary>
/// <param name="libraryId">Optional. The Id of the media library whose books are retrieved.</param>
/// <param name="paginationData">Optional. The pagination data of the query.</param>
/// <param name="searchTerm">Optional. The search term used to filter results.</param>
/// <param name="sortBy">Optional. The name of the field by which to sort the results.</param>
/// <param name="sortOrder">Optional. The direction in which to sort the results.</param>
/// <returns>The created query to get books.</returns>
public GetBooksQuery Create(
Guid? libraryId = null,
PaginationDataDto? paginationData = null,
string? searchTerm = null,
string? sortBy = null,
SortOrder? sortOrder = null)
{
return new GetBooksQuery(
paginationData ?? new PaginationDataDto
{
CurrentPage = _faker.Random.Number(1, 100),
PerPage = _faker.Random.Number(1, 200)
},
new LibraryFilterDto
{
LibraryId = libraryId ?? _faker.Random.Guid(),
SearchTerm = searchTerm
},
sortBy,
sortOrder ?? _faker.PickRandom<SortOrder>()
);
}
/// <summary>
/// Creates a list of <see cref="GetBooksQuery"/>.
/// </summary>
/// <param name="count">The number of elements to create.</param>
/// <returns>The created list.</returns>
public List<GetBooksQuery> CreateMany(int count = 3)
{
return [.. Enumerable.Range(0, count).Select(_ => Create())];
}
}
@@ -0,0 +1,64 @@
#region ========================================================================= USING =====================================================================================
using Bogus;
using Lumina.Application.Common.DTO.Filtering;
using Lumina.Application.Common.DTO.Pagination;
using Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BooksLibrary.Books.Queries.GetBooksLite;
using Lumina.Domain.SharedKernel.Common.Enums.Common;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
#endregion
namespace Lumina.Application.Fixtures.Core.MediaLibrary.WrittenContentLibrary.BooksLibrary.Books.Queries.GetBooksLite;
/// <summary>
/// Fixture class for the <see cref="GetBooksLiteQuery"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetBooksLiteQueryFixture
{
private readonly Faker _faker = new();
/// <summary>
/// Creates a random valid query to get the lightweight details of books.
/// </summary>
/// <param name="libraryId">Optional. The Id of the media library whose books are retrieved.</param>
/// <param name="paginationData">Optional. The pagination data of the query.</param>
/// <param name="searchTerm">Optional. The search term used to filter results.</param>
/// <param name="sortBy">Optional. The name of the field by which to sort the results.</param>
/// <param name="sortOrder">Optional. The direction in which to sort the results.</param>
/// <returns>The created query to get the lightweight details of books.</returns>
public GetBooksLiteQuery Create(
Guid? libraryId = null,
PaginationDataDto? paginationData = null,
string? searchTerm = null,
string? sortBy = null,
SortOrder? sortOrder = null)
{
return new GetBooksLiteQuery(
paginationData ?? new PaginationDataDto
{
CurrentPage = _faker.Random.Number(1, 100),
PerPage = _faker.Random.Number(1, 200)
},
new LibraryFilterDto
{
LibraryId = libraryId ?? _faker.Random.Guid(),
SearchTerm = searchTerm
},
sortBy,
sortOrder ?? _faker.PickRandom<SortOrder>()
);
}
/// <summary>
/// Creates a list of <see cref="GetBooksLiteQuery"/>.
/// </summary>
/// <param name="count">The number of elements to create.</param>
/// <returns>The created list.</returns>
public List<GetBooksLiteQuery> CreateMany(int count = 3)
{
return [.. Enumerable.Range(0, count).Select(_ => Create())];
}
}
@@ -0,0 +1,58 @@
#region ========================================================================= USING =====================================================================================
using Bogus;
using Lumina.Contracts.Requests.MediaLibrary.WrittenContentLibrary.BookLibrary.Books;
using Lumina.Domain.SharedKernel.Common.Enums.Common;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
#endregion
namespace Lumina.Contracts.Fixtures.Core.Requests.MediaLibrary.WrittenContentLibrary.BookLibrary.Books;
/// <summary>
/// Fixture class for the <see cref="GetBooksLiteRequest"/> record.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetBooksLiteRequestFixture
{
private readonly Faker _faker = new();
/// <summary>
/// Creates a <see cref="GetBooksLiteRequest"/> with default or random values.
/// </summary>
/// <param name="libraryId">Optional. The Id of the media library whose books are retrieved.</param>
/// <param name="currentPage">Optional. The page of results to retrieve.</param>
/// <param name="perPage">Optional. The maximum number of books to retrieve per page.</param>
/// <param name="searchTerm">Optional. The search term used to filter results.</param>
/// <param name="sortBy">Optional. The name of the field by which to sort the results.</param>
/// <param name="sortOrder">Optional. The direction in which to sort the results.</param>
/// <returns>The created <see cref="GetBooksLiteRequest"/>.</returns>
public GetBooksLiteRequest Create(
Guid? libraryId = null,
int? currentPage = null,
int? perPage = null,
string? searchTerm = null,
string? sortBy = null,
SortOrder? sortOrder = null)
{
return new GetBooksLiteRequest(
LibraryId: libraryId ?? _faker.Random.Guid(),
CurrentPage: currentPage ?? _faker.Random.Number(1, 100),
PerPage: perPage ?? _faker.Random.Number(1, 200),
SearchTerm: searchTerm ?? _faker.Lorem.Word(),
SortBy: sortBy ?? _faker.Lorem.Word(),
SortOrder: sortOrder ?? _faker.PickRandom<SortOrder>()
);
}
/// <summary>
/// Creates a list of <see cref="GetBooksLiteRequest"/>.
/// </summary>
/// <param name="count">The number of elements to create.</param>
/// <returns>The created list.</returns>
public List<GetBooksLiteRequest> CreateMany(int count = 3)
{
return [.. Enumerable.Range(0, count).Select(_ => Create())];
}
}
@@ -0,0 +1,58 @@
#region ========================================================================= USING =====================================================================================
using Bogus;
using Lumina.Contracts.Requests.MediaLibrary.WrittenContentLibrary.BookLibrary.Books;
using Lumina.Domain.SharedKernel.Common.Enums.Common;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
#endregion
namespace Lumina.Contracts.Fixtures.Core.Requests.MediaLibrary.WrittenContentLibrary.BookLibrary.Books;
/// <summary>
/// Fixture class for the <see cref="GetBooksRequest"/> record.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetBooksRequestFixture
{
private readonly Faker _faker = new();
/// <summary>
/// Creates a <see cref="GetBooksRequest"/> with default or random values.
/// </summary>
/// <param name="libraryId">Optional. The Id of the media library whose books are retrieved.</param>
/// <param name="currentPage">Optional. The page of results to retrieve.</param>
/// <param name="perPage">Optional. The maximum number of books to retrieve per page.</param>
/// <param name="searchTerm">Optional. The search term used to filter results.</param>
/// <param name="sortBy">Optional. The name of the field by which to sort the results.</param>
/// <param name="sortOrder">Optional. The direction in which to sort the results.</param>
/// <returns>The created <see cref="GetBooksRequest"/>.</returns>
public GetBooksRequest Create(
Guid? libraryId = null,
int? currentPage = null,
int? perPage = null,
string? searchTerm = null,
string? sortBy = null,
SortOrder? sortOrder = null)
{
return new GetBooksRequest(
LibraryId: libraryId ?? _faker.Random.Guid(),
CurrentPage: currentPage ?? _faker.Random.Number(1, 100),
PerPage: perPage ?? _faker.Random.Number(1, 200),
SearchTerm: searchTerm ?? _faker.Lorem.Word(),
SortBy: sortBy ?? _faker.Lorem.Word(),
SortOrder: sortOrder ?? _faker.PickRandom<SortOrder>()
);
}
/// <summary>
/// Creates a list of <see cref="GetBooksRequest"/>.
/// </summary>
/// <param name="count">The number of elements to create.</param>
/// <returns>The created list.</returns>
public List<GetBooksRequest> CreateMany(int count = 3)
{
return [.. Enumerable.Range(0, count).Select(_ => Create())];
}
}
@@ -1,9 +1,19 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Domain.Core.BoundedContexts.WrittenContentLibraryBoundedContext.BookLibraryAggregate;
using Lumina.Application.Common.DataAccess.Entities.Common;
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management;
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary;
using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
using Lumina.Contracts.Responses.Common;
using Lumina.Contracts.Responses.MediaLibrary.WrittenContentLibrary.BookLibrary.Books;
using Lumina.DataAccess.Core.UoW;
using Lumina.Domain.SharedKernel.Common.Enums.BookLibrary;
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
using Lumina.Presentation.Api.IntegrationTests.Common.Setup;
using Microsoft.AspNetCore.Http;
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;
@@ -25,7 +35,6 @@ public class GetBooksEndpointTests : IClassFixture<AuthenticatedLuminaApiFactory
private readonly AuthenticatedLuminaApiFactory _apiFactory;
private readonly JsonSerializerOptions _jsonOptions = new()
{
ReferenceHandler = ReferenceHandler.Preserve,
PropertyNameCaseInsensitive = true,
Converters = { new JsonStringEnumConverter(JsonNamingPolicy.CamelCase) }
};
@@ -49,30 +58,112 @@ public class GetBooksEndpointTests : IClassFixture<AuthenticatedLuminaApiFactory
}
[Fact]
public async Task GetBooks_WhenCalled_ShouldReturnBooks()
public async Task GetBooks_WhenCalledWithoutPaginationData_ShouldReturnAllBooks()
{
// Arrange
HttpResponseMessage response = await _client.GetAsync("/api/v1/books");
Guid userId = GetCurrentUserId();
Guid libraryId = Guid.NewGuid();
await SeedLibraryAsync(libraryId, userId);
await SeedBookAsync(libraryId, "Book A");
await SeedBookAsync(libraryId, "Book B");
// Act
response.EnsureSuccessStatusCode();
HttpResponseMessage response = await _client.GetAsync($"/api/v1/books?libraryId={libraryId}");
// Assert
response.EnsureSuccessStatusCode();
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
Book[]? bookResponse = await response.Content.ReadFromJsonAsync<Book[]>(_jsonOptions);
Assert.NotNull(bookResponse);
PaginatedResponse<BookResponse>? paginatedBooks = await response.Content.ReadFromJsonAsync<PaginatedResponse<BookResponse>>(_jsonOptions);
Assert.NotNull(paginatedBooks);
Assert.Equal(2, paginatedBooks!.Count);
Assert.Equal(2, paginatedBooks.Data.Count);
Assert.Equal(1, paginatedBooks.CurrentPage);
Assert.Equal(2, paginatedBooks.PerPage);
Assert.Equal(1, paginatedBooks.NumberOfPages);
Assert.Contains(paginatedBooks.Data, book => book.Metadata.Title == "Book A");
Assert.Contains(paginatedBooks.Data, book => book.Metadata.Title == "Book B");
}
[Fact]
public async Task GetBooks_WhenCalledWithSearchTerm_ShouldReturnOnlyMatchingBooks()
{
// Arrange
Guid userId = GetCurrentUserId();
Guid libraryId = Guid.NewGuid();
await SeedLibraryAsync(libraryId, userId);
await SeedBookAsync(libraryId, "The Fellowship of the Ring");
await SeedBookAsync(libraryId, "The Two Towers");
// Act
HttpResponseMessage response = await _client.GetAsync($"/api/v1/books?libraryId={libraryId}&searchTerm={Uri.EscapeDataString("Fellowship")}");
// Assert
response.EnsureSuccessStatusCode();
PaginatedResponse<BookResponse>? paginatedBooks = await response.Content.ReadFromJsonAsync<PaginatedResponse<BookResponse>>(_jsonOptions);
Assert.NotNull(paginatedBooks);
BookResponse book = Assert.Single(paginatedBooks!.Data);
Assert.Equal("The Fellowship of the Ring", book.Metadata.Title);
Assert.Equal(1, paginatedBooks.Count);
}
[Fact]
public async Task GetBooks_WhenCalledWithPaginationData_ShouldReturnRequestedPage()
{
// Arrange
Guid userId = GetCurrentUserId();
Guid libraryId = Guid.NewGuid();
await SeedLibraryAsync(libraryId, userId);
await SeedBookAsync(libraryId, "Book A");
await SeedBookAsync(libraryId, "Book B");
await SeedBookAsync(libraryId, "Book C");
// Act
HttpResponseMessage response = await _client.GetAsync($"/api/v1/books?libraryId={libraryId}&currentPage=2&perPage=2");
// Assert
response.EnsureSuccessStatusCode();
PaginatedResponse<BookResponse>? paginatedBooks = await response.Content.ReadFromJsonAsync<PaginatedResponse<BookResponse>>(_jsonOptions);
Assert.NotNull(paginatedBooks);
Assert.Equal(3, paginatedBooks!.Count);
Assert.Equal(2, paginatedBooks.NumberOfPages);
Assert.Equal(2, paginatedBooks.CurrentPage);
Assert.Equal(2, paginatedBooks.PerPage);
BookResponse book = Assert.Single(paginatedBooks.Data);
Assert.Equal("Book C", book.Metadata.Title);
}
[Fact]
public async Task GetBooks_WhenNoBooksExist_ShouldReturnEmptyPaginatedResponse()
{
// Arrange
Guid userId = GetCurrentUserId();
Guid libraryId = Guid.NewGuid();
await SeedLibraryAsync(libraryId, userId);
// Act
HttpResponseMessage response = await _client.GetAsync($"/api/v1/books?libraryId={libraryId}");
// Assert
response.EnsureSuccessStatusCode();
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
PaginatedResponse<BookResponse>? paginatedBooks = await response.Content.ReadFromJsonAsync<PaginatedResponse<BookResponse>>(_jsonOptions);
Assert.NotNull(paginatedBooks);
Assert.Empty(paginatedBooks!.Data);
Assert.Equal(0, paginatedBooks.Count);
}
[Fact]
public async Task GetBooks_WhenCalledWithCancellationToken_ShouldCompleteSuccessfully()
{
// Arrange
Guid userId = GetCurrentUserId();
Guid libraryId = Guid.NewGuid();
await SeedLibraryAsync(libraryId, userId);
using CancellationTokenSource cts = new(TimeSpan.FromSeconds(5));
// Act & Assert
Exception? exception = await Record.ExceptionAsync(async () =>
await _client.GetAsync($"/api/v1/books", cts.Token)
await _client.GetAsync($"/api/v1/books?libraryId={libraryId}", cts.Token)
);
Assert.Null(exception);
}
@@ -81,17 +172,183 @@ public class GetBooksEndpointTests : IClassFixture<AuthenticatedLuminaApiFactory
public async Task GetBooks_WhenCancellationTokenIsCanceled_ShouldThrowTaskCanceledException()
{
// Arrange
Guid userId = GetCurrentUserId();
Guid libraryId = Guid.NewGuid();
await SeedLibraryAsync(libraryId, userId);
using CancellationTokenSource cts = new();
// Act & Assert
Exception? exception = await Record.ExceptionAsync(async () =>
{
cts.Cancel();
await _client.GetAsync($"/api/v1/books", cts.Token);
await _client.GetAsync($"/api/v1/books?libraryId={libraryId}", cts.Token);
});
Assert.IsType<TaskCanceledException>(exception);
}
[Fact]
public async Task GetBooks_WhenLibraryBelongsToAnotherUser_ShouldReturnForbidden()
{
// Arrange
Guid otherUserId = await SeedUserAsync();
Guid libraryId = Guid.NewGuid();
await SeedLibraryAsync(libraryId, otherUserId);
await SeedBookAsync(libraryId, "Book A");
// Act
HttpResponseMessage response = await _client.GetAsync($"/api/v1/books?libraryId={libraryId}");
// Assert
Assert.Equal(HttpStatusCode.Forbidden, response.StatusCode);
}
[Fact]
public async Task GetBooks_WhenLibraryDoesNotExist_ShouldReturnForbidden()
{
// Arrange
Guid libraryId = Guid.NewGuid();
// Act
HttpResponseMessage response = await _client.GetAsync($"/api/v1/books?libraryId={libraryId}");
// Assert
Assert.Equal(HttpStatusCode.Forbidden, response.StatusCode);
}
[Fact]
public async Task GetBooks_WhenCalledByAdmin_ShouldReturnBooksOfAnyLibrary()
{
// Arrange
HttpClient adminClient = await _apiFactory.CreateAuthenticatedAdminClientAsync();
Guid otherUserId = await SeedUserAsync();
Guid libraryId = Guid.NewGuid();
await SeedLibraryAsync(libraryId, otherUserId);
await SeedBookAsync(libraryId, "Book A");
// Act
HttpResponseMessage response = await adminClient.GetAsync($"/api/v1/books?libraryId={libraryId}");
// Assert
response.EnsureSuccessStatusCode();
PaginatedResponse<BookResponse>? paginatedBooks = await response.Content.ReadFromJsonAsync<PaginatedResponse<BookResponse>>(_jsonOptions);
Assert.NotNull(paginatedBooks);
Assert.Equal(1, paginatedBooks!.Count);
}
[Fact]
public async Task GetBooks_WhenBooksHaveTagsGenresIsbnsAndRatings_ShouldReturnThemInTheResponse()
{
// Arrange
Guid userId = GetCurrentUserId();
Guid libraryId = Guid.NewGuid();
await SeedLibraryAsync(libraryId, userId);
BookEntity seededBook = await SeedBookAsync(libraryId, "Tags And Ratings Book");
// Act
HttpResponseMessage response = await _client.GetAsync($"/api/v1/books?libraryId={libraryId}");
// Assert
response.EnsureSuccessStatusCode();
PaginatedResponse<BookResponse>? paginatedBooks = await response.Content.ReadFromJsonAsync<PaginatedResponse<BookResponse>>(_jsonOptions);
Assert.NotNull(paginatedBooks);
BookResponse book = Assert.Single(paginatedBooks!.Data);
Assert.Equal(seededBook.Title, book.Metadata.Title);
Assert.Equal(seededBook.Tags.Select(tag => tag.Name), book.Metadata.Tags.Select(tag => tag.Name));
Assert.Equal(seededBook.Genres.Select(genre => genre.Name), book.Metadata.Genres.Select(genre => genre.Name));
Assert.Equal(seededBook.ISBNs.Select(isbn => isbn.Value), book.ISBNs.Select(isbn => isbn.Value));
Assert.Equal(seededBook.Ratings.Select(rating => rating.Value), book.Ratings.Select(rating => rating.Value));
Assert.Equal(seededBook.Ratings.Single().Source, book.Ratings.Single().Source);
}
/// <summary>
/// Seeds a <see cref="BookEntity"/> belonging to the media library identified by <paramref name="libraryId"/>.
/// </summary>
/// <param name="libraryId">The Id of the media library the book belongs to.</param>
/// <param name="title">The title of the book.</param>
/// <returns>The seeded book entity.</returns>
private async Task<BookEntity> SeedBookAsync(Guid libraryId, string title)
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
BookEntity book = new()
{
Id = Guid.NewGuid(),
LibraryId = libraryId,
Path = $"/books/{Guid.NewGuid()}.epub",
Title = title,
Tags = [new TagEntity($"Tag-{Guid.NewGuid()}")],
Genres = [new GenreEntity($"Genre-{Guid.NewGuid()}")],
ISBNs = [new IsbnEntity("9780395272237", IsbnFormat.Isbn13)],
Ratings = [new BookRatingEntity(4.5M, 5, BookRatingSource.Goodreads, 100)],
CreatedBy = Guid.NewGuid(),
CreatedOnUtc = DateTime.UtcNow,
UpdatedBy = null
};
dbContext.Books.Add(book);
await dbContext.SaveChangesAsync();
return book;
}
/// <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>
/// Seeds a <see cref="LibraryEntity"/> owned by <paramref name="userId"/>.
/// </summary>
/// <param name="libraryId">The Id of the library to seed.</param>
/// <param name="userId">The Id of the user that owns the library.</param>
/// <returns>A task representing the asynchronous operation.</returns>
private async Task SeedLibraryAsync(Guid libraryId, Guid userId)
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
dbContext.Libraries.Add(new LibraryEntity
{
Id = libraryId,
UserId = userId,
Title = "Test Library",
LibraryType = LibraryType.EBook,
ContentLocations = [],
CreatedBy = userId,
CreatedOnUtc = DateTime.UtcNow,
UpdatedBy = null
});
await dbContext.SaveChangesAsync();
}
/// <summary>
/// Seeds a <see cref="UserEntity"/> and returns its Id.
/// </summary>
/// <returns>The Id of the seeded user.</returns>
private async Task<Guid> SeedUserAsync()
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
Guid userId = Guid.NewGuid();
dbContext.Users.Add(new UserEntity
{
Id = userId,
Username = $"otheruser_{Guid.NewGuid()}",
Password = "TestPass123!",
Libraries = [],
UserPermissions = [],
UserRole = null,
CreatedBy = userId,
CreatedOnUtc = DateTime.UtcNow
});
await dbContext.SaveChangesAsync();
return userId;
}
/// <summary>
/// Disposes API factory resources.
/// </summary>
@@ -0,0 +1,293 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management;
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary;
using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
using Lumina.Contracts.Responses.Common;
using Lumina.Contracts.Responses.MediaLibrary.WrittenContentLibrary.BookLibrary.Books;
using Lumina.DataAccess.Core.UoW;
using Lumina.Presentation.Api.IntegrationTests.Common.Setup;
using Microsoft.AspNetCore.Http;
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.Text.Json.Serialization;
using System.Threading;
using System.Threading.Tasks;
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
#endregion
namespace Lumina.Presentation.Api.IntegrationTests.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.Books.GetBooksLite;
/// <summary>
/// Contains integration tests for the <see cref="GetBooksLiteEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetBooksLiteEndpointTests : IClassFixture<AuthenticatedLuminaApiFactory>, IAsyncLifetime
{
private HttpClient _client;
private readonly AuthenticatedLuminaApiFactory _apiFactory;
private readonly JsonSerializerOptions _jsonOptions = new()
{
PropertyNameCaseInsensitive = true,
Converters = { new JsonStringEnumConverter(JsonNamingPolicy.CamelCase) }
};
/// <summary>
/// Initializes a new instance of the <see cref="GetBooksLiteEndpointTests"/> class.
/// </summary>
/// <param name="apiFactory">Injected in-memory API factory.</param>
public GetBooksLiteEndpointTests(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 GetBooksLite_WhenCalledWithoutPaginationData_ShouldReturnAllBooks()
{
// Arrange
Guid userId = GetCurrentUserId();
Guid libraryId = Guid.NewGuid();
await SeedLibraryAsync(libraryId, userId);
await SeedBookAsync(libraryId, "Book A");
await SeedBookAsync(libraryId, "Book B");
// Act
HttpResponseMessage response = await _client.GetAsync($"/api/v1/books/lite?libraryId={libraryId}");
// Assert
response.EnsureSuccessStatusCode();
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
PaginatedResponse<BookLiteResponse>? paginatedBooks = await response.Content.ReadFromJsonAsync<PaginatedResponse<BookLiteResponse>>(_jsonOptions);
Assert.NotNull(paginatedBooks);
Assert.Equal(2, paginatedBooks!.Count);
Assert.Equal(2, paginatedBooks.Data.Count());
Assert.Equal(1, paginatedBooks.CurrentPage);
Assert.Equal(2, paginatedBooks.PerPage);
Assert.Equal(1, paginatedBooks.NumberOfPages);
Assert.Contains(paginatedBooks.Data, book => book.Title == "Book A");
Assert.Contains(paginatedBooks.Data, book => book.Title == "Book B");
}
[Fact]
public async Task GetBooksLite_WhenCalledWithSearchTerm_ShouldReturnOnlyMatchingBooks()
{
// Arrange
Guid userId = GetCurrentUserId();
Guid libraryId = Guid.NewGuid();
await SeedLibraryAsync(libraryId, userId);
await SeedBookAsync(libraryId, "The Fellowship of the Ring");
await SeedBookAsync(libraryId, "The Two Towers");
// Act
HttpResponseMessage response = await _client.GetAsync($"/api/v1/books/lite?libraryId={libraryId}&searchTerm={Uri.EscapeDataString("Fellowship")}");
// Assert
response.EnsureSuccessStatusCode();
PaginatedResponse<BookLiteResponse>? paginatedBooks = await response.Content.ReadFromJsonAsync<PaginatedResponse<BookLiteResponse>>(_jsonOptions);
Assert.NotNull(paginatedBooks);
BookLiteResponse book = Assert.Single(paginatedBooks!.Data);
Assert.Equal("The Fellowship of the Ring", book.Title);
Assert.Equal(1, paginatedBooks.Count);
}
[Fact]
public async Task GetBooksLite_WhenCalledWithPaginationData_ShouldReturnRequestedPage()
{
// Arrange
Guid userId = GetCurrentUserId();
Guid libraryId = Guid.NewGuid();
await SeedLibraryAsync(libraryId, userId);
await SeedBookAsync(libraryId, "Book A");
await SeedBookAsync(libraryId, "Book B");
await SeedBookAsync(libraryId, "Book C");
// Act
HttpResponseMessage response = await _client.GetAsync($"/api/v1/books/lite?libraryId={libraryId}&currentPage=2&perPage=2");
// Assert
response.EnsureSuccessStatusCode();
PaginatedResponse<BookLiteResponse>? paginatedBooks = await response.Content.ReadFromJsonAsync<PaginatedResponse<BookLiteResponse>>(_jsonOptions);
Assert.NotNull(paginatedBooks);
Assert.Equal(3, paginatedBooks!.Count);
Assert.Equal(2, paginatedBooks.NumberOfPages);
Assert.Equal(2, paginatedBooks.CurrentPage);
Assert.Equal(2, paginatedBooks.PerPage);
BookLiteResponse book = Assert.Single(paginatedBooks.Data);
Assert.Equal("Book C", book.Title);
}
[Fact]
public async Task GetBooksLite_WhenNoBooksExist_ShouldReturnEmptyPaginatedResponse()
{
// Arrange
Guid userId = GetCurrentUserId();
Guid libraryId = Guid.NewGuid();
await SeedLibraryAsync(libraryId, userId);
// Act
HttpResponseMessage response = await _client.GetAsync($"/api/v1/books/lite?libraryId={libraryId}");
// Assert
response.EnsureSuccessStatusCode();
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
PaginatedResponse<BookLiteResponse>? paginatedBooks = await response.Content.ReadFromJsonAsync<PaginatedResponse<BookLiteResponse>>(_jsonOptions);
Assert.NotNull(paginatedBooks);
Assert.Empty(paginatedBooks!.Data);
Assert.Equal(0, paginatedBooks.Count);
}
[Fact]
public async Task GetBooksLite_WhenLibraryBelongsToAnotherUser_ShouldReturnForbidden()
{
// Arrange
Guid otherUserId = await SeedUserAsync();
Guid libraryId = Guid.NewGuid();
await SeedLibraryAsync(libraryId, otherUserId);
await SeedBookAsync(libraryId, "Book A");
// Act
HttpResponseMessage response = await _client.GetAsync($"/api/v1/books/lite?libraryId={libraryId}");
// Assert
Assert.Equal(HttpStatusCode.Forbidden, response.StatusCode);
}
[Fact]
public async Task GetBooksLite_WhenLibraryDoesNotExist_ShouldReturnForbidden()
{
// Arrange
Guid libraryId = Guid.NewGuid();
// Act
HttpResponseMessage response = await _client.GetAsync($"/api/v1/books/lite?libraryId={libraryId}");
// Assert
Assert.Equal(HttpStatusCode.Forbidden, response.StatusCode);
}
[Fact]
public async Task GetBooksLite_WhenCalledByAdmin_ShouldReturnBooksOfAnyLibrary()
{
// Arrange
HttpClient adminClient = await _apiFactory.CreateAuthenticatedAdminClientAsync();
Guid otherUserId = await SeedUserAsync();
Guid libraryId = Guid.NewGuid();
await SeedLibraryAsync(libraryId, otherUserId);
await SeedBookAsync(libraryId, "Book A");
// Act
HttpResponseMessage response = await adminClient.GetAsync($"/api/v1/books/lite?libraryId={libraryId}");
// Assert
response.EnsureSuccessStatusCode();
PaginatedResponse<BookLiteResponse>? paginatedBooks = await response.Content.ReadFromJsonAsync<PaginatedResponse<BookLiteResponse>>(_jsonOptions);
Assert.NotNull(paginatedBooks);
Assert.Equal(1, paginatedBooks!.Count);
}
/// <summary>
/// Seeds a <see cref="BookEntity"/> belonging to the media library identified by <paramref name="libraryId"/>.
/// </summary>
/// <param name="libraryId">The Id of the media library the book belongs to.</param>
/// <param name="title">The title of the book.</param>
/// <returns>A task representing the asynchronous operation.</returns>
private async Task SeedBookAsync(Guid libraryId, string title)
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
dbContext.Books.Add(new BookEntity
{
Id = Guid.NewGuid(),
LibraryId = libraryId,
Path = $"/books/{Guid.NewGuid()}.epub",
Title = title,
CreatedBy = Guid.NewGuid(),
CreatedOnUtc = DateTime.UtcNow,
UpdatedBy = null
});
await dbContext.SaveChangesAsync();
}
/// <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>
/// Seeds a <see cref="LibraryEntity"/> owned by <paramref name="userId"/>.
/// </summary>
/// <param name="libraryId">The Id of the library to seed.</param>
/// <param name="userId">The Id of the user that owns the library.</param>
/// <returns>A task representing the asynchronous operation.</returns>
private async Task SeedLibraryAsync(Guid libraryId, Guid userId)
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
dbContext.Libraries.Add(new LibraryEntity
{
Id = libraryId,
UserId = userId,
Title = "Test Library",
LibraryType = LibraryType.EBook,
ContentLocations = [],
CreatedBy = userId,
CreatedOnUtc = DateTime.UtcNow,
UpdatedBy = null
});
await dbContext.SaveChangesAsync();
}
/// <summary>
/// Seeds a <see cref="UserEntity"/> and returns its Id.
/// </summary>
/// <returns>The Id of the seeded user.</returns>
private async Task<Guid> SeedUserAsync()
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
Guid userId = Guid.NewGuid();
dbContext.Users.Add(new UserEntity
{
Id = userId,
Username = $"otheruser_{Guid.NewGuid()}",
Password = "TestPass123!",
Libraries = [],
UserPermissions = [],
UserRole = null,
CreatedBy = userId,
CreatedOnUtc = DateTime.UtcNow
});
await dbContext.SaveChangesAsync();
return userId;
}
/// <summary>
/// Disposes API factory resources.
/// </summary>
public Task DisposeAsync()
{
_apiFactory.Dispose();
return Task.CompletedTask;
}
}
@@ -0,0 +1,169 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management;
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary;
using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
using Lumina.Contracts.Requests.Authentication;
using Lumina.Contracts.Responses.Authentication;
using Lumina.DataAccess.Core.UoW;
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
using Lumina.Infrastructure.Core.Security;
using Lumina.Presentation.Api.SecurityTests.Common.Setup;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;
using System.Diagnostics.CodeAnalysis;
using System.Net;
using System.Net.Http.Headers;
using System.Net.Http.Json;
using System.Text.Json;
#endregion
namespace Lumina.Presentation.Api.SecurityTests.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.Books.GetBooks;
/// <summary>
/// Contains security tests for the <c>/books</c> route.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetBooksEndpointTests : IClassFixture<LuminaApiFactory>
{
private readonly HttpClient _client;
private readonly LuminaApiFactory _apiFactory;
private readonly PasswordHashService _hashService = new();
private readonly JsonSerializerOptions _jsonOptions = new()
{
PropertyNameCaseInsensitive = true
};
/// <summary>
/// Initializes a new instance of the <see cref="GetBooksEndpointTests"/> class.
/// </summary>
/// <param name="apiFactory">Injected in-memory API factory.</param>
public GetBooksEndpointTests(LuminaApiFactory apiFactory)
{
_apiFactory = apiFactory;
_client = apiFactory.CreateClient();
}
[Fact]
public async Task GetBooks_WhenUnauthorized_ShouldReturnUnauthorizedResult()
{
// Act
HttpResponseMessage response = await _client.GetAsync("/api/v1/books");
// Assert
Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode);
string content = await response.Content.ReadAsStringAsync();
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
Assert.NotNull(problemDetails);
Assert.Equal(StatusCodes.Status401Unauthorized, problemDetails!["status"].GetInt32());
Assert.Equal("https://tools.ietf.org/html/rfc7235#section-3.1", problemDetails["type"].GetString());
Assert.Equal("Unauthorized", problemDetails["title"].GetString());
Assert.Equal("/api/v1/books", problemDetails["instance"].GetProperty("value").GetString());
Assert.Equal("Authentication failed", problemDetails["detail"].GetString());
}
[Theory]
[InlineData("' OR '1'='1")] // basic SQL injection
[InlineData("'; DROP TABLE Books--")] // destructive injection
public async Task GetBooks_WhenSearchTermContainsSqlInjection_ShouldNotLeakOrError(string maliciousSearchTerm)
{
// Arrange
HttpClient client = _apiFactory.CreateClient();
Guid userId = await CreateAndAuthenticateUserAsync(client);
Guid libraryId = Guid.NewGuid();
await SeedLibraryAsync(libraryId, userId);
await SeedBookAsync(libraryId, "Book A");
// Act
HttpResponseMessage response = await client.GetAsync($"/api/v1/books?libraryId={libraryId}&searchTerm={Uri.EscapeDataString(maliciousSearchTerm)}");
// Assert
response.EnsureSuccessStatusCode();
string content = await response.Content.ReadAsStringAsync();
Assert.DoesNotContain("SQL", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
}
/// <summary>
/// Creates a test user, authenticates it on <paramref name="client"/>, and returns its Id.
/// </summary>
/// <param name="client">The HTTP client to authenticate.</param>
/// <returns>The Id of the created test user.</returns>
private async Task<Guid> CreateAndAuthenticateUserAsync(HttpClient client)
{
client.DefaultRequestHeaders.Clear();
client.DefaultRequestHeaders.Add("X-Forwarded-For", $"192.168.1.{Random.Shared.Next(1, 255)}");
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
Guid userId = Guid.NewGuid();
string username = $"testuser_{Guid.NewGuid()}";
dbContext.Users.Add(new UserEntity
{
Id = userId,
Username = username,
Password = _hashService.HashString("TestPass123!"),
Libraries = [],
UserPermissions = [],
UserRole = null,
CreatedBy = userId,
CreatedOnUtc = DateTime.UtcNow
});
await dbContext.SaveChangesAsync();
HttpResponseMessage loginResponse = await client.PostAsJsonAsync("/api/v1/auth/login", new LoginRequest(username, "TestPass123!"));
string content = await loginResponse.Content.ReadAsStringAsync();
LoginResponse? loginResult = JsonSerializer.Deserialize<LoginResponse>(content, _jsonOptions);
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", loginResult!.Token);
return userId;
}
/// <summary>
/// Seeds a <see cref="LibraryEntity"/> owned by <paramref name="userId"/>.
/// </summary>
/// <param name="libraryId">The Id of the library to seed.</param>
/// <param name="userId">The Id of the user that owns the library.</param>
/// <returns>A task representing the asynchronous operation.</returns>
private async Task SeedLibraryAsync(Guid libraryId, Guid userId)
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
dbContext.Libraries.Add(new LibraryEntity
{
Id = libraryId,
UserId = userId,
Title = "Test Library",
LibraryType = LibraryType.EBook,
ContentLocations = [],
CreatedBy = userId,
CreatedOnUtc = DateTime.UtcNow,
UpdatedBy = null
});
await dbContext.SaveChangesAsync();
}
/// <summary>
/// Seeds a <see cref="BookEntity"/> belonging to the media library identified by <paramref name="libraryId"/>.
/// </summary>
/// <param name="libraryId">The Id of the media library the book belongs to.</param>
/// <param name="title">The title of the book.</param>
/// <returns>A task representing the asynchronous operation.</returns>
private async Task SeedBookAsync(Guid libraryId, string title)
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
dbContext.Books.Add(new BookEntity
{
Id = Guid.NewGuid(),
LibraryId = libraryId,
Path = $"/books/{Guid.NewGuid()}.epub",
Title = title,
CreatedBy = Guid.NewGuid(),
CreatedOnUtc = DateTime.UtcNow,
UpdatedBy = null
});
await dbContext.SaveChangesAsync();
}
}
@@ -0,0 +1,51 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Presentation.Api.SecurityTests.Common.Setup;
using Microsoft.AspNetCore.Http;
using System.Diagnostics.CodeAnalysis;
using System.Net;
using System.Text.Json;
#endregion
namespace Lumina.Presentation.Api.SecurityTests.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.Books.GetBooksLite;
/// <summary>
/// Contains security tests for the <c>/books/lite</c> route.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetBooksLiteEndpointTests : IClassFixture<LuminaApiFactory>
{
private readonly HttpClient _client;
private readonly JsonSerializerOptions _jsonOptions = new()
{
PropertyNameCaseInsensitive = true
};
/// <summary>
/// Initializes a new instance of the <see cref="GetBooksLiteEndpointTests"/> class.
/// </summary>
/// <param name="apiFactory">Injected in-memory API factory.</param>
public GetBooksLiteEndpointTests(LuminaApiFactory apiFactory)
{
_client = apiFactory.CreateClient();
}
[Fact]
public async Task GetBooksLite_WhenUnauthorized_ShouldReturnUnauthorizedResult()
{
// Act
HttpResponseMessage response = await _client.GetAsync("/api/v1/books/lite");
// Assert
Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode);
string content = await response.Content.ReadAsStringAsync();
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
Assert.NotNull(problemDetails);
Assert.Equal(StatusCodes.Status401Unauthorized, problemDetails!["status"].GetInt32());
Assert.Equal("https://tools.ietf.org/html/rfc7235#section-3.1", problemDetails["type"].GetString());
Assert.Equal("Unauthorized", problemDetails["title"].GetString());
Assert.Equal("/api/v1/books/lite", problemDetails["instance"].GetProperty("value").GetString());
Assert.Equal("Authentication failed", problemDetails["detail"].GetString());
}
}
@@ -1,9 +1,11 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary;
using Lumina.Application.Common.DTO.Pagination;
using Lumina.Application.Common.Mapping.Common.Metadata;
using Lumina.Application.Common.Mapping.MediaLibrary.WrittenContentLibrary.BookLibrary.Books;
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary;
using Lumina.Contracts.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary;
using Lumina.Contracts.Responses.Common;
using Lumina.Contracts.Responses.MediaLibrary.WrittenContentLibrary.BookLibrary.Books;
using Lumina.Domain.Common.Primitives;
using Lumina.Domain.Core.BoundedContexts.WrittenContentLibraryBoundedContext.BookLibraryAggregate;
@@ -335,4 +337,101 @@ public class BookEntityMappingTests
Assert.NotNull(results);
Assert.Equal(bookEntities.Count, results.Count());
}
[Fact]
public void ToResponses_WhenMappingPaginatedBookEntities_ShouldMapAllPropertiesCorrectly()
{
// Arrange
List<BookEntity> bookEntities = _bookEntityFixture.CreateMany(2);
PaginatedResultDto<BookEntity> paginatedBookEntities = new()
{
Data = bookEntities,
CurrentPage = 1,
PerPage = 10,
Count = 2,
NumberOfPages = 1
};
// Act
PaginatedResponse<BookResponse> result = paginatedBookEntities.ToResponses();
// Assert
Assert.NotNull(result);
Assert.Equal(paginatedBookEntities.Data.Count(), result.Data.Count());
Assert.Equal(paginatedBookEntities.CurrentPage, result.CurrentPage);
Assert.Equal(paginatedBookEntities.PerPage, result.PerPage);
Assert.Equal(paginatedBookEntities.Count, result.Count);
Assert.Equal(paginatedBookEntities.NumberOfPages, result.NumberOfPages);
}
[Fact]
public void ToLiteResponse_WhenMappingBookEntity_ShouldMapIdTitleAndReleaseYear()
{
// Arrange
BookEntity bookEntity = _bookEntityFixture.Create();
// Act
BookLiteResponse result = bookEntity.ToLiteResponse();
// Assert
Assert.NotNull(result);
Assert.Equal(bookEntity.Id, result.Id);
Assert.Equal(bookEntity.Title, result.Title);
Assert.Equal(bookEntity.ReReleaseYear ?? bookEntity.OriginalReleaseYear, result.ReleaseYear);
Assert.Null(result.CoverPath);
}
[Fact]
public void ToLiteResponse_WhenBookHasNoReReleaseYear_ShouldFallBackToOriginalReleaseYear()
{
// Arrange
BookEntity bookEntity = _bookEntityFixture.Create();
bookEntity.ReReleaseYear = null;
// Act
BookLiteResponse result = bookEntity.ToLiteResponse();
// Assert
Assert.Equal(bookEntity.OriginalReleaseYear, result.ReleaseYear);
}
[Fact]
public void ToLiteResponses_WhenMappingMultipleBookEntities_ShouldMapAllCorrectly()
{
// Arrange
List<BookEntity> bookEntities = _bookEntityFixture.CreateMany(2);
// Act
IReadOnlyList<BookLiteResponse> results = bookEntities.ToLiteResponses();
// Assert
Assert.NotNull(results);
Assert.Equal(bookEntities.Count, results.Count());
}
[Fact]
public void ToLiteResponses_WhenMappingPaginatedBookEntities_ShouldMapAllPropertiesCorrectly()
{
// Arrange
List<BookEntity> bookEntities = _bookEntityFixture.CreateMany(2);
PaginatedResultDto<BookEntity> paginatedBookEntities = new()
{
Data = bookEntities,
CurrentPage = 1,
PerPage = 10,
Count = 2,
NumberOfPages = 1
};
// Act
PaginatedResponse<BookLiteResponse> result = paginatedBookEntities.ToLiteResponses();
// Assert
Assert.NotNull(result);
Assert.Equal(paginatedBookEntities.Data.Count(), result.Data.Count());
Assert.Equal(paginatedBookEntities.CurrentPage, result.CurrentPage);
Assert.Equal(paginatedBookEntities.PerPage, result.PerPage);
Assert.Equal(paginatedBookEntities.Count, result.Count);
Assert.Equal(paginatedBookEntities.NumberOfPages, result.NumberOfPages);
}
}
@@ -0,0 +1,86 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.Mapping.MediaLibrary.WrittenContentLibrary.BookLibrary.Books;
using Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BooksLibrary.Books.Queries.GetBooksLite;
using Lumina.Contracts.Fixtures.Core.Requests.MediaLibrary.WrittenContentLibrary.BookLibrary.Books;
using Lumina.Contracts.Requests.MediaLibrary.WrittenContentLibrary.BookLibrary.Books;
using System.Diagnostics.CodeAnalysis;
#endregion
namespace Lumina.Application.UnitTests.Common.Mapping.MediaLibrary.WrittenContentLibrary.BookLibrary.Books;
/// <summary>
/// Contains unit tests for the <see cref="GetBooksLiteRequestMapping"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetBooksLiteRequestMappingTests
{
private readonly GetBooksLiteRequestFixture _getBooksLiteRequestFixture = new();
[Fact]
public void ToQuery_WhenMappingGetBooksLiteRequest_ShouldMapCorrectly()
{
// Arrange
GetBooksLiteRequest request = _getBooksLiteRequestFixture.Create();
// Act
GetBooksLiteQuery result = request.ToQuery();
// Assert
Assert.NotNull(result);
Assert.Equal(request.LibraryId, result.Filter.LibraryId);
Assert.Equal(request.SearchTerm, result.Filter.SearchTerm);
Assert.Equal(request.SortBy, result.SortBy);
Assert.Equal(request.SortOrder, result.SortOrder);
Assert.NotNull(result.PaginationData);
Assert.Equal(request.CurrentPage, result.PaginationData!.CurrentPage);
Assert.Equal(request.PerPage, result.PaginationData.PerPage);
}
[Fact]
public void ToQuery_WhenNoPaginationProvided_ShouldNotBuildPaginationData()
{
// Arrange
GetBooksLiteRequest request = _getBooksLiteRequestFixture.Create();
request = request with { CurrentPage = null, PerPage = null };
// Act
GetBooksLiteQuery result = request.ToQuery();
// Assert
Assert.NotNull(result);
Assert.Null(result.PaginationData);
Assert.Equal(request.LibraryId, result.Filter.LibraryId);
}
[Fact]
public void ToQuery_WhenOnlyPerPageProvided_ShouldDefaultCurrentPageToOne()
{
// Arrange
GetBooksLiteRequest request = _getBooksLiteRequestFixture.Create();
request = request with { CurrentPage = null, PerPage = 25 };
// Act
GetBooksLiteQuery result = request.ToQuery();
// Assert
Assert.NotNull(result.PaginationData);
Assert.Equal(1, result.PaginationData!.CurrentPage);
Assert.Equal(25, result.PaginationData.PerPage);
}
[Fact]
public void ToQuery_WhenOnlyCurrentPageProvided_ShouldDefaultPerPageToTwoHundred()
{
// Arrange
GetBooksLiteRequest request = _getBooksLiteRequestFixture.Create();
request = request with { CurrentPage = 3, PerPage = null };
// Act
GetBooksLiteQuery result = request.ToQuery();
// Assert
Assert.NotNull(result.PaginationData);
Assert.Equal(3, result.PaginationData!.CurrentPage);
Assert.Equal(200, result.PaginationData.PerPage);
}
}
@@ -0,0 +1,86 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.Mapping.MediaLibrary.WrittenContentLibrary.BookLibrary.Books;
using Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BooksLibrary.Books.Queries.GetBooks;
using Lumina.Contracts.Fixtures.Core.Requests.MediaLibrary.WrittenContentLibrary.BookLibrary.Books;
using Lumina.Contracts.Requests.MediaLibrary.WrittenContentLibrary.BookLibrary.Books;
using System.Diagnostics.CodeAnalysis;
#endregion
namespace Lumina.Application.UnitTests.Common.Mapping.MediaLibrary.WrittenContentLibrary.BookLibrary.Books;
/// <summary>
/// Contains unit tests for the <see cref="GetBooksRequestMapping"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetBooksRequestMappingTests
{
private readonly GetBooksRequestFixture _getBooksRequestFixture = new();
[Fact]
public void ToQuery_WhenMappingGetBooksRequest_ShouldMapCorrectly()
{
// Arrange
GetBooksRequest request = _getBooksRequestFixture.Create();
// Act
GetBooksQuery result = request.ToQuery();
// Assert
Assert.NotNull(result);
Assert.Equal(request.LibraryId, result.Filter.LibraryId);
Assert.Equal(request.SearchTerm, result.Filter.SearchTerm);
Assert.Equal(request.SortBy, result.SortBy);
Assert.Equal(request.SortOrder, result.SortOrder);
Assert.NotNull(result.PaginationData);
Assert.Equal(request.CurrentPage, result.PaginationData!.CurrentPage);
Assert.Equal(request.PerPage, result.PaginationData.PerPage);
}
[Fact]
public void ToQuery_WhenNoPaginationProvided_ShouldNotBuildPaginationData()
{
// Arrange
GetBooksRequest request = _getBooksRequestFixture.Create();
request = request with { CurrentPage = null, PerPage = null };
// Act
GetBooksQuery result = request.ToQuery();
// Assert
Assert.NotNull(result);
Assert.Null(result.PaginationData);
Assert.Equal(request.LibraryId, result.Filter.LibraryId);
}
[Fact]
public void ToQuery_WhenOnlyPerPageProvided_ShouldDefaultCurrentPageToOne()
{
// Arrange
GetBooksRequest request = _getBooksRequestFixture.Create();
request = request with { CurrentPage = null, PerPage = 25 };
// Act
GetBooksQuery result = request.ToQuery();
// Assert
Assert.NotNull(result.PaginationData);
Assert.Equal(1, result.PaginationData!.CurrentPage);
Assert.Equal(25, result.PaginationData.PerPage);
}
[Fact]
public void ToQuery_WhenOnlyCurrentPageProvided_ShouldDefaultPerPageToTwoHundred()
{
// Arrange
GetBooksRequest request = _getBooksRequestFixture.Create();
request = request with { CurrentPage = 3, PerPage = null };
// Act
GetBooksQuery result = request.ToQuery();
// Assert
Assert.NotNull(result.PaginationData);
Assert.Equal(3, result.PaginationData!.CurrentPage);
Assert.Equal(200, result.PaginationData.PerPage);
}
}
@@ -0,0 +1,94 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.Specifications;
using Lumina.Application.Fixtures.Common.Specifications;
using System;
using System.Diagnostics.CodeAnalysis;
using System.Linq.Expressions;
#endregion
namespace Lumina.Application.UnitTests.Common.Specifications;
/// <summary>
/// Contains unit tests for the <see cref="AndFilterSpecification{T}"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class AndFilterSpecificationTests
{
[Fact]
public void ToExpression_WhenBothSpecificationsSatisfyCriteria_ShouldReturnExpressionThatEvaluatesToTrue()
{
// Arrange
GreaterThanFilterSpecificationFixture left = new(5);
GreaterThanFilterSpecificationFixture right = new(10);
AndFilterSpecification<int> specification = new(left, right);
// Act
Expression<Func<int, bool>> expression = specification.ToExpression();
Func<int, bool> predicate = expression.Compile();
// Assert
Assert.True(predicate(20));
}
[Fact]
public void ToExpression_WhenOnlyLeftSpecificationSatisfiesCriteria_ShouldReturnExpressionThatEvaluatesToFalse()
{
// Arrange
GreaterThanFilterSpecificationFixture left = new(5);
GreaterThanFilterSpecificationFixture right = new(10);
AndFilterSpecification<int> specification = new(left, right);
// Act
Expression<Func<int, bool>> expression = specification.ToExpression();
Func<int, bool> predicate = expression.Compile();
// Assert
Assert.False(predicate(8));
}
[Fact]
public void ToExpression_WhenNeitherSpecificationSatisfiesCriteria_ShouldReturnExpressionThatEvaluatesToFalse()
{
// Arrange
GreaterThanFilterSpecificationFixture left = new(5);
GreaterThanFilterSpecificationFixture right = new(10);
AndFilterSpecification<int> specification = new(left, right);
// Act
Expression<Func<int, bool>> expression = specification.ToExpression();
Func<int, bool> predicate = expression.Compile();
// Assert
Assert.False(predicate(2));
}
[Fact]
public void IsSatisfiedBy_WhenBothSpecificationsAreSatisfied_ShouldReturnTrue()
{
// Arrange
AlwaysTrueFilterSpecificationFixture<int> left = new();
AlwaysTrueFilterSpecificationFixture<int> right = new();
AndFilterSpecification<int> specification = new(left, right);
// Act
bool result = specification.IsSatisfiedBy(0);
// Assert
Assert.True(result);
}
[Fact]
public void IsSatisfiedBy_WhenEitherSpecificationIsNotSatisfied_ShouldReturnFalse()
{
// Arrange
AlwaysTrueFilterSpecificationFixture<int> left = new();
AlwaysFalseFilterSpecificationFixture<int> right = new();
AndFilterSpecification<int> specification = new(left, right);
// Act
bool result = specification.IsSatisfiedBy(0);
// Assert
Assert.False(result);
}
}
@@ -0,0 +1,130 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.Specifications;
using Lumina.Application.Fixtures.Common.Specifications;
using System;
using System.Diagnostics.CodeAnalysis;
using System.Linq.Expressions;
#endregion
namespace Lumina.Application.UnitTests.Common.Specifications;
/// <summary>
/// Contains unit tests for the <see cref="FilterSpecification{T}"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class FilterSpecificationTests
{
[Fact]
public void ToExpression_WhenCalledOnConcreteSpecification_ShouldReturnExpressionMatchingCriteria()
{
// Arrange
GreaterThanFilterSpecificationFixture specification = new(10);
// Act
Expression<Func<int, bool>> expression = specification.ToExpression();
Func<int, bool> predicate = expression.Compile();
// Assert
Assert.True(predicate(15));
Assert.False(predicate(5));
}
[Fact]
public void IsSatisfiedBy_WhenEntitySatisfiesCriteria_ShouldReturnTrue()
{
// Arrange
GreaterThanFilterSpecificationFixture specification = new(10);
int entity = 20;
// Act
bool result = specification.IsSatisfiedBy(entity);
// Assert
Assert.True(result);
}
[Fact]
public void IsSatisfiedBy_WhenEntityDoesNotSatisfyCriteria_ShouldReturnFalse()
{
// Arrange
GreaterThanFilterSpecificationFixture specification = new(10);
int entity = 5;
// Act
bool result = specification.IsSatisfiedBy(entity);
// Assert
Assert.False(result);
}
[Fact]
public void And_WhenBothSpecificationsAreSatisfied_ShouldReturnSpecificationSatisfiedByEntity()
{
// Arrange
AlwaysTrueFilterSpecificationFixture<int> left = new();
AlwaysTrueFilterSpecificationFixture<int> right = new();
// Act
FilterSpecification<int> combined = left.And(right);
// Assert
Assert.IsType<AndFilterSpecification<int>>(combined);
Assert.True(combined.IsSatisfiedBy(0));
}
[Fact]
public void And_WhenOneSpecificationIsNotSatisfied_ShouldReturnSpecificationNotSatisfiedByEntity()
{
// Arrange
AlwaysTrueFilterSpecificationFixture<int> left = new();
AlwaysFalseFilterSpecificationFixture<int> right = new();
// Act
FilterSpecification<int> combined = left.And(right);
// Assert
Assert.False(combined.IsSatisfiedBy(0));
}
[Fact]
public void And_WhenBothSpecificationsAreNotSatisfied_ShouldReturnSpecificationNotSatisfiedByEntity()
{
// Arrange
AlwaysFalseFilterSpecificationFixture<int> left = new();
AlwaysFalseFilterSpecificationFixture<int> right = new();
// Act
FilterSpecification<int> combined = left.And(right);
// Assert
Assert.False(combined.IsSatisfiedBy(0));
}
[Fact]
public void Or_WhenAtLeastOneSpecificationIsSatisfied_ShouldReturnSpecificationSatisfiedByEntity()
{
// Arrange
AlwaysTrueFilterSpecificationFixture<int> left = new();
AlwaysFalseFilterSpecificationFixture<int> right = new();
// Act
FilterSpecification<int> combined = left.Or(right);
// Assert
Assert.True(combined.IsSatisfiedBy(0));
}
[Fact]
public void Or_WhenNeitherSpecificationIsSatisfied_ShouldReturnSpecificationNotSatisfiedByEntity()
{
// Arrange
AlwaysFalseFilterSpecificationFixture<int> left = new();
AlwaysFalseFilterSpecificationFixture<int> right = new();
// Act
FilterSpecification<int> combined = left.Or(right);
// Assert
Assert.False(combined.IsSatisfiedBy(0));
}
}
@@ -0,0 +1,110 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.Specifications;
using Lumina.Application.Fixtures.Common.Specifications;
using System;
using System.Diagnostics.CodeAnalysis;
using System.Linq.Expressions;
#endregion
namespace Lumina.Application.UnitTests.Common.Specifications;
/// <summary>
/// Contains unit tests for the <see cref="OrFilterSpecification{T}"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class OrFilterSpecificationTests
{
[Fact]
public void ToExpression_WhenOnlyLeftSpecificationSatisfiesCriteria_ShouldReturnExpressionThatEvaluatesToTrue()
{
// Arrange
GreaterThanFilterSpecificationFixture left = new(5);
GreaterThanFilterSpecificationFixture right = new(10);
OrFilterSpecification<int> specification = new(left, right);
// Act
Expression<Func<int, bool>> expression = specification.ToExpression();
Func<int, bool> predicate = expression.Compile();
// Assert
Assert.True(predicate(8));
}
[Fact]
public void ToExpression_WhenOnlyRightSpecificationSatisfiesCriteria_ShouldReturnExpressionThatEvaluatesToTrue()
{
// Arrange
GreaterThanFilterSpecificationFixture left = new(10);
GreaterThanFilterSpecificationFixture right = new(5);
OrFilterSpecification<int> specification = new(left, right);
// Act
Expression<Func<int, bool>> expression = specification.ToExpression();
Func<int, bool> predicate = expression.Compile();
// Assert
Assert.True(predicate(8));
}
[Fact]
public void ToExpression_WhenBothSpecificationsSatisfyCriteria_ShouldReturnExpressionThatEvaluatesToTrue()
{
// Arrange
GreaterThanFilterSpecificationFixture left = new(5);
GreaterThanFilterSpecificationFixture right = new(10);
OrFilterSpecification<int> specification = new(left, right);
// Act
Expression<Func<int, bool>> expression = specification.ToExpression();
Func<int, bool> predicate = expression.Compile();
// Assert
Assert.True(predicate(20));
}
[Fact]
public void ToExpression_WhenNeitherSpecificationSatisfiesCriteria_ShouldReturnExpressionThatEvaluatesToFalse()
{
// Arrange
GreaterThanFilterSpecificationFixture left = new(5);
GreaterThanFilterSpecificationFixture right = new(10);
OrFilterSpecification<int> specification = new(left, right);
// Act
Expression<Func<int, bool>> expression = specification.ToExpression();
Func<int, bool> predicate = expression.Compile();
// Assert
Assert.False(predicate(2));
}
[Fact]
public void IsSatisfiedBy_WhenAtLeastOneSpecificationIsSatisfied_ShouldReturnTrue()
{
// Arrange
AlwaysTrueFilterSpecificationFixture<int> left = new();
AlwaysFalseFilterSpecificationFixture<int> right = new();
OrFilterSpecification<int> specification = new(left, right);
// Act
bool result = specification.IsSatisfiedBy(0);
// Assert
Assert.True(result);
}
[Fact]
public void IsSatisfiedBy_WhenNeitherSpecificationIsSatisfied_ShouldReturnFalse()
{
// Arrange
AlwaysFalseFilterSpecificationFixture<int> left = new();
AlwaysFalseFilterSpecificationFixture<int> right = new();
OrFilterSpecification<int> specification = new(left, right);
// Act
bool result = specification.IsSatisfiedBy(0);
// Assert
Assert.False(result);
}
}
@@ -0,0 +1,334 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management;
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary;
using Lumina.Application.Common.DataAccess.Repositories.Books;
using Lumina.Application.Common.DataAccess.Repositories.MediaLibrary;
using Lumina.Application.Common.DataAccess.UoW;
using Lumina.Application.Common.Infrastructure.Authentication;
using Lumina.Application.Common.Infrastructure.Authorization;
using Lumina.Application.Common.Infrastructure.Validation;
using Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BooksLibrary.Books.Queries.GetBooks;
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary;
using Lumina.Application.Fixtures.Core.MediaLibrary.WrittenContentLibrary.BooksLibrary.Books.Queries.GetBooks;
using Lumina.Contracts.Responses.Common;
using Lumina.Contracts.Responses.MediaLibrary.WrittenContentLibrary.BookLibrary.Books;
using Lumina.Domain.Common.Errors;
using Lumina.Domain.Common.Primitives;
using Lumina.Domain.SharedKernel.Common.Enums.Common;
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
using NSubstitute;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using ApplicationErrors = Lumina.Application.Common.Errors.Errors;
using Lumina.Application.Common.DTO.Filtering;
using Lumina.Application.Common.DTO.Pagination;
#endregion
namespace Lumina.Application.UnitTests.Core.MediaLibrary.WrittenContentLibrary.BooksLibrary.Books.Queries.GetBooks;
/// <summary>
/// Contains unit tests for the <see cref="GetBooksQueryHandler"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetBooksQueryHandlerTests
{
private readonly IUnitOfWork _mockUnitOfWork;
private readonly IBookRepository _mockBookRepository;
private readonly ILibraryRepository _mockLibraryRepository;
private readonly IAuthorizationService _mockAuthorizationService;
private readonly ICurrentUserService _mockCurrentUserService;
private readonly IValidator<GetBooksQuery> _mockValidator;
private readonly GetBooksQueryHandler _sut;
private readonly Guid _userId;
private readonly BookEntityFixture _bookEntityFixture = new();
private readonly GetBooksQueryFixture _getBooksQueryFixture = new();
/// <summary>
/// Initializes a new instance of the <see cref="GetBooksQueryHandlerTests"/> class.
/// </summary>
public GetBooksQueryHandlerTests()
{
_mockBookRepository = Substitute.For<IBookRepository>();
_mockUnitOfWork = Substitute.For<IUnitOfWork>();
_mockUnitOfWork.BookRepository.Returns(_mockBookRepository);
_mockLibraryRepository = Substitute.For<ILibraryRepository>();
_mockUnitOfWork.LibraryRepository.Returns(_mockLibraryRepository);
_mockAuthorizationService = Substitute.For<IAuthorizationService>();
_mockCurrentUserService = Substitute.For<ICurrentUserService>();
_mockValidator = Substitute.For<IValidator<GetBooksQuery>>();
_userId = Guid.NewGuid();
// default stubs: the current user is not an admin, but owns the requested library
_mockCurrentUserService.UserId.Returns(_userId);
_mockAuthorizationService.IsInRoleAsync(_userId, "Admin", Arg.Any<CancellationToken>()).Returns(false);
_mockLibraryRepository.GetByIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>())
.Returns(Result.From((LibraryEntity?)new LibraryEntity
{
Id = Guid.NewGuid(),
UserId = _userId,
Title = "Test Library",
LibraryType = LibraryType.EBook,
ContentLocations = [],
CreatedBy = _userId,
CreatedOnUtc = DateTime.UtcNow,
UpdatedBy = null
}));
_mockValidator.Validate(Arg.Any<GetBooksQuery>()).Returns([]);
_sut = new GetBooksQueryHandler(_mockUnitOfWork, _mockAuthorizationService, _mockCurrentUserService, _mockValidator);
}
[Fact]
public async Task HandleAsync_WhenRepositoryReturnsPaginatedBooks_ShouldReturnMappedPaginatedResponses()
{
// Arrange
GetBooksQuery query = _getBooksQueryFixture.Create();
CancellationToken cancellationToken = CancellationToken.None;
List<BookEntity> bookEntities = _bookEntityFixture.CreateMany(2);
PaginatedResultDto<BookEntity> paginatedBooks = new()
{
Data = bookEntities,
CurrentPage = 1,
PerPage = 10,
Count = 2,
NumberOfPages = 1
};
_mockBookRepository.GetPaginatedAsync(
Arg.Any<PaginationDataDto?>(),
Arg.Any<string?>(),
Arg.Any<SortOrder?>(),
Arg.Any<LibraryFilterDto>(),
Arg.Any<CancellationToken>())
.Returns(Result.From(paginatedBooks));
// Act
Result<PaginatedResponse<BookResponse>> result = await _sut.HandleAsync(query, cancellationToken);
// Assert
Assert.False(result.IsFailure);
Assert.Equal(bookEntities.Count, result.Value.Data.Count);
Assert.Equal(paginatedBooks.CurrentPage, result.Value.CurrentPage);
Assert.Equal(paginatedBooks.PerPage, result.Value.PerPage);
Assert.Equal(paginatedBooks.Count, result.Value.Count);
Assert.Equal(paginatedBooks.NumberOfPages, result.Value.NumberOfPages);
}
[Fact]
public async Task HandleAsync_WhenRepositoryReturnsEmptyPage_ShouldReturnEmptyPaginatedResponses()
{
// Arrange
GetBooksQuery query = _getBooksQueryFixture.Create();
PaginatedResultDto<BookEntity> paginatedBooks = new()
{
Data = [],
CurrentPage = 1,
PerPage = 10,
Count = 0,
NumberOfPages = 0
};
_mockBookRepository.GetPaginatedAsync(
Arg.Any<PaginationDataDto?>(),
Arg.Any<string?>(),
Arg.Any<SortOrder?>(),
Arg.Any<LibraryFilterDto>(),
Arg.Any<CancellationToken>())
.Returns(Result.From(paginatedBooks));
// Act
Result<PaginatedResponse<BookResponse>> result = await _sut.HandleAsync(query, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
Assert.Empty(result.Value.Data);
}
[Fact]
public async Task HandleAsync_WhenRepositoryReturnsError_ShouldReturnFailureResult()
{
// Arrange
GetBooksQuery query = _getBooksQueryFixture.Create();
_mockBookRepository.GetPaginatedAsync(
Arg.Any<PaginationDataDto?>(),
Arg.Any<string?>(),
Arg.Any<SortOrder?>(),
Arg.Any<LibraryFilterDto>(),
Arg.Any<CancellationToken>())
.Returns(Errors.Library.FilterMustIncludeLibraryId);
// Act
Result<PaginatedResponse<BookResponse>> result = await _sut.HandleAsync(query, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(Errors.Library.FilterMustIncludeLibraryId, result.FirstError);
}
[Fact]
public async Task HandleAsync_WhenCalled_ShouldQueryRepositoryWithMappedFilterAndPagination()
{
// Arrange
GetBooksQuery query = _getBooksQueryFixture.Create();
CancellationToken cancellationToken = CancellationToken.None;
PaginatedResultDto<BookEntity> paginatedBooks = new()
{
Data = [],
CurrentPage = 1,
PerPage = 10,
Count = 0,
NumberOfPages = 0
};
_mockBookRepository.GetPaginatedAsync(
Arg.Any<PaginationDataDto?>(),
Arg.Any<string?>(),
Arg.Any<SortOrder?>(),
Arg.Any<LibraryFilterDto>(),
Arg.Any<CancellationToken>())
.Returns(Result.From(paginatedBooks));
// Act
await _sut.HandleAsync(query, cancellationToken);
// Assert
await _mockBookRepository.Received(1).GetPaginatedAsync(
Arg.Is<PaginationDataDto>(paginationData => paginationData.CurrentPage == query.PaginationData!.CurrentPage &&
paginationData.PerPage == query.PaginationData.PerPage),
Arg.Is(query.SortBy),
Arg.Is(query.SortOrder),
Arg.Is<LibraryFilterDto>(filter => filter.LibraryId == query.Filter.LibraryId && filter.SearchTerm == query.Filter.SearchTerm),
Arg.Is(cancellationToken));
}
[Fact]
public async Task HandleAsync_WhenQueryHasNoPaginationData_ShouldQueryRepositoryWithoutPagination()
{
// Arrange
GetBooksQuery query = new(
PaginationData: null,
Filter: new LibraryFilterDto { LibraryId = Guid.NewGuid() },
SortBy: null,
SortOrder: SortOrder.Ascending
);
PaginatedResultDto<BookEntity> paginatedBooks = new()
{
Data = [],
CurrentPage = 1,
PerPage = 10,
Count = 0,
NumberOfPages = 0
};
_mockBookRepository.GetPaginatedAsync(
Arg.Any<PaginationDataDto?>(),
Arg.Any<string?>(),
Arg.Any<SortOrder?>(),
Arg.Any<LibraryFilterDto>(),
Arg.Any<CancellationToken>())
.Returns(Result.From(paginatedBooks));
// Act
await _sut.HandleAsync(query, CancellationToken.None);
// Assert
await _mockBookRepository.Received(1).GetPaginatedAsync(
Arg.Is<PaginationDataDto?>(paginationData => paginationData == null),
Arg.Is(query.SortBy),
Arg.Is(query.SortOrder),
Arg.Is<LibraryFilterDto>(filter => filter.LibraryId == query.Filter.LibraryId && filter.SearchTerm == query.Filter.SearchTerm),
Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenUserIsAdmin_ShouldBypassLibraryOwnershipCheck()
{
// Arrange
GetBooksQuery query = _getBooksQueryFixture.Create();
_mockAuthorizationService.IsInRoleAsync(_userId, "Admin", Arg.Any<CancellationToken>()).Returns(true);
PaginatedResultDto<BookEntity> paginatedBooks = new()
{
Data = [],
CurrentPage = 1,
PerPage = 10,
Count = 0,
NumberOfPages = 0
};
_mockBookRepository.GetPaginatedAsync(
Arg.Any<PaginationDataDto?>(),
Arg.Any<string?>(),
Arg.Any<SortOrder?>(),
Arg.Any<LibraryFilterDto>(),
Arg.Any<CancellationToken>())
.Returns(Result.From(paginatedBooks));
// Act
Result<PaginatedResponse<BookResponse>> result = await _sut.HandleAsync(query, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
await _mockUnitOfWork.LibraryRepository.DidNotReceive().GetByIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenUserDoesNotOwnLibrary_ShouldReturnNotAuthorizedError()
{
// Arrange
GetBooksQuery query = _getBooksQueryFixture.Create();
Guid otherUserId = Guid.NewGuid();
_mockLibraryRepository.GetByIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>())
.Returns(Result.From((LibraryEntity?)new LibraryEntity
{
Id = Guid.NewGuid(),
UserId = otherUserId,
Title = "Someone else's library",
LibraryType = LibraryType.EBook,
ContentLocations = [],
CreatedBy = otherUserId,
CreatedOnUtc = DateTime.UtcNow,
UpdatedBy = null
}));
// Act
Result<PaginatedResponse<BookResponse>> result = await _sut.HandleAsync(query, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(ApplicationErrors.Authorization.NotAuthorized, result.FirstError);
await _mockBookRepository.DidNotReceive().GetPaginatedAsync(Arg.Any<PaginationDataDto?>(), Arg.Any<string?>(), Arg.Any<SortOrder?>(), Arg.Any<LibraryFilterDto>(), Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenLibraryDoesNotExist_ShouldReturnNotAuthorizedError()
{
// Arrange
GetBooksQuery query = _getBooksQueryFixture.Create();
_mockLibraryRepository.GetByIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>())
.Returns(Result<LibraryEntity?>.Success(null));
// Act
Result<PaginatedResponse<BookResponse>> result = await _sut.HandleAsync(query, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(ApplicationErrors.Authorization.NotAuthorized, result.FirstError);
await _mockBookRepository.DidNotReceive().GetPaginatedAsync(Arg.Any<PaginationDataDto?>(), Arg.Any<string?>(), Arg.Any<SortOrder?>(), Arg.Any<LibraryFilterDto>(), Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenValidationFails_ShouldReturnValidationErrorsWithoutQuerying()
{
// Arrange
GetBooksQuery query = _getBooksQueryFixture.Create();
_mockValidator.Validate(Arg.Any<GetBooksQuery>()).Returns([Errors.Library.LibraryIdCannotBeEmpty]);
// Act
Result<PaginatedResponse<BookResponse>> result = await _sut.HandleAsync(query, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(Errors.Library.LibraryIdCannotBeEmpty, result.FirstError);
await _mockAuthorizationService.DidNotReceive().IsInRoleAsync(Arg.Any<Guid>(), Arg.Any<string>(), Arg.Any<CancellationToken>());
await _mockBookRepository.DidNotReceive().GetPaginatedAsync(Arg.Any<PaginationDataDto?>(), Arg.Any<string?>(), Arg.Any<SortOrder?>(), Arg.Any<LibraryFilterDto>(), Arg.Any<CancellationToken>());
}
}
@@ -0,0 +1,49 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BooksLibrary.Books.Queries.GetBooks;
using Lumina.Application.Fixtures.Core.MediaLibrary.WrittenContentLibrary.BooksLibrary.Books.Queries.GetBooks;
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.BooksLibrary.Books.Queries.GetBooks;
/// <summary>
/// Contains unit tests for the <see cref="GetBooksQueryValidator"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetBooksQueryValidatorTests
{
private readonly GetBooksQueryValidator _validator = new();
private readonly GetBooksQueryFixture _getBooksQueryFixture = new();
[Fact]
public void Validate_WhenLibraryIdIsEmpty_ShouldHaveValidationError()
{
// Arrange
GetBooksQuery query = _getBooksQueryFixture.Create();
query = query with { Filter = query.Filter with { LibraryId = Guid.Empty } };
// Act
List<Error> result = _validator.TestValidate(query);
// Assert
result.ShouldHaveValidationError(Errors.Library.LibraryIdCannotBeEmpty);
}
[Fact]
public void Validate_WhenQueryIsValid_ShouldNotHaveValidationError()
{
// Arrange
GetBooksQuery query = _getBooksQueryFixture.Create();
// Act
List<Error> result = _validator.TestValidate(query);
// Assert
result.ShouldNotHaveAnyValidationErrors();
}
}
@@ -0,0 +1,334 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management;
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary;
using Lumina.Application.Common.DataAccess.Repositories.Books;
using Lumina.Application.Common.DataAccess.Repositories.MediaLibrary;
using Lumina.Application.Common.DataAccess.UoW;
using Lumina.Application.Common.Infrastructure.Authentication;
using Lumina.Application.Common.Infrastructure.Authorization;
using Lumina.Application.Common.Infrastructure.Validation;
using Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BooksLibrary.Books.Queries.GetBooksLite;
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary;
using Lumina.Application.Fixtures.Core.MediaLibrary.WrittenContentLibrary.BooksLibrary.Books.Queries.GetBooksLite;
using Lumina.Contracts.Responses.Common;
using Lumina.Contracts.Responses.MediaLibrary.WrittenContentLibrary.BookLibrary.Books;
using Lumina.Domain.Common.Errors;
using Lumina.Domain.Common.Primitives;
using Lumina.Domain.SharedKernel.Common.Enums.Common;
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
using NSubstitute;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using ApplicationErrors = Lumina.Application.Common.Errors.Errors;
using Lumina.Application.Common.DTO.Filtering;
using Lumina.Application.Common.DTO.Pagination;
#endregion
namespace Lumina.Application.UnitTests.Core.MediaLibrary.WrittenContentLibrary.BooksLibrary.Books.Queries.GetBooksLite;
/// <summary>
/// Contains unit tests for the <see cref="GetBooksLiteQueryHandler"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetBooksLiteQueryHandlerTests
{
private readonly IUnitOfWork _mockUnitOfWork;
private readonly IBookRepository _mockBookRepository;
private readonly ILibraryRepository _mockLibraryRepository;
private readonly IAuthorizationService _mockAuthorizationService;
private readonly ICurrentUserService _mockCurrentUserService;
private readonly IValidator<GetBooksLiteQuery> _mockValidator;
private readonly GetBooksLiteQueryHandler _sut;
private readonly Guid _userId;
private readonly BookEntityFixture _bookEntityFixture = new();
private readonly GetBooksLiteQueryFixture _getBooksLiteQueryFixture = new();
/// <summary>
/// Initializes a new instance of the <see cref="GetBooksLiteQueryHandlerTests"/> class.
/// </summary>
public GetBooksLiteQueryHandlerTests()
{
_mockBookRepository = Substitute.For<IBookRepository>();
_mockUnitOfWork = Substitute.For<IUnitOfWork>();
_mockUnitOfWork.BookRepository.Returns(_mockBookRepository);
_mockLibraryRepository = Substitute.For<ILibraryRepository>();
_mockUnitOfWork.LibraryRepository.Returns(_mockLibraryRepository);
_mockAuthorizationService = Substitute.For<IAuthorizationService>();
_mockCurrentUserService = Substitute.For<ICurrentUserService>();
_mockValidator = Substitute.For<IValidator<GetBooksLiteQuery>>();
_userId = Guid.NewGuid();
// default stubs: the current user is not an admin, but owns the requested library
_mockCurrentUserService.UserId.Returns(_userId);
_mockAuthorizationService.IsInRoleAsync(_userId, "Admin", Arg.Any<CancellationToken>()).Returns(false);
_mockLibraryRepository.GetByIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>())
.Returns(Result.From((LibraryEntity?)new LibraryEntity
{
Id = Guid.NewGuid(),
UserId = _userId,
Title = "Test Library",
LibraryType = LibraryType.EBook,
ContentLocations = [],
CreatedBy = _userId,
CreatedOnUtc = DateTime.UtcNow,
UpdatedBy = null
}));
_mockValidator.Validate(Arg.Any<GetBooksLiteQuery>()).Returns([]);
_sut = new GetBooksLiteQueryHandler(_mockUnitOfWork, _mockAuthorizationService, _mockCurrentUserService, _mockValidator);
}
[Fact]
public async Task HandleAsync_WhenRepositoryReturnsPaginatedBooks_ShouldReturnMappedPaginatedResponses()
{
// Arrange
GetBooksLiteQuery query = _getBooksLiteQueryFixture.Create();
CancellationToken cancellationToken = CancellationToken.None;
List<BookEntity> bookEntities = _bookEntityFixture.CreateMany(2);
PaginatedResultDto<BookEntity> paginatedBooks = new()
{
Data = bookEntities,
CurrentPage = 1,
PerPage = 10,
Count = 2,
NumberOfPages = 1
};
_mockBookRepository.GetPaginatedAsync(
Arg.Any<PaginationDataDto?>(),
Arg.Any<string?>(),
Arg.Any<SortOrder?>(),
Arg.Any<LibraryFilterDto>(),
Arg.Any<CancellationToken>())
.Returns(Result.From(paginatedBooks));
// Act
Result<PaginatedResponse<BookLiteResponse>> result = await _sut.HandleAsync(query, cancellationToken);
// Assert
Assert.False(result.IsFailure);
Assert.Equal(bookEntities.Count, result.Value.Data.Count);
Assert.Equal(paginatedBooks.CurrentPage, result.Value.CurrentPage);
Assert.Equal(paginatedBooks.PerPage, result.Value.PerPage);
Assert.Equal(paginatedBooks.Count, result.Value.Count);
Assert.Equal(paginatedBooks.NumberOfPages, result.Value.NumberOfPages);
}
[Fact]
public async Task HandleAsync_WhenRepositoryReturnsEmptyPage_ShouldReturnEmptyPaginatedResponses()
{
// Arrange
GetBooksLiteQuery query = _getBooksLiteQueryFixture.Create();
PaginatedResultDto<BookEntity> paginatedBooks = new()
{
Data = [],
CurrentPage = 1,
PerPage = 10,
Count = 0,
NumberOfPages = 0
};
_mockBookRepository.GetPaginatedAsync(
Arg.Any<PaginationDataDto?>(),
Arg.Any<string?>(),
Arg.Any<SortOrder?>(),
Arg.Any<LibraryFilterDto>(),
Arg.Any<CancellationToken>())
.Returns(Result.From(paginatedBooks));
// Act
Result<PaginatedResponse<BookLiteResponse>> result = await _sut.HandleAsync(query, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
Assert.Empty(result.Value.Data);
}
[Fact]
public async Task HandleAsync_WhenRepositoryReturnsError_ShouldReturnFailureResult()
{
// Arrange
GetBooksLiteQuery query = _getBooksLiteQueryFixture.Create();
_mockBookRepository.GetPaginatedAsync(
Arg.Any<PaginationDataDto?>(),
Arg.Any<string?>(),
Arg.Any<SortOrder?>(),
Arg.Any<LibraryFilterDto>(),
Arg.Any<CancellationToken>())
.Returns(Errors.Library.FilterMustIncludeLibraryId);
// Act
Result<PaginatedResponse<BookLiteResponse>> result = await _sut.HandleAsync(query, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(Errors.Library.FilterMustIncludeLibraryId, result.FirstError);
}
[Fact]
public async Task HandleAsync_WhenCalled_ShouldQueryRepositoryWithMappedFilterAndPagination()
{
// Arrange
GetBooksLiteQuery query = _getBooksLiteQueryFixture.Create();
CancellationToken cancellationToken = CancellationToken.None;
PaginatedResultDto<BookEntity> paginatedBooks = new()
{
Data = [],
CurrentPage = 1,
PerPage = 10,
Count = 0,
NumberOfPages = 0
};
_mockBookRepository.GetPaginatedAsync(
Arg.Any<PaginationDataDto?>(),
Arg.Any<string?>(),
Arg.Any<SortOrder?>(),
Arg.Any<LibraryFilterDto>(),
Arg.Any<CancellationToken>())
.Returns(Result.From(paginatedBooks));
// Act
await _sut.HandleAsync(query, cancellationToken);
// Assert
await _mockBookRepository.Received(1).GetPaginatedAsync(
Arg.Is<PaginationDataDto>(paginationData => paginationData.CurrentPage == query.PaginationData!.CurrentPage &&
paginationData.PerPage == query.PaginationData.PerPage),
Arg.Is(query.SortBy),
Arg.Is(query.SortOrder),
Arg.Is<LibraryFilterDto>(filter => filter.LibraryId == query.Filter.LibraryId && filter.SearchTerm == query.Filter.SearchTerm),
Arg.Is(cancellationToken));
}
[Fact]
public async Task HandleAsync_WhenQueryHasNoPaginationData_ShouldQueryRepositoryWithoutPagination()
{
// Arrange
GetBooksLiteQuery query = new(
PaginationData: null,
Filter: new LibraryFilterDto { LibraryId = Guid.NewGuid() },
SortBy: null,
SortOrder: SortOrder.Ascending
);
PaginatedResultDto<BookEntity> paginatedBooks = new()
{
Data = [],
CurrentPage = 1,
PerPage = 10,
Count = 0,
NumberOfPages = 0
};
_mockBookRepository.GetPaginatedAsync(
Arg.Any<PaginationDataDto?>(),
Arg.Any<string?>(),
Arg.Any<SortOrder?>(),
Arg.Any<LibraryFilterDto>(),
Arg.Any<CancellationToken>())
.Returns(Result.From(paginatedBooks));
// Act
await _sut.HandleAsync(query, CancellationToken.None);
// Assert
await _mockBookRepository.Received(1).GetPaginatedAsync(
Arg.Is<PaginationDataDto?>(paginationData => paginationData == null),
Arg.Is(query.SortBy),
Arg.Is(query.SortOrder),
Arg.Is<LibraryFilterDto>(filter => filter.LibraryId == query.Filter.LibraryId && filter.SearchTerm == query.Filter.SearchTerm),
Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenUserIsAdmin_ShouldBypassLibraryOwnershipCheck()
{
// Arrange
GetBooksLiteQuery query = _getBooksLiteQueryFixture.Create();
_mockAuthorizationService.IsInRoleAsync(_userId, "Admin", Arg.Any<CancellationToken>()).Returns(true);
PaginatedResultDto<BookEntity> paginatedBooks = new()
{
Data = [],
CurrentPage = 1,
PerPage = 10,
Count = 0,
NumberOfPages = 0
};
_mockBookRepository.GetPaginatedAsync(
Arg.Any<PaginationDataDto?>(),
Arg.Any<string?>(),
Arg.Any<SortOrder?>(),
Arg.Any<LibraryFilterDto>(),
Arg.Any<CancellationToken>())
.Returns(Result.From(paginatedBooks));
// Act
Result<PaginatedResponse<BookLiteResponse>> result = await _sut.HandleAsync(query, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
await _mockUnitOfWork.LibraryRepository.DidNotReceive().GetByIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenUserDoesNotOwnLibrary_ShouldReturnNotAuthorizedError()
{
// Arrange
GetBooksLiteQuery query = _getBooksLiteQueryFixture.Create();
Guid otherUserId = Guid.NewGuid();
_mockLibraryRepository.GetByIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>())
.Returns(Result.From((LibraryEntity?)new LibraryEntity
{
Id = Guid.NewGuid(),
UserId = otherUserId,
Title = "Someone else's library",
LibraryType = LibraryType.EBook,
ContentLocations = [],
CreatedBy = otherUserId,
CreatedOnUtc = DateTime.UtcNow,
UpdatedBy = null
}));
// Act
Result<PaginatedResponse<BookLiteResponse>> result = await _sut.HandleAsync(query, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(ApplicationErrors.Authorization.NotAuthorized, result.FirstError);
await _mockBookRepository.DidNotReceive().GetPaginatedAsync(Arg.Any<PaginationDataDto?>(), Arg.Any<string?>(), Arg.Any<SortOrder?>(), Arg.Any<LibraryFilterDto>(), Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenLibraryDoesNotExist_ShouldReturnNotAuthorizedError()
{
// Arrange
GetBooksLiteQuery query = _getBooksLiteQueryFixture.Create();
_mockLibraryRepository.GetByIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>())
.Returns(Result<LibraryEntity?>.Success(null));
// Act
Result<PaginatedResponse<BookLiteResponse>> result = await _sut.HandleAsync(query, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(ApplicationErrors.Authorization.NotAuthorized, result.FirstError);
await _mockBookRepository.DidNotReceive().GetPaginatedAsync(Arg.Any<PaginationDataDto?>(), Arg.Any<string?>(), Arg.Any<SortOrder?>(), Arg.Any<LibraryFilterDto>(), Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenValidationFails_ShouldReturnValidationErrorsWithoutQuerying()
{
// Arrange
GetBooksLiteQuery query = _getBooksLiteQueryFixture.Create();
_mockValidator.Validate(Arg.Any<GetBooksLiteQuery>()).Returns([Errors.Library.LibraryIdCannotBeEmpty]);
// Act
Result<PaginatedResponse<BookLiteResponse>> result = await _sut.HandleAsync(query, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(Errors.Library.LibraryIdCannotBeEmpty, result.FirstError);
await _mockAuthorizationService.DidNotReceive().IsInRoleAsync(Arg.Any<Guid>(), Arg.Any<string>(), Arg.Any<CancellationToken>());
await _mockBookRepository.DidNotReceive().GetPaginatedAsync(Arg.Any<PaginationDataDto?>(), Arg.Any<string?>(), Arg.Any<SortOrder?>(), Arg.Any<LibraryFilterDto>(), Arg.Any<CancellationToken>());
}
}
@@ -0,0 +1,49 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BooksLibrary.Books.Queries.GetBooksLite;
using Lumina.Application.Fixtures.Core.MediaLibrary.WrittenContentLibrary.BooksLibrary.Books.Queries.GetBooksLite;
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.BooksLibrary.Books.Queries.GetBooksLite;
/// <summary>
/// Contains unit tests for the <see cref="GetBooksLiteQueryValidator"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetBooksLiteQueryValidatorTests
{
private readonly GetBooksLiteQueryValidator _validator = new();
private readonly GetBooksLiteQueryFixture _getBooksLiteQueryFixture = new();
[Fact]
public void Validate_WhenLibraryIdIsEmpty_ShouldHaveValidationError()
{
// Arrange
GetBooksLiteQuery query = _getBooksLiteQueryFixture.Create();
query = query with { Filter = query.Filter with { LibraryId = Guid.Empty } };
// Act
List<Error> result = _validator.TestValidate(query);
// Assert
result.ShouldHaveValidationError(Errors.Library.LibraryIdCannotBeEmpty);
}
[Fact]
public void Validate_WhenQueryIsValid_ShouldNotHaveValidationError()
{
// Arrange
GetBooksLiteQuery query = _getBooksLiteQueryFixture.Create();
// Act
List<Error> result = _validator.TestValidate(query);
// Assert
result.ShouldNotHaveAnyValidationErrors();
}
}
@@ -2,12 +2,15 @@
using EntityFrameworkCore.Testing.NSubstitute;
using Lumina.Application.Common.DataAccess.Entities.Common;
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary;
using Lumina.Application.Common.DTO.Filtering;
using Lumina.Application.Common.DTO.Pagination;
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary;
using Lumina.DataAccess.Core.Repositories.Books;
using Lumina.DataAccess.Core.UoW;
using Lumina.Domain.Common.Errors;
using Lumina.Domain.Common.Primitives;
using Lumina.Domain.SharedKernel.Common.Enums.BookLibrary;
using Lumina.Domain.SharedKernel.Common.Enums.Common;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.ChangeTracking;
using System;
@@ -326,4 +329,193 @@ public class BookRepositoryTests
Assert.True(result.IsFailure);
Assert.Equal(Errors.WrittenContent.BookNotFound, result.FirstError);
}
[Fact]
public async Task GetPaginatedAsync_WhenFilterIncludesLibraryId_ShouldReturnPaginatedBooks()
{
// Arrange
Guid libraryId = Guid.NewGuid();
List<BookEntity> books = _bookEntityFixture.CreateMany(3);
foreach (BookEntity book in books)
book.LibraryId = libraryId;
_mockContext.Books.AddRange(books);
await _mockContext.SaveChangesAsync();
PaginationDataDto paginationData = new() { CurrentPage = 1, PerPage = 10 };
LibraryFilterDto filter = new() { LibraryId = libraryId };
// Act
Result<PaginatedResultDto<BookEntity>> result = await _sut.GetPaginatedAsync(paginationData, null, null, filter, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
Assert.Equal(3, result.Value.Count);
Assert.Equal(3, result.Value.Data.Count);
Assert.Equal(1, result.Value.CurrentPage);
Assert.Equal(10, result.Value.PerPage);
Assert.Equal(1, result.Value.NumberOfPages);
}
[Fact]
public async Task GetPaginatedAsync_WhenFilterDoesNotIncludeLibraryId_ShouldReturnError()
{
// Arrange
PaginationDataDto paginationData = new() { CurrentPage = 1, PerPage = 10 };
BaseFilterDto filter = new();
// Act
Result<PaginatedResultDto<BookEntity>> result = await _sut.GetPaginatedAsync(paginationData, null, null, filter, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(Errors.Library.FilterMustIncludeLibraryId, result.FirstError);
}
[Fact]
public async Task GetPaginatedAsync_WhenFilterLibraryIdIsEmpty_ShouldReturnError()
{
// Arrange
PaginationDataDto paginationData = new() { CurrentPage = 1, PerPage = 10 };
LibraryFilterDto filter = new() { LibraryId = Guid.Empty };
// Act
Result<PaginatedResultDto<BookEntity>> result = await _sut.GetPaginatedAsync(paginationData, null, null, filter, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(Errors.Library.FilterMustIncludeLibraryId, result.FirstError);
}
[Fact]
public async Task GetPaginatedAsync_WhenPaginationDataIsNull_ShouldReturnAllBooks()
{
// Arrange
Guid libraryId = Guid.NewGuid();
List<BookEntity> books = _bookEntityFixture.CreateMany(3);
foreach (BookEntity book in books)
book.LibraryId = libraryId;
_mockContext.Books.AddRange(books);
await _mockContext.SaveChangesAsync();
LibraryFilterDto filter = new() { LibraryId = libraryId };
// Act
Result<PaginatedResultDto<BookEntity>> result = await _sut.GetPaginatedAsync(null, null, null, filter, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
Assert.Equal(3, result.Value.Count);
Assert.Equal(3, result.Value.Data.Count);
Assert.Equal(1, result.Value.CurrentPage);
Assert.Equal(3, result.Value.PerPage);
Assert.Equal(1, result.Value.NumberOfPages);
}
[Fact]
public async Task GetPaginatedAsync_WhenSearchTermProvided_ShouldReturnOnlyMatchingBooks()
{
// Arrange
Guid libraryId = Guid.NewGuid();
BookEntity fellowshipBook = _bookEntityFixture.Create();
fellowshipBook.LibraryId = libraryId;
fellowshipBook.Title = "The Fellowship of the Ring";
BookEntity towersBook = _bookEntityFixture.Create();
towersBook.LibraryId = libraryId;
towersBook.Title = "The Two Towers";
_mockContext.Books.AddRange(fellowshipBook, towersBook);
await _mockContext.SaveChangesAsync();
PaginationDataDto paginationData = new() { CurrentPage = 1, PerPage = 10 };
LibraryFilterDto filter = new() { LibraryId = libraryId, SearchTerm = "Fellowship" };
// Act
Result<PaginatedResultDto<BookEntity>> result = await _sut.GetPaginatedAsync(paginationData, null, null, filter, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
BookEntity book = Assert.Single(result.Value.Data);
Assert.Equal("The Fellowship of the Ring", book.Title);
Assert.Equal(1, result.Value.Count);
}
[Fact]
public async Task GetPaginatedAsync_WhenPageSizeSmallerThanBookCount_ShouldReturnCorrectPageMetadata()
{
// Arrange
Guid libraryId = Guid.NewGuid();
List<BookEntity> books = _bookEntityFixture.CreateMany(5);
foreach (BookEntity book in books)
book.LibraryId = libraryId;
_mockContext.Books.AddRange(books);
await _mockContext.SaveChangesAsync();
PaginationDataDto paginationData = new() { CurrentPage = 2, PerPage = 2 };
LibraryFilterDto filter = new() { LibraryId = libraryId };
// Act
Result<PaginatedResultDto<BookEntity>> result = await _sut.GetPaginatedAsync(paginationData, null, null, filter, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
Assert.Equal(5, result.Value.Count);
Assert.Equal(3, result.Value.NumberOfPages);
Assert.Equal(2, result.Value.CurrentPage);
Assert.Equal(2, result.Value.PerPage);
Assert.Equal(2, result.Value.Data.Count);
}
[Fact]
public async Task GetPaginatedAsync_WhenSortByTitleDescending_ShouldReturnBooksInDescendingOrder()
{
// Arrange
Guid libraryId = Guid.NewGuid();
BookEntity bookA = _bookEntityFixture.Create();
bookA.LibraryId = libraryId;
bookA.Title = "Book A";
BookEntity bookB = _bookEntityFixture.Create();
bookB.LibraryId = libraryId;
bookB.Title = "Book B";
_mockContext.Books.AddRange(bookA, bookB);
await _mockContext.SaveChangesAsync();
PaginationDataDto paginationData = new() { CurrentPage = 1, PerPage = 10 };
LibraryFilterDto filter = new() { LibraryId = libraryId };
// Act
Result<PaginatedResultDto<BookEntity>> result = await _sut.GetPaginatedAsync(paginationData, "title", SortOrder.Descending, filter, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
Assert.Equal(["Book B", "Book A"], result.Value.Data.Select(book => book.Title));
}
[Fact]
public async Task GetPaginatedAsync_WhenCalled_ShouldIncludeRelatedEntities()
{
// Arrange
Guid libraryId = Guid.NewGuid();
BookEntity book = _bookEntityFixture.Create();
book.LibraryId = libraryId;
book.Tags = [new TagEntity("Tag1"), new TagEntity("Tag2")];
book.Genres = [new GenreEntity("Genre1"), new GenreEntity("Genre2")];
book.ISBNs = [new IsbnEntity("1234567890", IsbnFormat.Isbn10), new IsbnEntity("1234567890123", IsbnFormat.Isbn13)];
book.Ratings = [new BookRatingEntity(4.5M, 5, BookRatingSource.Goodreads, 100)];
_mockContext.Books.Add(book);
await _mockContext.SaveChangesAsync();
PaginationDataDto paginationData = new() { CurrentPage = 1, PerPage = 10 };
LibraryFilterDto filter = new() { LibraryId = libraryId };
// Act
Result<PaginatedResultDto<BookEntity>> result = await _sut.GetPaginatedAsync(paginationData, null, null, filter, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
BookEntity retrievedBook = Assert.Single(result.Value.Data);
Assert.Equal(2, retrievedBook.Tags.Count);
Assert.Equal(2, retrievedBook.Genres.Count);
Assert.Equal(2, retrievedBook.ISBNs.Count);
Assert.Single(retrievedBook.Ratings);
Assert.Equal(4.5M, retrievedBook.Ratings.First().Value);
}
}
@@ -0,0 +1,233 @@
#region ========================================================================= USING =====================================================================================
using FastEndpoints;
using Lumina.Application.Common.CQRS;
using Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BooksLibrary.Books.Queries.GetBooks;
using Lumina.Contracts.DTO.MediaLibrary.WrittenContentLibrary;
using Lumina.Contracts.Fixtures.Core.Requests.MediaLibrary.WrittenContentLibrary.BookLibrary.Books;
using Lumina.Contracts.Requests.MediaLibrary.WrittenContentLibrary.BookLibrary.Books;
using Lumina.Contracts.Responses.Common;
using Lumina.Contracts.Responses.MediaLibrary.WrittenContentLibrary.BookLibrary.Books;
using Lumina.Domain.Common.Primitives;
using Lumina.Domain.Common.Errors;
using Lumina.Domain.SharedKernel.Common.Enums.BookLibrary;
using Lumina.Presentation.Api.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.Books.GetBooks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Http.HttpResults;
using NSubstitute;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Presentation.Api.UnitTests.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.Books.GetBooks;
/// <summary>
/// Contains unit tests for the <see cref="GetBooksEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetBooksEndpointTests
{
private readonly IQueryHandler<GetBooksQuery, Result<PaginatedResponse<BookResponse>>> _mockHandler;
private readonly GetBooksEndpoint _sut;
private readonly GetBooksRequestFixture _getBooksRequestFixture = new();
/// <summary>
/// Initializes a new instance of the <see cref="GetBooksEndpointTests"/> class.
/// </summary>
public GetBooksEndpointTests()
{
_mockHandler = Substitute.For<IQueryHandler<GetBooksQuery, Result<PaginatedResponse<BookResponse>>>>();
_sut = Factory.Create<GetBooksEndpoint>(_mockHandler);
}
[Fact]
public async Task ExecuteAsync_WhenSuccessful_ShouldReturnOkResultWithPaginatedBookResponses()
{
// Arrange
GetBooksRequest request = _getBooksRequestFixture.Create();
CancellationToken cancellationToken = CancellationToken.None;
PaginatedResponse<BookResponse> expectedResponse = CreatePaginatedResponse(bookCount: 2);
_mockHandler.HandleAsync(Arg.Any<GetBooksQuery>(), Arg.Any<CancellationToken>())
.Returns(Result.From(expectedResponse));
// Act
IResult result = await _sut.ExecuteAsync(request, cancellationToken);
// Assert
Ok<PaginatedResponse<BookResponse>> okResult = Assert.IsType<Ok<PaginatedResponse<BookResponse>>>(result);
Assert.Equal(expectedResponse, okResult.Value);
}
[Fact]
public async Task ExecuteAsync_WhenHandlerReturnsError_ShouldReturnProblemResult()
{
// Arrange
GetBooksRequest request = _getBooksRequestFixture.Create();
CancellationToken cancellationToken = CancellationToken.None;
Error expectedError = Error.NotFound("Book.NotFound", "The requested book was not found.");
_mockHandler.HandleAsync(Arg.Any<GetBooksQuery>(), Arg.Any<CancellationToken>())
.Returns(expectedError);
// Act
IResult result = await _sut.ExecuteAsync(request, cancellationToken);
// Assert
ProblemHttpResult problemDetails = Assert.IsType<ProblemHttpResult>(result);
Assert.Equal(StatusCodes.Status404NotFound, problemDetails.StatusCode);
Assert.Equal("application/problem+json", problemDetails.ContentType);
Assert.IsType<Microsoft.AspNetCore.Mvc.ProblemDetails>(problemDetails.ProblemDetails);
Assert.Equal("Book.NotFound", problemDetails.ProblemDetails.Title);
Assert.Equal("The requested book was not found.", problemDetails.ProblemDetails.Detail);
Assert.Equal(StatusCodes.Status404NotFound, problemDetails.ProblemDetails.Status);
Assert.Equal("https://tools.ietf.org/html/rfc9110#section-15.5.5", problemDetails.ProblemDetails.Type);
Assert.NotNull(problemDetails.ProblemDetails.Extensions["traceId"]);
}
[Fact]
public async Task ExecuteAsync_WhenHandlerReturnsValidationError_ShouldReturnValidationProblemResult()
{
// Arrange
GetBooksRequest request = _getBooksRequestFixture.Create();
CancellationToken cancellationToken = CancellationToken.None;
Error expectedError = Errors.Library.LibraryIdCannotBeEmpty;
_mockHandler.HandleAsync(Arg.Any<GetBooksQuery>(), Arg.Any<CancellationToken>())
.Returns(expectedError);
// Act
IResult result = await _sut.ExecuteAsync(request, cancellationToken);
// Assert
ProblemHttpResult problemDetails = Assert.IsType<ProblemHttpResult>(result);
Assert.Equal(StatusCodes.Status422UnprocessableEntity, problemDetails.StatusCode);
Assert.Equal("application/problem+json", problemDetails.ContentType);
HttpValidationProblemDetails validationProblemDetails = Assert.IsType<HttpValidationProblemDetails>(problemDetails.ProblemDetails);
Assert.Equal(StatusCodes.Status422UnprocessableEntity, validationProblemDetails.Status);
Assert.Equal("General.Validation", validationProblemDetails.Title);
Assert.Equal("OneOrMoreValidationErrorsOccurred", validationProblemDetails.Detail);
Assert.Equal("https://tools.ietf.org/html/rfc4918#section-11.2", validationProblemDetails.Type);
Assert.Single(validationProblemDetails.Errors);
Assert.Equal(new[] { "LibraryIdCannotBeEmpty" }, validationProblemDetails.Errors["General.Validation"]);
}
[Fact]
public async Task ExecuteAsync_WhenCalled_ShouldSendGetBooksQueryToSender()
{
// Arrange
GetBooksRequest request = _getBooksRequestFixture.Create();
CancellationToken cancellationToken = CancellationToken.None;
_mockHandler.HandleAsync(Arg.Any<GetBooksQuery>(), Arg.Any<CancellationToken>())
.Returns(Result.From(CreatePaginatedResponse(bookCount: 0)));
// Act
await _sut.ExecuteAsync(request, cancellationToken);
// Assert
await _mockHandler.Received(1).HandleAsync(Arg.Is<GetBooksQuery>(query =>
query.Filter.LibraryId == request.LibraryId &&
query.Filter.SearchTerm == request.SearchTerm &&
query.SortBy == request.SortBy &&
query.SortOrder == request.SortOrder &&
query.PaginationData != null &&
query.PaginationData.CurrentPage == request.CurrentPage &&
query.PaginationData.PerPage == request.PerPage),
Arg.Is(cancellationToken));
}
[Fact]
public async Task ExecuteAsync_WhenCancellationRequested_ShouldCancelOperation()
{
// Arrange
GetBooksRequest request = _getBooksRequestFixture.Create();
CancellationTokenSource cts = new();
TaskCompletionSource<bool> operationStarted = new();
TaskCompletionSource<bool> cancellationRequested = new();
_mockHandler.HandleAsync(Arg.Any<GetBooksQuery>(), Arg.Any<CancellationToken>())
.Returns(callInfo => Task.Run(async () =>
{
operationStarted.SetResult(true);
await cancellationRequested.Task;
callInfo.Arg<CancellationToken>().ThrowIfCancellationRequested();
return Result.From(CreatePaginatedResponse(bookCount: 0));
}, callInfo.Arg<CancellationToken>()));
// Act
Task<IResult> operationTask = _sut.ExecuteAsync(request, cts.Token);
await operationStarted.Task;
cts.Cancel();
cancellationRequested.SetResult(true);
// Assert
await Assert.ThrowsAnyAsync<OperationCanceledException>(() => operationTask);
}
/// <summary>
/// Creates a <see cref="PaginatedResponse{BookResponse}"/> with the specified number of books.
/// </summary>
/// <param name="bookCount">The number of book responses to include in the data collection.</param>
/// <returns>A configured paginated response instance.</returns>
private static PaginatedResponse<BookResponse> CreatePaginatedResponse(int bookCount)
{
List<BookResponse> books = [];
for (int index = 0; index < bookCount; index++)
books.Add(CreateBookResponse());
return new PaginatedResponse<BookResponse>
{
Data = books,
CurrentPage = 1,
PerPage = 10,
Count = bookCount,
NumberOfPages = bookCount > 0 ? 1 : 0
};
}
/// <summary>
/// Creates a minimal valid <see cref="BookResponse"/>.
/// </summary>
/// <returns>A configured book response instance.</returns>
private static BookResponse CreateBookResponse()
{
return new BookResponse(
Id: Guid.NewGuid(),
LibraryId: Guid.NewGuid(),
Path: "/books/test.epub",
Metadata: new WrittenContentMetadataDto(
Title: "Test Book",
OriginalTitle: null,
Description: null,
ReleaseInfo: null,
Genres: null,
Tags: null,
Language: null,
OriginalLanguage: null,
Publisher: null,
PageCount: null
),
Format: null,
Edition: null,
VolumeNumber: null,
Series: null,
ASIN: null,
GoodreadsId: null,
LCCN: null,
OCLCNumber: null,
OpenLibraryId: null,
LibraryThingId: null,
GoogleBooksId: null,
BarnesAndNobleId: null,
AppleBooksId: null,
ISBNs: null,
Contributors: null,
Ratings: null,
MetadataStatus: MetadataStatus.Pending,
LastMetadataUpdateUtc: null,
MetadataProvider: null,
CreatedOnUtc: DateTime.UtcNow,
UpdatedOnUtc: null
);
}
}
@@ -0,0 +1,190 @@
#region ========================================================================= USING =====================================================================================
using FastEndpoints;
using Lumina.Application.Common.CQRS;
using Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BooksLibrary.Books.Queries.GetBooksLite;
using Lumina.Contracts.Fixtures.Core.Requests.MediaLibrary.WrittenContentLibrary.BookLibrary.Books;
using Lumina.Contracts.Requests.MediaLibrary.WrittenContentLibrary.BookLibrary.Books;
using Lumina.Contracts.Responses.Common;
using Lumina.Contracts.Responses.MediaLibrary.WrittenContentLibrary.BookLibrary.Books;
using Lumina.Domain.Common.Primitives;
using Lumina.Domain.Common.Errors;
using Lumina.Presentation.Api.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.Books.GetBooksLite;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Http.HttpResults;
using NSubstitute;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Presentation.Api.UnitTests.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.Books.GetBooksLite;
/// <summary>
/// Contains unit tests for the <see cref="GetBooksLiteEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetBooksLiteEndpointTests
{
private readonly IQueryHandler<GetBooksLiteQuery, Result<PaginatedResponse<BookLiteResponse>>> _mockHandler;
private readonly GetBooksLiteEndpoint _sut;
private readonly GetBooksLiteRequestFixture _getBooksLiteRequestFixture = new();
/// <summary>
/// Initializes a new instance of the <see cref="GetBooksLiteEndpointTests"/> class.
/// </summary>
public GetBooksLiteEndpointTests()
{
_mockHandler = Substitute.For<IQueryHandler<GetBooksLiteQuery, Result<PaginatedResponse<BookLiteResponse>>>>();
_sut = Factory.Create<GetBooksLiteEndpoint>(_mockHandler);
}
[Fact]
public async Task ExecuteAsync_WhenSuccessful_ShouldReturnOkResultWithPaginatedBookLiteResponses()
{
// Arrange
GetBooksLiteRequest request = _getBooksLiteRequestFixture.Create();
CancellationToken cancellationToken = CancellationToken.None;
PaginatedResponse<BookLiteResponse> expectedResponse = CreatePaginatedResponse(bookCount: 2);
_mockHandler.HandleAsync(Arg.Any<GetBooksLiteQuery>(), Arg.Any<CancellationToken>())
.Returns(Result.From(expectedResponse));
// Act
IResult result = await _sut.ExecuteAsync(request, cancellationToken);
// Assert
Ok<PaginatedResponse<BookLiteResponse>> okResult = Assert.IsType<Ok<PaginatedResponse<BookLiteResponse>>>(result);
Assert.Equal(expectedResponse, okResult.Value);
}
[Fact]
public async Task ExecuteAsync_WhenHandlerReturnsError_ShouldReturnProblemResult()
{
// Arrange
GetBooksLiteRequest request = _getBooksLiteRequestFixture.Create();
CancellationToken cancellationToken = CancellationToken.None;
Error expectedError = Error.NotFound("Book.NotFound", "The requested book was not found.");
_mockHandler.HandleAsync(Arg.Any<GetBooksLiteQuery>(), Arg.Any<CancellationToken>())
.Returns(expectedError);
// Act
IResult result = await _sut.ExecuteAsync(request, cancellationToken);
// Assert
ProblemHttpResult problemDetails = Assert.IsType<ProblemHttpResult>(result);
Assert.Equal(StatusCodes.Status404NotFound, problemDetails.StatusCode);
Assert.Equal("application/problem+json", problemDetails.ContentType);
Assert.IsType<Microsoft.AspNetCore.Mvc.ProblemDetails>(problemDetails.ProblemDetails);
Assert.Equal("Book.NotFound", problemDetails.ProblemDetails.Title);
Assert.Equal("The requested book was not found.", problemDetails.ProblemDetails.Detail);
Assert.Equal(StatusCodes.Status404NotFound, problemDetails.ProblemDetails.Status);
Assert.Equal("https://tools.ietf.org/html/rfc9110#section-15.5.5", problemDetails.ProblemDetails.Type);
Assert.NotNull(problemDetails.ProblemDetails.Extensions["traceId"]);
}
[Fact]
public async Task ExecuteAsync_WhenHandlerReturnsValidationError_ShouldReturnValidationProblemResult()
{
// Arrange
GetBooksLiteRequest request = _getBooksLiteRequestFixture.Create();
CancellationToken cancellationToken = CancellationToken.None;
Error expectedError = Errors.Library.LibraryIdCannotBeEmpty;
_mockHandler.HandleAsync(Arg.Any<GetBooksLiteQuery>(), Arg.Any<CancellationToken>())
.Returns(expectedError);
// Act
IResult result = await _sut.ExecuteAsync(request, cancellationToken);
// Assert
ProblemHttpResult problemDetails = Assert.IsType<ProblemHttpResult>(result);
Assert.Equal(StatusCodes.Status422UnprocessableEntity, problemDetails.StatusCode);
Assert.Equal("application/problem+json", problemDetails.ContentType);
HttpValidationProblemDetails validationProblemDetails = Assert.IsType<HttpValidationProblemDetails>(problemDetails.ProblemDetails);
Assert.Equal(StatusCodes.Status422UnprocessableEntity, validationProblemDetails.Status);
Assert.Equal("General.Validation", validationProblemDetails.Title);
Assert.Equal("OneOrMoreValidationErrorsOccurred", validationProblemDetails.Detail);
Assert.Equal("https://tools.ietf.org/html/rfc4918#section-11.2", validationProblemDetails.Type);
Assert.Single(validationProblemDetails.Errors);
Assert.Equal(new[] { "LibraryIdCannotBeEmpty" }, validationProblemDetails.Errors["General.Validation"]);
}
[Fact]
public async Task ExecuteAsync_WhenCalled_ShouldSendGetBooksLiteQueryToSender()
{
// Arrange
GetBooksLiteRequest request = _getBooksLiteRequestFixture.Create();
CancellationToken cancellationToken = CancellationToken.None;
_mockHandler.HandleAsync(Arg.Any<GetBooksLiteQuery>(), Arg.Any<CancellationToken>())
.Returns(Result.From(CreatePaginatedResponse(bookCount: 0)));
// Act
await _sut.ExecuteAsync(request, cancellationToken);
// Assert
await _mockHandler.Received(1).HandleAsync(Arg.Is<GetBooksLiteQuery>(query =>
query.Filter.LibraryId == request.LibraryId &&
query.Filter.SearchTerm == request.SearchTerm &&
query.SortBy == request.SortBy &&
query.SortOrder == request.SortOrder &&
query.PaginationData != null &&
query.PaginationData.CurrentPage == request.CurrentPage &&
query.PaginationData.PerPage == request.PerPage),
Arg.Is(cancellationToken));
}
[Fact]
public async Task ExecuteAsync_WhenCancellationRequested_ShouldCancelOperation()
{
// Arrange
GetBooksLiteRequest request = _getBooksLiteRequestFixture.Create();
CancellationTokenSource cts = new();
TaskCompletionSource<bool> operationStarted = new();
TaskCompletionSource<bool> cancellationRequested = new();
_mockHandler.HandleAsync(Arg.Any<GetBooksLiteQuery>(), Arg.Any<CancellationToken>())
.Returns(callInfo => Task.Run(async () =>
{
operationStarted.SetResult(true);
await cancellationRequested.Task;
callInfo.Arg<CancellationToken>().ThrowIfCancellationRequested();
return Result.From(CreatePaginatedResponse(bookCount: 0));
}, callInfo.Arg<CancellationToken>()));
// Act
Task<IResult> operationTask = _sut.ExecuteAsync(request, cts.Token);
await operationStarted.Task;
cts.Cancel();
cancellationRequested.SetResult(true);
// Assert
await Assert.ThrowsAnyAsync<OperationCanceledException>(() => operationTask);
}
/// <summary>
/// Creates a <see cref="PaginatedResponse{BookLiteResponse}"/> with the specified number of books.
/// </summary>
/// <param name="bookCount">The number of book responses to include in the data collection.</param>
/// <returns>A configured paginated response instance.</returns>
private static PaginatedResponse<BookLiteResponse> CreatePaginatedResponse(int bookCount)
{
List<BookLiteResponse> books = [];
for (int index = 0; index < bookCount; index++)
books.Add(new BookLiteResponse(
Id: Guid.NewGuid(),
Title: "Test Book",
ReleaseYear: 2001,
CoverPath: null
));
return new PaginatedResponse<BookLiteResponse>
{
Data = books,
CurrentPage = 1,
PerPage = 10,
Count = bookCount,
NumberOfPages = bookCount > 0 ? 1 : 0
};
}
}