Refactors the book, artist, and album slices across the stack

This commit is contained in:
BinaryAlley committed 2026-09-17 13:30:48 -07:00
1 parent 8aaf9fe64e
commit ea6eb9f796
439 files changed
+28235 -3156

No files matched your search

@@ -1,7 +1,7 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary;
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary;
using Lumina.DataAccess.Core.Repositories.Books;
using Lumina.DataAccess.Core.Repositories.BookLibrary;
using Lumina.DataAccess.Core.UoW;
using Lumina.Domain.Common.Errors;
using Lumina.Domain.Common.Primitives;
@@ -16,7 +16,7 @@ using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.DataAccess.IntegrationTests.Core.Repositories.Books;
namespace Lumina.DataAccess.IntegrationTests.Core.Repositories.BookLibrary;
/// <summary>
/// Contains integration tests for the <see cref="BookRepository"/> class, exercising it against a real SQLite database.
@@ -43,12 +43,12 @@ public class BookRepositoryTests
changedBook.LibraryId = libraryId;
changedBook.Path = "/books/changed.epub";
changedBook.MetadataStatus = MetadataStatus.Enriched;
changedBook.BookArtwork = [_bookArtworkEntityFixture.Create(bookId: changedBook.Id, artworkType: ArtworkType.Cover, ordinal: 0, status: ArtworkStatus.Enriched)];
changedBook.Artwork = [_bookArtworkEntityFixture.Create(bookId: changedBook.Id, artworkType: ArtworkType.Cover, ordinal: 0, status: ArtworkStatus.Enriched)];
BookEntity unchangedBook = _bookEntityFixture.Create();
unchangedBook.LibraryId = libraryId;
unchangedBook.Path = "/books/unchanged.epub";
unchangedBook.MetadataStatus = MetadataStatus.Enriched;
unchangedBook.BookArtwork = [_bookArtworkEntityFixture.Create(bookId: unchangedBook.Id, artworkType: ArtworkType.Cover, ordinal: 0, status: ArtworkStatus.Enriched)];
unchangedBook.Artwork = [_bookArtworkEntityFixture.Create(bookId: unchangedBook.Id, artworkType: ArtworkType.Cover, ordinal: 0, status: ArtworkStatus.Enriched)];
context.Books.AddRange(changedBook, unchangedBook);
await context.SaveChangesAsync();
@@ -58,10 +58,10 @@ public class BookRepositoryTests
// Assert
Assert.False(result.IsFailure);
Assert.Equal(Result.Updated, result.Value);
BookEntity? resetBook = await context.Books.AsNoTracking().Include(book => book.BookArtwork).FirstOrDefaultAsync(book => book.Id == changedBook.Id);
BookEntity? resetBook = await context.Books.AsNoTracking().Include(book => book.Artwork).FirstOrDefaultAsync(book => book.Id == changedBook.Id);
Assert.NotNull(resetBook);
Assert.Equal(MetadataStatus.Pending, resetBook!.MetadataStatus);
Assert.Equal(ArtworkStatus.Pending, resetBook.BookArtwork.Single().Status);
Assert.Equal(ArtworkStatus.Pending, resetBook.Artwork.Single().Status);
BookEntity? keptBook = await context.Books.AsNoTracking().FirstOrDefaultAsync(book => book.Id == unchangedBook.Id);
Assert.NotNull(keptBook);
Assert.Equal(MetadataStatus.Enriched, keptBook!.MetadataStatus);
@@ -116,10 +116,10 @@ public class BookRepositoryTests
Guid libraryId = Guid.NewGuid();
BookEntity book = _bookEntityFixture.Create();
book.LibraryId = libraryId;
book.BookArtwork = [_bookArtworkEntityFixture.Create(bookId: book.Id, artworkType: ArtworkType.Cover, ordinal: 0, status: ArtworkStatus.Enriched)];
book.Artwork = [_bookArtworkEntityFixture.Create(bookId: book.Id, artworkType: ArtworkType.Cover, ordinal: 0, status: ArtworkStatus.Enriched)];
BookEntity bookOfAnotherLibrary = _bookEntityFixture.Create();
bookOfAnotherLibrary.LibraryId = Guid.NewGuid();
bookOfAnotherLibrary.BookArtwork = [_bookArtworkEntityFixture.Create(bookId: bookOfAnotherLibrary.Id, artworkType: ArtworkType.Cover, ordinal: 0, status: ArtworkStatus.Enriched)];
bookOfAnotherLibrary.Artwork = [_bookArtworkEntityFixture.Create(bookId: bookOfAnotherLibrary.Id, artworkType: ArtworkType.Cover, ordinal: 0, status: ArtworkStatus.Enriched)];
context.Books.AddRange(book, bookOfAnotherLibrary);
await context.SaveChangesAsync();
@@ -64,6 +64,7 @@ public class BooksFileSystemDiscoveryJobTests
_mockServiceScope.ServiceProvider.Returns(_mockServiceProvider);
_mockUnitOfWork = Substitute.For<IUnitOfWork>();
_mockUnitOfWork.SaveChangesAsync(Arg.Any<CancellationToken>()).Returns(Result.Success);
_mockLibraryRepository = Substitute.For<ILibraryRepository>();
_mockStagingResultsRepository = Substitute.For<ILibraryScanStagingResultsRepository>();
_mockDirectoryScanFingerprintRepository = Substitute.For<IDirectoryScanFingerprintRepository>();
@@ -105,7 +106,7 @@ public class BooksFileSystemDiscoveryJobTests
libraryType: LibraryType.Book,
contentLocations: [temporaryLibraryDirectory.Path],
shouldSkipUnchangedDirectoriesDuringScan: false);
_mockLibraryRepository.GetByIdAsync(_libraryId.Value, Arg.Any<CancellationToken>())
_mockLibraryRepository.GetByIdAsync(_libraryId.Value, cancellationToken: Arg.Any<CancellationToken>())
.Returns(Result.From<LibraryEntity?>(libraryEntity));
_mockStagingResultsRepository.InsertRangeAsync(Arg.Any<IReadOnlyCollection<LibraryScanStagingResultsEntity>>(), Arg.Any<CancellationToken>())
.Returns(Result.From(Result.Created));
@@ -154,7 +155,7 @@ public class BooksFileSystemDiscoveryJobTests
libraryType: LibraryType.Book,
contentLocations: [temporaryLibraryDirectory.Path],
shouldSkipUnchangedDirectoriesDuringScan: true);
_mockLibraryRepository.GetByIdAsync(_libraryId.Value, Arg.Any<CancellationToken>())
_mockLibraryRepository.GetByIdAsync(_libraryId.Value, cancellationToken: Arg.Any<CancellationToken>())
.Returns(Result.From<LibraryEntity?>(libraryEntity));
_mockDirectoryScanFingerprintRepository.GetMappedByLibraryIdAsync(_libraryId.Value, Arg.Any<CancellationToken>())
.Returns(Result.From(new Dictionary<string, DirectoryScanFingerprintEntity>
@@ -200,7 +201,7 @@ public class BooksFileSystemDiscoveryJobTests
libraryType: LibraryType.Book,
contentLocations: [temporaryLibraryDirectory.Path],
shouldSkipUnchangedDirectoriesDuringScan: true);
_mockLibraryRepository.GetByIdAsync(_libraryId.Value, Arg.Any<CancellationToken>())
_mockLibraryRepository.GetByIdAsync(_libraryId.Value, cancellationToken: Arg.Any<CancellationToken>())
.Returns(Result.From<LibraryEntity?>(libraryEntity));
_mockDirectoryScanFingerprintRepository.GetMappedByLibraryIdAsync(_libraryId.Value, Arg.Any<CancellationToken>())
.Returns(Error.Failure("Database.Error", "Failed to load the directory scan fingerprints"));
@@ -228,7 +229,7 @@ public class BooksFileSystemDiscoveryJobTests
libraryType: LibraryType.Book,
contentLocations: [temporaryLibraryDirectory.Path],
shouldSkipUnchangedDirectoriesDuringScan: true);
_mockLibraryRepository.GetByIdAsync(_libraryId.Value, Arg.Any<CancellationToken>())
_mockLibraryRepository.GetByIdAsync(_libraryId.Value, cancellationToken: Arg.Any<CancellationToken>())
.Returns(Result.From<LibraryEntity?>(libraryEntity));
_mockDirectoryScanFingerprintRepository.GetMappedByLibraryIdAsync(_libraryId.Value, Arg.Any<CancellationToken>())
.Returns(Result.From(new Dictionary<string, DirectoryScanFingerprintEntity>()));
@@ -259,7 +260,7 @@ public class BooksFileSystemDiscoveryJobTests
libraryType: LibraryType.Book,
contentLocations: [temporaryLibraryDirectory.Path],
shouldSkipUnchangedDirectoriesDuringScan: false);
_mockLibraryRepository.GetByIdAsync(_libraryId.Value, Arg.Any<CancellationToken>())
_mockLibraryRepository.GetByIdAsync(_libraryId.Value, cancellationToken: Arg.Any<CancellationToken>())
.Returns(Result.From<LibraryEntity?>(libraryEntity));
_mockStagingResultsRepository.InsertRangeAsync(Arg.Any<IReadOnlyCollection<LibraryScanStagingResultsEntity>>(), Arg.Any<CancellationToken>())
.Returns(Error.Failure("Database.Error", "Failed to insert the staging results"));
@@ -289,7 +290,7 @@ public class BooksFileSystemDiscoveryJobTests
libraryType: LibraryType.Book,
contentLocations: [temporaryLibraryDirectory.Path],
shouldSkipUnchangedDirectoriesDuringScan: false);
_mockLibraryRepository.GetByIdAsync(_libraryId.Value, Arg.Any<CancellationToken>())
_mockLibraryRepository.GetByIdAsync(_libraryId.Value, cancellationToken: Arg.Any<CancellationToken>())
.Returns(Result.From<LibraryEntity?>(libraryEntity));
_mockStagingResultsRepository.InsertRangeAsync(Arg.Any<IReadOnlyCollection<LibraryScanStagingResultsEntity>>(), Arg.Any<CancellationToken>())
.Returns(Result.From(Result.Created));
@@ -67,6 +67,7 @@ public class BookReadingServiceTests : IDisposable
_mockPluginManager.GetPlugins().Returns([_mockPlugin]);
_mockUnitOfWork = Substitute.For<IUnitOfWork>();
_mockUnitOfWork.SaveChangesAsync(Arg.Any<CancellationToken>()).Returns(Result.Success);
_mockConfigurationRepository = Substitute.For<ILibraryBookReaderConfigurationRepository>();
_mockUnitOfWork.LibraryBookReaderConfigurationRepository.Returns(_mockConfigurationRepository);
LibraryBookReaderConfigurationEntity enabledConfiguration = _configurationEntityFixture.Create(libraryId: _libraryId, pluginId: _pluginId, isEnabled: true);
@@ -1,286 +0,0 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Domain.SharedKernel.Common.Enums.BookLibrary;
using Lumina.Domain.SharedKernel.Common.Enums.Common;
using Lumina.Domain.Common.Primitives;
using Lumina.Domain.Common.ValueObjects.Metadata;
using Lumina.Domain.Core.BoundedContexts.MediaContributorBoundedContext.MediaContributorAggregate.ValueObjects;
using Lumina.Domain.Core.BoundedContexts.WrittenContentLibraryBoundedContext.BookLibraryAggregate;
using Lumina.Domain.Core.BoundedContexts.WrittenContentLibraryBoundedContext.BookLibraryAggregate.Entities;
using Lumina.Domain.Core.BoundedContexts.WrittenContentLibraryBoundedContext.BookLibraryAggregate.ValueObjects;
using Lumina.Domain.Core.BoundedContexts.WrittenContentLibraryBoundedContext.ExternalIdentifiers.LibraryManagementBoundedContext.LibraryAggregate;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Text.Json;
using System.Text.Json.Serialization;
#endregion
namespace Lumina.Presentation.Api.IntegrationTests.Common.Converters;
/// <summary>
/// Custom JSON converter for the <see cref="Book"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class BookJsonConverter : JsonConverter<Book>
{
/// <summary>
/// Reads and converts JSON to a <see cref="Book"/> object.
/// </summary>
/// <param name="reader">The JSON reader.</param>
/// <param name="typeToConvert">The type of the object to convert.</param>
/// <param name="options">The serializer options.</param>
/// <returns>The converted <see cref="Book"/> object.</returns>
public override Book Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
{
using (JsonDocument doc = JsonDocument.ParseValue(ref reader))
{
JsonElement root = doc.RootElement;
Guid id = root.GetProperty("id").GetGuid();
Guid libraryId = root.GetProperty("libraryId").GetGuid();
string path = root.GetProperty("path").GetString()!;
DateTime createdOnUtc = root.GetProperty("createdOnUtc").GetDateTime();
WrittenContentMetadata metadata = DeserializeMetadata(root.GetProperty("metadata"));
BookFormat? format = null;
if (root.TryGetProperty("format", out JsonElement formatElement))
{
if (formatElement.ValueKind == JsonValueKind.String)
{
string formatString = formatElement.GetString()!;
if (Enum.TryParse(formatString, out BookFormat parsedFormat))
format = parsedFormat;
}
}
string? edition = root.GetProperty("edition").GetString();
int volumeNumber = root.GetProperty("volumeNumber").GetInt32();
BookSeries series = DeserializeBookSeries(root.GetProperty("series"));
string? asin = root.GetProperty("asin").GetString();
string? goodreadsId = root.GetProperty("goodreadsId").GetString();
string? lccn = root.GetProperty("lccn").GetString();
string? oclcNumber = root.GetProperty("oclcNumber").GetString();
string? openLibraryId = root.GetProperty("openLibraryId").GetString();
string? libraryThingId = root.GetProperty("libraryThingId").GetString();
string? googleBooksId = root.GetProperty("googleBooksId").GetString();
string? barnesAndNobleId = root.GetProperty("barnesAndNobleId").GetString();
string? appleBooksId = root.GetProperty("appleBooksId").GetString();
List<Isbn> isbns = DeserializeIsbns(root.GetProperty("isbNs"));
List<MediaContributorId> contributorIds = DeserializeContributorIds(root.GetProperty("contributors"));
List<BookRating> ratings = DeserializeRatings(root.GetProperty("ratings"));
Result<Book> createBookResult = Book.Create(
BookId.Create(id),
LibraryId.Create(libraryId),
path,
metadata,
Optional<BookFormat>.FromNullable(format),
Optional<string>.FromNullable(edition),
volumeNumber,
Optional<BookSeries>.FromNullable(series),
Optional<string>.FromNullable(asin),
Optional<string>.FromNullable(goodreadsId),
Optional<string>.FromNullable(lccn),
Optional<string>.FromNullable(oclcNumber),
Optional<string>.FromNullable(openLibraryId),
Optional<string>.FromNullable(libraryThingId),
Optional<string>.FromNullable(googleBooksId),
Optional<string>.FromNullable(barnesAndNobleId),
Optional<string>.FromNullable(appleBooksId),
createdOnUtc,
default,
isbns,
contributorIds,
ratings: ratings
);
if (createBookResult.IsFailure)
throw new JsonException($"Failed to create Book: {string.Join(", ", createBookResult.Errors)}");
return createBookResult.Value;
}
}
/// <summary>
/// Writes a <see cref="Book"/> object to JSON. This method is not implemented.
/// </summary>
/// <param name="writer">The JSON writer.</param>
/// <param name="value">The <see cref="Book"/> object to write.</param>
/// <param name="options">The serializer options.</param>
public override void Write(Utf8JsonWriter writer, Book value, JsonSerializerOptions options)
{
throw new NotImplementedException("Serialization is not implemented for Book class.");
}
/// <summary>
/// Deserializes the metadata from JSON.
/// </summary>
/// <param name="element">The JSON element containing the metadata.</param>
/// <returns>The deserialized <see cref="WrittenContentMetadata"/>.</returns>
private static WrittenContentMetadata DeserializeMetadata(JsonElement element)
{
string? title = element.GetProperty("title").GetString();
string? originalTitle = element.GetProperty("originalTitle").GetString();
string? description = element.GetProperty("description").GetString();
ReleaseInfo releaseInfo = DeserializeReleaseInfo(element.GetProperty("releaseInfo"));
List<Genre> genres = DeserializeGenres(element.GetProperty("genres"));
List<Tag> tags = DeserializeTags(element.GetProperty("tags"));
LanguageInfo? language = DeserializeLanguageInfo(element.GetProperty("language"));
LanguageInfo? originalLanguage = DeserializeLanguageInfo(element.GetProperty("originalLanguage"));
string? publisher = element.GetProperty("publisher").GetString();
int? pageCount = null;
if (element.TryGetProperty("pageCount", out JsonElement pageCountElement))
if (pageCountElement.ValueKind != JsonValueKind.Null)
pageCount = pageCountElement.GetInt32();
Result<WrittenContentMetadata> metadataResult = WrittenContentMetadata.Create(
title!,
Optional<string>.FromNullable(originalTitle),
Optional<string>.FromNullable(description),
releaseInfo,
genres,
tags,
Optional<LanguageInfo>.FromNullable(language),
Optional<LanguageInfo>.FromNullable(originalLanguage),
Optional<string>.FromNullable(publisher),
Optional<int>.FromNullable(pageCount)
);
if (metadataResult.IsFailure)
throw new JsonException($"Failed to create WrittenContentMetadata: {string.Join(", ", metadataResult.Errors)}");
return metadataResult.Value;
}
/// <summary>
/// Deserializes the release info from JSON.
/// </summary>
/// <param name="element">The JSON element containing the release info.</param>
/// <returns>The deserialized <see cref="ReleaseInfo"/>.</returns>
private static ReleaseInfo DeserializeReleaseInfo(JsonElement element)
{
DateOnly? originalReleaseDate = element.TryGetProperty("originalReleaseDate", out JsonElement ordElement) && ordElement.ValueKind != JsonValueKind.Null ?
DateOnly.Parse(ordElement.GetString()!) : (DateOnly?)null;
int? originalReleaseYear = element.TryGetProperty("originalReleaseYear", out JsonElement oryElement) && oryElement.ValueKind == JsonValueKind.Number
? oryElement.GetInt32() : (int?)null;
DateOnly? reReleaseDate = element.TryGetProperty("reReleaseDate", out JsonElement rrdElement) && rrdElement.ValueKind == JsonValueKind.String ?
DateOnly.Parse(rrdElement.GetString()!) : (DateOnly?)null;
int? reReleaseYear = element.TryGetProperty("reReleaseYear", out JsonElement rryElement) && rryElement.ValueKind == JsonValueKind.Number
? rryElement.GetInt32() : (int?)null;
string? releaseCountry = element.TryGetProperty("releaseCountry", out JsonElement rcElement) ?
rcElement.GetString() : null;
string? releaseVersion = element.TryGetProperty("releaseVersion", out JsonElement rvElement) ?
rvElement.GetString() : null;
Optional<ReleaseCountry> releaseCountryValue = Optional<ReleaseCountry>.None();
if (releaseCountry is not null && Enum.TryParse(releaseCountry, ignoreCase: true, out ReleaseCountry parsedReleaseCountry))
releaseCountryValue = parsedReleaseCountry;
Result<ReleaseInfo> releaseInfoResult = ReleaseInfo.Create(
Optional<DateOnly>.FromNullable(originalReleaseDate),
Optional<int>.FromNullable(originalReleaseYear),
Optional<DateOnly>.FromNullable(reReleaseDate),
Optional<int>.FromNullable(reReleaseYear),
releaseCountryValue,
Optional<string>.FromNullable(releaseVersion)
);
if (releaseInfoResult.IsFailure)
throw new JsonException($"Failed to create ReleaseInfo: {string.Join(", ", releaseInfoResult.Errors)}");
return releaseInfoResult.Value;
}
/// <summary>
/// Deserializes the genres from JSON.
/// </summary>
/// <param name="element">The JSON element containing the genres.</param>
/// <returns>The deserialized list of <see cref="Genre"/>.</returns>
private static List<Genre> DeserializeGenres(JsonElement element)
{
return [.. element.EnumerateArray().Select(g => Genre.Create(g.GetProperty("name").GetString()!).Value)];
}
/// <summary>
/// Deserializes the tags from JSON.
/// </summary>
/// <param name="element">The JSON element containing the tags.</param>
/// <returns>The deserialized list of <see cref="Tag"/>.</returns>
private static List<Tag> DeserializeTags(JsonElement element)
{
return [.. element.EnumerateArray().Select(t => Tag.Create(t.GetProperty("name").GetString()!).Value)];
}
/// <summary>
/// Deserializes the language info from JSON.
/// </summary>
/// <param name="element">The JSON element containing the language info.</param>
/// <returns>The deserialized <see cref="LanguageInfo"/>.</returns>
private static LanguageInfo? DeserializeLanguageInfo(JsonElement element)
{
if (element.ValueKind != JsonValueKind.Null)
{
string? languageCode = element.GetProperty("languageCode").GetString();
string? languageName = element.GetProperty("languageName").GetString();
string? nativeName = element.TryGetProperty("nativeName", out JsonElement nnElement) ? nnElement.GetString() : null;
Result<LanguageInfo> languageInfoResult = LanguageInfo.Create(
languageCode!,
languageName!,
Optional<string>.FromNullable(nativeName)
);
if (languageInfoResult.IsFailure)
throw new JsonException($"Failed to create LanguageInfo: {string.Join(", ", languageInfoResult.Errors)}");
return languageInfoResult.Value;
}
else
return null;
}
/// <summary>
/// Deserializes the book series from JSON.
/// </summary>
/// <param name="element">The JSON element containing the book series.</param>
/// <returns>The deserialized <see cref="BookSeries"/>.</returns>
private static BookSeries DeserializeBookSeries(JsonElement element)
{
// TODO: implement when book series are implemented
return null!;
}
/// <summary>
/// Deserializes the ISBNs from JSON.
/// </summary>
/// <param name="element">The JSON element containing the ISBNs.</param>
/// <returns>The deserialized list of <see cref="Isbn"/>.</returns>
private static List<Isbn> DeserializeIsbns(JsonElement element)
{
return [.. element.EnumerateArray()
.Select(i => Isbn.Create(i.GetProperty("value").GetString()!,
Enum.Parse<IsbnFormat>(i.GetProperty("format").GetString()!)).Value)];
}
/// <summary>
/// Deserializes the contributor IDs from JSON.
/// </summary>
/// <param name="element">The JSON element containing the contributor IDs.</param>
/// <returns>The deserialized list of <see cref="MediaContributorId"/>.</returns>
private static List<MediaContributorId> DeserializeContributorIds(JsonElement element)
{
// TODO: implement when contributors are implemented
return [];
}
/// <summary>
/// Deserializes the ratings from JSON.
/// </summary>
/// <param name="element">The JSON element containing the ratings.</param>
/// <returns>The deserialized list of <see cref="BookRating"/>.</returns>
private static List<BookRating> DeserializeRatings(JsonElement element)
{
return [.. element.EnumerateArray()
.Select(r => BookRating.Create(
r.GetProperty("value").GetInt32(),
r.GetProperty("maxValue").GetInt32(),
Optional<BookRatingSource>.FromNullable(Enum.Parse<BookRatingSource>(r.GetProperty("source").GetString()!)),
Optional<int>.FromNullable(
r.TryGetProperty("voteCount", out JsonElement voteCountElement) && voteCountElement.ValueKind != JsonValueKind.Null
? voteCountElement.GetInt32()
: (int?)null)
).Value)];
}
}
@@ -1,4 +1,4 @@
#region ========================================================================= USING =====================================================================================
#region ========================================================================= USING =====================================================================================
using Bogus;
using Lumina.Application.Common.DataAccess.Entities.MediaContributors;
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary;
@@ -11,14 +11,13 @@ using Lumina.Contracts.Fixtures.Core.DTO.MediaLibrary.WrittenContentLibrary;
using Lumina.Contracts.Fixtures.Core.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary;
using Lumina.Contracts.Fixtures.Core.Requests.MediaLibrary.WrittenContentLibrary.BookLibrary.Books;
using Lumina.Contracts.Requests.MediaLibrary.WrittenContentLibrary.BookLibrary.Books;
using Lumina.Contracts.Responses.MediaLibrary.WrittenContentLibrary.BookLibrary.Books;
using Lumina.DataAccess.Core.UoW;
using Lumina.Domain.Common.Errors;
using Lumina.Domain.Core.BoundedContexts.WrittenContentLibraryBoundedContext.BookLibraryAggregate;
using Lumina.Domain.SharedKernel.Common.Enums.BookLibrary;
using Lumina.Domain.SharedKernel.Common.Enums.Common;
using Lumina.Domain.SharedKernel.Common.Enums.MediaContributors;
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
using Lumina.Presentation.Api.IntegrationTests.Common.Converters;
using Lumina.Presentation.Api.IntegrationTests.Common.Setup;
using Microsoft.AspNetCore.Http;
using Microsoft.EntityFrameworkCore;
@@ -33,6 +32,7 @@ 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;
#endregion
@@ -48,12 +48,8 @@ public class AddBookEndpointTests : IClassFixture<AuthenticatedLuminaApiFactory>
private readonly AuthenticatedLuminaApiFactory _apiFactory;
private readonly JsonSerializerOptions _jsonOptions = new()
{
ReferenceHandler = ReferenceHandler.Preserve,
PropertyNameCaseInsensitive = true,
Converters = {
new JsonStringEnumConverter(JsonNamingPolicy.CamelCase),
new BookJsonConverter()
}
Converters = { new JsonStringEnumConverter(JsonNamingPolicy.CamelCase) }
};
private readonly AddBookRequestFixture _requestBookFixture = new();
private readonly WrittenContentMetadataDtoFixture _writtenContentMetadataDtoFixture = new();
@@ -106,62 +102,62 @@ public class AddBookEndpointTests : IClassFixture<AuthenticatedLuminaApiFactory>
// Assert
response.EnsureSuccessStatusCode();
Book? bookResponse = await response.Content.ReadFromJsonAsync<Book>(_jsonOptions);
BookResponse? bookResponse = await response.Content.ReadFromJsonAsync<BookResponse>(_jsonOptions);
Assert.Equal(HttpStatusCode.Created, response.StatusCode);
Assert.NotNull(bookResponse);
// metadata checks
Assert.Equal(bookRequest.Metadata!.Title, bookResponse!.Metadata.Title);
Assert.Equal(bookRequest.Metadata.OriginalTitle, bookResponse.Metadata.OriginalTitle.Value);
Assert.Equal(bookRequest.Metadata.Description, bookResponse.Metadata.Description.Value);
Assert.Equal(bookRequest.Metadata.Publisher, bookResponse.Metadata.Publisher.Value);
Assert.Equal(bookRequest.Metadata.PageCount, bookResponse.Metadata.PageCount.Value);
Assert.Equal(bookRequest.Metadata.OriginalTitle, bookResponse.Metadata.OriginalTitle);
Assert.Equal(bookRequest.Metadata.Description, bookResponse.Metadata.Description);
Assert.Equal(bookRequest.Metadata.Publisher, bookResponse.Metadata.Publisher);
Assert.Equal(bookRequest.Metadata.PageCount, bookResponse.Metadata.PageCount);
Assert.Equal(bookRequest.Metadata.ReleaseInfo!.OriginalReleaseDate, bookResponse.Metadata.ReleaseInfo.OriginalReleaseDate.Value);
Assert.Equal(bookRequest.Metadata.ReleaseInfo.OriginalReleaseYear, bookResponse.Metadata.ReleaseInfo.OriginalReleaseYear.Value);
Assert.Equal(bookRequest.Metadata.ReleaseInfo.ReReleaseDate, bookResponse.Metadata.ReleaseInfo.ReReleaseDate.Value);
Assert.Equal(bookRequest.Metadata.ReleaseInfo.ReReleaseYear, bookResponse.Metadata.ReleaseInfo.ReReleaseYear.Value);
Assert.Equal(bookRequest.Metadata.ReleaseInfo!.ReleaseCountry, bookResponse.Metadata.ReleaseInfo.ReleaseCountry.Value);
Assert.Equal(bookRequest.Metadata.ReleaseInfo.ReleaseVersion, bookResponse.Metadata.ReleaseInfo.ReleaseVersion.Value);
Assert.Equal(bookRequest.Metadata.ReleaseInfo!.OriginalReleaseDate, bookResponse.Metadata.ReleaseInfo!.OriginalReleaseDate);
Assert.Equal(bookRequest.Metadata.ReleaseInfo.OriginalReleaseYear, bookResponse.Metadata.ReleaseInfo.OriginalReleaseYear);
Assert.Equal(bookRequest.Metadata.ReleaseInfo.ReReleaseDate, bookResponse.Metadata.ReleaseInfo.ReReleaseDate);
Assert.Equal(bookRequest.Metadata.ReleaseInfo.ReReleaseYear, bookResponse.Metadata.ReleaseInfo.ReReleaseYear);
Assert.Equal(bookRequest.Metadata.ReleaseInfo.ReleaseCountry, bookResponse.Metadata.ReleaseInfo.ReleaseCountry);
Assert.Equal(bookRequest.Metadata.ReleaseInfo.ReleaseVersion, bookResponse.Metadata.ReleaseInfo.ReleaseVersion);
// language checks
Assert.Equal(bookRequest.Metadata.Language!.LanguageCode, bookResponse.Metadata.Language.Value.LanguageCode);
Assert.Equal(bookRequest.Metadata.Language.LanguageName, bookResponse.Metadata.Language.Value.LanguageName);
Assert.Equal(bookRequest.Metadata.Language.NativeName, bookResponse.Metadata.Language.Value.NativeName.Value);
Assert.Equal(bookRequest.Metadata.Language!.LanguageCode, bookResponse.Metadata.Language!.LanguageCode);
Assert.Equal(bookRequest.Metadata.Language.LanguageName, bookResponse.Metadata.Language.LanguageName);
Assert.Equal(bookRequest.Metadata.Language.NativeName, bookResponse.Metadata.Language.NativeName);
// original language checks
Assert.Equal(bookRequest.Metadata.OriginalLanguage!.LanguageCode, bookResponse.Metadata.OriginalLanguage.Value.LanguageCode);
Assert.Equal(bookRequest.Metadata.OriginalLanguage.LanguageName, bookResponse.Metadata.OriginalLanguage.Value.LanguageName);
Assert.Equal(bookRequest.Metadata.OriginalLanguage.NativeName, bookResponse.Metadata.OriginalLanguage.Value.NativeName.Value);
Assert.Equal(bookRequest.Metadata.OriginalLanguage!.LanguageCode, bookResponse.Metadata.OriginalLanguage!.LanguageCode);
Assert.Equal(bookRequest.Metadata.OriginalLanguage.LanguageName, bookResponse.Metadata.OriginalLanguage.LanguageName);
Assert.Equal(bookRequest.Metadata.OriginalLanguage.NativeName, bookResponse.Metadata.OriginalLanguage.NativeName);
// genres checks
Assert.Equal(bookRequest.Metadata.Genres!.Count, bookResponse.Metadata.Genres.Count);
Assert.Equal(bookRequest.Metadata.Genres!.Count, bookResponse.Metadata.Genres!.Count);
Assert.Equal(
bookRequest.Metadata.Genres.Select(genre => genre.Name).OrderBy(x => x),
bookResponse.Metadata.Genres.Select(genre => genre.Name).OrderBy(x => x));
// tags checks
Assert.Equal(bookRequest.Metadata.Tags!.Count, bookResponse.Metadata.Tags.Count);
Assert.Equal(bookRequest.Metadata.Tags!.Count, bookResponse.Metadata.Tags!.Count);
Assert.Equal(
bookRequest.Metadata.Tags.Select(tag => tag.Name).OrderBy(x => x),
bookResponse.Metadata.Tags.Select(tag => tag.Name).OrderBy(x => x));
// book specific properties
Assert.Equal(bookRequest.Format, bookResponse.Format.Value);
Assert.Equal(bookRequest.Edition, bookResponse.Edition.Value);
Assert.Equal(bookRequest.VolumeNumber, bookResponse.VolumeNumber.Value);
Assert.Equal(bookRequest.ASIN, bookResponse.ASIN.Value);
Assert.Equal(bookRequest.GoodreadsId, bookResponse.GoodreadsId.Value);
Assert.Equal(bookRequest.LCCN, bookResponse.LCCN.Value);
Assert.Equal(bookRequest.OCLCNumber, bookResponse.OCLCNumber.Value);
Assert.Equal(bookRequest.OpenLibraryId, bookResponse.OpenLibraryId.Value);
Assert.Equal(bookRequest.LibraryThingId, bookResponse.LibraryThingId.Value);
Assert.Equal(bookRequest.GoogleBooksId, bookResponse.GoogleBooksId.Value);
Assert.Equal(bookRequest.BarnesAndNobleId, bookResponse.BarnesAndNobleId.Value);
Assert.Equal(bookRequest.AppleBooksId, bookResponse.AppleBooksId.Value);
Assert.Equal(bookRequest.Format, bookResponse.Format);
Assert.Equal(bookRequest.Edition, bookResponse.Edition);
Assert.Equal(bookRequest.VolumeNumber, bookResponse.VolumeNumber);
Assert.Equal(bookRequest.ASIN, bookResponse.ASIN);
Assert.Equal(bookRequest.GoodreadsId, bookResponse.GoodreadsId);
Assert.Equal(bookRequest.LCCN, bookResponse.LCCN);
Assert.Equal(bookRequest.OCLCNumber, bookResponse.OCLCNumber);
Assert.Equal(bookRequest.OpenLibraryId, bookResponse.OpenLibraryId);
Assert.Equal(bookRequest.LibraryThingId, bookResponse.LibraryThingId);
Assert.Equal(bookRequest.GoogleBooksId, bookResponse.GoogleBooksId);
Assert.Equal(bookRequest.BarnesAndNobleId, bookResponse.BarnesAndNobleId);
Assert.Equal(bookRequest.AppleBooksId, bookResponse.AppleBooksId);
// ISBNs checks
Assert.Equal(bookRequest.ISBNs!.Count, bookResponse.ISBNs.Count);
Assert.Equal(bookRequest.ISBNs!.Count, bookResponse.ISBNs!.Count);
var requestIsbnData = bookRequest.ISBNs.Select(isbn => new { isbn.Value, isbn.Format }).OrderBy(x => x.Value).ToList();
var responseIsbnData = bookResponse.ISBNs.Select(isbn => new { isbn.Value, isbn.Format }).OrderBy(x => x.Value).ToList();
Assert.Equal(requestIsbnData.Count, responseIsbnData.Count);
@@ -172,9 +168,9 @@ public class AddBookEndpointTests : IClassFixture<AuthenticatedLuminaApiFactory>
}
// ratings checks
Assert.Equal(bookRequest.Ratings!.Count, bookResponse.Ratings.Count);
Assert.Equal(bookRequest.Ratings!.Count, bookResponse.Ratings!.Count);
var requestRatingData = bookRequest.Ratings.Select(r => new { r.Source, r.Value, r.MaxValue, r.VoteCount }).OrderBy(x => x.Source).ToList();
var responseRatingData = bookResponse.Ratings.Select(r => new { Source = r.Source.Value, r.Value, r.MaxValue, VoteCount = r.VoteCount.Value }).OrderBy(x => x.Source).ToList();
var responseRatingData = bookResponse.Ratings.Select(r => new { r.Source, r.Value, r.MaxValue, r.VoteCount }).OrderBy(x => x.Source).ToList();
Assert.Equal(requestRatingData.Count, responseRatingData.Count);
for (int i = 0; i < requestRatingData.Count; i++)
{
@@ -186,18 +182,18 @@ public class AddBookEndpointTests : IClassFixture<AuthenticatedLuminaApiFactory>
// series checks
if (bookRequest.Series is not null)
Assert.Equal(bookRequest.Series.Title, bookResponse.Series.Value.Metadata.Title);
Assert.Equal(bookRequest.Series.Title, bookResponse.Series!.Title);
else
Assert.Null(bookResponse.Series.Value);
Assert.Null(bookResponse.Series);
// check Location header
Assert.NotNull(response.Headers.Location);
string locationUri = response.Headers.Location!.ToString();
Assert.EndsWith($"/api/v1/libraries/{_libraryId}/books/{bookResponse.Id.Value}", locationUri);
Assert.EndsWith($"/api/v1/libraries/{_libraryId}/books/{bookResponse.Id}", locationUri);
// extract ID from Location header and compare
string idFromHeader = locationUri.Split('/').Last();
Assert.Equal(idFromHeader, bookResponse!.Id.ToString());
Assert.Equal(idFromHeader, bookResponse.Id.ToString());
}
[Fact]
@@ -1119,7 +1115,7 @@ public class AddBookEndpointTests : IClassFixture<AuthenticatedLuminaApiFactory>
HttpResponseMessage response = await PostBookAsync(bookRequest);
// Assert
await AssertUnprocessableEntityWithValidationErrors(response, Errors.WrittenContent.ContributorsListCannotBeNull.Description);
await AssertUnprocessableEntityWithValidationErrors(response, Errors.MediaContributor.ContributorsListCannotBeNull.Description);
}
[Fact]
@@ -1235,15 +1231,15 @@ public class AddBookEndpointTests : IClassFixture<AuthenticatedLuminaApiFactory>
// Assert
response.EnsureSuccessStatusCode();
Assert.Equal(HttpStatusCode.Created, response.StatusCode);
Book? bookResponse = await response.Content.ReadFromJsonAsync<Book>(_jsonOptions);
BookResponse? bookResponse = await response.Content.ReadFromJsonAsync<BookResponse>(_jsonOptions);
Assert.NotNull(bookResponse);
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
List<BookContributorEntity> links = [.. dbContext.Books
.Include(book => book.BookContributors)
.Single(book => book.Id == bookResponse!.Id.Value)
.BookContributors];
.Include(book => book.Contributors)
.Single(book => book.Id == bookResponse!.Id)
.Contributors];
Assert.Equal(2, links.Count);
Assert.All(links, link => Assert.Equal(contributorId, link.MediaContributorId));
Assert.Contains(links, link => link.Role == MediaContributorRole.Author);
@@ -1754,6 +1750,51 @@ public class AddBookEndpointTests : IClassFixture<AuthenticatedLuminaApiFactory>
Assert.Contains("LibraryIdCannotBeEmpty", content, StringComparison.OrdinalIgnoreCase);
}
[Fact]
public async Task AddBook_WhenUnauthorized_ShouldReturnUnauthorizedResult()
{
// Arrange
HttpClient unauthenticatedClient = _apiFactory.CreateClient();
Guid libraryId = Guid.NewGuid();
AddBookRequest request = _requestBookFixture.Create(contributors: []);
// Act
HttpResponseMessage response = await unauthenticatedClient.PostAsJsonAsync($"/api/v1/libraries/{libraryId}/books", request);
// Assert
Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode);
}
[Fact]
public async Task AddBook_WhenCalledWithCancellationToken_ShouldCompleteSuccessfully()
{
// Arrange
AddBookRequest bookRequest = _requestBookFixture.Create(contributors: []);
using CancellationTokenSource cts = new(TimeSpan.FromSeconds(5));
// Act & Assert
Exception? exception = await Record.ExceptionAsync(async () =>
await _client.PostAsJsonAsync($"/api/v1/libraries/{_libraryId}/books", bookRequest, cts.Token)
);
Assert.Null(exception);
}
[Fact]
public async Task AddBook_WhenCancellationTokenIsCanceled_ShouldThrowTaskCanceledException()
{
// Arrange
AddBookRequest bookRequest = _requestBookFixture.Create(contributors: []);
using CancellationTokenSource cts = new();
// Act & Assert
Exception? exception = await Record.ExceptionAsync(async () =>
{
cts.Cancel();
await _client.PostAsJsonAsync($"/api/v1/libraries/{_libraryId}/books", bookRequest, cts.Token);
});
Assert.IsType<TaskCanceledException>(exception);
}
/// <summary>
/// Posts a request to add a book to the media library owned by the authenticated user of the current test.
/// </summary>
@@ -1821,7 +1862,7 @@ public class AddBookEndpointTests : IClassFixture<AuthenticatedLuminaApiFactory>
{
HttpResponseMessage response = await PostBookAsync(bookRequest);
response.EnsureSuccessStatusCode();
Book? bookResponse = await response.Content.ReadFromJsonAsync<Book>(_jsonOptions);
BookResponse? bookResponse = await response.Content.ReadFromJsonAsync<BookResponse>(_jsonOptions);
Assert.Equal(HttpStatusCode.Created, response.StatusCode);
Assert.NotNull(bookResponse);
}
@@ -4,6 +4,7 @@ using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentL
using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management;
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary;
using Lumina.Application.Fixtures.Common.DataAccess.Entities.UsersManagement;
using Lumina.Contracts.Responses.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Reading;
using Lumina.DataAccess.Core.UoW;
using Lumina.Presentation.Api.IntegrationTests.Common.Setup;
@@ -36,6 +37,7 @@ public class GetReadingAvailabilityEndpointTests : IClassFixture<AuthenticatedLu
};
private readonly LibraryEntityFixture _libraryEntityFixture = new();
private readonly BookEntityFixture _bookEntityFixture = new();
private readonly UserEntityFixture _userEntityFixture = new();
/// <summary>
/// Initializes a new instance of the <see cref="GetReadingAvailabilityEndpointTests"/> class.
@@ -63,7 +65,7 @@ public class GetReadingAvailabilityEndpointTests : IClassFixture<AuthenticatedLu
(Guid libraryId, Guid bookId) = await SeedBookAsync(userId);
// Act
HttpResponseMessage response = await _client.GetAsync($"/api/v1/books/{bookId}/reading/availability");
HttpResponseMessage response = await _client.GetAsync($"/api/v1/libraries/{libraryId}/books/{bookId}/reading/availability");
// Assert
response.EnsureSuccessStatusCode();
@@ -79,7 +81,7 @@ public class GetReadingAvailabilityEndpointTests : IClassFixture<AuthenticatedLu
public async Task GetReadingAvailability_WhenBookDoesNotExist_ShouldReturnBookNotFoundProblem()
{
// Act
HttpResponseMessage response = await _client.GetAsync($"/api/v1/books/{Guid.NewGuid()}/reading/availability");
HttpResponseMessage response = await _client.GetAsync($"/api/v1/libraries/{Guid.NewGuid()}/books/{Guid.NewGuid()}/reading/availability");
// Assert
Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);
@@ -91,6 +93,57 @@ public class GetReadingAvailabilityEndpointTests : IClassFixture<AuthenticatedLu
Assert.DoesNotContain("Exception", content, StringComparison.Ordinal);
}
[Fact]
public async Task GetReadingAvailability_WhenBookBelongsToAnotherUser_ShouldReturnForbidden()
{
// Arrange
Guid otherUserId = await SeedOtherUserAsync();
(Guid libraryId, Guid bookId) = await SeedBookAsync(otherUserId);
// Act
HttpResponseMessage response = await _client.GetAsync($"/api/v1/libraries/{libraryId}/books/{bookId}/reading/availability");
// Assert
Assert.Equal(HttpStatusCode.Forbidden, response.StatusCode);
using JsonDocument problemDetails = JsonDocument.Parse(await response.Content.ReadAsStringAsync());
Assert.Equal("General.Unauthorized", problemDetails.RootElement.GetProperty("title").GetString());
Assert.Equal("NotAuthorized", problemDetails.RootElement.GetProperty("detail").GetString());
Assert.DoesNotContain("Exception", problemDetails.RootElement.GetRawText(), StringComparison.Ordinal);
}
[Fact]
public async Task GetReadingAvailability_WhenBookBelongsToAnotherLibrary_ShouldReturnBookNotFoundProblem()
{
// Arrange
Guid userId = GetCurrentUserId();
(_, Guid bookId) = await SeedBookAsync(userId);
// Act
HttpResponseMessage response = await _client.GetAsync($"/api/v1/libraries/{Guid.NewGuid()}/books/{bookId}/reading/availability");
// Assert
// The route library id is enforced, so a book can never be read through another library's route, and the mismatch is
// reported as not found, without disclosing that the book exists in another library.
Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);
string content = await response.Content.ReadAsStringAsync();
Assert.Contains("BookNotFound", content, StringComparison.Ordinal);
}
[Fact]
public async Task GetReadingAvailability_WhenRouteIdsAreNotParseable_ShouldReturnUnprocessableEntity()
{
// Act
HttpResponseMessage response = await _client.GetAsync("/api/v1/libraries/not-a-guid/books/not-a-guid/reading/availability");
// Assert
// The route values are kept as raw strings, so the unparseable Ids reach the query validator, which reports clean
// validation errors instead of failing the request binding.
Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode);
string content = await response.Content.ReadAsStringAsync();
Assert.Contains("LibraryIdCannotBeEmpty", content, StringComparison.OrdinalIgnoreCase);
Assert.Contains("BookIdCannotBeEmpty", content, StringComparison.OrdinalIgnoreCase);
}
[Fact]
public async Task GetReadingAvailability_WhenUnauthorized_ShouldReturnUnauthorizedResult()
{
@@ -98,7 +151,7 @@ public class GetReadingAvailabilityEndpointTests : IClassFixture<AuthenticatedLu
HttpClient unauthenticatedClient = _apiFactory.CreateClient();
// Act
HttpResponseMessage response = await unauthenticatedClient.GetAsync($"/api/v1/books/{Guid.NewGuid()}/reading/availability");
HttpResponseMessage response = await unauthenticatedClient.GetAsync($"/api/v1/libraries/{Guid.NewGuid()}/books/{Guid.NewGuid()}/reading/availability");
// Assert
Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode);
@@ -123,6 +176,20 @@ public class GetReadingAvailabilityEndpointTests : IClassFixture<AuthenticatedLu
return (libraryId, bookId);
}
/// <summary>
/// Seeds a user that is not the authenticated one and returns its Id.
/// </summary>
/// <returns>The Id of the seeded user.</returns>
private async Task<Guid> SeedOtherUserAsync()
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
Guid userId = Guid.NewGuid();
dbContext.Users.Add(_userEntityFixture.Create(id: userId, username: $"otheruser_{Guid.NewGuid()}", password: "TestPass123!"));
await dbContext.SaveChangesAsync();
return userId;
}
/// <summary>
/// Gets the Id of the currently authenticated test user.
/// </summary>
@@ -13,6 +13,7 @@ using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Text.Json;
using System.Threading.Tasks;
#endregion
@@ -52,7 +53,7 @@ public class GetReadingManifestEndpointTests : IClassFixture<AuthenticatedLumina
public async Task GetReadingManifest_WhenBookDoesNotExist_ShouldReturnBookNotFoundProblem()
{
// Act
HttpResponseMessage response = await _client.GetAsync($"/api/v1/books/{Guid.NewGuid()}/reading/manifest");
HttpResponseMessage response = await _client.GetAsync($"/api/v1/libraries/{Guid.NewGuid()}/books/{Guid.NewGuid()}/reading/manifest");
// Assert
Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);
@@ -66,13 +67,35 @@ public class GetReadingManifestEndpointTests : IClassFixture<AuthenticatedLumina
{
// Arrange
Guid otherUserId = await SeedOtherUserAsync();
Guid bookId = await SeedBookAsync(otherUserId);
(Guid libraryId, Guid bookId) = await SeedBookAsync(otherUserId);
// Act
HttpResponseMessage response = await _client.GetAsync($"/api/v1/books/{bookId}/reading/manifest");
HttpResponseMessage response = await _client.GetAsync($"/api/v1/libraries/{libraryId}/books/{bookId}/reading/manifest");
// Assert
Assert.Equal(HttpStatusCode.Forbidden, response.StatusCode);
using JsonDocument problemDetails = JsonDocument.Parse(await response.Content.ReadAsStringAsync());
Assert.Equal("General.Unauthorized", problemDetails.RootElement.GetProperty("title").GetString());
Assert.Equal("NotAuthorized", problemDetails.RootElement.GetProperty("detail").GetString());
Assert.DoesNotContain("Exception", problemDetails.RootElement.GetRawText(), StringComparison.Ordinal);
}
[Fact]
public async Task GetReadingManifest_WhenBookBelongsToAnotherLibrary_ShouldReturnBookNotFoundProblem()
{
// Arrange
Guid userId = GetCurrentUserId();
(_, Guid bookId) = await SeedBookAsync(userId);
// Act
HttpResponseMessage response = await _client.GetAsync($"/api/v1/libraries/{Guid.NewGuid()}/books/{bookId}/reading/manifest");
// Assert
// The route library id is enforced, so a book can never be read through another library's route, and the mismatch is
// reported as not found, without disclosing that the book exists in another library.
Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);
string content = await response.Content.ReadAsStringAsync();
Assert.Contains("BookNotFound", content, StringComparison.Ordinal);
}
[Fact]
@@ -80,10 +103,10 @@ public class GetReadingManifestEndpointTests : IClassFixture<AuthenticatedLumina
{
// Arrange
Guid userId = GetCurrentUserId();
Guid bookId = await SeedBookAsync(userId);
(Guid libraryId, Guid bookId) = await SeedBookAsync(userId);
// Act
HttpResponseMessage response = await _client.GetAsync($"/api/v1/books/{bookId}/reading/manifest");
HttpResponseMessage response = await _client.GetAsync($"/api/v1/libraries/{libraryId}/books/{bookId}/reading/manifest");
// Assert
string content = await response.Content.ReadAsStringAsync();
@@ -98,18 +121,33 @@ public class GetReadingManifestEndpointTests : IClassFixture<AuthenticatedLumina
HttpClient unauthenticatedClient = _apiFactory.CreateClient();
// Act
HttpResponseMessage response = await unauthenticatedClient.GetAsync($"/api/v1/books/{Guid.NewGuid()}/reading/manifest");
HttpResponseMessage response = await unauthenticatedClient.GetAsync($"/api/v1/libraries/{Guid.NewGuid()}/books/{Guid.NewGuid()}/reading/manifest");
// Assert
Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode);
}
[Fact]
public async Task GetReadingManifest_WhenRouteIdsAreNotParseable_ShouldReturnUnprocessableEntity()
{
// Act
HttpResponseMessage response = await _client.GetAsync("/api/v1/libraries/not-a-guid/books/not-a-guid/reading/manifest");
// Assert
// The route values are kept as raw strings, so the unparseable Ids reach the query validator, which reports clean
// validation errors instead of failing the request binding.
Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode);
string content = await response.Content.ReadAsStringAsync();
Assert.Contains("LibraryIdCannotBeEmpty", content, StringComparison.OrdinalIgnoreCase);
Assert.Contains("BookIdCannotBeEmpty", content, StringComparison.OrdinalIgnoreCase);
}
/// <summary>
/// Seeds a library owned by <paramref name="userId"/> and an EPUB book belonging to it.
/// </summary>
/// <param name="userId">The Id of the user that owns the library.</param>
/// <returns>The Id of the seeded book.</returns>
private async Task<Guid> SeedBookAsync(Guid userId)
/// <returns>The Ids of the seeded library and book.</returns>
private async Task<(Guid libraryId, Guid bookId)> SeedBookAsync(Guid userId)
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
@@ -120,7 +158,7 @@ public class GetReadingManifestEndpointTests : IClassFixture<AuthenticatedLumina
dbContext.Libraries.Add(library);
dbContext.Books.Add(book);
await dbContext.SaveChangesAsync();
return bookId;
return (libraryId, bookId);
}
/// <summary>
@@ -13,6 +13,7 @@ using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Text.Json;
using System.Threading.Tasks;
#endregion
@@ -52,7 +53,7 @@ public class GetReadingResourceEndpointTests : IClassFixture<AuthenticatedLumina
public async Task GetReadingResource_WhenBookDoesNotExist_ShouldReturnBookNotFoundProblem()
{
// Act
HttpResponseMessage response = await _client.GetAsync($"/api/v1/books/{Guid.NewGuid()}/reading/resources/cover");
HttpResponseMessage response = await _client.GetAsync($"/api/v1/libraries/{Guid.NewGuid()}/books/{Guid.NewGuid()}/reading/resources/cover");
// Assert
Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);
@@ -66,13 +67,35 @@ public class GetReadingResourceEndpointTests : IClassFixture<AuthenticatedLumina
{
// Arrange
Guid otherUserId = await SeedOtherUserAsync();
Guid bookId = await SeedBookAsync(otherUserId);
(Guid libraryId, Guid bookId) = await SeedBookAsync(otherUserId);
// Act
HttpResponseMessage response = await _client.GetAsync($"/api/v1/books/{bookId}/reading/resources/cover");
HttpResponseMessage response = await _client.GetAsync($"/api/v1/libraries/{libraryId}/books/{bookId}/reading/resources/cover");
// Assert
Assert.Equal(HttpStatusCode.Forbidden, response.StatusCode);
using JsonDocument problemDetails = JsonDocument.Parse(await response.Content.ReadAsStringAsync());
Assert.Equal("General.Unauthorized", problemDetails.RootElement.GetProperty("title").GetString());
Assert.Equal("NotAuthorized", problemDetails.RootElement.GetProperty("detail").GetString());
Assert.DoesNotContain("Exception", problemDetails.RootElement.GetRawText(), StringComparison.Ordinal);
}
[Fact]
public async Task GetReadingResource_WhenBookBelongsToAnotherLibrary_ShouldReturnBookNotFoundProblem()
{
// Arrange
Guid userId = GetCurrentUserId();
(_, Guid bookId) = await SeedBookAsync(userId);
// Act
HttpResponseMessage response = await _client.GetAsync($"/api/v1/libraries/{Guid.NewGuid()}/books/{bookId}/reading/resources/cover");
// Assert
// The route library id is enforced, so a book can never be read through another library's route, and the mismatch is
// reported as not found, without disclosing that the book exists in another library.
Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);
string content = await response.Content.ReadAsStringAsync();
Assert.Contains("BookNotFound", content, StringComparison.Ordinal);
}
[Fact]
@@ -80,10 +103,10 @@ public class GetReadingResourceEndpointTests : IClassFixture<AuthenticatedLumina
{
// Arrange
Guid userId = GetCurrentUserId();
Guid bookId = await SeedBookAsync(userId);
(Guid libraryId, Guid bookId) = await SeedBookAsync(userId);
// Act
HttpResponseMessage response = await _client.GetAsync($"/api/v1/books/{bookId}/reading/resources/cover");
HttpResponseMessage response = await _client.GetAsync($"/api/v1/libraries/{libraryId}/books/{bookId}/reading/resources/cover");
// Assert
string content = await response.Content.ReadAsStringAsync();
@@ -98,18 +121,33 @@ public class GetReadingResourceEndpointTests : IClassFixture<AuthenticatedLumina
HttpClient unauthenticatedClient = _apiFactory.CreateClient();
// Act
HttpResponseMessage response = await unauthenticatedClient.GetAsync($"/api/v1/books/{Guid.NewGuid()}/reading/resources/cover");
HttpResponseMessage response = await unauthenticatedClient.GetAsync($"/api/v1/libraries/{Guid.NewGuid()}/books/{Guid.NewGuid()}/reading/resources/cover");
// Assert
Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode);
}
[Fact]
public async Task GetReadingResource_WhenRouteIdsAreNotParseable_ShouldReturnUnprocessableEntity()
{
// Act
HttpResponseMessage response = await _client.GetAsync("/api/v1/libraries/not-a-guid/books/not-a-guid/reading/resources/cover");
// Assert
// The route values are kept as raw strings, so the unparseable Ids reach the query validator, which reports clean
// validation errors instead of failing the request binding.
Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode);
string content = await response.Content.ReadAsStringAsync();
Assert.Contains("LibraryIdCannotBeEmpty", content, StringComparison.OrdinalIgnoreCase);
Assert.Contains("BookIdCannotBeEmpty", content, StringComparison.OrdinalIgnoreCase);
}
/// <summary>
/// Seeds a library owned by <paramref name="userId"/> and an EPUB book belonging to it.
/// </summary>
/// <param name="userId">The Id of the user that owns the library.</param>
/// <returns>The Id of the seeded book.</returns>
private async Task<Guid> SeedBookAsync(Guid userId)
/// <returns>The Ids of the seeded library and book.</returns>
private async Task<(Guid libraryId, Guid bookId)> SeedBookAsync(Guid userId)
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
@@ -120,7 +158,7 @@ public class GetReadingResourceEndpointTests : IClassFixture<AuthenticatedLumina
dbContext.Libraries.Add(library);
dbContext.Books.Add(book);
await dbContext.SaveChangesAsync();
return bookId;
return (libraryId, bookId);
}
/// <summary>
@@ -13,6 +13,7 @@ using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Text.Json;
using System.Threading.Tasks;
#endregion
@@ -52,7 +53,7 @@ public class GetReadingSectionEndpointTests : IClassFixture<AuthenticatedLuminaA
public async Task GetReadingSection_WhenBookDoesNotExist_ShouldReturnBookNotFoundProblem()
{
// Act
HttpResponseMessage response = await _client.GetAsync($"/api/v1/books/{Guid.NewGuid()}/reading/sections/chapter-1");
HttpResponseMessage response = await _client.GetAsync($"/api/v1/libraries/{Guid.NewGuid()}/books/{Guid.NewGuid()}/reading/sections/chapter-1");
// Assert
Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);
@@ -66,13 +67,35 @@ public class GetReadingSectionEndpointTests : IClassFixture<AuthenticatedLuminaA
{
// Arrange
Guid otherUserId = await SeedOtherUserAsync();
Guid bookId = await SeedBookAsync(otherUserId);
(Guid libraryId, Guid bookId) = await SeedBookAsync(otherUserId);
// Act
HttpResponseMessage response = await _client.GetAsync($"/api/v1/books/{bookId}/reading/sections/chapter-1");
HttpResponseMessage response = await _client.GetAsync($"/api/v1/libraries/{libraryId}/books/{bookId}/reading/sections/chapter-1");
// Assert
Assert.Equal(HttpStatusCode.Forbidden, response.StatusCode);
using JsonDocument problemDetails = JsonDocument.Parse(await response.Content.ReadAsStringAsync());
Assert.Equal("General.Unauthorized", problemDetails.RootElement.GetProperty("title").GetString());
Assert.Equal("NotAuthorized", problemDetails.RootElement.GetProperty("detail").GetString());
Assert.DoesNotContain("Exception", problemDetails.RootElement.GetRawText(), StringComparison.Ordinal);
}
[Fact]
public async Task GetReadingSection_WhenBookBelongsToAnotherLibrary_ShouldReturnBookNotFoundProblem()
{
// Arrange
Guid userId = GetCurrentUserId();
(_, Guid bookId) = await SeedBookAsync(userId);
// Act
HttpResponseMessage response = await _client.GetAsync($"/api/v1/libraries/{Guid.NewGuid()}/books/{bookId}/reading/sections/chapter-1");
// Assert
// The route library id is enforced, so a book can never be read through another library's route, and the mismatch is
// reported as not found, without disclosing that the book exists in another library.
Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);
string content = await response.Content.ReadAsStringAsync();
Assert.Contains("BookNotFound", content, StringComparison.Ordinal);
}
[Fact]
@@ -80,10 +103,10 @@ public class GetReadingSectionEndpointTests : IClassFixture<AuthenticatedLuminaA
{
// Arrange
Guid userId = GetCurrentUserId();
Guid bookId = await SeedBookAsync(userId);
(Guid libraryId, Guid bookId) = await SeedBookAsync(userId);
// Act
HttpResponseMessage response = await _client.GetAsync($"/api/v1/books/{bookId}/reading/sections/chapter-1");
HttpResponseMessage response = await _client.GetAsync($"/api/v1/libraries/{libraryId}/books/{bookId}/reading/sections/chapter-1");
// Assert
string content = await response.Content.ReadAsStringAsync();
@@ -98,18 +121,33 @@ public class GetReadingSectionEndpointTests : IClassFixture<AuthenticatedLuminaA
HttpClient unauthenticatedClient = _apiFactory.CreateClient();
// Act
HttpResponseMessage response = await unauthenticatedClient.GetAsync($"/api/v1/books/{Guid.NewGuid()}/reading/sections/chapter-1");
HttpResponseMessage response = await unauthenticatedClient.GetAsync($"/api/v1/libraries/{Guid.NewGuid()}/books/{Guid.NewGuid()}/reading/sections/chapter-1");
// Assert
Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode);
}
[Fact]
public async Task GetReadingSection_WhenRouteIdsAreNotParseable_ShouldReturnUnprocessableEntity()
{
// Act
HttpResponseMessage response = await _client.GetAsync("/api/v1/libraries/not-a-guid/books/not-a-guid/reading/sections/chapter-1");
// Assert
// The route values are kept as raw strings, so the unparseable Ids reach the query validator, which reports clean
// validation errors instead of failing the request binding.
Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode);
string content = await response.Content.ReadAsStringAsync();
Assert.Contains("LibraryIdCannotBeEmpty", content, StringComparison.OrdinalIgnoreCase);
Assert.Contains("BookIdCannotBeEmpty", content, StringComparison.OrdinalIgnoreCase);
}
/// <summary>
/// Seeds a library owned by <paramref name="userId"/> and an EPUB book belonging to it.
/// </summary>
/// <param name="userId">The Id of the user that owns the library.</param>
/// <returns>The Id of the seeded book.</returns>
private async Task<Guid> SeedBookAsync(Guid userId)
/// <returns>The Ids of the seeded library and book.</returns>
private async Task<(Guid libraryId, Guid bookId)> SeedBookAsync(Guid userId)
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
@@ -120,7 +158,7 @@ public class GetReadingSectionEndpointTests : IClassFixture<AuthenticatedLuminaA
dbContext.Libraries.Add(library);
dbContext.Books.Add(book);
await dbContext.SaveChangesAsync();
return bookId;
return (libraryId, bookId);
}
/// <summary>
@@ -1,4 +1,4 @@
#region ========================================================================= USING =====================================================================================
#region ========================================================================= USING =====================================================================================
using Bogus;
using Lumina.Application.Common.DataAccess.Entities.MediaContributors;
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management;
@@ -35,6 +35,7 @@ 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;
#endregion
@@ -134,9 +135,9 @@ public class UpdateBookEndpointTests : IClassFixture<AuthenticatedLuminaApiFacto
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
List<BookContributorEntity> links = dbContext.Books
.Include(book => book.BookContributors)
.Include(book => book.Contributors)
.Single(book => book.Id == bookId)
.BookContributors
.Contributors
.ToList();
Assert.Equal(2, links.Count);
Assert.All(links, link => Assert.Equal(contributorId, link.MediaContributorId));
@@ -1792,6 +1793,40 @@ public class UpdateBookEndpointTests : IClassFixture<AuthenticatedLuminaApiFacto
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
}
[Fact]
public async Task UpdateBook_WhenCalledWithCancellationToken_ShouldCompleteSuccessfully()
{
// Arrange
Guid userId = GetCurrentUserId();
(Guid libraryId, Guid bookId) = await SeedLibraryAndBookAsync(userId, "Original Title");
UpdateBookRequest request = _requestBookFixture.Create();
using CancellationTokenSource cts = new(TimeSpan.FromSeconds(5));
// Act & Assert
Exception? exception = await Record.ExceptionAsync(async () =>
await _client.PutAsJsonAsync($"/api/v1/libraries/{libraryId}/books/{bookId}", request, cts.Token)
);
Assert.Null(exception);
}
[Fact]
public async Task UpdateBook_WhenCancellationTokenIsCanceled_ShouldThrowTaskCanceledException()
{
// Arrange
Guid userId = GetCurrentUserId();
(Guid libraryId, Guid bookId) = await SeedLibraryAndBookAsync(userId, "Original Title");
UpdateBookRequest request = _requestBookFixture.Create();
using CancellationTokenSource cts = new();
// Act & Assert
Exception? exception = await Record.ExceptionAsync(async () =>
{
cts.Cancel();
await _client.PutAsJsonAsync($"/api/v1/libraries/{libraryId}/books/{bookId}", request, cts.Token);
});
Assert.IsType<TaskCanceledException>(exception);
}
/// <summary>
/// Updates the book described by the provided request, seeding the media library, the book and the referenced media contributors.
/// </summary>
@@ -6,6 +6,7 @@ using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management;
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary;
using Lumina.Application.Fixtures.Common.DataAccess.Entities.UsersManagement;
using Lumina.Contracts.Responses.MediaLibrary.WrittenContentLibrary.BookLibrary.Books;
using Lumina.DataAccess.Core.UoW;
using Lumina.Domain.SharedKernel.Common.Enums.BookLibrary;
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
@@ -63,19 +64,19 @@ public class UpdateBookCoverEndpointTests : IClassFixture<AuthenticatedLuminaApi
(Guid libraryId, Guid bookId) = await SeedLibraryAndBookWithCoverAsync(userId, "/media/books/old-cover.jpg");
// Act
HttpResponseMessage response = await _client.PutAsync($"/api/v1/books/{bookId}/cover", CreateCoverForm("cover.png"));
HttpResponseMessage response = await _client.PutAsync($"/api/v1/libraries/{libraryId}/books/{bookId}/cover", CreateCoverForm("cover.png"));
// Assert
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
string content = await response.Content.ReadAsStringAsync();
string storedPath = JsonSerializer.Deserialize<string>(content)!;
string storedPath = JsonSerializer.Deserialize<UpdateBookCoverResponse>(content, new JsonSerializerOptions { PropertyNameCaseInsensitive = true })!.CoverPath;
Assert.False(string.IsNullOrWhiteSpace(storedPath));
Assert.Contains("cover.png", storedPath, StringComparison.OrdinalIgnoreCase);
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
BookArtworkEntity coverArtwork = dbContext.Books
.SelectMany(book => book.BookArtwork)
.SelectMany(book => book.Artwork)
.Single(artwork => artwork.BookId == bookId && artwork.ArtworkType == ArtworkType.Cover);
Assert.Equal(storedPath, coverArtwork.FileName);
Assert.Equal(ArtworkStatus.Enriched, coverArtwork.Status);
@@ -86,21 +87,21 @@ public class UpdateBookCoverEndpointTests : IClassFixture<AuthenticatedLuminaApi
{
// Arrange
Guid userId = GetCurrentUserId();
(_, Guid bookId) = await SeedLibraryAndBookAsync(userId);
(Guid libraryId, Guid bookId) = await SeedLibraryAndBookAsync(userId);
// Act
HttpResponseMessage response = await _client.PutAsync($"/api/v1/books/{bookId}/cover", CreateCoverForm("cover.png"));
HttpResponseMessage response = await _client.PutAsync($"/api/v1/libraries/{libraryId}/books/{bookId}/cover", CreateCoverForm("cover.png"));
// Assert
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
string content = await response.Content.ReadAsStringAsync();
string storedPath = JsonSerializer.Deserialize<string>(content)!;
string storedPath = JsonSerializer.Deserialize<UpdateBookCoverResponse>(content, new JsonSerializerOptions { PropertyNameCaseInsensitive = true })!.CoverPath;
Assert.False(string.IsNullOrWhiteSpace(storedPath));
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
BookArtworkEntity coverArtwork = dbContext.Books
.SelectMany(book => book.BookArtwork)
.SelectMany(book => book.Artwork)
.Single(artwork => artwork.BookId == bookId && artwork.ArtworkType == ArtworkType.Cover);
Assert.Equal(storedPath, coverArtwork.FileName);
}
@@ -109,7 +110,7 @@ public class UpdateBookCoverEndpointTests : IClassFixture<AuthenticatedLuminaApi
public async Task UpdateBookCover_WhenBookDoesNotExist_ShouldReturnBookNotFoundProblem()
{
// Act
HttpResponseMessage response = await _client.PutAsync($"/api/v1/books/{Guid.NewGuid()}/cover", CreateCoverForm("cover.png"));
HttpResponseMessage response = await _client.PutAsync($"/api/v1/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/books/{Guid.NewGuid()}/cover", CreateCoverForm("cover.png"));
// Assert
Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);
@@ -123,7 +124,7 @@ public class UpdateBookCoverEndpointTests : IClassFixture<AuthenticatedLuminaApi
public async Task UpdateBookCover_WhenRouteIdIsNotParseable_ShouldReturnUnprocessableEntity()
{
// Act
HttpResponseMessage response = await _client.PutAsync($"/api/v1/books/not-a-guid/cover", CreateCoverForm("cover.png"));
HttpResponseMessage response = await _client.PutAsync($"/api/v1/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/books/not-a-guid/cover", CreateCoverForm("cover.png"));
// Assert
Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode);
@@ -138,10 +139,10 @@ public class UpdateBookCoverEndpointTests : IClassFixture<AuthenticatedLuminaApi
{
// Arrange
(Guid otherUserId, _) = await SeedOtherUserAsync();
(_, Guid bookId) = await SeedLibraryAndBookAsync(otherUserId);
(Guid libraryId, Guid bookId) = await SeedLibraryAndBookAsync(otherUserId);
// Act
HttpResponseMessage response = await _client.PutAsync($"/api/v1/books/{bookId}/cover", CreateCoverForm("cover.png"));
HttpResponseMessage response = await _client.PutAsync($"/api/v1/libraries/{libraryId}/books/{bookId}/cover", CreateCoverForm("cover.png"));
// Assert
Assert.Equal(HttpStatusCode.Forbidden, response.StatusCode);
@@ -151,6 +152,25 @@ public class UpdateBookCoverEndpointTests : IClassFixture<AuthenticatedLuminaApi
Assert.Equal("NotAuthorized", problemDetails.RootElement.GetProperty("detail").GetString());
}
[Fact]
public async Task UpdateBookCover_WhenBookBelongsToAnotherLibrary_ShouldReturnBookNotFoundProblem()
{
// Arrange
Guid userId = GetCurrentUserId();
(_, Guid bookId) = await SeedLibraryAndBookAsync(userId);
Guid otherLibraryId = Guid.NewGuid();
// Act
HttpResponseMessage response = await _client.PutAsync($"/api/v1/libraries/{otherLibraryId}/books/{bookId}/cover", CreateCoverForm("cover.png"));
// Assert
Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);
string content = await response.Content.ReadAsStringAsync();
using JsonDocument problemDetails = JsonDocument.Parse(content);
Assert.Equal("General.NotFound", problemDetails.RootElement.GetProperty("title").GetString());
Assert.Equal("BookNotFound", problemDetails.RootElement.GetProperty("detail").GetString());
}
[Fact]
public async Task UpdateBookCover_WhenUnauthorized_ShouldReturnUnauthorizedResult()
{
@@ -158,12 +178,78 @@ public class UpdateBookCoverEndpointTests : IClassFixture<AuthenticatedLuminaApi
HttpClient unauthenticatedClient = _apiFactory.CreateClient();
// Act
HttpResponseMessage response = await unauthenticatedClient.PutAsync($"/api/v1/books/{Guid.NewGuid()}/cover", CreateCoverForm("cover.png"));
HttpResponseMessage response = await unauthenticatedClient.PutAsync($"/api/v1/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/books/{Guid.NewGuid()}/cover", CreateCoverForm("cover.png"));
// Assert
Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode);
}
[Fact]
public async Task UpdateBookCover_WhenNoFileIsUploaded_ShouldReturnUnprocessableEntityWithBookCoverCannotBeNull()
{
// Arrange
MultipartFormDataContent form = [];
form.Add(new StringContent("unrelated-field"), "unrelated-field");
// Act
HttpResponseMessage response = await _client.PutAsync($"/api/v1/libraries/{Guid.NewGuid()}/books/{Guid.NewGuid()}/cover", form);
// Assert
Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode);
string content = await response.Content.ReadAsStringAsync();
using JsonDocument problemDetails = JsonDocument.Parse(content);
Assert.Equal("General.Validation", problemDetails.RootElement.GetProperty("title").GetString());
Assert.Contains("BookCoverCannotBeNull", content, StringComparison.OrdinalIgnoreCase);
}
[Fact]
public async Task UpdateBookCover_WhenUploadedFileIsNotAnImage_ShouldReturnUnprocessableEntityWithCoverFileMustBeAnImage()
{
// Arrange
Guid userId = GetCurrentUserId();
(Guid libraryId, Guid bookId) = await SeedLibraryAndBookAsync(userId);
MultipartFormDataContent form = CreateCoverForm([1, 2, 3, 4, 5, 6, 7, 8], "cover.png");
// Act
HttpResponseMessage response = await _client.PutAsync($"/api/v1/libraries/{libraryId}/books/{bookId}/cover", form);
// Assert
Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode);
string content = await response.Content.ReadAsStringAsync();
using JsonDocument problemDetails = JsonDocument.Parse(content);
Assert.Equal("General.Validation", problemDetails.RootElement.GetProperty("title").GetString());
Assert.Contains("CoverFileMustBeAnImage", content, StringComparison.OrdinalIgnoreCase);
}
[Fact]
public async Task UpdateBookCover_WhenUploadedFileIsTooLarge_ShouldReturnUnprocessableEntityWithFileTooLarge()
{
// Arrange
Guid userId = GetCurrentUserId();
(Guid libraryId, Guid bookId) = await SeedLibraryAndBookAsync(userId);
// The artwork size limit is 10 MiB, so the payload exceeds it by one byte.
byte[] payload = new byte[(10 * 1024 * 1024) + 1];
payload[0] = 137;
payload[1] = 80;
payload[2] = 78;
payload[3] = 71;
payload[4] = 13;
payload[5] = 10;
payload[6] = 26;
payload[7] = 10;
MultipartFormDataContent form = CreateCoverForm(payload, "cover.png");
// Act
HttpResponseMessage response = await _client.PutAsync($"/api/v1/libraries/{libraryId}/books/{bookId}/cover", form);
// Assert
Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode);
string content = await response.Content.ReadAsStringAsync();
using JsonDocument problemDetails = JsonDocument.Parse(content);
Assert.Equal("General.Validation", problemDetails.RootElement.GetProperty("title").GetString());
Assert.Contains("FileTooLarge", content, StringComparison.OrdinalIgnoreCase);
}
/// <summary>
/// Creates a multipart form carrying a minimal PNG-like payload.
/// </summary>
@@ -181,6 +267,17 @@ public class UpdateBookCoverEndpointTests : IClassFixture<AuthenticatedLuminaApi
payload[5] = 10;
payload[6] = 26;
payload[7] = 10;
return CreateCoverForm(payload, fileName);
}
/// <summary>
/// Creates a multipart form carrying the provided payload as an uploaded file.
/// </summary>
/// <param name="payload">The bytes of the uploaded file.</param>
/// <param name="fileName">The name of the uploaded file.</param>
/// <returns>A configured <see cref="MultipartFormDataContent"/> instance.</returns>
private static MultipartFormDataContent CreateCoverForm(byte[] payload, string fileName)
{
MultipartFormDataContent form = [];
ByteArrayContent fileContent = new(payload);
fileContent.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
@@ -203,7 +300,7 @@ public class UpdateBookCoverEndpointTests : IClassFixture<AuthenticatedLuminaApi
LibraryEntity library = _libraryEntityFixture.Create(id: libraryId, userId: userId, title: "Test Library", libraryType: LibraryType.EBook, contentLocations: []);
BookEntity book = _bookEntityFixture.Create(id: bookId, libraryId: libraryId, path: $"/books/{bookId:N}.epub", title: "Test Book", includeMetadata: false);
BookArtworkEntity existingCover = _bookArtworkEntityFixture.Create(bookId: bookId, artworkType: ArtworkType.Cover, fileName: existingCoverFileName, status: ArtworkStatus.Enriched);
book.BookArtwork.Add(existingCover);
book.Artwork.Add(existingCover);
dbContext.Libraries.Add(library);
dbContext.Books.Add(book);
await dbContext.SaveChangesAsync();
@@ -38,11 +38,11 @@ public class EditBookViewEndpointTests : IClassFixture<LuminaWebFactory>
_apiFactory.ApiClientStub.Reset();
BookDetailsDto expectedBook = _bookDetailsDtoFixture.Create();
expectedBook.Metadata!.Title = "A book";
_apiFactory.ApiClientStub.RegisterGetResponse($"books/{expectedBook.Id}", expectedBook);
_apiFactory.ApiClientStub.RegisterGetResponse($"libraries/{expectedBook.LibraryId}/books/{expectedBook.Id}", expectedBook);
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
// Act
HttpResponseMessage response = await webClient.Client.GetAsync($"/en-us/library/written-content-library/books-library/books/{expectedBook.Id}");
HttpResponseMessage response = await webClient.Client.GetAsync($"/en-us/library/written-content-library/books-library/books/{expectedBook.Id}?libraryId={expectedBook.LibraryId}");
string content = await response.Content.ReadAsStringAsync();
// Assert
@@ -38,11 +38,12 @@ public class GetBookDetailsEndpointTests : IClassFixture<LuminaWebFactory>
{
// Arrange
_apiFactory.ApiClientStub.Reset();
Guid libraryId = Guid.NewGuid();
Guid bookId = Guid.NewGuid();
BookDetailsDto expectedBook = _bookDetailsDtoFixture.Create(id: bookId);
_apiFactory.ApiClientStub.RegisterGetResponse($"books/{bookId}", expectedBook);
_apiFactory.ApiClientStub.RegisterGetResponse($"libraries/{libraryId}/books/{bookId}", expectedBook);
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
HttpRequestMessage getRequest = new(HttpMethod.Get, $"/en-us/library/written-content-library/books-library/books/{bookId}/api-get-book");
HttpRequestMessage getRequest = new(HttpMethod.Get, $"/en-us/library/written-content-library/books-library/books/{bookId}/api-get-book?libraryId={libraryId}");
getRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
// Act
@@ -55,7 +56,7 @@ public class GetBookDetailsEndpointTests : IClassFixture<LuminaWebFactory>
using JsonDocument json = JsonDocument.Parse(content);
Assert.True(json.RootElement.GetProperty("success").GetBoolean());
Assert.Equal(bookId, json.RootElement.GetProperty("data").GetProperty("id").GetGuid());
Assert.Contains($"books/{bookId}", _apiFactory.ApiClientStub.GetEndpointsCalled);
Assert.Contains($"libraries/{libraryId}/books/{bookId}", _apiFactory.ApiClientStub.GetEndpointsCalled);
}
[Fact]
@@ -66,10 +67,10 @@ public class GetBookDetailsEndpointTests : IClassFixture<LuminaWebFactory>
HttpClient anonymousClient = WebTestHelpers.CreateAnonymousClient(_apiFactory);
// Act
HttpResponseMessage response = await anonymousClient.GetAsync($"/en-us/library/written-content-library/books-library/books/{Guid.NewGuid()}/api-get-book");
HttpResponseMessage response = await anonymousClient.GetAsync($"/en-us/library/written-content-library/books-library/books/{Guid.NewGuid()}/api-get-book?libraryId={Guid.NewGuid()}");
// Assert
Assert.Equal(HttpStatusCode.Redirect, response.StatusCode);
Assert.DoesNotContain(_apiFactory.ApiClientStub.GetEndpointsCalled, endpoint => endpoint.StartsWith("books/", StringComparison.OrdinalIgnoreCase));
Assert.DoesNotContain(_apiFactory.ApiClientStub.GetEndpointsCalled, endpoint => endpoint.StartsWith("libraries/", StringComparison.OrdinalIgnoreCase));
}
}
@@ -42,7 +42,7 @@ public class GetLibraryItemsEndpointTests : IClassFixture<LuminaWebFactory>
Guid libraryId = Guid.NewGuid();
string searchTerm = "Harry";
PaginatedBookLiteDto expectedResponse = _paginatedBookLiteDtoFixture.Create(data: [_bookLiteDtoFixture.Create(title: "Harry Potter")]);
string expectedEndpoint = $"books/lite?libraryId={libraryId}&currentPage=1&perPage=20&searchTerm={searchTerm}&shouldIgnoreThePrefixForAlphaPicker=True";
string expectedEndpoint = $"libraries/{libraryId}/books/lite?currentPage=1&perPage=20&searchTerm={searchTerm}&shouldIgnoreThePrefixForAlphaPicker=True";
_apiFactory.ApiClientStub.RegisterGetResponse(expectedEndpoint, expectedResponse);
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
HttpRequestMessage getRequest = new(HttpMethod.Get, $"/en-us/library/written-content-library/books-library/books/api-get-library-items?libraryId={libraryId}&currentPage=1&perPage=20&searchTerm={searchTerm}&shouldIgnoreThePrefixForAlphaPicker=true");
@@ -38,11 +38,12 @@ public class GetReadingAvailabilityEndpointTests : IClassFixture<LuminaWebFactor
{
// Arrange
_apiFactory.ApiClientStub.Reset();
Guid libraryId = Guid.NewGuid();
Guid bookId = Guid.NewGuid();
ReadingAvailabilityDto availability = _readingAvailabilityDtoFixture.Create(bookId: bookId, isAvailable: true);
_apiFactory.ApiClientStub.RegisterGetResponse($"books/{bookId}/reading/availability", availability);
_apiFactory.ApiClientStub.RegisterGetResponse($"libraries/{libraryId}/books/{bookId}/reading/availability", availability);
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
HttpRequestMessage getRequest = new(HttpMethod.Get, $"/en-us/library/written-content-library/books-library/books/{bookId}/api-get-reading-availability");
HttpRequestMessage getRequest = new(HttpMethod.Get, $"/en-us/library/written-content-library/books-library/books/{bookId}/api-get-reading-availability?libraryId={libraryId}");
getRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
// Act
@@ -62,10 +63,11 @@ public class GetReadingAvailabilityEndpointTests : IClassFixture<LuminaWebFactor
{
// Arrange
_apiFactory.ApiClientStub.Reset();
Guid libraryId = Guid.NewGuid();
Guid bookId = Guid.NewGuid();
_apiFactory.ApiClientStub.RegisterGetResponse($"books/{bookId}/reading/availability", _readingAvailabilityDtoFixture.Create(bookId: bookId));
_apiFactory.ApiClientStub.RegisterGetResponse($"libraries/{libraryId}/books/{bookId}/reading/availability", _readingAvailabilityDtoFixture.Create(bookId: bookId));
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
HttpRequestMessage getRequest = new(HttpMethod.Get, $"/en-us/library/written-content-library/books-library/books/{bookId}/api-get-reading-availability");
HttpRequestMessage getRequest = new(HttpMethod.Get, $"/en-us/library/written-content-library/books-library/books/{bookId}/api-get-reading-availability?libraryId={libraryId}");
getRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
// Act
@@ -73,7 +75,7 @@ public class GetReadingAvailabilityEndpointTests : IClassFixture<LuminaWebFactor
// Assert
response.EnsureSuccessStatusCode();
Assert.Contains($"books/{bookId}/reading/availability", _apiFactory.ApiClientStub.GetEndpointsCalled);
Assert.Contains($"libraries/{libraryId}/books/{bookId}/reading/availability", _apiFactory.ApiClientStub.GetEndpointsCalled);
}
[Fact]
@@ -41,11 +41,12 @@ public class GetReadingManifestEndpointTests : IClassFixture<LuminaWebFactory>
{
// Arrange
_apiFactory.ApiClientStub.Reset();
Guid libraryId = Guid.NewGuid();
Guid bookId = Guid.NewGuid();
ReadingManifestDto manifest = _readingManifestDtoFixture.Create(title: "Test Book");
_apiFactory.ApiClientStub.RegisterGetResponse($"books/{bookId}/reading/manifest", manifest);
_apiFactory.ApiClientStub.RegisterGetResponse($"libraries/{libraryId}/books/{bookId}/reading/manifest", manifest);
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
HttpRequestMessage getRequest = new(HttpMethod.Get, $"/en-us/library/written-content-library/books-library/books/{bookId}/api-get-reading-manifest");
HttpRequestMessage getRequest = new(HttpMethod.Get, $"/en-us/library/written-content-library/books-library/books/{bookId}/api-get-reading-manifest?libraryId={libraryId}");
getRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
// Act
@@ -65,12 +66,13 @@ public class GetReadingManifestEndpointTests : IClassFixture<LuminaWebFactory>
{
// Arrange
_apiFactory.ApiClientStub.Reset();
Guid libraryId = Guid.NewGuid();
Guid bookId = Guid.NewGuid();
_apiFactory.ApiClientStub.RegisterGetException($"books/{bookId}/reading/manifest", new ApiException(
_apiFactory.ApiClientStub.RegisterGetException($"libraries/{libraryId}/books/{bookId}/reading/manifest", new ApiException(
_problemDetailsDtoFixture.Create(detail: "NoReaderAvailable"),
HttpStatusCode.NotFound));
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
HttpRequestMessage getRequest = new(HttpMethod.Get, $"/en-us/library/written-content-library/books-library/books/{bookId}/api-get-reading-manifest");
HttpRequestMessage getRequest = new(HttpMethod.Get, $"/en-us/library/written-content-library/books-library/books/{bookId}/api-get-reading-manifest?libraryId={libraryId}");
getRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
// Act
@@ -38,12 +38,13 @@ public class GetReadingSectionEndpointTests : IClassFixture<LuminaWebFactory>
{
// Arrange
_apiFactory.ApiClientStub.Reset();
Guid libraryId = Guid.NewGuid();
Guid bookId = Guid.NewGuid();
string locationRef = "chapter-1";
ReadingSectionDto section = _readingSectionDtoFixture.Create(locationRef: locationRef, contentHtml: "<p>Content</p>");
_apiFactory.ApiClientStub.RegisterGetResponse($"books/{bookId}/reading/sections/{locationRef}", section);
_apiFactory.ApiClientStub.RegisterGetResponse($"libraries/{libraryId}/books/{bookId}/reading/sections/{locationRef}", section);
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
HttpRequestMessage getRequest = new(HttpMethod.Get, $"/en-us/library/written-content-library/books-library/books/{bookId}/api-get-reading-section?locationRef={locationRef}");
HttpRequestMessage getRequest = new(HttpMethod.Get, $"/en-us/library/written-content-library/books-library/books/{bookId}/api-get-reading-section?locationRef={locationRef}&libraryId={libraryId}");
getRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
// Act
@@ -1,5 +1,10 @@
#region ========================================================================= USING =====================================================================================
#region ========================================================================= USING =====================================================================================
using Lumina.Presentation.Web.Common.DTO.Common;
using Lumina.Presentation.Web.Common.DTO.WrittenContentLibrary.BookLibrary;
using Lumina.Presentation.Web.Common.Exceptions;
using Lumina.Presentation.Web.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.Books.UpdateBookCover;
using Lumina.Presentation.Web.Fixtures.Common.DTO.Common;
using Lumina.Presentation.Web.Fixtures.Common.DTO.WrittenContentLibrary.BookLibrary;
using Lumina.Presentation.Web.Fixtures.Common.TestHelpers;
using Lumina.Presentation.Web.IntegrationTests.Common.Setup;
using System;
@@ -21,6 +26,8 @@ namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.Library.Writte
public class UpdateBookCoverEndpointTests : IClassFixture<LuminaWebFactory>
{
private readonly LuminaWebFactory _apiFactory;
private readonly ProblemDetailsDtoFixture _problemDetailsDtoFixture = new();
private readonly UpdateBookCoverDtoFixture _updateBookCoverDtoFixture = new();
/// <summary>
/// Initializes a new instance of the <see cref="UpdateBookCoverEndpointTests"/> class.
@@ -36,11 +43,12 @@ public class UpdateBookCoverEndpointTests : IClassFixture<LuminaWebFactory>
{
// Arrange
_apiFactory.ApiClientStub.Reset();
Guid libraryId = Guid.NewGuid();
Guid bookId = Guid.NewGuid();
string expectedPath = "/media/books/cover.png";
_apiFactory.ApiClientStub.RegisterPutResponse($"books/{bookId}/cover", expectedPath);
_apiFactory.ApiClientStub.RegisterPutResponse($"libraries/{libraryId}/books/{bookId}/cover", _updateBookCoverDtoFixture.Create(coverPath: expectedPath));
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
HttpRequestMessage uploadRequest = CreateUploadRequest(bookId, "cover.png");
HttpRequestMessage uploadRequest = CreateUploadRequest(bookId, libraryId, "cover.png");
uploadRequest.Headers.Add("RequestVerificationToken", webClient.AntiforgeryToken);
// Act
@@ -53,7 +61,7 @@ public class UpdateBookCoverEndpointTests : IClassFixture<LuminaWebFactory>
using JsonDocument json = JsonDocument.Parse(content);
Assert.True(json.RootElement.GetProperty("success").GetBoolean());
Assert.Equal(expectedPath, json.RootElement.GetProperty("data").GetString());
Assert.Contains(_apiFactory.ApiClientStub.PutRequests, putRequest => putRequest.Endpoint == $"books/{bookId}/cover" && putRequest.Data as string == "cover.png");
Assert.Contains(_apiFactory.ApiClientStub.PutRequests, putRequest => putRequest.Endpoint == $"libraries/{libraryId}/books/{bookId}/cover" && putRequest.Data as string == "cover.png");
}
[Fact]
@@ -61,11 +69,12 @@ public class UpdateBookCoverEndpointTests : IClassFixture<LuminaWebFactory>
{
// Arrange
_apiFactory.ApiClientStub.Reset();
Guid libraryId = Guid.NewGuid();
Guid routeId = Guid.NewGuid();
Guid formId = Guid.NewGuid();
_apiFactory.ApiClientStub.RegisterPutResponse($"books/{routeId}/cover", "/media/books/cover.png");
_apiFactory.ApiClientStub.RegisterPutResponse($"libraries/{libraryId}/books/{routeId}/cover", _updateBookCoverDtoFixture.Create(coverPath: "/media/books/cover.png"));
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
HttpRequestMessage uploadRequest = CreateUploadRequest(routeId, "cover.png");
HttpRequestMessage uploadRequest = CreateUploadRequest(routeId, libraryId, "cover.png");
uploadRequest.Headers.Add("RequestVerificationToken", webClient.AntiforgeryToken);
MultipartFormDataContent form = (MultipartFormDataContent)uploadRequest.Content!;
form.Add(new StringContent(formId.ToString()), "id");
@@ -77,8 +86,8 @@ public class UpdateBookCoverEndpointTests : IClassFixture<LuminaWebFactory>
// Assert
response.EnsureSuccessStatusCode();
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
Assert.Contains(_apiFactory.ApiClientStub.PutRequests, putRequest => putRequest.Endpoint == $"books/{routeId}/cover");
Assert.DoesNotContain(_apiFactory.ApiClientStub.PutRequests, putRequest => putRequest.Endpoint == $"books/{formId}/cover");
Assert.Contains(_apiFactory.ApiClientStub.PutRequests, putRequest => putRequest.Endpoint == $"libraries/{libraryId}/books/{routeId}/cover");
Assert.DoesNotContain(_apiFactory.ApiClientStub.PutRequests, putRequest => putRequest.Endpoint == $"libraries/{libraryId}/books/{formId}/cover");
}
[Fact]
@@ -86,28 +95,32 @@ public class UpdateBookCoverEndpointTests : IClassFixture<LuminaWebFactory>
{
// Arrange
_apiFactory.ApiClientStub.Reset();
Guid libraryId = Guid.NewGuid();
Guid bookId = Guid.NewGuid();
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
HttpRequestMessage uploadRequest = CreateUploadRequest(bookId, "cover.png");
HttpRequestMessage uploadRequest = CreateUploadRequest(bookId, libraryId, "cover.png");
// Act
HttpResponseMessage response = await webClient.Client.SendAsync(uploadRequest);
// Assert
Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode);
Assert.DoesNotContain(_apiFactory.ApiClientStub.PutRequests, putRequest => putRequest.Endpoint == $"books/{bookId}/cover");
Assert.DoesNotContain(_apiFactory.ApiClientStub.PutRequests, putRequest => putRequest.Endpoint == $"libraries/{libraryId}/books/{bookId}/cover");
}
[Fact]
public async Task UpdateBookCover_WhenCalledWithoutUploadedFile_ShouldReturnBadRequest()
public async Task UpdateBookCover_WhenCalledWithoutUploadedFile_ShouldForwardRequestAndReturnFailure()
{
// Arrange
_apiFactory.ApiClientStub.Reset();
Guid libraryId = Guid.NewGuid();
Guid bookId = Guid.NewGuid();
ProblemDetailsDto problemDetails = _problemDetailsDtoFixture.Create(title: "General.Validation", detail: "BookCoverCannotBeNull");
_apiFactory.ApiClientStub.RegisterPutException($"libraries/{libraryId}/books/{bookId}/cover", new ApiException(problemDetails, HttpStatusCode.UnprocessableEntity, $"libraries/{libraryId}/books/{bookId}/cover"));
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
MultipartFormDataContent noFileForm = [];
noFileForm.Add(new StringContent("unrelated-field"));
HttpRequestMessage uploadRequest = new(HttpMethod.Put, $"/en-us/library/written-content-library/books-library/books/{bookId}/api-update-cover")
HttpRequestMessage uploadRequest = new(HttpMethod.Put, $"/en-us/library/written-content-library/books-library/books/{bookId}/api-update-cover?libraryId={libraryId}")
{
Content = noFileForm
};
@@ -116,10 +129,14 @@ public class UpdateBookCoverEndpointTests : IClassFixture<LuminaWebFactory>
// Act
HttpResponseMessage response = await webClient.Client.SendAsync(uploadRequest);
string content = await response.Content.ReadAsStringAsync();
// Assert
Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode);
Assert.DoesNotContain(_apiFactory.ApiClientStub.PutRequests, putRequest => putRequest.Endpoint == $"books/{bookId}/cover");
// The web does not short-circuit the missing file; it forwards the request, and the API reports the missing cover
// with the same BookCoverCannotBeNull validation error any other client receives.
Assert.Contains(_apiFactory.ApiClientStub.PutRequests, putRequest => putRequest.Endpoint == $"libraries/{libraryId}/books/{bookId}/cover" && putRequest.Data == null);
using JsonDocument json = JsonDocument.Parse(content);
Assert.False(json.RootElement.GetProperty("success").GetBoolean());
}
[Fact]
@@ -128,7 +145,7 @@ public class UpdateBookCoverEndpointTests : IClassFixture<LuminaWebFactory>
// Arrange
_apiFactory.ApiClientStub.Reset();
HttpClient anonymousClient = WebTestHelpers.CreateAnonymousClient(_apiFactory);
HttpRequestMessage uploadRequest = CreateUploadRequest(Guid.NewGuid(), "cover.png");
HttpRequestMessage uploadRequest = CreateUploadRequest(Guid.NewGuid(), Guid.NewGuid(), "cover.png");
// Act
HttpResponseMessage response = await anonymousClient.SendAsync(uploadRequest);
@@ -142,15 +159,16 @@ public class UpdateBookCoverEndpointTests : IClassFixture<LuminaWebFactory>
/// Builds the multipart PUT request that uploads a cover to the book identified by <paramref name="bookId"/>.
/// </summary>
/// <param name="bookId">The route Id of the book whose cover is uploaded.</param>
/// <param name="libraryId">The Id of the media library the book belongs to.</param>
/// <param name="fileName">The name of the uploaded file.</param>
/// <returns>The configured upload request.</returns>
private static HttpRequestMessage CreateUploadRequest(Guid bookId, string fileName)
private static HttpRequestMessage CreateUploadRequest(Guid bookId, Guid libraryId, string fileName)
{
MultipartFormDataContent form = [];
ByteArrayContent fileContent = new(Encoding.UTF8.GetBytes("fake cover payload"));
fileContent.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
form.Add(fileContent, "cover", fileName);
return new HttpRequestMessage(HttpMethod.Put, $"/en-us/library/written-content-library/books-library/books/{bookId}/api-update-cover")
return new HttpRequestMessage(HttpMethod.Put, $"/en-us/library/written-content-library/books-library/books/{bookId}/api-update-cover?libraryId={libraryId}")
{
Content = form
};