Adds tests for the book reading feature

This commit is contained in:
BinaryAlley committed 2026-09-02 04:45:51 -07:00
1 parent f7ccdf3d1c
commit 3a3c0c047c
192 files changed
+14104 -342

No files matched your search

@@ -1,6 +1,6 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.Mapping.MediaLibrary.WrittenContentLibrary.BookLibrary.Books;
using Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BooksLibrary.Books.Commands.AddBook;
using Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Commands.AddBook;
using Lumina.Contracts.Fixtures.Core.DTO.MediaContributors;
using Lumina.Contracts.Fixtures.Core.DTO.MediaLibrary.WrittenContentLibrary;
using Lumina.Contracts.Fixtures.Core.Requests.MediaLibrary.WrittenContentLibrary.BookLibrary.Books;
@@ -1,6 +1,6 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.Mapping.MediaLibrary.WrittenContentLibrary.BookLibrary.Books;
using Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BooksLibrary.Books.Queries.GetBooksLite;
using Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.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;
@@ -1,6 +1,6 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.Mapping.MediaLibrary.WrittenContentLibrary.BookLibrary.Books;
using Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BooksLibrary.Books.Queries.GetBooks;
using Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.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;
@@ -0,0 +1,32 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.Mapping.MediaLibrary.WrittenContentLibrary.BookLibrary.Books;
using Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Reading.Queries.GetReadingManifest;
using Lumina.Contracts.Fixtures.Core.Requests.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Reading;
using Lumina.Contracts.Requests.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Reading;
using System.Diagnostics.CodeAnalysis;
#endregion
namespace Lumina.Application.UnitTests.Common.Mapping.MediaLibrary.WrittenContentLibrary.BookLibrary.Books;
/// <summary>
/// Contains unit tests for the <see cref="GetReadingManifestRequestMapping"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetReadingManifestRequestMappingTests
{
private readonly GetReadingManifestRequestFixture _requestFixture = new();
[Fact]
public void ToQuery_WhenMappingValidRequest_ShouldMapCorrectly()
{
// Arrange
GetReadingManifestRequest request = _requestFixture.Create();
// Act
GetReadingManifestQuery result = request.ToQuery();
// Assert
Assert.NotNull(result);
Assert.Equal(request.BookId, result.BookId);
}
}
@@ -0,0 +1,33 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.Mapping.MediaLibrary.WrittenContentLibrary.BookLibrary.Books;
using Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Reading.Queries.GetReadingResource;
using Lumina.Contracts.Fixtures.Core.Requests.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Reading;
using Lumina.Contracts.Requests.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Reading;
using System.Diagnostics.CodeAnalysis;
#endregion
namespace Lumina.Application.UnitTests.Common.Mapping.MediaLibrary.WrittenContentLibrary.BookLibrary.Books;
/// <summary>
/// Contains unit tests for the <see cref="GetReadingResourceRequestMapping"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetReadingResourceRequestMappingTests
{
private readonly GetReadingResourceRequestFixture _requestFixture = new();
[Fact]
public void ToQuery_WhenMappingValidRequest_ShouldMapCorrectly()
{
// Arrange
GetReadingResourceRequest request = _requestFixture.Create();
// Act
GetReadingResourceQuery result = request.ToQuery();
// Assert
Assert.NotNull(result);
Assert.Equal(request.BookId, result.BookId);
Assert.Equal(request.ResourceKey, result.ResourceKey);
}
}
@@ -0,0 +1,33 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.Mapping.MediaLibrary.WrittenContentLibrary.BookLibrary.Books;
using Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Reading.Queries.GetReadingSection;
using Lumina.Contracts.Fixtures.Core.Requests.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Reading;
using Lumina.Contracts.Requests.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Reading;
using System.Diagnostics.CodeAnalysis;
#endregion
namespace Lumina.Application.UnitTests.Common.Mapping.MediaLibrary.WrittenContentLibrary.BookLibrary.Books;
/// <summary>
/// Contains unit tests for the <see cref="GetReadingSectionRequestMapping"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetReadingSectionRequestMappingTests
{
private readonly GetReadingSectionRequestFixture _requestFixture = new();
[Fact]
public void ToQuery_WhenMappingValidRequest_ShouldMapCorrectly()
{
// Arrange
GetReadingSectionRequest request = _requestFixture.Create();
// Act
GetReadingSectionQuery result = request.ToQuery();
// Assert
Assert.NotNull(result);
Assert.Equal(request.BookId, result.BookId);
Assert.Equal(request.LocationRef, result.LocationRef);
}
}
@@ -0,0 +1,40 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.Mapping.MediaLibrary.WrittenContentLibrary.BookLibrary.Books;
using Lumina.Contracts.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary.Reading;
using Lumina.Contracts.Fixtures.Core.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary.Reading;
using Lumina.Contracts.Responses.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Reading;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
#endregion
namespace Lumina.Application.UnitTests.Common.Mapping.MediaLibrary.WrittenContentLibrary.BookLibrary.Books;
/// <summary>
/// Contains unit tests for the <see cref="ReadingDocumentDtoMapping"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class ReadingDocumentDtoMappingTests
{
private readonly ReadingDocumentDtoFixture _readingDocumentDtoFixture = new();
[Fact]
public void ToResponse_WhenMappingValidDocument_ShouldMapCorrectly()
{
// Arrange
ReadingDocumentDto document = _readingDocumentDtoFixture.Create();
// Act
ReadingManifestResponse result = document.ToResponse();
// Assert
Assert.NotNull(result);
Assert.Equal(document.Title, result.Title);
Assert.Equal(document.Author, result.Author);
Assert.Equal(document.CoverResourceKey, result.CoverResourceKey);
Assert.Equal(document.TableOfContents.Count, result.TableOfContents.Count);
Assert.Equal(document.Spine.Select(item => item.LocationRef), result.Spine.Select(item => item.LocationRef));
Assert.Equal(document.Spine.Select(item => item.Title), result.Spine.Select(item => item.Title));
Assert.Equal(document.Resources.Keys, result.ResourceKeys);
Assert.Equal(document.HasTextContent, result.HasTextContent);
}
}
@@ -0,0 +1,36 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.Mapping.MediaLibrary.WrittenContentLibrary.BookLibrary.Books;
using Lumina.Contracts.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary.Reading;
using Lumina.Contracts.Fixtures.Core.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary.Reading;
using Lumina.Contracts.Responses.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Reading;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
#endregion
namespace Lumina.Application.UnitTests.Common.Mapping.MediaLibrary.WrittenContentLibrary.BookLibrary.Books;
/// <summary>
/// Contains unit tests for the <see cref="ReadingTocEntryDtoMapping"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class ReadingTocEntryDtoMappingTests
{
private readonly ReadingTocEntryDtoFixture _readingTocEntryDtoFixture = new();
[Fact]
public void ToResponse_WhenMappingValidEntry_ShouldMapCorrectly()
{
// Arrange
ReadingTocEntryDto entry = _readingTocEntryDtoFixture.Create(children: [_readingTocEntryDtoFixture.Create()]);
// Act
ReadingTocEntryResponse result = entry.ToResponse();
// Assert
Assert.NotNull(result);
Assert.Equal(entry.Label, result.Label);
Assert.Equal(entry.LocationRef, result.LocationRef);
Assert.Equal(entry.Children.Count, result.Children.Count);
Assert.Equal(entry.Children.Select(child => child.Label), result.Children.Select(child => child.Label));
}
}
@@ -0,0 +1,32 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.Mapping.Plugins;
using Lumina.Application.Core.Plugins.Queries.GetLibraryBookReaders;
using Lumina.Contracts.Fixtures.Core.Requests.Plugins;
using Lumina.Contracts.Requests.Plugins;
using System.Diagnostics.CodeAnalysis;
#endregion
namespace Lumina.Application.UnitTests.Common.Mapping.Plugins;
/// <summary>
/// Contains unit tests for the <see cref="GetLibraryBookReadersRequestMapping"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetLibraryBookReadersRequestMappingTests
{
private readonly GetLibraryBookReadersRequestFixture _requestFixture = new();
[Fact]
public void ToQuery_WhenMappingValidRequest_ShouldMapCorrectly()
{
// Arrange
GetLibraryBookReadersRequest request = _requestFixture.Create();
// Act
GetLibraryBookReadersQuery result = request.ToQuery();
// Assert
Assert.NotNull(result);
Assert.Equal(request.LibraryId, result.LibraryId);
}
}
@@ -0,0 +1,39 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DataAccess.Entities.Plugins;
using Lumina.Application.Common.Mapping.Plugins;
using Lumina.Application.Fixtures.Common.DataAccess.Entities.Plugins;
using Lumina.Contracts.Responses.Plugins;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
#endregion
namespace Lumina.Application.UnitTests.Common.Mapping.Plugins;
/// <summary>
/// Contains unit tests for the <see cref="LibraryBookReaderConfigurationEntityMapping"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class LibraryBookReaderConfigurationEntityMappingTests
{
private readonly LibraryBookReaderConfigurationEntityFixture _configurationEntityFixture = new();
[Fact]
public void ToResponse_WhenMappingValidConfiguration_ShouldMapCorrectly()
{
// Arrange
Guid pluginId = Guid.NewGuid();
LibraryBookReaderConfigurationEntity configuration = _configurationEntityFixture.Create(pluginId: pluginId, isEnabled: false);
IReadOnlyList<string> supportedExtensions = [".epub", ".pdf"];
// Act
LibraryBookReaderResponse result = configuration.ToResponse("My Reader", supportedExtensions);
// Assert
Assert.NotNull(result);
Assert.Equal(pluginId, result.PluginId);
Assert.Equal("My Reader", result.Name);
Assert.Equal(supportedExtensions, result.SupportedExtensions);
Assert.False(result.IsEnabled);
}
}
@@ -0,0 +1,34 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.Mapping.Plugins;
using Lumina.Application.Core.Plugins.Commands.SetLibraryBookReaderEnabled;
using Lumina.Contracts.Fixtures.Core.Requests.Plugins;
using Lumina.Contracts.Requests.Plugins;
using System.Diagnostics.CodeAnalysis;
#endregion
namespace Lumina.Application.UnitTests.Common.Mapping.Plugins;
/// <summary>
/// Contains unit tests for the <see cref="SetLibraryBookReaderEnabledRequestMapping"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class SetLibraryBookReaderEnabledRequestMappingTests
{
private readonly SetLibraryBookReaderEnabledRequestFixture _requestFixture = new();
[Fact]
public void ToCommand_WhenMappingValidRequest_ShouldMapCorrectly()
{
// Arrange
SetLibraryBookReaderEnabledRequest request = _requestFixture.Create();
// Act
SetLibraryBookReaderEnabledCommand result = request.ToCommand();
// Assert
Assert.NotNull(result);
Assert.Equal(request.LibraryId, result.LibraryId);
Assert.Equal(request.PluginId, result.PluginId);
Assert.Equal(request.IsEnabled, result.IsEnabled);
}
}
@@ -25,7 +25,9 @@ public class UpdateUserSettingsRequestMappingTests
itemsPerPage: 48,
shouldIgnoreThePrefixForAlphaPicker: false,
isThemeCachingEnabled: true,
shouldAggregateMetadataWhenMissing: false
shouldAggregateMetadataWhenMissing: false,
shouldRenderPdfAsImages: true,
shouldPreserveBookStyles: true
);
// Act
@@ -37,5 +39,7 @@ public class UpdateUserSettingsRequestMappingTests
Assert.Equal(request.ItemsPerPage, result.ItemsPerPage);
Assert.Equal(request.ShouldIgnoreThePrefixForAlphaPicker, result.ShouldIgnoreThePrefixForAlphaPicker);
Assert.Equal(request.IsThemeCachingEnabled, result.IsThemeCachingEnabled);
Assert.Equal(request.ShouldRenderPdfAsImages, result.ShouldRenderPdfAsImages);
Assert.Equal(request.ShouldPreserveBookStyles, result.ShouldPreserveBookStyles);
}
}
@@ -35,6 +35,8 @@ public class UserSettingsEntityMappingTests
Assert.Equal(entity.ItemsPerPage, result.Value.ItemsPerPage);
Assert.Equal(entity.ShouldIgnoreThePrefixForAlphaPicker, result.Value.ShouldIgnoreThePrefixForAlphaPicker);
Assert.Equal(entity.IsThemeCachingEnabled, result.Value.IsThemeCachingEnabled);
Assert.Equal(entity.ShouldRenderPdfAsImages, result.Value.ShouldRenderPdfAsImages);
Assert.Equal(entity.ShouldPreserveBookStyles, result.Value.ShouldPreserveBookStyles);
}
[Fact]
@@ -53,5 +55,7 @@ public class UserSettingsEntityMappingTests
Assert.Equal(entity.ItemsPerPage, result.ItemsPerPage);
Assert.Equal(entity.ShouldIgnoreThePrefixForAlphaPicker, result.ShouldIgnoreThePrefixForAlphaPicker);
Assert.Equal(entity.IsThemeCachingEnabled, result.IsThemeCachingEnabled);
Assert.Equal(entity.ShouldRenderPdfAsImages, result.ShouldRenderPdfAsImages);
Assert.Equal(entity.ShouldPreserveBookStyles, result.ShouldPreserveBookStyles);
}
}
@@ -35,6 +35,8 @@ public class UserSettingsMappingTests
Assert.Equal(domainEntity.IsPaginationEnabled, result.IsPaginationEnabled);
Assert.Equal(domainEntity.ItemsPerPage, result.ItemsPerPage);
Assert.Equal(domainEntity.ShouldIgnoreThePrefixForAlphaPicker, result.ShouldIgnoreThePrefixForAlphaPicker);
Assert.Equal(domainEntity.ShouldRenderPdfAsImages, result.ShouldRenderPdfAsImages);
Assert.Equal(domainEntity.ShouldPreserveBookStyles, result.ShouldPreserveBookStyles);
}
[Fact]
@@ -53,5 +55,7 @@ public class UserSettingsMappingTests
Assert.Equal(domainEntity.IsPaginationEnabled, result.IsPaginationEnabled);
Assert.Equal(domainEntity.ItemsPerPage, result.ItemsPerPage);
Assert.Equal(domainEntity.ShouldIgnoreThePrefixForAlphaPicker, result.ShouldIgnoreThePrefixForAlphaPicker);
Assert.Equal(domainEntity.ShouldRenderPdfAsImages, result.ShouldRenderPdfAsImages);
Assert.Equal(domainEntity.ShouldPreserveBookStyles, result.ShouldPreserveBookStyles);
}
}
@@ -5,7 +5,7 @@ using Lumina.Application.Common.DataAccess.Repositories.Books;
using Lumina.Application.Common.DataAccess.Repositories.MediaLibrary;
using Lumina.Application.Common.DataAccess.UoW;
using Lumina.Application.Core.MediaLibrary.Management.Events;
using Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BooksLibrary.Artwork;
using Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Artwork;
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management;
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary;
using Lumina.Domain.Common.Exceptions;
@@ -5,9 +5,9 @@ using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentL
using Lumina.Application.Common.DataAccess.Repositories.Books;
using Lumina.Application.Common.DataAccess.UoW;
using Lumina.Application.Common.Infrastructure.Validation;
using Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BooksLibrary.Books.Commands.AddBook;
using Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Commands.AddBook;
using Lumina.Application.Fixtures.Common.Setup;
using Lumina.Application.Fixtures.Core.MediaLibrary.WrittenContentLibrary.BooksLibrary.Books.Commands.AddBook;
using Lumina.Application.Fixtures.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Commands.AddBook;
using Lumina.Contracts.Fixtures.Core.DTO.Common;
using Lumina.Contracts.Fixtures.Core.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary;
using Lumina.Contracts.Responses.MediaLibrary.WrittenContentLibrary.BookLibrary.Books;
@@ -21,7 +21,7 @@ using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Application.UnitTests.Core.MediaLibrary.WrittenContentLibrary.BooksLibrary.Books.Commands.AddBook;
namespace Lumina.Application.UnitTests.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Commands.AddBook;
/// <summary>
/// Contains unit tests for the <see cref="AddBookCommandHandler"/> class.
@@ -1,7 +1,7 @@
#region ========================================================================= USING =====================================================================================
using Bogus;
using Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BooksLibrary.Books.Commands.AddBook;
using Lumina.Application.Fixtures.Core.MediaLibrary.WrittenContentLibrary.BooksLibrary.Books.Commands.AddBook;
using Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Commands.AddBook;
using Lumina.Application.Fixtures.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Commands.AddBook;
using Lumina.Application.UnitTests.Common.Setup;
using Lumina.Domain.Common.Errors;
using Lumina.Domain.Common.Primitives;
@@ -12,7 +12,7 @@ using System.Diagnostics.CodeAnalysis;
using System.Linq;
#endregion
namespace Lumina.Application.UnitTests.Core.MediaLibrary.WrittenContentLibrary.BooksLibrary.Books.Commands.AddBook;
namespace Lumina.Application.UnitTests.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Commands.AddBook;
/// <summary>
/// Contains unit tests for the <see cref="AddBookCommandValidator"/> class.
@@ -8,10 +8,10 @@ using Lumina.Application.Common.Infrastructure.Authentication;
using Lumina.Application.Common.Infrastructure.Authorization;
using Lumina.Application.Common.Infrastructure.Authorization.Policies.LibraryOwnership;
using Lumina.Application.Common.Infrastructure.Validation;
using Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BooksLibrary.Books.Queries.GetBooks;
using Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Queries.GetBooks;
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary;
using Lumina.Application.Fixtures.Common.DTO.Pagination;
using Lumina.Application.Fixtures.Core.MediaLibrary.WrittenContentLibrary.BooksLibrary.Books.Queries.GetBooks;
using Lumina.Application.Fixtures.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Queries.GetBooks;
using Lumina.Contracts.Responses.Common;
using Lumina.Contracts.Responses.MediaLibrary.WrittenContentLibrary.BookLibrary.Books;
using Lumina.Domain.Common.Errors;
@@ -26,7 +26,7 @@ using System.Threading.Tasks;
using ApplicationErrors = Lumina.Application.Common.Errors.Errors;
#endregion
namespace Lumina.Application.UnitTests.Core.MediaLibrary.WrittenContentLibrary.BooksLibrary.Books.Queries.GetBooks;
namespace Lumina.Application.UnitTests.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Queries.GetBooks;
/// <summary>
/// Contains unit tests for the <see cref="GetBooksQueryHandler"/> class.
@@ -1,6 +1,6 @@
#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.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Queries.GetBooks;
using Lumina.Application.Fixtures.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Queries.GetBooks;
using Lumina.Application.UnitTests.Common.Setup;
using Lumina.Domain.Common.Errors;
using Lumina.Domain.Common.Primitives;
@@ -9,7 +9,7 @@ using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
#endregion
namespace Lumina.Application.UnitTests.Core.MediaLibrary.WrittenContentLibrary.BooksLibrary.Books.Queries.GetBooks;
namespace Lumina.Application.UnitTests.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Queries.GetBooks;
/// <summary>
/// Contains unit tests for the <see cref="GetBooksQueryValidator"/> class.
@@ -8,10 +8,10 @@ using Lumina.Application.Common.Infrastructure.Authentication;
using Lumina.Application.Common.Infrastructure.Authorization;
using Lumina.Application.Common.Infrastructure.Authorization.Policies.LibraryOwnership;
using Lumina.Application.Common.Infrastructure.Validation;
using Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BooksLibrary.Books.Queries.GetBooksLite;
using Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Queries.GetBooksLite;
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary;
using Lumina.Application.Fixtures.Common.DTO.Pagination;
using Lumina.Application.Fixtures.Core.MediaLibrary.WrittenContentLibrary.BooksLibrary.Books.Queries.GetBooksLite;
using Lumina.Application.Fixtures.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Queries.GetBooksLite;
using Lumina.Contracts.Responses.Common;
using Lumina.Contracts.Responses.MediaLibrary.WrittenContentLibrary.BookLibrary.Books;
using Lumina.Domain.Common.Errors;
@@ -26,7 +26,7 @@ using System.Threading.Tasks;
using ApplicationErrors = Lumina.Application.Common.Errors.Errors;
#endregion
namespace Lumina.Application.UnitTests.Core.MediaLibrary.WrittenContentLibrary.BooksLibrary.Books.Queries.GetBooksLite;
namespace Lumina.Application.UnitTests.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Queries.GetBooksLite;
/// <summary>
/// Contains unit tests for the <see cref="GetBooksLiteQueryHandler"/> class.
@@ -1,6 +1,6 @@
#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.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Queries.GetBooksLite;
using Lumina.Application.Fixtures.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Queries.GetBooksLite;
using Lumina.Application.UnitTests.Common.Setup;
using Lumina.Domain.Common.Errors;
using Lumina.Domain.Common.Primitives;
@@ -9,7 +9,7 @@ using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
#endregion
namespace Lumina.Application.UnitTests.Core.MediaLibrary.WrittenContentLibrary.BooksLibrary.Books.Queries.GetBooksLite;
namespace Lumina.Application.UnitTests.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Queries.GetBooksLite;
/// <summary>
/// Contains unit tests for the <see cref="GetBooksLiteQueryValidator"/> class.
@@ -0,0 +1,208 @@
#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.Authorization.Policies.LibraryOwnership;
using Lumina.Application.Common.Infrastructure.Validation;
using Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Reading.Queries.GetReadingAvailability;
using Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Reading;
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management;
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary;
using Lumina.Application.Fixtures.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Reading.Queries.GetReadingAvailability;
using Lumina.Contracts.Fixtures.Core.Responses.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Reading;
using Lumina.Contracts.Responses.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Reading;
using Lumina.Domain.Common.Errors;
using Lumina.Domain.Common.Primitives;
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
using NSubstitute;
using System;
using System.Diagnostics.CodeAnalysis;
using System.Threading;
using System.Threading.Tasks;
using ApplicationErrors = Lumina.Application.Common.Errors.Errors;
using DomainErrors = Lumina.Domain.Common.Errors.Errors;
#endregion
namespace Lumina.Application.UnitTests.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Reading.Queries.GetReadingAvailability;
/// <summary>
/// Contains unit tests for the <see cref="GetReadingAvailabilityQueryHandler"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetReadingAvailabilityQueryHandlerTests
{
private readonly IUnitOfWork _mockUnitOfWork;
private readonly IBookRepository _mockBookRepository;
private readonly ILibraryRepository _mockLibraryRepository;
private readonly IAuthorizationService _mockAuthorizationService;
private readonly ICurrentUserService _mockCurrentUserService;
private readonly IBookReadingService _mockBookReadingService;
private readonly IValidator<GetReadingAvailabilityQuery> _mockValidator;
private readonly GetReadingAvailabilityQueryHandler _sut;
private readonly Guid _userId;
private readonly GetReadingAvailabilityQueryFixture _getReadingAvailabilityQueryFixture = new();
private readonly BookEntityFixture _bookEntityFixture = new();
private readonly LibraryEntityFixture _libraryEntityFixture = new();
private readonly ReadingAvailabilityResponseFixture _readingAvailabilityResponseFixture = new();
/// <summary>
/// Initializes a new instance of the <see cref="GetReadingAvailabilityQueryHandlerTests"/> class.
/// </summary>
public GetReadingAvailabilityQueryHandlerTests()
{
_mockBookRepository = Substitute.For<IBookRepository>();
_mockLibraryRepository = Substitute.For<ILibraryRepository>();
_mockUnitOfWork = Substitute.For<IUnitOfWork>();
_mockUnitOfWork.BookRepository.Returns(_mockBookRepository);
_mockUnitOfWork.LibraryRepository.Returns(_mockLibraryRepository);
_mockAuthorizationService = Substitute.For<IAuthorizationService>();
_mockCurrentUserService = Substitute.For<ICurrentUserService>();
_mockBookReadingService = Substitute.For<IBookReadingService>();
_mockValidator = Substitute.For<IValidator<GetReadingAvailabilityQuery>>();
_userId = Guid.NewGuid();
// Default stubs: the current user is authenticated and the library ownership policy allows access.
_mockCurrentUserService.UserId.Returns(_userId);
_mockAuthorizationService.EvaluatePolicyAsync<ILibraryOwnershipPolicy>(_userId, Arg.Any<LibraryOwnershipPolicyContext>(), Arg.Any<CancellationToken>())
.Returns(true);
_mockValidator.Validate(Arg.Any<GetReadingAvailabilityQuery>()).Returns([]);
_sut = new GetReadingAvailabilityQueryHandler(_mockUnitOfWork, _mockAuthorizationService, _mockCurrentUserService, _mockBookReadingService, _mockValidator);
}
[Fact]
public async Task HandleAsync_WhenBookIsAvailable_ShouldReturnAvailabilityResponse()
{
// Arrange
GetReadingAvailabilityQuery query = _getReadingAvailabilityQueryFixture.Create();
CancellationToken cancellationToken = CancellationToken.None;
BookEntity book = _bookEntityFixture.Create(id: query.BookId);
LibraryEntity library = _libraryEntityFixture.Create(id: book.LibraryId, libraryType: LibraryType.EBook);
ReadingAvailabilityResponse expectedResponse = _readingAvailabilityResponseFixture.Create(bookId: book.Id, libraryId: book.LibraryId, isAvailable: true);
_mockBookRepository.GetByIdAsync(query.BookId, cancellationToken).Returns(Result.From<BookEntity?>(book));
_mockLibraryRepository.GetByIdAsync(book.LibraryId, cancellationToken).Returns(Result.From<LibraryEntity?>(library));
_mockBookReadingService.GetAvailabilityAsync(book.Id, book.LibraryId, book.Path, library.LibraryType, cancellationToken).Returns(expectedResponse);
// Act
Result<ReadingAvailabilityResponse> result = await _sut.HandleAsync(query, cancellationToken);
// Assert
Assert.False(result.IsFailure);
Assert.Equal(expectedResponse, result.Value);
}
[Fact]
public async Task HandleAsync_WhenBookIsNotAvailable_ShouldReturnAvailabilityResponseWithErrorCode()
{
// Arrange
GetReadingAvailabilityQuery query = _getReadingAvailabilityQueryFixture.Create();
CancellationToken cancellationToken = CancellationToken.None;
BookEntity book = _bookEntityFixture.Create(id: query.BookId);
LibraryEntity library = _libraryEntityFixture.Create(id: book.LibraryId, libraryType: LibraryType.EBook);
ReadingAvailabilityResponse expectedResponse = _readingAvailabilityResponseFixture.Create(bookId: book.Id, libraryId: book.LibraryId, isAvailable: false, errorCode: nameof(Errors.Reading.ReaderDisabled));
_mockBookRepository.GetByIdAsync(query.BookId, cancellationToken).Returns(Result.From<BookEntity?>(book));
_mockLibraryRepository.GetByIdAsync(book.LibraryId, cancellationToken).Returns(Result.From<LibraryEntity?>(library));
_mockBookReadingService.GetAvailabilityAsync(book.Id, book.LibraryId, book.Path, library.LibraryType, cancellationToken).Returns(expectedResponse);
// Act
Result<ReadingAvailabilityResponse> result = await _sut.HandleAsync(query, cancellationToken);
// Assert
Assert.False(result.IsFailure);
Assert.Equal("ReaderDisabled", result.Value.ErrorCode);
Assert.False(result.Value.IsAvailable);
}
[Fact]
public async Task HandleAsync_WhenBookDoesNotExist_ShouldReturnBookNotFoundError()
{
// Arrange
GetReadingAvailabilityQuery query = _getReadingAvailabilityQueryFixture.Create();
_mockBookRepository.GetByIdAsync(query.BookId, Arg.Any<CancellationToken>()).Returns(Result.From<BookEntity?>(null));
// Act
Result<ReadingAvailabilityResponse> result = await _sut.HandleAsync(query, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(DomainErrors.Reading.BookNotFound, result.FirstError);
await _mockBookReadingService.DidNotReceive().GetAvailabilityAsync(Arg.Any<Guid>(), Arg.Any<Guid>(), Arg.Any<string>(), Arg.Any<LibraryType>(), Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenLibraryDoesNotExist_ShouldReturnLibraryNotFoundError()
{
// Arrange
GetReadingAvailabilityQuery query = _getReadingAvailabilityQueryFixture.Create();
BookEntity book = _bookEntityFixture.Create(id: query.BookId);
_mockBookRepository.GetByIdAsync(query.BookId, Arg.Any<CancellationToken>()).Returns(Result.From<BookEntity?>(book));
_mockLibraryRepository.GetByIdAsync(book.LibraryId, Arg.Any<CancellationToken>()).Returns(Result.From<LibraryEntity?>(null));
// Act
Result<ReadingAvailabilityResponse> result = await _sut.HandleAsync(query, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(DomainErrors.Library.LibraryNotFound, result.FirstError);
await _mockBookReadingService.DidNotReceive().GetAvailabilityAsync(Arg.Any<Guid>(), Arg.Any<Guid>(), Arg.Any<string>(), Arg.Any<LibraryType>(), Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenPolicyDeniesAccess_ShouldReturnNotAuthorizedError()
{
// Arrange
GetReadingAvailabilityQuery query = _getReadingAvailabilityQueryFixture.Create();
BookEntity book = _bookEntityFixture.Create(id: query.BookId);
_mockBookRepository.GetByIdAsync(query.BookId, Arg.Any<CancellationToken>()).Returns(Result.From<BookEntity?>(book));
_mockAuthorizationService.EvaluatePolicyAsync<ILibraryOwnershipPolicy>(_userId, Arg.Any<LibraryOwnershipPolicyContext>(), Arg.Any<CancellationToken>())
.Returns(false);
// Act
Result<ReadingAvailabilityResponse> result = await _sut.HandleAsync(query, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(ApplicationErrors.Authorization.NotAuthorized, result.FirstError);
await _mockLibraryRepository.DidNotReceive().GetByIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
await _mockBookReadingService.DidNotReceive().GetAvailabilityAsync(Arg.Any<Guid>(), Arg.Any<Guid>(), Arg.Any<string>(), Arg.Any<LibraryType>(), Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenUserIsNotAuthenticated_ShouldReturnNotAuthorizedError()
{
// Arrange
GetReadingAvailabilityQuery query = _getReadingAvailabilityQueryFixture.Create();
_mockCurrentUserService.UserId.Returns((Guid?)null);
// Act
Result<ReadingAvailabilityResponse> result = await _sut.HandleAsync(query, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(ApplicationErrors.Authorization.NotAuthorized, result.FirstError);
await _mockAuthorizationService.DidNotReceive().EvaluatePolicyAsync<ILibraryOwnershipPolicy>(Arg.Any<Guid>(), Arg.Any<LibraryOwnershipPolicyContext>(), Arg.Any<CancellationToken>());
await _mockBookRepository.DidNotReceive().GetByIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenValidationFails_ShouldReturnValidationErrorsWithoutCheckingAvailability()
{
// Arrange
GetReadingAvailabilityQuery query = _getReadingAvailabilityQueryFixture.Create();
_mockValidator.Validate(Arg.Any<GetReadingAvailabilityQuery>()).Returns([Errors.Reading.BookIdCannotBeEmpty]);
// Act
Result<ReadingAvailabilityResponse> result = await _sut.HandleAsync(query, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(Errors.Reading.BookIdCannotBeEmpty, result.FirstError);
await _mockAuthorizationService.DidNotReceive().EvaluatePolicyAsync<ILibraryOwnershipPolicy>(Arg.Any<Guid>(), Arg.Any<LibraryOwnershipPolicyContext>(), Arg.Any<CancellationToken>());
await _mockBookRepository.DidNotReceive().GetByIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
await _mockBookReadingService.DidNotReceive().GetAvailabilityAsync(Arg.Any<Guid>(), Arg.Any<Guid>(), Arg.Any<string>(), Arg.Any<LibraryType>(), Arg.Any<CancellationToken>());
}
}
@@ -0,0 +1,48 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Reading.Queries.GetReadingAvailability;
using Lumina.Application.Fixtures.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Reading.Queries.GetReadingAvailability;
using Lumina.Application.UnitTests.Common.Setup;
using Lumina.Domain.Common.Errors;
using Lumina.Domain.Common.Primitives;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
#endregion
namespace Lumina.Application.UnitTests.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Reading.Queries.GetReadingAvailability;
/// <summary>
/// Contains unit tests for the <see cref="GetReadingAvailabilityQueryValidator"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetReadingAvailabilityQueryValidatorTests
{
private readonly GetReadingAvailabilityQueryValidator _validator = new();
private readonly GetReadingAvailabilityQueryFixture _getReadingAvailabilityQueryFixture = new();
[Fact]
public void Validate_WhenBookIdIsEmpty_ShouldHaveValidationError()
{
// Arrange
GetReadingAvailabilityQuery query = _getReadingAvailabilityQueryFixture.Create(bookId: Guid.Empty);
// Act
List<Error> result = _validator.TestValidate(query);
// Assert
result.ShouldHaveValidationError(Errors.Reading.BookIdCannotBeEmpty);
}
[Fact]
public void Validate_WhenBookIdIsValid_ShouldNotHaveValidationError()
{
// Arrange
GetReadingAvailabilityQuery query = _getReadingAvailabilityQueryFixture.Create();
// Act
List<Error> result = _validator.TestValidate(query);
// Assert
result.ShouldNotHaveValidationError(Errors.Reading.BookIdCannotBeEmpty);
}
}
@@ -0,0 +1,217 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management;
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary;
using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
using Lumina.Application.Common.DataAccess.Repositories.Books;
using Lumina.Application.Common.DataAccess.Repositories.MediaLibrary;
using Lumina.Application.Common.DataAccess.Repositories.Users;
using Lumina.Application.Common.DataAccess.UoW;
using Lumina.Application.Common.Infrastructure.Authentication;
using Lumina.Application.Common.Infrastructure.Authorization;
using Lumina.Application.Common.Infrastructure.Authorization.Policies.LibraryOwnership;
using Lumina.Application.Common.Infrastructure.Validation;
using Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Reading.Queries.GetReadingManifest;
using Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Reading;
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.Application.Fixtures.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Reading.Queries.GetReadingManifest;
using Lumina.Contracts.Fixtures.Core.Responses.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Reading;
using Lumina.Contracts.Responses.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Reading;
using Lumina.Domain.Common.Errors;
using Lumina.Domain.Common.Primitives;
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
using NSubstitute;
using System;
using System.Diagnostics.CodeAnalysis;
using System.Threading;
using System.Threading.Tasks;
using ApplicationErrors = Lumina.Application.Common.Errors.Errors;
using DomainErrors = Lumina.Domain.Common.Errors.Errors;
#endregion
namespace Lumina.Application.UnitTests.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Reading.Queries.GetReadingManifest;
/// <summary>
/// Contains unit tests for the <see cref="GetReadingManifestQueryHandler"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetReadingManifestQueryHandlerTests
{
private readonly IUnitOfWork _mockUnitOfWork;
private readonly IBookRepository _mockBookRepository;
private readonly ILibraryRepository _mockLibraryRepository;
private readonly IUserSettingsRepository _mockUserSettingsRepository;
private readonly IAuthorizationService _mockAuthorizationService;
private readonly ICurrentUserService _mockCurrentUserService;
private readonly IBookReadingService _mockBookReadingService;
private readonly IValidator<GetReadingManifestQuery> _mockValidator;
private readonly GetReadingManifestQueryHandler _sut;
private readonly Guid _userId;
private readonly GetReadingManifestQueryFixture _getReadingManifestQueryFixture = new();
private readonly BookEntityFixture _bookEntityFixture = new();
private readonly LibraryEntityFixture _libraryEntityFixture = new();
private readonly UserSettingsEntityFixture _userSettingsEntityFixture = new();
private readonly ReadingManifestResponseFixture _readingManifestResponseFixture = new();
/// <summary>
/// Initializes a new instance of the <see cref="GetReadingManifestQueryHandlerTests"/> class.
/// </summary>
public GetReadingManifestQueryHandlerTests()
{
_mockBookRepository = Substitute.For<IBookRepository>();
_mockLibraryRepository = Substitute.For<ILibraryRepository>();
_mockUserSettingsRepository = Substitute.For<IUserSettingsRepository>();
_mockUnitOfWork = Substitute.For<IUnitOfWork>();
_mockUnitOfWork.BookRepository.Returns(_mockBookRepository);
_mockUnitOfWork.LibraryRepository.Returns(_mockLibraryRepository);
_mockUnitOfWork.UserSettingsRepository.Returns(_mockUserSettingsRepository);
_mockAuthorizationService = Substitute.For<IAuthorizationService>();
_mockCurrentUserService = Substitute.For<ICurrentUserService>();
_mockBookReadingService = Substitute.For<IBookReadingService>();
_mockValidator = Substitute.For<IValidator<GetReadingManifestQuery>>();
_userId = Guid.NewGuid();
// Default stubs: the current user is authenticated and the library ownership policy allows access.
_mockCurrentUserService.UserId.Returns(_userId);
_mockAuthorizationService.EvaluatePolicyAsync<ILibraryOwnershipPolicy>(_userId, Arg.Any<LibraryOwnershipPolicyContext>(), Arg.Any<CancellationToken>())
.Returns(true);
_mockValidator.Validate(Arg.Any<GetReadingManifestQuery>()).Returns([]);
_mockUserSettingsRepository.GetByUserIdAsync(_userId, Arg.Any<CancellationToken>()).Returns(Result.From<UserSettingsEntity?>(null));
_sut = new GetReadingManifestQueryHandler(_mockUnitOfWork, _mockAuthorizationService, _mockCurrentUserService, _mockBookReadingService, _mockValidator);
}
[Fact]
public async Task HandleAsync_WhenSuccessful_ShouldReturnManifestResponse()
{
// Arrange
GetReadingManifestQuery query = _getReadingManifestQueryFixture.Create();
CancellationToken cancellationToken = CancellationToken.None;
BookEntity book = _bookEntityFixture.Create(id: query.BookId);
LibraryEntity library = _libraryEntityFixture.Create(id: book.LibraryId, libraryType: LibraryType.EBook);
ReadingManifestResponse expectedResponse = _readingManifestResponseFixture.Create();
_mockBookRepository.GetByIdAsync(query.BookId, cancellationToken).Returns(Result.From<BookEntity?>(book));
_mockLibraryRepository.GetByIdAsync(book.LibraryId, cancellationToken).Returns(Result.From<LibraryEntity?>(library));
_mockBookReadingService.GetManifestAsync(book.Id, book.LibraryId, book.Path, library.LibraryType, shouldRenderPdfAsImages: false, cancellationToken).Returns(expectedResponse);
// Act
Result<ReadingManifestResponse> result = await _sut.HandleAsync(query, cancellationToken);
// Assert
Assert.False(result.IsFailure);
Assert.Equal(expectedResponse, result.Value);
}
[Fact]
public async Task HandleAsync_WhenUserHasRenderPdfAsImagesEnabled_ShouldUseTheSetting()
{
// Arrange
GetReadingManifestQuery query = _getReadingManifestQueryFixture.Create();
CancellationToken cancellationToken = CancellationToken.None;
BookEntity book = _bookEntityFixture.Create(id: query.BookId);
LibraryEntity library = _libraryEntityFixture.Create(id: book.LibraryId, libraryType: LibraryType.EBook);
UserSettingsEntity settings = _userSettingsEntityFixture.Create(userId: _userId, shouldRenderPdfAsImages: true);
ReadingManifestResponse expectedResponse = _readingManifestResponseFixture.Create();
_mockUserSettingsRepository.GetByUserIdAsync(_userId, cancellationToken).Returns(Result.From<UserSettingsEntity?>(settings));
_mockBookRepository.GetByIdAsync(query.BookId, cancellationToken).Returns(Result.From<BookEntity?>(book));
_mockLibraryRepository.GetByIdAsync(book.LibraryId, cancellationToken).Returns(Result.From<LibraryEntity?>(library));
_mockBookReadingService.GetManifestAsync(book.Id, book.LibraryId, book.Path, library.LibraryType, shouldRenderPdfAsImages: true, cancellationToken).Returns(expectedResponse);
// Act
Result<ReadingManifestResponse> result = await _sut.HandleAsync(query, cancellationToken);
// Assert
Assert.False(result.IsFailure);
Assert.Equal(expectedResponse, result.Value);
}
[Fact]
public async Task HandleAsync_WhenBookDoesNotExist_ShouldReturnBookNotFoundError()
{
// Arrange
GetReadingManifestQuery query = _getReadingManifestQueryFixture.Create();
_mockBookRepository.GetByIdAsync(query.BookId, Arg.Any<CancellationToken>()).Returns(Result.From<BookEntity?>(null));
// Act
Result<ReadingManifestResponse> result = await _sut.HandleAsync(query, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(DomainErrors.Reading.BookNotFound, result.FirstError);
await _mockBookReadingService.DidNotReceive().GetManifestAsync(Arg.Any<Guid>(), Arg.Any<Guid>(), Arg.Any<string>(), Arg.Any<LibraryType>(), Arg.Any<bool>(), Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenLibraryDoesNotExist_ShouldReturnLibraryNotFoundError()
{
// Arrange
GetReadingManifestQuery query = _getReadingManifestQueryFixture.Create();
BookEntity book = _bookEntityFixture.Create(id: query.BookId);
_mockBookRepository.GetByIdAsync(query.BookId, Arg.Any<CancellationToken>()).Returns(Result.From<BookEntity?>(book));
_mockLibraryRepository.GetByIdAsync(book.LibraryId, Arg.Any<CancellationToken>()).Returns(Result.From<LibraryEntity?>(null));
// Act
Result<ReadingManifestResponse> result = await _sut.HandleAsync(query, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(DomainErrors.Library.LibraryNotFound, result.FirstError);
await _mockBookReadingService.DidNotReceive().GetManifestAsync(Arg.Any<Guid>(), Arg.Any<Guid>(), Arg.Any<string>(), Arg.Any<LibraryType>(), Arg.Any<bool>(), Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenPolicyDeniesAccess_ShouldReturnNotAuthorizedError()
{
// Arrange
GetReadingManifestQuery query = _getReadingManifestQueryFixture.Create();
BookEntity book = _bookEntityFixture.Create(id: query.BookId);
_mockBookRepository.GetByIdAsync(query.BookId, Arg.Any<CancellationToken>()).Returns(Result.From<BookEntity?>(book));
_mockAuthorizationService.EvaluatePolicyAsync<ILibraryOwnershipPolicy>(_userId, Arg.Any<LibraryOwnershipPolicyContext>(), Arg.Any<CancellationToken>())
.Returns(false);
// Act
Result<ReadingManifestResponse> result = await _sut.HandleAsync(query, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(ApplicationErrors.Authorization.NotAuthorized, result.FirstError);
await _mockLibraryRepository.DidNotReceive().GetByIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
await _mockBookReadingService.DidNotReceive().GetManifestAsync(Arg.Any<Guid>(), Arg.Any<Guid>(), Arg.Any<string>(), Arg.Any<LibraryType>(), Arg.Any<bool>(), Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenUserIsNotAuthenticated_ShouldReturnNotAuthorizedError()
{
// Arrange
GetReadingManifestQuery query = _getReadingManifestQueryFixture.Create();
_mockCurrentUserService.UserId.Returns((Guid?)null);
// Act
Result<ReadingManifestResponse> result = await _sut.HandleAsync(query, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(ApplicationErrors.Authorization.NotAuthorized, result.FirstError);
await _mockAuthorizationService.DidNotReceive().EvaluatePolicyAsync<ILibraryOwnershipPolicy>(Arg.Any<Guid>(), Arg.Any<LibraryOwnershipPolicyContext>(), Arg.Any<CancellationToken>());
await _mockBookRepository.DidNotReceive().GetByIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenValidationFails_ShouldReturnValidationErrorsWithoutCheckingAvailability()
{
// Arrange
GetReadingManifestQuery query = _getReadingManifestQueryFixture.Create();
_mockValidator.Validate(Arg.Any<GetReadingManifestQuery>()).Returns([Errors.Reading.BookIdCannotBeEmpty]);
// Act
Result<ReadingManifestResponse> result = await _sut.HandleAsync(query, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(Errors.Reading.BookIdCannotBeEmpty, result.FirstError);
await _mockAuthorizationService.DidNotReceive().EvaluatePolicyAsync<ILibraryOwnershipPolicy>(Arg.Any<Guid>(), Arg.Any<LibraryOwnershipPolicyContext>(), Arg.Any<CancellationToken>());
await _mockBookRepository.DidNotReceive().GetByIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
await _mockBookReadingService.DidNotReceive().GetManifestAsync(Arg.Any<Guid>(), Arg.Any<Guid>(), Arg.Any<string>(), Arg.Any<LibraryType>(), Arg.Any<bool>(), Arg.Any<CancellationToken>());
}
}
@@ -0,0 +1,48 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Reading.Queries.GetReadingManifest;
using Lumina.Application.Fixtures.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Reading.Queries.GetReadingManifest;
using Lumina.Application.UnitTests.Common.Setup;
using Lumina.Domain.Common.Errors;
using Lumina.Domain.Common.Primitives;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
#endregion
namespace Lumina.Application.UnitTests.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Reading.Queries.GetReadingManifest;
/// <summary>
/// Contains unit tests for the <see cref="GetReadingManifestQueryValidator"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetReadingManifestQueryValidatorTests
{
private readonly GetReadingManifestQueryValidator _validator = new();
private readonly GetReadingManifestQueryFixture _getReadingManifestQueryFixture = new();
[Fact]
public void Validate_WhenBookIdIsEmpty_ShouldHaveValidationError()
{
// Arrange
GetReadingManifestQuery query = _getReadingManifestQueryFixture.Create(bookId: Guid.Empty);
// Act
List<Error> result = _validator.TestValidate(query);
// Assert
result.ShouldHaveValidationError(Errors.Reading.BookIdCannotBeEmpty);
}
[Fact]
public void Validate_WhenBookIdIsValid_ShouldNotHaveValidationError()
{
// Arrange
GetReadingManifestQuery query = _getReadingManifestQueryFixture.Create();
// Act
List<Error> result = _validator.TestValidate(query);
// Assert
result.ShouldNotHaveValidationError(Errors.Reading.BookIdCannotBeEmpty);
}
}
@@ -0,0 +1,214 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management;
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary;
using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
using Lumina.Application.Common.DataAccess.Repositories.Books;
using Lumina.Application.Common.DataAccess.Repositories.MediaLibrary;
using Lumina.Application.Common.DataAccess.Repositories.Users;
using Lumina.Application.Common.DataAccess.UoW;
using Lumina.Application.Common.Infrastructure.Authentication;
using Lumina.Application.Common.Infrastructure.Authorization;
using Lumina.Application.Common.Infrastructure.Authorization.Policies.LibraryOwnership;
using Lumina.Application.Common.Infrastructure.Validation;
using Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Reading.Queries.GetReadingResource;
using Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Reading;
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.Application.Fixtures.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Reading.Queries.GetReadingResource;
using Lumina.Contracts.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary.Reading;
using Lumina.Contracts.Fixtures.Core.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary.Reading;
using Lumina.Domain.Common.Errors;
using Lumina.Domain.Common.Primitives;
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
using NSubstitute;
using System;
using System.Diagnostics.CodeAnalysis;
using System.Threading;
using System.Threading.Tasks;
using ApplicationErrors = Lumina.Application.Common.Errors.Errors;
using DomainErrors = Lumina.Domain.Common.Errors.Errors;
#endregion
namespace Lumina.Application.UnitTests.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Reading.Queries.GetReadingResource;
/// <summary>
/// Contains unit tests for the <see cref="GetReadingResourceQueryHandler"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetReadingResourceQueryHandlerTests
{
private readonly IUnitOfWork _mockUnitOfWork;
private readonly IBookRepository _mockBookRepository;
private readonly ILibraryRepository _mockLibraryRepository;
private readonly IUserSettingsRepository _mockUserSettingsRepository;
private readonly IAuthorizationService _mockAuthorizationService;
private readonly ICurrentUserService _mockCurrentUserService;
private readonly IBookReadingService _mockBookReadingService;
private readonly IValidator<GetReadingResourceQuery> _mockValidator;
private readonly GetReadingResourceQueryHandler _sut;
private readonly Guid _userId;
private readonly GetReadingResourceQueryFixture _getReadingResourceQueryFixture = new();
private readonly BookEntityFixture _bookEntityFixture = new();
private readonly LibraryEntityFixture _libraryEntityFixture = new();
private readonly UserSettingsEntityFixture _userSettingsEntityFixture = new();
private readonly ReadingResourceDataDtoFixture _readingResourceDataDtoFixture = new();
/// <summary>
/// Initializes a new instance of the <see cref="GetReadingResourceQueryHandlerTests"/> class.
/// </summary>
public GetReadingResourceQueryHandlerTests()
{
_mockBookRepository = Substitute.For<IBookRepository>();
_mockLibraryRepository = Substitute.For<ILibraryRepository>();
_mockUserSettingsRepository = Substitute.For<IUserSettingsRepository>();
_mockUnitOfWork = Substitute.For<IUnitOfWork>();
_mockUnitOfWork.BookRepository.Returns(_mockBookRepository);
_mockUnitOfWork.LibraryRepository.Returns(_mockLibraryRepository);
_mockUnitOfWork.UserSettingsRepository.Returns(_mockUserSettingsRepository);
_mockAuthorizationService = Substitute.For<IAuthorizationService>();
_mockCurrentUserService = Substitute.For<ICurrentUserService>();
_mockBookReadingService = Substitute.For<IBookReadingService>();
_mockValidator = Substitute.For<IValidator<GetReadingResourceQuery>>();
_userId = Guid.NewGuid();
// default stubs: the current user is authenticated and the library ownership policy allows access
_mockCurrentUserService.UserId.Returns(_userId);
_mockAuthorizationService.EvaluatePolicyAsync<ILibraryOwnershipPolicy>(_userId, Arg.Any<LibraryOwnershipPolicyContext>(), Arg.Any<CancellationToken>())
.Returns(true);
_mockValidator.Validate(Arg.Any<GetReadingResourceQuery>()).Returns([]);
_mockUserSettingsRepository.GetByUserIdAsync(_userId, Arg.Any<CancellationToken>()).Returns(Result.From<UserSettingsEntity?>(null));
_sut = new GetReadingResourceQueryHandler(_mockUnitOfWork, _mockAuthorizationService, _mockCurrentUserService, _mockBookReadingService, _mockValidator);
}
[Fact]
public async Task HandleAsync_WhenSuccessful_ShouldReturnResourceDataDto()
{
// Arrange
GetReadingResourceQuery query = _getReadingResourceQueryFixture.Create();
CancellationToken cancellationToken = CancellationToken.None;
BookEntity book = _bookEntityFixture.Create(id: query.BookId);
LibraryEntity library = _libraryEntityFixture.Create(id: book.LibraryId, libraryType: LibraryType.EBook);
ReadingResourceDataDto expectedResponse = _readingResourceDataDtoFixture.Create();
_mockBookRepository.GetByIdAsync(query.BookId, cancellationToken).Returns(Result.From<BookEntity?>(book));
_mockLibraryRepository.GetByIdAsync(book.LibraryId, cancellationToken).Returns(Result.From<LibraryEntity?>(library));
_mockBookReadingService.GetResourceAsync(book.Id, book.LibraryId, book.Path, library.LibraryType, query.ResourceKey, shouldRenderPdfAsImages: false, cancellationToken).Returns(expectedResponse);
// Act
Result<ReadingResourceDataDto> result = await _sut.HandleAsync(query, cancellationToken);
// Assert
Assert.False(result.IsFailure);
Assert.Equal(expectedResponse, result.Value);
}
[Fact]
public async Task HandleAsync_WhenUserHasRenderPdfAsImagesEnabled_ShouldUseTheSetting()
{
// Arrange
GetReadingResourceQuery query = _getReadingResourceQueryFixture.Create();
CancellationToken cancellationToken = CancellationToken.None;
BookEntity book = _bookEntityFixture.Create(id: query.BookId);
LibraryEntity library = _libraryEntityFixture.Create(id: book.LibraryId, libraryType: LibraryType.EBook);
UserSettingsEntity settings = _userSettingsEntityFixture.Create(userId: _userId, shouldRenderPdfAsImages: true);
ReadingResourceDataDto expectedResponse = _readingResourceDataDtoFixture.Create();
_mockUserSettingsRepository.GetByUserIdAsync(_userId, cancellationToken).Returns(Result.From<UserSettingsEntity?>(settings));
_mockBookRepository.GetByIdAsync(query.BookId, cancellationToken).Returns(Result.From<BookEntity?>(book));
_mockLibraryRepository.GetByIdAsync(book.LibraryId, cancellationToken).Returns(Result.From<LibraryEntity?>(library));
_mockBookReadingService.GetResourceAsync(book.Id, book.LibraryId, book.Path, library.LibraryType, query.ResourceKey, shouldRenderPdfAsImages: true, cancellationToken).Returns(expectedResponse);
// Act
Result<ReadingResourceDataDto> result = await _sut.HandleAsync(query, cancellationToken);
// Assert
Assert.False(result.IsFailure);
Assert.Equal(expectedResponse, result.Value);
}
[Fact]
public async Task HandleAsync_WhenBookDoesNotExist_ShouldReturnBookNotFoundError()
{
// Arrange
GetReadingResourceQuery query = _getReadingResourceQueryFixture.Create();
_mockBookRepository.GetByIdAsync(query.BookId, Arg.Any<CancellationToken>()).Returns(Result.From<BookEntity?>(null));
// Act
Result<ReadingResourceDataDto> result = await _sut.HandleAsync(query, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(DomainErrors.Reading.BookNotFound, result.FirstError);
await _mockBookReadingService.DidNotReceive().GetResourceAsync(Arg.Any<Guid>(), Arg.Any<Guid>(), Arg.Any<string>(), Arg.Any<LibraryType>(), Arg.Any<string>(), Arg.Any<bool>(), Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenLibraryDoesNotExist_ShouldReturnLibraryNotFoundError()
{
// Arrange
GetReadingResourceQuery query = _getReadingResourceQueryFixture.Create();
BookEntity book = _bookEntityFixture.Create(id: query.BookId);
_mockBookRepository.GetByIdAsync(query.BookId, Arg.Any<CancellationToken>()).Returns(Result.From<BookEntity?>(book));
_mockLibraryRepository.GetByIdAsync(book.LibraryId, Arg.Any<CancellationToken>()).Returns(Result.From<LibraryEntity?>(null));
// Act
Result<ReadingResourceDataDto> result = await _sut.HandleAsync(query, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(DomainErrors.Library.LibraryNotFound, result.FirstError);
await _mockBookReadingService.DidNotReceive().GetResourceAsync(Arg.Any<Guid>(), Arg.Any<Guid>(), Arg.Any<string>(), Arg.Any<LibraryType>(), Arg.Any<string>(), Arg.Any<bool>(), Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenPolicyDeniesAccess_ShouldReturnNotAuthorizedError()
{
// Arrange
GetReadingResourceQuery query = _getReadingResourceQueryFixture.Create();
BookEntity book = _bookEntityFixture.Create(id: query.BookId);
_mockBookRepository.GetByIdAsync(query.BookId, Arg.Any<CancellationToken>()).Returns(Result.From<BookEntity?>(book));
_mockAuthorizationService.EvaluatePolicyAsync<ILibraryOwnershipPolicy>(_userId, Arg.Any<LibraryOwnershipPolicyContext>(), Arg.Any<CancellationToken>())
.Returns(false);
// Act
Result<ReadingResourceDataDto> result = await _sut.HandleAsync(query, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(ApplicationErrors.Authorization.NotAuthorized, result.FirstError);
await _mockBookReadingService.DidNotReceive().GetResourceAsync(Arg.Any<Guid>(), Arg.Any<Guid>(), Arg.Any<string>(), Arg.Any<LibraryType>(), Arg.Any<string>(), Arg.Any<bool>(), Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenUserIsNotAuthenticated_ShouldReturnNotAuthorizedError()
{
// Arrange
GetReadingResourceQuery query = _getReadingResourceQueryFixture.Create();
_mockCurrentUserService.UserId.Returns((Guid?)null);
// Act
Result<ReadingResourceDataDto> result = await _sut.HandleAsync(query, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(ApplicationErrors.Authorization.NotAuthorized, result.FirstError);
await _mockBookRepository.DidNotReceive().GetByIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenValidationFails_ShouldReturnValidationErrorsWithoutFetchingTheResource()
{
// Arrange
GetReadingResourceQuery query = _getReadingResourceQueryFixture.Create();
_mockValidator.Validate(Arg.Any<GetReadingResourceQuery>()).Returns([Errors.Reading.ResourceKeyCannotBeEmpty]);
// Act
Result<ReadingResourceDataDto> result = await _sut.HandleAsync(query, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(Errors.Reading.ResourceKeyCannotBeEmpty, result.FirstError);
await _mockBookRepository.DidNotReceive().GetByIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
await _mockBookReadingService.DidNotReceive().GetResourceAsync(Arg.Any<Guid>(), Arg.Any<Guid>(), Arg.Any<string>(), Arg.Any<LibraryType>(), Arg.Any<string>(), Arg.Any<bool>(), Arg.Any<CancellationToken>());
}
}
@@ -0,0 +1,62 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Reading.Queries.GetReadingResource;
using Lumina.Application.Fixtures.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Reading.Queries.GetReadingResource;
using Lumina.Application.UnitTests.Common.Setup;
using Lumina.Domain.Common.Errors;
using Lumina.Domain.Common.Primitives;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
#endregion
namespace Lumina.Application.UnitTests.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Reading.Queries.GetReadingResource;
/// <summary>
/// Contains unit tests for the <see cref="GetReadingResourceQueryValidator"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetReadingResourceQueryValidatorTests
{
private readonly GetReadingResourceQueryValidator _validator = new();
private readonly GetReadingResourceQueryFixture _getReadingResourceQueryFixture = new();
[Fact]
public void Validate_WhenBookIdIsEmpty_ShouldHaveValidationError()
{
// Arrange
GetReadingResourceQuery query = _getReadingResourceQueryFixture.Create(bookId: Guid.Empty);
// Act
List<Error> result = _validator.TestValidate(query);
// Assert
result.ShouldHaveValidationError(Errors.Reading.BookIdCannotBeEmpty);
}
[Fact]
public void Validate_WhenResourceKeyIsEmpty_ShouldHaveValidationError()
{
// Arrange
GetReadingResourceQuery query = _getReadingResourceQueryFixture.Create(resourceKey: string.Empty);
// Act
List<Error> result = _validator.TestValidate(query);
// Assert
result.ShouldHaveValidationError(Errors.Reading.ResourceKeyCannotBeEmpty);
}
[Fact]
public void Validate_WhenQueryIsValid_ShouldNotHaveValidationError()
{
// Arrange
GetReadingResourceQuery query = _getReadingResourceQueryFixture.Create();
// Act
List<Error> result = _validator.TestValidate(query);
// Assert
result.ShouldNotHaveValidationError(Errors.Reading.BookIdCannotBeEmpty);
result.ShouldNotHaveValidationError(Errors.Reading.ResourceKeyCannotBeEmpty);
}
}
@@ -0,0 +1,263 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management;
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary;
using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
using Lumina.Application.Common.DataAccess.Repositories.Books;
using Lumina.Application.Common.DataAccess.Repositories.MediaLibrary;
using Lumina.Application.Common.DataAccess.Repositories.Users;
using Lumina.Application.Common.DataAccess.UoW;
using Lumina.Application.Common.Infrastructure.Authentication;
using Lumina.Application.Common.Infrastructure.Authorization;
using Lumina.Application.Common.Infrastructure.Authorization.Policies.LibraryOwnership;
using Lumina.Application.Common.Infrastructure.Validation;
using Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Reading.Queries.GetReadingSection;
using Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Reading;
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.Application.Fixtures.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Reading.Queries.GetReadingSection;
using Lumina.Contracts.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary.Reading;
using Lumina.Contracts.Fixtures.Core.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary.Reading;
using Lumina.Domain.Common.Errors;
using Lumina.Domain.Common.Primitives;
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
using NSubstitute;
using System;
using System.Diagnostics.CodeAnalysis;
using System.Threading;
using System.Threading.Tasks;
using ApplicationErrors = Lumina.Application.Common.Errors.Errors;
using DomainErrors = Lumina.Domain.Common.Errors.Errors;
#endregion
namespace Lumina.Application.UnitTests.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Reading.Queries.GetReadingSection;
/// <summary>
/// Contains unit tests for the <see cref="GetReadingSectionQueryHandler"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetReadingSectionQueryHandlerTests
{
private readonly IUnitOfWork _mockUnitOfWork;
private readonly IBookRepository _mockBookRepository;
private readonly ILibraryRepository _mockLibraryRepository;
private readonly IUserSettingsRepository _mockUserSettingsRepository;
private readonly IAuthorizationService _mockAuthorizationService;
private readonly ICurrentUserService _mockCurrentUserService;
private readonly IBookReadingService _mockBookReadingService;
private readonly IValidator<GetReadingSectionQuery> _mockValidator;
private readonly GetReadingSectionQueryHandler _sut;
private readonly Guid _userId;
private readonly GetReadingSectionQueryFixture _getReadingSectionQueryFixture = new();
private readonly BookEntityFixture _bookEntityFixture = new();
private readonly LibraryEntityFixture _libraryEntityFixture = new();
private readonly UserSettingsEntityFixture _userSettingsEntityFixture = new();
private readonly ReadingSectionDtoFixture _readingSectionDtoFixture = new();
/// <summary>
/// Initializes a new instance of the <see cref="GetReadingSectionQueryHandlerTests"/> class.
/// </summary>
public GetReadingSectionQueryHandlerTests()
{
_mockBookRepository = Substitute.For<IBookRepository>();
_mockLibraryRepository = Substitute.For<ILibraryRepository>();
_mockUserSettingsRepository = Substitute.For<IUserSettingsRepository>();
_mockUnitOfWork = Substitute.For<IUnitOfWork>();
_mockUnitOfWork.BookRepository.Returns(_mockBookRepository);
_mockUnitOfWork.LibraryRepository.Returns(_mockLibraryRepository);
_mockUnitOfWork.UserSettingsRepository.Returns(_mockUserSettingsRepository);
_mockAuthorizationService = Substitute.For<IAuthorizationService>();
_mockCurrentUserService = Substitute.For<ICurrentUserService>();
_mockBookReadingService = Substitute.For<IBookReadingService>();
_mockValidator = Substitute.For<IValidator<GetReadingSectionQuery>>();
_userId = Guid.NewGuid();
// default stubs: the current user is authenticated and the library ownership policy allows access
_mockCurrentUserService.UserId.Returns(_userId);
_mockAuthorizationService.EvaluatePolicyAsync<ILibraryOwnershipPolicy>(_userId, Arg.Any<LibraryOwnershipPolicyContext>(), Arg.Any<CancellationToken>())
.Returns(true);
_mockValidator.Validate(Arg.Any<GetReadingSectionQuery>()).Returns([]);
_mockUserSettingsRepository.GetByUserIdAsync(_userId, Arg.Any<CancellationToken>()).Returns(Result.From<UserSettingsEntity?>(null));
_sut = new GetReadingSectionQueryHandler(_mockUnitOfWork, _mockAuthorizationService, _mockCurrentUserService, _mockBookReadingService, _mockValidator);
}
[Fact]
public async Task HandleAsync_WhenSuccessful_ShouldReturnSectionDto()
{
// Arrange
GetReadingSectionQuery query = _getReadingSectionQueryFixture.Create();
CancellationToken cancellationToken = CancellationToken.None;
BookEntity book = _bookEntityFixture.Create(id: query.BookId);
LibraryEntity library = _libraryEntityFixture.Create(id: book.LibraryId, libraryType: LibraryType.EBook);
ReadingSectionDto expectedResponse = _readingSectionDtoFixture.Create(locationRef: query.LocationRef);
_mockBookRepository.GetByIdAsync(query.BookId, cancellationToken).Returns(Result.From<BookEntity?>(book));
_mockLibraryRepository.GetByIdAsync(book.LibraryId, cancellationToken).Returns(Result.From<LibraryEntity?>(library));
_mockBookReadingService.GetSectionAsync(book.Id, book.LibraryId, book.Path, library.LibraryType, query.LocationRef, shouldRenderPdfAsImages: false, shouldPreserveStyles: true, cancellationToken).Returns(expectedResponse);
// Act
Result<ReadingSectionDto> result = await _sut.HandleAsync(query, cancellationToken);
// Assert
Assert.False(result.IsFailure);
Assert.Equal(expectedResponse, result.Value);
}
[Fact]
public async Task HandleAsync_WhenUserHasRenderPdfAsImagesEnabled_ShouldUseTheSetting()
{
// Arrange
GetReadingSectionQuery query = _getReadingSectionQueryFixture.Create();
CancellationToken cancellationToken = CancellationToken.None;
BookEntity book = _bookEntityFixture.Create(id: query.BookId);
LibraryEntity library = _libraryEntityFixture.Create(id: book.LibraryId, libraryType: LibraryType.EBook);
UserSettingsEntity settings = _userSettingsEntityFixture.Create(userId: _userId, shouldRenderPdfAsImages: true, shouldPreserveBookStyles: true);
ReadingSectionDto expectedResponse = _readingSectionDtoFixture.Create(locationRef: query.LocationRef);
_mockUserSettingsRepository.GetByUserIdAsync(_userId, cancellationToken).Returns(Result.From<UserSettingsEntity?>(settings));
_mockBookRepository.GetByIdAsync(query.BookId, cancellationToken).Returns(Result.From<BookEntity?>(book));
_mockLibraryRepository.GetByIdAsync(book.LibraryId, cancellationToken).Returns(Result.From<LibraryEntity?>(library));
_mockBookReadingService.GetSectionAsync(book.Id, book.LibraryId, book.Path, library.LibraryType, query.LocationRef, shouldRenderPdfAsImages: true, shouldPreserveStyles: true, cancellationToken).Returns(expectedResponse);
// Act
Result<ReadingSectionDto> result = await _sut.HandleAsync(query, cancellationToken);
// Assert
Assert.False(result.IsFailure);
Assert.Equal(expectedResponse, result.Value);
}
[Theory]
[InlineData(true)] // the user chose to preserve the styles of the books
[InlineData(false)] // the user chose to strip the styles of the books
public async Task HandleAsync_WhenUserHasPreserveBookStylesSetting_ShouldPassItToTheService(bool shouldPreserveBookStyles)
{
// Arrange
GetReadingSectionQuery query = _getReadingSectionQueryFixture.Create();
CancellationToken cancellationToken = CancellationToken.None;
BookEntity book = _bookEntityFixture.Create(id: query.BookId);
LibraryEntity library = _libraryEntityFixture.Create(id: book.LibraryId, libraryType: LibraryType.EBook);
UserSettingsEntity settings = _userSettingsEntityFixture.Create(userId: _userId, shouldRenderPdfAsImages: false, shouldPreserveBookStyles: shouldPreserveBookStyles);
ReadingSectionDto expectedResponse = _readingSectionDtoFixture.Create(locationRef: query.LocationRef);
_mockUserSettingsRepository.GetByUserIdAsync(_userId, cancellationToken).Returns(Result.From<UserSettingsEntity?>(settings));
_mockBookRepository.GetByIdAsync(query.BookId, cancellationToken).Returns(Result.From<BookEntity?>(book));
_mockLibraryRepository.GetByIdAsync(book.LibraryId, cancellationToken).Returns(Result.From<LibraryEntity?>(library));
_mockBookReadingService.GetSectionAsync(Arg.Any<Guid>(), Arg.Any<Guid>(), Arg.Any<string>(), Arg.Any<LibraryType>(), Arg.Any<string>(), Arg.Any<bool>(), Arg.Any<bool>(), Arg.Any<CancellationToken>()).Returns(expectedResponse);
// Act
Result<ReadingSectionDto> result = await _sut.HandleAsync(query, cancellationToken);
// Assert
Assert.False(result.IsFailure);
Assert.Equal(expectedResponse, result.Value);
await _mockBookReadingService.Received(1).GetSectionAsync(book.Id, book.LibraryId, book.Path, library.LibraryType, query.LocationRef, shouldRenderPdfAsImages: false, shouldPreserveStyles: shouldPreserveBookStyles, cancellationToken);
}
[Fact]
public async Task HandleAsync_WhenNoSettingsExist_ShouldDefaultToPreservingBookStyles()
{
// Arrange
GetReadingSectionQuery query = _getReadingSectionQueryFixture.Create();
CancellationToken cancellationToken = CancellationToken.None;
BookEntity book = _bookEntityFixture.Create(id: query.BookId);
LibraryEntity library = _libraryEntityFixture.Create(id: book.LibraryId, libraryType: LibraryType.EBook);
ReadingSectionDto expectedResponse = _readingSectionDtoFixture.Create(locationRef: query.LocationRef);
_mockBookRepository.GetByIdAsync(query.BookId, cancellationToken).Returns(Result.From<BookEntity?>(book));
_mockLibraryRepository.GetByIdAsync(book.LibraryId, cancellationToken).Returns(Result.From<LibraryEntity?>(library));
_mockBookReadingService.GetSectionAsync(Arg.Any<Guid>(), Arg.Any<Guid>(), Arg.Any<string>(), Arg.Any<LibraryType>(), Arg.Any<string>(), Arg.Any<bool>(), Arg.Any<bool>(), Arg.Any<CancellationToken>()).Returns(expectedResponse);
// Act
Result<ReadingSectionDto> result = await _sut.HandleAsync(query, cancellationToken);
// Assert
Assert.False(result.IsFailure);
Assert.Equal(expectedResponse, result.Value);
await _mockBookReadingService.Received(1).GetSectionAsync(book.Id, book.LibraryId, book.Path, library.LibraryType, query.LocationRef, shouldRenderPdfAsImages: false, shouldPreserveStyles: true, cancellationToken);
await _mockBookReadingService.DidNotReceive().GetSectionAsync(Arg.Any<Guid>(), Arg.Any<Guid>(), Arg.Any<string>(), Arg.Any<LibraryType>(), Arg.Any<string>(), Arg.Any<bool>(), Arg.Is<bool>(false), Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenBookDoesNotExist_ShouldReturnBookNotFoundError()
{
// Arrange
GetReadingSectionQuery query = _getReadingSectionQueryFixture.Create();
_mockBookRepository.GetByIdAsync(query.BookId, Arg.Any<CancellationToken>()).Returns(Result.From<BookEntity?>(null));
// Act
Result<ReadingSectionDto> result = await _sut.HandleAsync(query, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(DomainErrors.Reading.BookNotFound, result.FirstError);
await _mockBookReadingService.DidNotReceive().GetSectionAsync(Arg.Any<Guid>(), Arg.Any<Guid>(), Arg.Any<string>(), Arg.Any<LibraryType>(), Arg.Any<string>(), Arg.Any<bool>(), Arg.Any<bool>(), Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenLibraryDoesNotExist_ShouldReturnLibraryNotFoundError()
{
// Arrange
GetReadingSectionQuery query = _getReadingSectionQueryFixture.Create();
BookEntity book = _bookEntityFixture.Create(id: query.BookId);
_mockBookRepository.GetByIdAsync(query.BookId, Arg.Any<CancellationToken>()).Returns(Result.From<BookEntity?>(book));
_mockLibraryRepository.GetByIdAsync(book.LibraryId, Arg.Any<CancellationToken>()).Returns(Result.From<LibraryEntity?>(null));
// Act
Result<ReadingSectionDto> result = await _sut.HandleAsync(query, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(DomainErrors.Library.LibraryNotFound, result.FirstError);
await _mockBookReadingService.DidNotReceive().GetSectionAsync(Arg.Any<Guid>(), Arg.Any<Guid>(), Arg.Any<string>(), Arg.Any<LibraryType>(), Arg.Any<string>(), Arg.Any<bool>(), Arg.Any<bool>(), Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenPolicyDeniesAccess_ShouldReturnNotAuthorizedError()
{
// Arrange
GetReadingSectionQuery query = _getReadingSectionQueryFixture.Create();
BookEntity book = _bookEntityFixture.Create(id: query.BookId);
_mockBookRepository.GetByIdAsync(query.BookId, Arg.Any<CancellationToken>()).Returns(Result.From<BookEntity?>(book));
_mockAuthorizationService.EvaluatePolicyAsync<ILibraryOwnershipPolicy>(_userId, Arg.Any<LibraryOwnershipPolicyContext>(), Arg.Any<CancellationToken>())
.Returns(false);
// Act
Result<ReadingSectionDto> result = await _sut.HandleAsync(query, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(ApplicationErrors.Authorization.NotAuthorized, result.FirstError);
await _mockBookReadingService.DidNotReceive().GetSectionAsync(Arg.Any<Guid>(), Arg.Any<Guid>(), Arg.Any<string>(), Arg.Any<LibraryType>(), Arg.Any<string>(), Arg.Any<bool>(), Arg.Any<bool>(), Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenUserIsNotAuthenticated_ShouldReturnNotAuthorizedError()
{
// Arrange
GetReadingSectionQuery query = _getReadingSectionQueryFixture.Create();
_mockCurrentUserService.UserId.Returns((Guid?)null);
// Act
Result<ReadingSectionDto> result = await _sut.HandleAsync(query, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(ApplicationErrors.Authorization.NotAuthorized, result.FirstError);
await _mockBookRepository.DidNotReceive().GetByIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenValidationFails_ShouldReturnValidationErrorsWithoutFetchingTheSection()
{
// Arrange
GetReadingSectionQuery query = _getReadingSectionQueryFixture.Create();
_mockValidator.Validate(Arg.Any<GetReadingSectionQuery>()).Returns([Errors.Reading.LocationRefCannotBeEmpty]);
// Act
Result<ReadingSectionDto> result = await _sut.HandleAsync(query, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(Errors.Reading.LocationRefCannotBeEmpty, result.FirstError);
await _mockBookRepository.DidNotReceive().GetByIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
await _mockBookReadingService.DidNotReceive().GetSectionAsync(Arg.Any<Guid>(), Arg.Any<Guid>(), Arg.Any<string>(), Arg.Any<LibraryType>(), Arg.Any<string>(), Arg.Any<bool>(), Arg.Any<bool>(), Arg.Any<CancellationToken>());
}
}
@@ -0,0 +1,62 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Reading.Queries.GetReadingSection;
using Lumina.Application.Fixtures.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Reading.Queries.GetReadingSection;
using Lumina.Application.UnitTests.Common.Setup;
using Lumina.Domain.Common.Errors;
using Lumina.Domain.Common.Primitives;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
#endregion
namespace Lumina.Application.UnitTests.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Reading.Queries.GetReadingSection;
/// <summary>
/// Contains unit tests for the <see cref="GetReadingSectionQueryValidator"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetReadingSectionQueryValidatorTests
{
private readonly GetReadingSectionQueryValidator _validator = new();
private readonly GetReadingSectionQueryFixture _getReadingSectionQueryFixture = new();
[Fact]
public void Validate_WhenBookIdIsEmpty_ShouldHaveValidationError()
{
// Arrange
GetReadingSectionQuery query = _getReadingSectionQueryFixture.Create(bookId: Guid.Empty);
// Act
List<Error> result = _validator.TestValidate(query);
// Assert
result.ShouldHaveValidationError(Errors.Reading.BookIdCannotBeEmpty);
}
[Fact]
public void Validate_WhenLocationRefIsEmpty_ShouldHaveValidationError()
{
// Arrange
GetReadingSectionQuery query = _getReadingSectionQueryFixture.Create(locationRef: string.Empty);
// Act
List<Error> result = _validator.TestValidate(query);
// Assert
result.ShouldHaveValidationError(Errors.Reading.LocationRefCannotBeEmpty);
}
[Fact]
public void Validate_WhenQueryIsValid_ShouldNotHaveValidationError()
{
// Arrange
GetReadingSectionQuery query = _getReadingSectionQueryFixture.Create();
// Act
List<Error> result = _validator.TestValidate(query);
// Assert
result.ShouldNotHaveValidationError(Errors.Reading.BookIdCannotBeEmpty);
result.ShouldNotHaveValidationError(Errors.Reading.LocationRefCannotBeEmpty);
}
}
@@ -0,0 +1,209 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DataAccess.Entities.Plugins;
using Lumina.Application.Common.DataAccess.Repositories.Plugins;
using Lumina.Application.Common.DataAccess.UoW;
using Lumina.Application.Common.Infrastructure.Authentication;
using Lumina.Application.Common.Infrastructure.Authorization;
using Lumina.Application.Common.Infrastructure.Authorization.Policies.LibraryOwnership;
using Lumina.Application.Common.Infrastructure.Reading;
using Lumina.Application.Common.Infrastructure.Validation;
using Lumina.Application.Core.Plugins.Commands.SetLibraryBookReaderEnabled;
using Lumina.Application.Fixtures.Common.DataAccess.Entities.Plugins;
using Lumina.Application.Fixtures.Core.Plugins.Commands.SetLibraryBookReaderEnabled;
using Lumina.Domain.Common.Errors;
using Lumina.Domain.Common.Primitives;
using NSubstitute;
using System;
using System.Diagnostics.CodeAnalysis;
using System.Threading;
using System.Threading.Tasks;
using ApplicationErrors = Lumina.Application.Common.Errors.Errors;
#endregion
namespace Lumina.Application.UnitTests.Core.Plugins.Commands.SetLibraryBookReaderEnabled;
/// <summary>
/// Contains unit tests for the <see cref="SetLibraryBookReaderEnabledCommandHandler"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class SetLibraryBookReaderEnabledCommandHandlerTests
{
private readonly IUnitOfWork _mockUnitOfWork;
private readonly ILibraryBookReaderConfigurationRepository _mockLibraryBookReaderConfigurationRepository;
private readonly IAuthorizationService _mockAuthorizationService;
private readonly ICurrentUserService _mockCurrentUserService;
private readonly IBookReaderEnablementCache _mockEnablementCache;
private readonly IValidator<SetLibraryBookReaderEnabledCommand> _mockValidator;
private readonly SetLibraryBookReaderEnabledCommandHandler _sut;
private readonly SetLibraryBookReaderEnabledCommandFixture _setLibraryBookReaderEnabledCommandFixture = new();
private readonly LibraryBookReaderConfigurationEntityFixture _configurationEntityFixture = new();
private readonly Guid _userId;
/// <summary>
/// Initializes a new instance of the <see cref="SetLibraryBookReaderEnabledCommandHandlerTests"/> class.
/// </summary>
public SetLibraryBookReaderEnabledCommandHandlerTests()
{
_mockUnitOfWork = Substitute.For<IUnitOfWork>();
_mockLibraryBookReaderConfigurationRepository = Substitute.For<ILibraryBookReaderConfigurationRepository>();
_mockUnitOfWork.LibraryBookReaderConfigurationRepository.Returns(_mockLibraryBookReaderConfigurationRepository);
_mockAuthorizationService = Substitute.For<IAuthorizationService>();
_mockCurrentUserService = Substitute.For<ICurrentUserService>();
_mockEnablementCache = Substitute.For<IBookReaderEnablementCache>();
_mockValidator = Substitute.For<IValidator<SetLibraryBookReaderEnabledCommand>>();
_userId = Guid.NewGuid();
// Default stubs: the current user is authenticated and the library ownership policy allows access.
_mockCurrentUserService.UserId.Returns(_userId);
_mockAuthorizationService.EvaluatePolicyAsync<ILibraryOwnershipPolicy>(_userId, Arg.Any<LibraryOwnershipPolicyContext>(), Arg.Any<CancellationToken>())
.Returns(true);
_mockValidator.Validate(Arg.Any<SetLibraryBookReaderEnabledCommand>()).Returns([]);
_mockLibraryBookReaderConfigurationRepository.UpsertAsync(Arg.Any<LibraryBookReaderConfigurationEntity>(), Arg.Any<CancellationToken>())
.Returns(Result.Updated);
_sut = new SetLibraryBookReaderEnabledCommandHandler(_mockAuthorizationService, _mockCurrentUserService, _mockEnablementCache, _mockUnitOfWork, _mockValidator);
}
[Fact]
public async Task HandleAsync_WhenConfigurationDoesNotExist_ShouldInsertNewConfigurationAndPersist()
{
// Arrange
SetLibraryBookReaderEnabledCommand command = _setLibraryBookReaderEnabledCommandFixture.Create(isEnabled: false);
_mockLibraryBookReaderConfigurationRepository.GetByLibraryAndPluginIdAsync(command.LibraryId, command.PluginId, Arg.Any<CancellationToken>())
.Returns(Result.From<LibraryBookReaderConfigurationEntity?>(null));
// Act
Result<Success> result = await _sut.HandleAsync(command, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
await _mockLibraryBookReaderConfigurationRepository.Received(1).UpsertAsync(
Arg.Is<LibraryBookReaderConfigurationEntity>(configuration =>
configuration.LibraryId == command.LibraryId &&
configuration.PluginId == command.PluginId &&
configuration.IsEnabled == command.IsEnabled),
Arg.Any<CancellationToken>());
await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any<CancellationToken>());
_mockEnablementCache.Received(1).Invalidate(command.LibraryId, command.PluginId);
}
[Fact]
public async Task HandleAsync_WhenConfigurationExists_ShouldUpdateItsEnabledStateAndPersist()
{
// Arrange
SetLibraryBookReaderEnabledCommand command = _setLibraryBookReaderEnabledCommandFixture.Create(isEnabled: true);
LibraryBookReaderConfigurationEntity existingConfiguration = _configurationEntityFixture.Create(
libraryId: command.LibraryId,
pluginId: command.PluginId,
isEnabled: false);
_mockLibraryBookReaderConfigurationRepository.GetByLibraryAndPluginIdAsync(command.LibraryId, command.PluginId, Arg.Any<CancellationToken>())
.Returns(Result.From<LibraryBookReaderConfigurationEntity?>(existingConfiguration));
// Act
Result<Success> result = await _sut.HandleAsync(command, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
Assert.True(existingConfiguration.IsEnabled);
await _mockLibraryBookReaderConfigurationRepository.Received(1).UpsertAsync(existingConfiguration, Arg.Any<CancellationToken>());
await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any<CancellationToken>());
_mockEnablementCache.Received(1).Invalidate(command.LibraryId, command.PluginId);
}
[Fact]
public async Task HandleAsync_WhenValidatorReturnsError_ShouldReturnValidationErrorAndNotPersist()
{
// Arrange
SetLibraryBookReaderEnabledCommand command = _setLibraryBookReaderEnabledCommandFixture.Create();
_mockValidator.Validate(Arg.Any<SetLibraryBookReaderEnabledCommand>()).Returns([Errors.Plugins.PluginIdCannotBeEmpty]);
// Act
Result<Success> result = await _sut.HandleAsync(command, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(Errors.Plugins.PluginIdCannotBeEmpty, result.FirstError);
await _mockLibraryBookReaderConfigurationRepository.DidNotReceive().GetByLibraryAndPluginIdAsync(Arg.Any<Guid>(), Arg.Any<Guid>(), Arg.Any<CancellationToken>());
await _mockLibraryBookReaderConfigurationRepository.DidNotReceive().UpsertAsync(Arg.Any<LibraryBookReaderConfigurationEntity>(), Arg.Any<CancellationToken>());
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
_mockEnablementCache.DidNotReceive().Invalidate(Arg.Any<Guid>(), Arg.Any<Guid>());
}
[Fact]
public async Task HandleAsync_WhenOwnershipPolicyDeniesAccess_ShouldReturnNotAuthorizedErrorAndNotPersist()
{
// Arrange
SetLibraryBookReaderEnabledCommand command = _setLibraryBookReaderEnabledCommandFixture.Create();
_mockAuthorizationService.EvaluatePolicyAsync<ILibraryOwnershipPolicy>(_userId, Arg.Any<LibraryOwnershipPolicyContext>(), Arg.Any<CancellationToken>())
.Returns(false);
// Act
Result<Success> result = await _sut.HandleAsync(command, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(ApplicationErrors.Authorization.NotAuthorized, result.FirstError);
await _mockLibraryBookReaderConfigurationRepository.DidNotReceive().GetByLibraryAndPluginIdAsync(Arg.Any<Guid>(), Arg.Any<Guid>(), Arg.Any<CancellationToken>());
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
_mockEnablementCache.DidNotReceive().Invalidate(Arg.Any<Guid>(), Arg.Any<Guid>());
}
[Fact]
public async Task HandleAsync_WhenUserIsNotAuthenticated_ShouldReturnNotAuthorizedErrorAndNotPersist()
{
// Arrange
SetLibraryBookReaderEnabledCommand command = _setLibraryBookReaderEnabledCommandFixture.Create();
_mockCurrentUserService.UserId.Returns((Guid?)null);
// Act
Result<Success> result = await _sut.HandleAsync(command, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(ApplicationErrors.Authorization.NotAuthorized, result.FirstError);
await _mockLibraryBookReaderConfigurationRepository.DidNotReceive().GetByLibraryAndPluginIdAsync(Arg.Any<Guid>(), Arg.Any<Guid>(), Arg.Any<CancellationToken>());
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
_mockEnablementCache.DidNotReceive().Invalidate(Arg.Any<Guid>(), Arg.Any<Guid>());
}
[Fact]
public async Task HandleAsync_WhenGetConfigurationFails_ShouldReturnErrorAndNotPersist()
{
// Arrange
SetLibraryBookReaderEnabledCommand command = _setLibraryBookReaderEnabledCommandFixture.Create();
Error error = Error.Failure(description: "Failed to get configuration");
_mockLibraryBookReaderConfigurationRepository.GetByLibraryAndPluginIdAsync(command.LibraryId, command.PluginId, Arg.Any<CancellationToken>())
.Returns(error);
// Act
Result<Success> result = await _sut.HandleAsync(command, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(error, result.FirstError);
await _mockLibraryBookReaderConfigurationRepository.DidNotReceive().UpsertAsync(Arg.Any<LibraryBookReaderConfigurationEntity>(), Arg.Any<CancellationToken>());
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
_mockEnablementCache.DidNotReceive().Invalidate(Arg.Any<Guid>(), Arg.Any<Guid>());
}
[Fact]
public async Task HandleAsync_WhenUpsertFails_ShouldReturnErrorAndNotPersist()
{
// Arrange
SetLibraryBookReaderEnabledCommand command = _setLibraryBookReaderEnabledCommandFixture.Create();
Error error = Error.Failure(description: "Failed to upsert configuration");
_mockLibraryBookReaderConfigurationRepository.GetByLibraryAndPluginIdAsync(command.LibraryId, command.PluginId, Arg.Any<CancellationToken>())
.Returns(Result.From<LibraryBookReaderConfigurationEntity?>(null));
_mockLibraryBookReaderConfigurationRepository.UpsertAsync(Arg.Any<LibraryBookReaderConfigurationEntity>(), Arg.Any<CancellationToken>())
.Returns(error);
// Act
Result<Success> result = await _sut.HandleAsync(command, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(error, result.FirstError);
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
_mockEnablementCache.DidNotReceive().Invalidate(Arg.Any<Guid>(), Arg.Any<Guid>());
}
}
@@ -0,0 +1,62 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Core.Plugins.Commands.SetLibraryBookReaderEnabled;
using Lumina.Application.Fixtures.Core.Plugins.Commands.SetLibraryBookReaderEnabled;
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.Plugins.Commands.SetLibraryBookReaderEnabled;
/// <summary>
/// Contains unit tests for the <see cref="SetLibraryBookReaderEnabledCommandValidator"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class SetLibraryBookReaderEnabledCommandValidatorTests
{
private readonly SetLibraryBookReaderEnabledCommandValidator _validator = new();
private readonly SetLibraryBookReaderEnabledCommandFixture _setLibraryBookReaderEnabledCommandFixture = new();
[Fact]
public void Validate_WhenLibraryIdIsEmpty_ShouldHaveValidationError()
{
// Arrange
SetLibraryBookReaderEnabledCommand command = _setLibraryBookReaderEnabledCommandFixture.Create(libraryId: Guid.Empty);
// Act
List<Error> result = _validator.TestValidate(command);
// Assert
result.ShouldHaveValidationError(Errors.Plugins.LibraryIdCannotBeEmpty);
}
[Fact]
public void Validate_WhenPluginIdIsEmpty_ShouldHaveValidationError()
{
// Arrange
SetLibraryBookReaderEnabledCommand command = _setLibraryBookReaderEnabledCommandFixture.Create(pluginId: Guid.Empty);
// Act
List<Error> result = _validator.TestValidate(command);
// Assert
result.ShouldHaveValidationError(Errors.Plugins.PluginIdCannotBeEmpty);
}
[Fact]
public void Validate_WhenCommandIsValid_ShouldNotHaveValidationError()
{
// Arrange
SetLibraryBookReaderEnabledCommand command = _setLibraryBookReaderEnabledCommandFixture.Create();
// Act
List<Error> result = _validator.TestValidate(command);
// Assert
result.ShouldNotHaveValidationError(Errors.Plugins.LibraryIdCannotBeEmpty);
result.ShouldNotHaveValidationError(Errors.Plugins.PluginIdCannotBeEmpty);
}
}
@@ -0,0 +1,241 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DataAccess.Entities.Plugins;
using Lumina.Application.Common.DataAccess.Repositories.Plugins;
using Lumina.Application.Common.DataAccess.UoW;
using Lumina.Application.Common.Infrastructure.Authentication;
using Lumina.Application.Common.Infrastructure.Authorization;
using Lumina.Application.Common.Infrastructure.Authorization.Policies.LibraryOwnership;
using Lumina.Application.Common.Infrastructure.Reading;
using Lumina.Application.Common.Infrastructure.Validation;
using Lumina.Application.Core.Plugins.Queries.GetLibraryBookReaders;
using Lumina.Application.Fixtures.Common.DataAccess.Entities.Plugins;
using Lumina.Application.Fixtures.Core.Plugins.Queries.GetLibraryBookReaders;
using Lumina.Contracts.Responses.Plugins;
using Lumina.Domain.Common.Errors;
using Lumina.Domain.Common.Primitives;
using NSubstitute;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Threading;
using System.Threading.Tasks;
using ApplicationErrors = Lumina.Application.Common.Errors.Errors;
#endregion
namespace Lumina.Application.UnitTests.Core.Plugins.Queries.GetLibraryBookReaders;
/// <summary>
/// Contains unit tests for the <see cref="GetLibraryBookReadersQueryHandler"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetLibraryBookReadersQueryHandlerTests
{
private readonly IUnitOfWork _mockUnitOfWork;
private readonly ILibraryBookReaderConfigurationRepository _mockLibraryBookReaderConfigurationRepository;
private readonly IPluginRepository _mockPluginRepository;
private readonly IAuthorizationService _mockAuthorizationService;
private readonly ICurrentUserService _mockCurrentUserService;
private readonly IBookReaderRegistry _mockBookReaderRegistry;
private readonly IValidator<GetLibraryBookReadersQuery> _mockValidator;
private readonly GetLibraryBookReadersQueryHandler _sut;
private readonly GetLibraryBookReadersQueryFixture _getLibraryBookReadersQueryFixture = new();
private readonly LibraryBookReaderConfigurationEntityFixture _configurationEntityFixture = new();
private readonly PluginEntityFixture _pluginEntityFixture = new();
private readonly Guid _userId;
/// <summary>
/// Initializes a new instance of the <see cref="GetLibraryBookReadersQueryHandlerTests"/> class.
/// </summary>
public GetLibraryBookReadersQueryHandlerTests()
{
_mockUnitOfWork = Substitute.For<IUnitOfWork>();
_mockLibraryBookReaderConfigurationRepository = Substitute.For<ILibraryBookReaderConfigurationRepository>();
_mockPluginRepository = Substitute.For<IPluginRepository>();
_mockUnitOfWork.LibraryBookReaderConfigurationRepository.Returns(_mockLibraryBookReaderConfigurationRepository);
_mockUnitOfWork.PluginRepository.Returns(_mockPluginRepository);
_mockAuthorizationService = Substitute.For<IAuthorizationService>();
_mockCurrentUserService = Substitute.For<ICurrentUserService>();
_mockBookReaderRegistry = Substitute.For<IBookReaderRegistry>();
_mockValidator = Substitute.For<IValidator<GetLibraryBookReadersQuery>>();
_userId = Guid.NewGuid();
// Default stubs: the current user is authenticated and the library ownership policy allows access.
_mockCurrentUserService.UserId.Returns(_userId);
_mockAuthorizationService.EvaluatePolicyAsync<ILibraryOwnershipPolicy>(_userId, Arg.Any<LibraryOwnershipPolicyContext>(), Arg.Any<CancellationToken>())
.Returns(true);
_mockValidator.Validate(Arg.Any<GetLibraryBookReadersQuery>()).Returns([]);
_mockBookReaderRegistry.GetSupportedExtensionsByPluginId().Returns(new Dictionary<Guid, IReadOnlyList<string>>());
_sut = new GetLibraryBookReadersQueryHandler(_mockAuthorizationService, _mockCurrentUserService, _mockBookReaderRegistry, _mockUnitOfWork, _mockValidator);
}
[Fact]
public async Task HandleAsync_WhenLibraryIdIsEmpty_ShouldReturnValidationError()
{
// Arrange
GetLibraryBookReadersQuery query = _getLibraryBookReadersQueryFixture.Create();
_mockValidator.Validate(Arg.Any<GetLibraryBookReadersQuery>()).Returns([Errors.Plugins.LibraryIdCannotBeEmpty]);
// Act
Result<IReadOnlyList<LibraryBookReaderResponse>> result = await _sut.HandleAsync(query, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(Errors.Plugins.LibraryIdCannotBeEmpty, result.FirstError);
await _mockLibraryBookReaderConfigurationRepository.DidNotReceive().GetByLibraryIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenConfigurationsExist_ShouldReturnEnabledReadersFirstOrderedByNameWithPluginNames()
{
// Arrange
GetLibraryBookReadersQuery query = _getLibraryBookReadersQueryFixture.Create();
Guid enabledPluginId = Guid.NewGuid();
Guid disabledPluginId = Guid.NewGuid();
List<LibraryBookReaderConfigurationEntity> configurations =
[
_configurationEntityFixture.Create(libraryId: query.LibraryId, pluginId: enabledPluginId, isEnabled: true),
_configurationEntityFixture.Create(libraryId: query.LibraryId, pluginId: disabledPluginId, isEnabled: false)
];
_mockLibraryBookReaderConfigurationRepository.GetByLibraryIdAsync(query.LibraryId, Arg.Any<CancellationToken>())
.Returns(Result.From<IReadOnlyList<LibraryBookReaderConfigurationEntity>>(configurations));
List<PluginEntity> plugins =
[
_pluginEntityFixture.Create(enabledPluginId, "A Reader"),
_pluginEntityFixture.Create(disabledPluginId, "B Reader")
];
_mockPluginRepository.GetAllAsync(Arg.Any<CancellationToken>()).Returns(plugins);
Dictionary<Guid, IReadOnlyList<string>> supportedExtensions = new()
{
[enabledPluginId] = [".epub"],
[disabledPluginId] = [".pdf"]
};
_mockBookReaderRegistry.GetSupportedExtensionsByPluginId().Returns(supportedExtensions);
// Act
Result<IReadOnlyList<LibraryBookReaderResponse>> result = await _sut.HandleAsync(query, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
Assert.Equal(2, result.Value.Count);
Assert.Equal(enabledPluginId, result.Value[0].PluginId);
Assert.True(result.Value[0].IsEnabled);
Assert.Equal(".epub", Assert.Single(result.Value[0].SupportedExtensions));
Assert.Equal(disabledPluginId, result.Value[1].PluginId);
Assert.False(result.Value[1].IsEnabled);
Assert.Equal(".pdf", Assert.Single(result.Value[1].SupportedExtensions));
}
[Fact]
public async Task HandleAsync_WhenPluginIsMissingFromDetectedPlugins_ShouldUseEmptyNameAndNoExtensions()
{
// Arrange
GetLibraryBookReadersQuery query = _getLibraryBookReadersQueryFixture.Create();
Guid unknownPluginId = Guid.NewGuid();
List<LibraryBookReaderConfigurationEntity> configurations =
[
_configurationEntityFixture.Create(libraryId: query.LibraryId, pluginId: unknownPluginId, isEnabled: true)
];
_mockLibraryBookReaderConfigurationRepository.GetByLibraryIdAsync(query.LibraryId, Arg.Any<CancellationToken>())
.Returns(Result.From<IReadOnlyList<LibraryBookReaderConfigurationEntity>>(configurations));
_mockPluginRepository.GetAllAsync(Arg.Any<CancellationToken>())
.Returns(Result.From<IEnumerable<PluginEntity>>([_pluginEntityFixture.Create()]));
// Act
Result<IReadOnlyList<LibraryBookReaderResponse>> result = await _sut.HandleAsync(query, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
LibraryBookReaderResponse response = Assert.Single(result.Value);
Assert.Equal(unknownPluginId, response.PluginId);
Assert.Equal(string.Empty, response.Name);
Assert.Empty(response.SupportedExtensions);
}
[Fact]
public async Task HandleAsync_WhenNoConfigurationsExist_ShouldReturnEmptyList()
{
// Arrange
GetLibraryBookReadersQuery query = _getLibraryBookReadersQueryFixture.Create();
_mockLibraryBookReaderConfigurationRepository.GetByLibraryIdAsync(query.LibraryId, Arg.Any<CancellationToken>())
.Returns(Result.From<IReadOnlyList<LibraryBookReaderConfigurationEntity>>([]));
_mockPluginRepository.GetAllAsync(Arg.Any<CancellationToken>())
.Returns(Result.From<IEnumerable<PluginEntity>>([]));
// Act
Result<IReadOnlyList<LibraryBookReaderResponse>> result = await _sut.HandleAsync(query, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
Assert.Empty(result.Value);
}
[Fact]
public async Task HandleAsync_WhenGetConfigurationsFails_ShouldReturnError()
{
// Arrange
GetLibraryBookReadersQuery query = _getLibraryBookReadersQueryFixture.Create();
Error error = Error.Failure(description: "Failed to get configurations");
_mockLibraryBookReaderConfigurationRepository.GetByLibraryIdAsync(query.LibraryId, Arg.Any<CancellationToken>())
.Returns(error);
// Act
Result<IReadOnlyList<LibraryBookReaderResponse>> result = await _sut.HandleAsync(query, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
await _mockPluginRepository.DidNotReceive().GetAllAsync(Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenGetPluginsFails_ShouldReturnError()
{
// Arrange
GetLibraryBookReadersQuery query = _getLibraryBookReadersQueryFixture.Create();
_mockLibraryBookReaderConfigurationRepository.GetByLibraryIdAsync(query.LibraryId, Arg.Any<CancellationToken>())
.Returns(Result.From<IReadOnlyList<LibraryBookReaderConfigurationEntity>>([]));
_mockPluginRepository.GetAllAsync(Arg.Any<CancellationToken>())
.Returns(Error.Failure(description: "Failed to get plugins"));
// Act
Result<IReadOnlyList<LibraryBookReaderResponse>> result = await _sut.HandleAsync(query, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
}
[Fact]
public async Task HandleAsync_WhenOwnershipPolicyDeniesAccess_ShouldReturnNotAuthorizedError()
{
// Arrange
GetLibraryBookReadersQuery query = _getLibraryBookReadersQueryFixture.Create();
_mockAuthorizationService.EvaluatePolicyAsync<ILibraryOwnershipPolicy>(_userId, Arg.Any<LibraryOwnershipPolicyContext>(), Arg.Any<CancellationToken>())
.Returns(false);
// Act
Result<IReadOnlyList<LibraryBookReaderResponse>> result = await _sut.HandleAsync(query, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(ApplicationErrors.Authorization.NotAuthorized, result.FirstError);
await _mockLibraryBookReaderConfigurationRepository.DidNotReceive().GetByLibraryIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
await _mockPluginRepository.DidNotReceive().GetAllAsync(Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenUserIsNotAuthenticated_ShouldReturnNotAuthorizedError()
{
// Arrange
GetLibraryBookReadersQuery query = _getLibraryBookReadersQueryFixture.Create();
_mockCurrentUserService.UserId.Returns((Guid?)null);
// Act
Result<IReadOnlyList<LibraryBookReaderResponse>> result = await _sut.HandleAsync(query, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(ApplicationErrors.Authorization.NotAuthorized, result.FirstError);
await _mockAuthorizationService.DidNotReceive().EvaluatePolicyAsync<ILibraryOwnershipPolicy>(Arg.Any<Guid>(), Arg.Any<LibraryOwnershipPolicyContext>(), Arg.Any<CancellationToken>());
await _mockLibraryBookReaderConfigurationRepository.DidNotReceive().GetByLibraryIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
}
}
@@ -0,0 +1,48 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Core.Plugins.Queries.GetLibraryBookReaders;
using Lumina.Application.Fixtures.Core.Plugins.Queries.GetLibraryBookReaders;
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.Plugins.Queries.GetLibraryBookReaders;
/// <summary>
/// Contains unit tests for the <see cref="GetLibraryBookReadersQueryValidator"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetLibraryBookReadersQueryValidatorTests
{
private readonly GetLibraryBookReadersQueryValidator _validator = new();
private readonly GetLibraryBookReadersQueryFixture _getLibraryBookReadersQueryFixture = new();
[Fact]
public void Validate_WhenLibraryIdIsEmpty_ShouldHaveValidationError()
{
// Arrange
GetLibraryBookReadersQuery query = _getLibraryBookReadersQueryFixture.Create(libraryId: Guid.Empty);
// Act
List<Error> result = _validator.TestValidate(query);
// Assert
result.ShouldHaveValidationError(Errors.Plugins.LibraryIdCannotBeEmpty);
}
[Fact]
public void Validate_WhenLibraryIdIsValid_ShouldNotHaveValidationError()
{
// Arrange
GetLibraryBookReadersQuery query = _getLibraryBookReadersQueryFixture.Create();
// Act
List<Error> result = _validator.TestValidate(query);
// Assert
result.ShouldNotHaveValidationError(Errors.Plugins.LibraryIdCannotBeEmpty);
}
}
@@ -74,7 +74,9 @@ public class UpdateUserSettingsCommandHandlerTests
settings.UserId == _userId &&
settings.IsPaginationEnabled == command.IsPaginationEnabled &&
settings.ItemsPerPage == command.ItemsPerPage &&
settings.ShouldIgnoreThePrefixForAlphaPicker == command.ShouldIgnoreThePrefixForAlphaPicker),
settings.ShouldIgnoreThePrefixForAlphaPicker == command.ShouldIgnoreThePrefixForAlphaPicker &&
settings.ShouldRenderPdfAsImages == command.ShouldRenderPdfAsImages &&
settings.ShouldPreserveBookStyles == command.ShouldPreserveBookStyles),
Arg.Any<CancellationToken>());
await _mockUserSettingsRepository.DidNotReceive().UpdateAsync(Arg.Any<UserSettingsEntity>(), Arg.Any<CancellationToken>());
await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any<CancellationToken>());
@@ -102,7 +104,9 @@ public class UpdateUserSettingsCommandHandlerTests
settings.UserId == _userId &&
settings.IsPaginationEnabled == command.IsPaginationEnabled &&
settings.ItemsPerPage == command.ItemsPerPage &&
settings.ShouldIgnoreThePrefixForAlphaPicker == command.ShouldIgnoreThePrefixForAlphaPicker),
settings.ShouldIgnoreThePrefixForAlphaPicker == command.ShouldIgnoreThePrefixForAlphaPicker &&
settings.ShouldRenderPdfAsImages == command.ShouldRenderPdfAsImages &&
settings.ShouldPreserveBookStyles == command.ShouldPreserveBookStyles),
Arg.Any<CancellationToken>());
await _mockUserSettingsRepository.DidNotReceive().InsertAsync(Arg.Any<UserSettingsEntity>(), Arg.Any<CancellationToken>());
await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any<CancellationToken>());
@@ -166,4 +170,82 @@ public class UpdateUserSettingsCommandHandlerTests
await _mockUserSettingsRepository.DidNotReceive().UpdateAsync(Arg.Any<UserSettingsEntity>(), Arg.Any<CancellationToken>());
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenInsertFails_ShouldReturnErrorAndNotSaveChanges()
{
// Arrange
UpdateUserSettingsCommand command = _updateUserSettingsCommandFixture.Create();
_mockUserSettingsRepository.GetByUserIdAsync(_userId, Arg.Any<CancellationToken>())
.Returns(Result.From<UserSettingsEntity?>(null));
Error error = Error.Failure("Database.Error", "Failed to insert user settings");
_mockUserSettingsRepository.InsertAsync(Arg.Any<UserSettingsEntity>(), Arg.Any<CancellationToken>())
.Returns(error);
// Act
Result<Updated> result = await _sut.HandleAsync(command, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(error, result.FirstError);
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenToDomainEntityFails_ShouldReturnErrorAndNotUpdate()
{
// Arrange
UpdateUserSettingsCommand command = _updateUserSettingsCommandFixture.Create();
// An entity carrying an invalid items-per-page value fails to convert to its domain aggregate.
UserSettingsEntity existingSettings = _userSettingsEntityFixture.Create(userId: _userId, itemsPerPage: 0);
_mockUserSettingsRepository.GetByUserIdAsync(_userId, Arg.Any<CancellationToken>())
.Returns(Result.From<UserSettingsEntity?>(existingSettings));
// Act
Result<Updated> result = await _sut.HandleAsync(command, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
await _mockUserSettingsRepository.DidNotReceive().UpdateAsync(Arg.Any<UserSettingsEntity>(), Arg.Any<CancellationToken>());
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenUpdateSettingsFails_ShouldReturnErrorAndNotPersist()
{
// Arrange
UpdateUserSettingsCommand command = _updateUserSettingsCommandFixture.Create(itemsPerPage: 0);
UserSettingsEntity existingSettings = _userSettingsEntityFixture.Create(userId: _userId);
_mockUserSettingsRepository.GetByUserIdAsync(_userId, Arg.Any<CancellationToken>())
.Returns(Result.From<UserSettingsEntity?>(existingSettings));
// Act
Result<Updated> result = await _sut.HandleAsync(command, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
await _mockUserSettingsRepository.DidNotReceive().UpdateAsync(Arg.Any<UserSettingsEntity>(), Arg.Any<CancellationToken>());
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenUpdateFails_ShouldReturnErrorAndNotSaveChanges()
{
// Arrange
UpdateUserSettingsCommand command = _updateUserSettingsCommandFixture.Create();
UserSettingsEntity existingSettings = _userSettingsEntityFixture.Create(userId: _userId);
_mockUserSettingsRepository.GetByUserIdAsync(_userId, Arg.Any<CancellationToken>())
.Returns(Result.From<UserSettingsEntity?>(existingSettings));
Error error = Error.Failure("Database.Error", "Failed to update user settings");
_mockUserSettingsRepository.UpdateAsync(Arg.Any<UserSettingsEntity>(), Arg.Any<CancellationToken>())
.Returns(error);
// Act
Result<Updated> result = await _sut.HandleAsync(command, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(error, result.FirstError);
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
}
}
@@ -0,0 +1,49 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Contracts.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary.Reading;
using Lumina.Contracts.Fixtures.Core.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary.Reading;
using System.Diagnostics.CodeAnalysis;
using System.Text.Json;
#endregion
namespace Lumina.Contracts.UnitTests.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary.Reading;
/// <summary>
/// Contains unit tests for the <see cref="ReadingDocumentDto"/> record.
/// </summary>
[ExcludeFromCodeCoverage]
public class ReadingDocumentDtoTests
{
private readonly ReadingDocumentDtoFixture _fixture = new();
private readonly JsonSerializerOptions _jsonOptions = new()
{
PropertyNameCaseInsensitive = true
};
[Fact]
public void Create_WhenCalled_ShouldReturnValidReadingDocumentDto()
{
// Act
ReadingDocumentDto sut = _fixture.Create();
// Assert
Assert.NotNull(sut);
Assert.False(string.IsNullOrWhiteSpace(sut.Title));
Assert.NotEmpty(sut.Spine);
Assert.NotNull(sut.Resources);
}
[Fact]
public void RoundTrip_WhenSerializingReadingDocumentDto_ShouldPreserveValues()
{
// Arrange
ReadingDocumentDto expected = _fixture.Create();
// Act
string json = JsonSerializer.Serialize(expected, _jsonOptions);
ReadingDocumentDto? actual = JsonSerializer.Deserialize<ReadingDocumentDto>(json, _jsonOptions);
// Assert
Assert.NotNull(actual);
Assert.Equivalent(expected, actual);
}
}
@@ -0,0 +1,62 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Contracts.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary.Reading;
using Lumina.Contracts.Fixtures.Core.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary.Reading;
using System;
using System.Diagnostics.CodeAnalysis;
using System.Text.Json;
#endregion
namespace Lumina.Contracts.UnitTests.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary.Reading;
/// <summary>
/// Contains unit tests for the <see cref="ReadingResourceDataDto"/> record.
/// </summary>
[ExcludeFromCodeCoverage]
public class ReadingResourceDataDtoTests
{
private readonly ReadingResourceDataDtoFixture _fixture = new();
private readonly JsonSerializerOptions _jsonOptions = new()
{
PropertyNameCaseInsensitive = true
};
[Fact]
public void Create_WhenCalled_ShouldReturnValidReadingResourceDataDto()
{
// Act
ReadingResourceDataDto sut = _fixture.Create();
// Assert
Assert.NotNull(sut);
Assert.NotEmpty(sut.Data);
Assert.False(string.IsNullOrWhiteSpace(sut.MimeType));
}
[Fact]
public void Create_WhenProvidedData_ShouldPreserveIt()
{
// Arrange
byte[] data = Guid.NewGuid().ToByteArray();
// Act
ReadingResourceDataDto sut = _fixture.Create(data: data);
// Assert
Assert.Equal(data, sut.Data);
}
[Fact]
public void RoundTrip_WhenSerializingReadingResourceDataDto_ShouldPreserveValues()
{
// Arrange
ReadingResourceDataDto expected = _fixture.Create();
// Act
string json = JsonSerializer.Serialize(expected, _jsonOptions);
ReadingResourceDataDto? actual = JsonSerializer.Deserialize<ReadingResourceDataDto>(json, _jsonOptions);
// Assert
Assert.NotNull(actual);
Assert.Equivalent(expected, actual);
}
}
@@ -0,0 +1,48 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Contracts.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary.Reading;
using Lumina.Contracts.Fixtures.Core.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary.Reading;
using System.Diagnostics.CodeAnalysis;
using System.Text.Json;
#endregion
namespace Lumina.Contracts.UnitTests.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary.Reading;
/// <summary>
/// Contains unit tests for the <see cref="ReadingResourceInfoDto"/> record.
/// </summary>
[ExcludeFromCodeCoverage]
public class ReadingResourceInfoDtoTests
{
private readonly ReadingResourceInfoDtoFixture _fixture = new();
private readonly JsonSerializerOptions _jsonOptions = new()
{
PropertyNameCaseInsensitive = true
};
[Fact]
public void Create_WhenCalled_ShouldReturnValidReadingResourceInfoDto()
{
// Act
ReadingResourceInfoDto sut = _fixture.Create();
// Assert
Assert.NotNull(sut);
Assert.False(string.IsNullOrWhiteSpace(sut.RelativeFilePath));
Assert.False(string.IsNullOrWhiteSpace(sut.MimeType));
}
[Fact]
public void RoundTrip_WhenSerializingReadingResourceInfoDto_ShouldPreserveValues()
{
// Arrange
ReadingResourceInfoDto expected = _fixture.Create();
// Act
string json = JsonSerializer.Serialize(expected, _jsonOptions);
ReadingResourceInfoDto? actual = JsonSerializer.Deserialize<ReadingResourceInfoDto>(json, _jsonOptions);
// Assert
Assert.NotNull(actual);
Assert.Equal(expected, actual);
}
}
@@ -0,0 +1,48 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Contracts.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary.Reading;
using Lumina.Contracts.Fixtures.Core.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary.Reading;
using System.Diagnostics.CodeAnalysis;
using System.Text.Json;
#endregion
namespace Lumina.Contracts.UnitTests.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary.Reading;
/// <summary>
/// Contains unit tests for the <see cref="ReadingSectionDto"/> record.
/// </summary>
[ExcludeFromCodeCoverage]
public class ReadingSectionDtoTests
{
private readonly ReadingSectionDtoFixture _fixture = new();
private readonly JsonSerializerOptions _jsonOptions = new()
{
PropertyNameCaseInsensitive = true
};
[Fact]
public void Create_WhenCalled_ShouldReturnValidReadingSectionDto()
{
// Act
ReadingSectionDto sut = _fixture.Create();
// Assert
Assert.NotNull(sut);
Assert.False(string.IsNullOrWhiteSpace(sut.LocationRef));
Assert.False(string.IsNullOrWhiteSpace(sut.ContentHtml));
}
[Fact]
public void RoundTrip_WhenSerializingReadingSectionDto_ShouldPreserveValues()
{
// Arrange
ReadingSectionDto expected = _fixture.Create();
// Act
string json = JsonSerializer.Serialize(expected, _jsonOptions);
ReadingSectionDto? actual = JsonSerializer.Deserialize<ReadingSectionDto>(json, _jsonOptions);
// Assert
Assert.NotNull(actual);
Assert.Equal(expected, actual);
}
}
@@ -0,0 +1,48 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Contracts.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary.Reading;
using Lumina.Contracts.Fixtures.Core.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary.Reading;
using System.Diagnostics.CodeAnalysis;
using System.Text.Json;
#endregion
namespace Lumina.Contracts.UnitTests.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary.Reading;
/// <summary>
/// Contains unit tests for the <see cref="ReadingSpineItemDto"/> record.
/// </summary>
[ExcludeFromCodeCoverage]
public class ReadingSpineItemDtoTests
{
private readonly ReadingSpineItemDtoFixture _fixture = new();
private readonly JsonSerializerOptions _jsonOptions = new()
{
PropertyNameCaseInsensitive = true
};
[Fact]
public void Create_WhenCalled_ShouldReturnValidReadingSpineItemDto()
{
// Act
ReadingSpineItemDto sut = _fixture.Create();
// Assert
Assert.NotNull(sut);
Assert.False(string.IsNullOrWhiteSpace(sut.LocationRef));
Assert.False(string.IsNullOrWhiteSpace(sut.RelativeSectionFilePath));
}
[Fact]
public void RoundTrip_WhenSerializingReadingSpineItemDto_ShouldPreserveValues()
{
// Arrange
ReadingSpineItemDto expected = _fixture.Create();
// Act
string json = JsonSerializer.Serialize(expected, _jsonOptions);
ReadingSpineItemDto? actual = JsonSerializer.Deserialize<ReadingSpineItemDto>(json, _jsonOptions);
// Assert
Assert.NotNull(actual);
Assert.Equal(expected, actual);
}
}
@@ -0,0 +1,48 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Contracts.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary.Reading;
using Lumina.Contracts.Fixtures.Core.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary.Reading;
using System.Diagnostics.CodeAnalysis;
using System.Text.Json;
#endregion
namespace Lumina.Contracts.UnitTests.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary.Reading;
/// <summary>
/// Contains unit tests for the <see cref="ReadingTocEntryDto"/> record.
/// </summary>
[ExcludeFromCodeCoverage]
public class ReadingTocEntryDtoTests
{
private readonly ReadingTocEntryDtoFixture _fixture = new();
private readonly JsonSerializerOptions _jsonOptions = new()
{
PropertyNameCaseInsensitive = true
};
[Fact]
public void Create_WhenCalled_ShouldReturnValidReadingTocEntryDto()
{
// Act
ReadingTocEntryDto sut = _fixture.Create();
// Assert
Assert.NotNull(sut);
Assert.False(string.IsNullOrWhiteSpace(sut.Label));
Assert.False(string.IsNullOrWhiteSpace(sut.LocationRef));
}
[Fact]
public void RoundTrip_WhenSerializingReadingTocEntryDto_ShouldPreserveValues()
{
// Arrange
ReadingTocEntryDto expected = _fixture.Create();
// Act
string json = JsonSerializer.Serialize(expected, _jsonOptions);
ReadingTocEntryDto? actual = JsonSerializer.Deserialize<ReadingTocEntryDto>(json, _jsonOptions);
// Assert
Assert.NotNull(actual);
Assert.Equivalent(expected, actual);
}
}
@@ -1,6 +1,6 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Contracts.Fixtures.Core.Requests.Authorization;
using Lumina.Contracts.Requests.Authorization;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Text.Json;
@@ -14,38 +14,46 @@ namespace Lumina.Contracts.UnitTests.Requests.Authorization;
[ExcludeFromCodeCoverage]
public class AddRoleRequestTests
{
private readonly AddRoleRequestFixture _addRoleRequestFixture = new();
private readonly JsonSerializerOptions _jsonOptions = new()
{
PropertyNameCaseInsensitive = true
};
[Fact]
public void Create_WhenCalled_ShouldReturnValidAddRoleRequest()
{
// Act
AddRoleRequest sut = _addRoleRequestFixture.Create();
// Assert
Assert.NotNull(sut);
Assert.False(string.IsNullOrWhiteSpace(sut.RoleName));
}
[Fact]
public void Constructor_WhenPassingNullPermissions_ShouldReturnNullPermissions()
{
// Act
AddRoleRequest sut = new(RoleName: "Admin", Permissions: null);
// Assert
Assert.Null(sut.Permissions);
}
[Fact]
public void RoundTrip_WhenSerializingAddRoleRequest_ShouldPreserveValues()
{
// Arrange
List<Guid> permissions = [Guid.NewGuid(), Guid.NewGuid()];
AddRoleRequest expected = new("Admin", permissions);
AddRoleRequest expected = _addRoleRequestFixture.Create();
// Act
string json = JsonSerializer.Serialize(expected, _jsonOptions);
AddRoleRequest? actual = JsonSerializer.Deserialize<AddRoleRequest>(json, _jsonOptions);
// Assert
Assert.NotNull(actual);
Assert.Equivalent(expected, actual);
}
[Fact]
public void RoundTrip_WhenSerializingAddRoleRequestWithNullPermissions_ShouldPreserveNull()
{
// Arrange
AddRoleRequest expected = new("Admin", null);
// Act
string json = JsonSerializer.Serialize(expected, _jsonOptions);
AddRoleRequest? actual = JsonSerializer.Deserialize<AddRoleRequest>(json, _jsonOptions);
// Assert
Assert.NotNull(actual);
Assert.Null(actual.Permissions);
}
}
@@ -1,6 +1,6 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Contracts.Fixtures.Core.Requests.Authorization;
using Lumina.Contracts.Requests.Authorization;
using System;
using System.Diagnostics.CodeAnalysis;
using System.Text.Json;
#endregion
@@ -13,17 +13,39 @@ namespace Lumina.Contracts.UnitTests.Requests.Authorization;
[ExcludeFromCodeCoverage]
public class DeleteRoleRequestTests
{
private readonly DeleteRoleRequestFixture _deleteRoleRequestFixture = new();
private readonly JsonSerializerOptions _jsonOptions = new()
{
PropertyNameCaseInsensitive = true
};
[Fact]
public void Create_WhenCalled_ShouldReturnValidDeleteRoleRequest()
{
// Act
DeleteRoleRequest sut = _deleteRoleRequestFixture.Create();
// Assert
Assert.NotNull(sut);
Assert.True(sut.RoleId.HasValue);
}
[Fact]
public void Constructor_WhenPassingNullRoleId_ShouldReturnNullRoleId()
{
// Act
DeleteRoleRequest sut = new(RoleId: null);
// Assert
Assert.Null(sut.RoleId);
}
[Fact]
public void RoundTrip_WhenSerializingDeleteRoleRequest_ShouldPreserveValues()
{
// Arrange
Guid roleId = Guid.NewGuid();
DeleteRoleRequest expected = new(roleId);
DeleteRoleRequest expected = _deleteRoleRequestFixture.Create();
// Act
string json = JsonSerializer.Serialize(expected, _jsonOptions);
@@ -33,19 +55,4 @@ public class DeleteRoleRequestTests
Assert.NotNull(actual);
Assert.Equal(expected, actual);
}
[Fact]
public void RoundTrip_WhenSerializingDeleteRoleRequestWithNullRoleId_ShouldPreserveNull()
{
// Arrange
DeleteRoleRequest expected = new(null);
// Act
string json = JsonSerializer.Serialize(expected, _jsonOptions);
DeleteRoleRequest? actual = JsonSerializer.Deserialize<DeleteRoleRequest>(json, _jsonOptions);
// Assert
Assert.NotNull(actual);
Assert.Null(actual.RoleId);
}
}
@@ -1,4 +1,5 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Contracts.Fixtures.Core.Requests.Authorization;
using Lumina.Contracts.Requests.Authorization;
using System;
using System.Diagnostics.CodeAnalysis;
@@ -13,17 +14,43 @@ namespace Lumina.Contracts.UnitTests.Requests.Authorization;
[ExcludeFromCodeCoverage]
public class GetRolePermissionsRequestTests
{
private readonly GetRolePermissionsRequestFixture _getRolePermissionsRequestFixture = new();
private readonly JsonSerializerOptions _jsonOptions = new()
{
PropertyNameCaseInsensitive = true
};
[Fact]
public void Create_WhenCalled_ShouldReturnValidGetRolePermissionsRequest()
{
// Act
GetRolePermissionsRequest sut = _getRolePermissionsRequestFixture.Create();
// Assert
Assert.NotNull(sut);
Assert.NotEqual(Guid.Empty, sut.RoleId);
}
[Fact]
public void Equality_WhenTwoInstancesHaveSameValues_ShouldBeEqual()
{
// Arrange
GetRolePermissionsRequest first = _getRolePermissionsRequestFixture.Create();
GetRolePermissionsRequest second = first with { };
// Act
bool areEqual = first == second;
// Assert
Assert.True(areEqual);
}
[Fact]
public void RoundTrip_WhenSerializingGetRolePermissionsRequest_ShouldPreserveValues()
{
// Arrange
Guid roleId = Guid.NewGuid();
GetRolePermissionsRequest expected = new(roleId);
GetRolePermissionsRequest expected = _getRolePermissionsRequestFixture.Create();
// Act
string json = JsonSerializer.Serialize(expected, _jsonOptions);
@@ -33,19 +60,4 @@ public class GetRolePermissionsRequestTests
Assert.NotNull(actual);
Assert.Equal(expected, actual);
}
[Fact]
public void Equality_WhenTwoInstancesHaveSameValues_ShouldBeEqual()
{
// Arrange
Guid roleId = Guid.NewGuid();
GetRolePermissionsRequest first = new(roleId);
GetRolePermissionsRequest second = new(roleId);
// Act
bool areEqual = first == second;
// Assert
Assert.True(areEqual);
}
}
@@ -1,6 +1,6 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Contracts.Fixtures.Core.Requests.Authorization;
using Lumina.Contracts.Requests.Authorization;
using System;
using System.Diagnostics.CodeAnalysis;
using System.Text.Json;
#endregion
@@ -13,17 +13,39 @@ namespace Lumina.Contracts.UnitTests.Requests.Authorization;
[ExcludeFromCodeCoverage]
public class GetUserPermissionsRequestTests
{
private readonly GetUserPermissionsRequestFixture _getUserPermissionsRequestFixture = new();
private readonly JsonSerializerOptions _jsonOptions = new()
{
PropertyNameCaseInsensitive = true
};
[Fact]
public void Create_WhenCalled_ShouldReturnValidGetUserPermissionsRequest()
{
// Act
GetUserPermissionsRequest sut = _getUserPermissionsRequestFixture.Create();
// Assert
Assert.NotNull(sut);
Assert.True(sut.UserId.HasValue);
}
[Fact]
public void Constructor_WhenPassingNullUserId_ShouldReturnNullUserId()
{
// Act
GetUserPermissionsRequest sut = new(UserId: null);
// Assert
Assert.Null(sut.UserId);
}
[Fact]
public void RoundTrip_WhenSerializingGetUserPermissionsRequest_ShouldPreserveValues()
{
// Arrange
Guid userId = Guid.NewGuid();
GetUserPermissionsRequest expected = new(userId);
GetUserPermissionsRequest expected = _getUserPermissionsRequestFixture.Create();
// Act
string json = JsonSerializer.Serialize(expected, _jsonOptions);
@@ -33,19 +55,4 @@ public class GetUserPermissionsRequestTests
Assert.NotNull(actual);
Assert.Equal(expected, actual);
}
[Fact]
public void RoundTrip_WhenSerializingGetUserPermissionsRequestWithNullUserId_ShouldPreserveNull()
{
// Arrange
GetUserPermissionsRequest expected = new(null);
// Act
string json = JsonSerializer.Serialize(expected, _jsonOptions);
GetUserPermissionsRequest? actual = JsonSerializer.Deserialize<GetUserPermissionsRequest>(json, _jsonOptions);
// Assert
Assert.NotNull(actual);
Assert.Null(actual.UserId);
}
}
@@ -1,6 +1,6 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Contracts.Fixtures.Core.Requests.Authorization;
using Lumina.Contracts.Requests.Authorization;
using System;
using System.Diagnostics.CodeAnalysis;
using System.Text.Json;
#endregion
@@ -13,17 +13,39 @@ namespace Lumina.Contracts.UnitTests.Requests.Authorization;
[ExcludeFromCodeCoverage]
public class GetUserRoleRequestTests
{
private readonly GetUserRoleRequestFixture _getUserRoleRequestFixture = new();
private readonly JsonSerializerOptions _jsonOptions = new()
{
PropertyNameCaseInsensitive = true
};
[Fact]
public void Create_WhenCalled_ShouldReturnValidGetUserRoleRequest()
{
// Act
GetUserRoleRequest sut = _getUserRoleRequestFixture.Create();
// Assert
Assert.NotNull(sut);
Assert.True(sut.UserId.HasValue);
}
[Fact]
public void Constructor_WhenPassingNullUserId_ShouldReturnNullUserId()
{
// Act
GetUserRoleRequest sut = new(UserId: null);
// Assert
Assert.Null(sut.UserId);
}
[Fact]
public void RoundTrip_WhenSerializingGetUserRoleRequest_ShouldPreserveValues()
{
// Arrange
Guid userId = Guid.NewGuid();
GetUserRoleRequest expected = new(userId);
GetUserRoleRequest expected = _getUserRoleRequestFixture.Create();
// Act
string json = JsonSerializer.Serialize(expected, _jsonOptions);
@@ -33,19 +55,4 @@ public class GetUserRoleRequestTests
Assert.NotNull(actual);
Assert.Equal(expected, actual);
}
[Fact]
public void RoundTrip_WhenSerializingGetUserRoleRequestWithNullUserId_ShouldPreserveNull()
{
// Arrange
GetUserRoleRequest expected = new(null);
// Act
string json = JsonSerializer.Serialize(expected, _jsonOptions);
GetUserRoleRequest? actual = JsonSerializer.Deserialize<GetUserRoleRequest>(json, _jsonOptions);
// Assert
Assert.NotNull(actual);
Assert.Null(actual.UserId);
}
}
@@ -1,4 +1,5 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Contracts.Fixtures.Core.Requests.MediaLibrary.Management;
using Lumina.Contracts.Requests.MediaLibrary.Management;
using System;
using System.Diagnostics.CodeAnalysis;
@@ -13,18 +14,44 @@ namespace Lumina.Contracts.UnitTests.Requests.MediaLibrary.Management;
[ExcludeFromCodeCoverage]
public class CancelLibraryScanRequestTests
{
private readonly CancelLibraryScanRequestFixture _cancelLibraryScanRequestFixture = new();
private readonly JsonSerializerOptions _jsonOptions = new()
{
PropertyNameCaseInsensitive = true
};
[Fact]
public void Create_WhenCalled_ShouldReturnValidCancelLibraryScanRequest()
{
// Act
CancelLibraryScanRequest sut = _cancelLibraryScanRequestFixture.Create();
// Assert
Assert.NotNull(sut);
Assert.NotEqual(Guid.Empty, sut.LibraryId);
Assert.NotEqual(Guid.Empty, sut.ScanId);
}
[Fact]
public void Equality_WhenTwoInstancesHaveSameValues_ShouldBeEqual()
{
// Arrange
CancelLibraryScanRequest first = _cancelLibraryScanRequestFixture.Create();
CancelLibraryScanRequest second = first with { };
// Act
bool areEqual = first == second;
// Assert
Assert.True(areEqual);
}
[Fact]
public void RoundTrip_WhenSerializingCancelLibraryScanRequest_ShouldPreserveValues()
{
// Arrange
Guid libraryId = Guid.NewGuid();
Guid scanId = Guid.NewGuid();
CancelLibraryScanRequest expected = new(libraryId, scanId);
CancelLibraryScanRequest expected = _cancelLibraryScanRequestFixture.Create();
// Act
string json = JsonSerializer.Serialize(expected, _jsonOptions);
@@ -34,20 +61,4 @@ public class CancelLibraryScanRequestTests
Assert.NotNull(actual);
Assert.Equal(expected, actual);
}
[Fact]
public void Equality_WhenTwoInstancesHaveSameValues_ShouldBeEqual()
{
// Arrange
Guid libraryId = Guid.NewGuid();
Guid scanId = Guid.NewGuid();
CancelLibraryScanRequest first = new(libraryId, scanId);
CancelLibraryScanRequest second = new(libraryId, scanId);
// Act
bool areEqual = first == second;
// Assert
Assert.True(areEqual);
}
}
@@ -1,4 +1,5 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Contracts.Fixtures.Core.Requests.MediaLibrary.Management;
using Lumina.Contracts.Requests.MediaLibrary.Management;
using System;
using System.Diagnostics.CodeAnalysis;
@@ -13,17 +14,43 @@ namespace Lumina.Contracts.UnitTests.Requests.MediaLibrary.Management;
[ExcludeFromCodeCoverage]
public class DeleteLibraryRequestTests
{
private readonly DeleteLibraryRequestFixture _deleteLibraryRequestFixture = new();
private readonly JsonSerializerOptions _jsonOptions = new()
{
PropertyNameCaseInsensitive = true
};
[Fact]
public void Create_WhenCalled_ShouldReturnValidDeleteLibraryRequest()
{
// Act
DeleteLibraryRequest sut = _deleteLibraryRequestFixture.Create();
// Assert
Assert.NotNull(sut);
Assert.NotEqual(Guid.Empty, sut.Id);
}
[Fact]
public void Equality_WhenTwoInstancesHaveSameValues_ShouldBeEqual()
{
// Arrange
DeleteLibraryRequest first = _deleteLibraryRequestFixture.Create();
DeleteLibraryRequest second = first with { };
// Act
bool areEqual = first == second;
// Assert
Assert.True(areEqual);
}
[Fact]
public void RoundTrip_WhenSerializingDeleteLibraryRequest_ShouldPreserveValues()
{
// Arrange
Guid id = Guid.NewGuid();
DeleteLibraryRequest expected = new(id);
DeleteLibraryRequest expected = _deleteLibraryRequestFixture.Create();
// Act
string json = JsonSerializer.Serialize(expected, _jsonOptions);
@@ -33,19 +60,4 @@ public class DeleteLibraryRequestTests
Assert.NotNull(actual);
Assert.Equal(expected, actual);
}
[Fact]
public void Equality_WhenTwoInstancesHaveSameValues_ShouldBeEqual()
{
// Arrange
Guid id = Guid.NewGuid();
DeleteLibraryRequest first = new(id);
DeleteLibraryRequest second = new(id);
// Act
bool areEqual = first == second;
// Assert
Assert.True(areEqual);
}
}
@@ -1,4 +1,5 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Contracts.Fixtures.Core.Requests.MediaLibrary.Management;
using Lumina.Contracts.Requests.MediaLibrary.Management;
using System;
using System.Diagnostics.CodeAnalysis;
@@ -13,17 +14,43 @@ namespace Lumina.Contracts.UnitTests.Requests.MediaLibrary.Management;
[ExcludeFromCodeCoverage]
public class GetLibraryRequestTests
{
private readonly GetLibraryRequestFixture _getLibraryRequestFixture = new();
private readonly JsonSerializerOptions _jsonOptions = new()
{
PropertyNameCaseInsensitive = true
};
[Fact]
public void Create_WhenCalled_ShouldReturnValidGetLibraryRequest()
{
// Act
GetLibraryRequest sut = _getLibraryRequestFixture.Create();
// Assert
Assert.NotNull(sut);
Assert.NotEqual(Guid.Empty, sut.Id);
}
[Fact]
public void Equality_WhenTwoInstancesHaveSameValues_ShouldBeEqual()
{
// Arrange
GetLibraryRequest first = _getLibraryRequestFixture.Create();
GetLibraryRequest second = first with { };
// Act
bool areEqual = first == second;
// Assert
Assert.True(areEqual);
}
[Fact]
public void RoundTrip_WhenSerializingGetLibraryRequest_ShouldPreserveValues()
{
// Arrange
Guid id = Guid.NewGuid();
GetLibraryRequest expected = new(id);
GetLibraryRequest expected = _getLibraryRequestFixture.Create();
// Act
string json = JsonSerializer.Serialize(expected, _jsonOptions);
@@ -33,19 +60,4 @@ public class GetLibraryRequestTests
Assert.NotNull(actual);
Assert.Equal(expected, actual);
}
[Fact]
public void Equality_WhenTwoInstancesHaveSameValues_ShouldBeEqual()
{
// Arrange
Guid id = Guid.NewGuid();
GetLibraryRequest first = new(id);
GetLibraryRequest second = new(id);
// Act
bool areEqual = first == second;
// Assert
Assert.True(areEqual);
}
}
@@ -1,4 +1,5 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Contracts.Fixtures.Core.Requests.MediaLibrary.Management;
using Lumina.Contracts.Requests.MediaLibrary.Management;
using System;
using System.Diagnostics.CodeAnalysis;
@@ -13,18 +14,44 @@ namespace Lumina.Contracts.UnitTests.Requests.MediaLibrary.Management;
[ExcludeFromCodeCoverage]
public class GetLibraryScanProgressRequestTests
{
private readonly GetLibraryScanProgressRequestFixture _getLibraryScanProgressRequestFixture = new();
private readonly JsonSerializerOptions _jsonOptions = new()
{
PropertyNameCaseInsensitive = true
};
[Fact]
public void Create_WhenCalled_ShouldReturnValidGetLibraryScanProgressRequest()
{
// Act
GetLibraryScanProgressRequest sut = _getLibraryScanProgressRequestFixture.Create();
// Assert
Assert.NotNull(sut);
Assert.NotEqual(Guid.Empty, sut.LibraryId);
Assert.NotEqual(Guid.Empty, sut.ScanId);
}
[Fact]
public void Equality_WhenTwoInstancesHaveSameValues_ShouldBeEqual()
{
// Arrange
GetLibraryScanProgressRequest first = _getLibraryScanProgressRequestFixture.Create();
GetLibraryScanProgressRequest second = first with { };
// Act
bool areEqual = first == second;
// Assert
Assert.True(areEqual);
}
[Fact]
public void RoundTrip_WhenSerializingGetLibraryScanProgressRequest_ShouldPreserveValues()
{
// Arrange
Guid libraryId = Guid.NewGuid();
Guid scanId = Guid.NewGuid();
GetLibraryScanProgressRequest expected = new(libraryId, scanId);
GetLibraryScanProgressRequest expected = _getLibraryScanProgressRequestFixture.Create();
// Act
string json = JsonSerializer.Serialize(expected, _jsonOptions);
@@ -34,20 +61,4 @@ public class GetLibraryScanProgressRequestTests
Assert.NotNull(actual);
Assert.Equal(expected, actual);
}
[Fact]
public void Equality_WhenTwoInstancesHaveSameValues_ShouldBeEqual()
{
// Arrange
Guid libraryId = Guid.NewGuid();
Guid scanId = Guid.NewGuid();
GetLibraryScanProgressRequest first = new(libraryId, scanId);
GetLibraryScanProgressRequest second = new(libraryId, scanId);
// Act
bool areEqual = first == second;
// Assert
Assert.True(areEqual);
}
}
@@ -1,4 +1,5 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Contracts.Fixtures.Core.Requests.MediaLibrary.Management;
using Lumina.Contracts.Requests.MediaLibrary.Management;
using System;
using System.Diagnostics.CodeAnalysis;
@@ -13,17 +14,43 @@ namespace Lumina.Contracts.UnitTests.Requests.MediaLibrary.Management;
[ExcludeFromCodeCoverage]
public class ScanLibraryRequestTests
{
private readonly ScanLibraryRequestFixture _scanLibraryRequestFixture = new();
private readonly JsonSerializerOptions _jsonOptions = new()
{
PropertyNameCaseInsensitive = true
};
[Fact]
public void Create_WhenCalled_ShouldReturnValidScanLibraryRequest()
{
// Act
ScanLibraryRequest sut = _scanLibraryRequestFixture.Create();
// Assert
Assert.NotNull(sut);
Assert.NotEqual(Guid.Empty, sut.Id);
}
[Fact]
public void Equality_WhenTwoInstancesHaveSameValues_ShouldBeEqual()
{
// Arrange
ScanLibraryRequest first = _scanLibraryRequestFixture.Create();
ScanLibraryRequest second = first with { };
// Act
bool areEqual = first == second;
// Assert
Assert.True(areEqual);
}
[Fact]
public void RoundTrip_WhenSerializingScanLibraryRequest_ShouldPreserveValues()
{
// Arrange
Guid id = Guid.NewGuid();
ScanLibraryRequest expected = new(id);
ScanLibraryRequest expected = _scanLibraryRequestFixture.Create();
// Act
string json = JsonSerializer.Serialize(expected, _jsonOptions);
@@ -33,19 +60,4 @@ public class ScanLibraryRequestTests
Assert.NotNull(actual);
Assert.Equal(expected, actual);
}
[Fact]
public void Equality_WhenTwoInstancesHaveSameValues_ShouldBeEqual()
{
// Arrange
Guid id = Guid.NewGuid();
ScanLibraryRequest first = new(id);
ScanLibraryRequest second = new(id);
// Act
bool areEqual = first == second;
// Assert
Assert.True(areEqual);
}
}
@@ -1,4 +1,5 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Contracts.Fixtures.Core.Requests.MediaLibrary.WrittenContentLibrary.BookLibrary.Books;
using Lumina.Contracts.Requests.MediaLibrary.WrittenContentLibrary.BookLibrary.Books;
using System.Diagnostics.CodeAnalysis;
using System.Text.Json;
@@ -12,16 +13,39 @@ namespace Lumina.Contracts.UnitTests.Requests.MediaLibrary.WrittenContentLibrary
[ExcludeFromCodeCoverage]
public class GetBookRequestTests
{
private readonly GetBookRequestFixture _getBookRequestFixture = new();
private readonly JsonSerializerOptions _jsonOptions = new()
{
PropertyNameCaseInsensitive = true
};
[Fact]
public void Create_WhenCalled_ShouldReturnValidGetBookRequest()
{
// Act
GetBookRequest sut = _getBookRequestFixture.Create();
// Assert
Assert.NotNull(sut);
Assert.False(string.IsNullOrWhiteSpace(sut.Id));
}
[Fact]
public void Constructor_WhenPassingNullId_ShouldReturnNullId()
{
// Act
GetBookRequest sut = new(Id: null);
// Assert
Assert.Null(sut.Id);
}
[Fact]
public void RoundTrip_WhenSerializingGetBookRequest_ShouldPreserveValues()
{
// Arrange
GetBookRequest expected = new("bookId-123");
GetBookRequest expected = _getBookRequestFixture.Create();
// Act
string json = JsonSerializer.Serialize(expected, _jsonOptions);
@@ -31,19 +55,4 @@ public class GetBookRequestTests
Assert.NotNull(actual);
Assert.Equal(expected, actual);
}
[Fact]
public void RoundTrip_WhenSerializingGetBookRequestWithNullId_ShouldPreserveNull()
{
// Arrange
GetBookRequest expected = new(null);
// Act
string json = JsonSerializer.Serialize(expected, _jsonOptions);
GetBookRequest? actual = JsonSerializer.Deserialize<GetBookRequest>(json, _jsonOptions);
// Assert
Assert.NotNull(actual);
Assert.Null(actual.Id);
}
}
@@ -0,0 +1,49 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Contracts.Fixtures.Core.Requests.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Reading;
using Lumina.Contracts.Requests.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Reading;
using System;
using System.Diagnostics.CodeAnalysis;
using System.Text.Json;
#endregion
namespace Lumina.Contracts.UnitTests.Requests.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Reading;
/// <summary>
/// Contains unit tests for the <see cref="GetReadingAvailabilityRequest"/> record.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetReadingAvailabilityRequestTests
{
private readonly GetReadingAvailabilityRequestFixture _getReadingAvailabilityRequestFixture = new();
private readonly JsonSerializerOptions _jsonOptions = new()
{
PropertyNameCaseInsensitive = true
};
[Fact]
public void Create_WhenCalled_ShouldReturnValidGetReadingAvailabilityRequest()
{
// Act
GetReadingAvailabilityRequest sut = _getReadingAvailabilityRequestFixture.Create();
// Assert
Assert.NotNull(sut);
Assert.NotEqual(Guid.Empty, sut.BookId);
}
[Fact]
public void RoundTrip_WhenSerializingGetReadingAvailabilityRequest_ShouldPreserveValues()
{
// Arrange
GetReadingAvailabilityRequest expected = _getReadingAvailabilityRequestFixture.Create();
// Act
string json = JsonSerializer.Serialize(expected, _jsonOptions);
GetReadingAvailabilityRequest? actual = JsonSerializer.Deserialize<GetReadingAvailabilityRequest>(json, _jsonOptions);
// Assert
Assert.NotNull(actual);
Assert.Equal(expected, actual);
}
}
@@ -0,0 +1,49 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Contracts.Fixtures.Core.Requests.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Reading;
using Lumina.Contracts.Requests.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Reading;
using System;
using System.Diagnostics.CodeAnalysis;
using System.Text.Json;
#endregion
namespace Lumina.Contracts.UnitTests.Requests.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Reading;
/// <summary>
/// Contains unit tests for the <see cref="GetReadingManifestRequest"/> record.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetReadingManifestRequestTests
{
private readonly GetReadingManifestRequestFixture _getReadingManifestRequestFixture = new();
private readonly JsonSerializerOptions _jsonOptions = new()
{
PropertyNameCaseInsensitive = true
};
[Fact]
public void Create_WhenCalled_ShouldReturnValidGetReadingManifestRequest()
{
// Act
GetReadingManifestRequest sut = _getReadingManifestRequestFixture.Create();
// Assert
Assert.NotNull(sut);
Assert.NotEqual(Guid.Empty, sut.BookId);
}
[Fact]
public void RoundTrip_WhenSerializingGetReadingManifestRequest_ShouldPreserveValues()
{
// Arrange
GetReadingManifestRequest expected = _getReadingManifestRequestFixture.Create();
// Act
string json = JsonSerializer.Serialize(expected, _jsonOptions);
GetReadingManifestRequest? actual = JsonSerializer.Deserialize<GetReadingManifestRequest>(json, _jsonOptions);
// Assert
Assert.NotNull(actual);
Assert.Equal(expected, actual);
}
}
@@ -0,0 +1,50 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Contracts.Fixtures.Core.Requests.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Reading;
using Lumina.Contracts.Requests.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Reading;
using System;
using System.Diagnostics.CodeAnalysis;
using System.Text.Json;
#endregion
namespace Lumina.Contracts.UnitTests.Requests.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Reading;
/// <summary>
/// Contains unit tests for the <see cref="GetReadingResourceRequest"/> record.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetReadingResourceRequestTests
{
private readonly GetReadingResourceRequestFixture _getReadingResourceRequestFixture = new();
private readonly JsonSerializerOptions _jsonOptions = new()
{
PropertyNameCaseInsensitive = true
};
[Fact]
public void Create_WhenCalled_ShouldReturnValidGetReadingResourceRequest()
{
// Act
GetReadingResourceRequest sut = _getReadingResourceRequestFixture.Create();
// Assert
Assert.NotNull(sut);
Assert.NotEqual(Guid.Empty, sut.BookId);
Assert.False(string.IsNullOrWhiteSpace(sut.ResourceKey));
}
[Fact]
public void RoundTrip_WhenSerializingGetReadingResourceRequest_ShouldPreserveValues()
{
// Arrange
GetReadingResourceRequest expected = _getReadingResourceRequestFixture.Create();
// Act
string json = JsonSerializer.Serialize(expected, _jsonOptions);
GetReadingResourceRequest? actual = JsonSerializer.Deserialize<GetReadingResourceRequest>(json, _jsonOptions);
// Assert
Assert.NotNull(actual);
Assert.Equal(expected, actual);
}
}
@@ -0,0 +1,50 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Contracts.Fixtures.Core.Requests.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Reading;
using Lumina.Contracts.Requests.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Reading;
using System;
using System.Diagnostics.CodeAnalysis;
using System.Text.Json;
#endregion
namespace Lumina.Contracts.UnitTests.Requests.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Reading;
/// <summary>
/// Contains unit tests for the <see cref="GetReadingSectionRequest"/> record.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetReadingSectionRequestTests
{
private readonly GetReadingSectionRequestFixture _getReadingSectionRequestFixture = new();
private readonly JsonSerializerOptions _jsonOptions = new()
{
PropertyNameCaseInsensitive = true
};
[Fact]
public void Create_WhenCalled_ShouldReturnValidGetReadingSectionRequest()
{
// Act
GetReadingSectionRequest sut = _getReadingSectionRequestFixture.Create();
// Assert
Assert.NotNull(sut);
Assert.NotEqual(Guid.Empty, sut.BookId);
Assert.False(string.IsNullOrWhiteSpace(sut.LocationRef));
}
[Fact]
public void RoundTrip_WhenSerializingGetReadingSectionRequest_ShouldPreserveValues()
{
// Arrange
GetReadingSectionRequest expected = _getReadingSectionRequestFixture.Create();
// Act
string json = JsonSerializer.Serialize(expected, _jsonOptions);
GetReadingSectionRequest? actual = JsonSerializer.Deserialize<GetReadingSectionRequest>(json, _jsonOptions);
// Assert
Assert.NotNull(actual);
Assert.Equal(expected, actual);
}
}
@@ -0,0 +1,49 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Contracts.Fixtures.Core.Requests.Plugins;
using Lumina.Contracts.Requests.Plugins;
using System;
using System.Diagnostics.CodeAnalysis;
using System.Text.Json;
#endregion
namespace Lumina.Contracts.UnitTests.Requests.Plugins;
/// <summary>
/// Contains unit tests for the <see cref="GetLibraryBookReadersRequest"/> record.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetLibraryBookReadersRequestTests
{
private readonly GetLibraryBookReadersRequestFixture _getLibraryBookReadersRequestFixture = new();
private readonly JsonSerializerOptions _jsonOptions = new()
{
PropertyNameCaseInsensitive = true
};
[Fact]
public void Create_WhenCalled_ShouldReturnValidGetLibraryBookReadersRequest()
{
// Act
GetLibraryBookReadersRequest sut = _getLibraryBookReadersRequestFixture.Create();
// Assert
Assert.NotNull(sut);
Assert.NotEqual(Guid.Empty, sut.LibraryId);
}
[Fact]
public void RoundTrip_WhenSerializingGetLibraryBookReadersRequest_ShouldPreserveValues()
{
// Arrange
GetLibraryBookReadersRequest expected = _getLibraryBookReadersRequestFixture.Create();
// Act
string json = JsonSerializer.Serialize(expected, _jsonOptions);
GetLibraryBookReadersRequest? actual = JsonSerializer.Deserialize<GetLibraryBookReadersRequest>(json, _jsonOptions);
// Assert
Assert.NotNull(actual);
Assert.Equal(expected, actual);
}
}
@@ -1,4 +1,5 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Contracts.Fixtures.Core.Requests.Plugins;
using Lumina.Contracts.Requests.Plugins;
using System;
using System.Diagnostics.CodeAnalysis;
@@ -13,17 +14,43 @@ namespace Lumina.Contracts.UnitTests.Requests.Plugins;
[ExcludeFromCodeCoverage]
public class GetLibraryMetadataProvidersRequestTests
{
private readonly GetLibraryMetadataProvidersRequestFixture _getLibraryMetadataProvidersRequestFixture = new();
private readonly JsonSerializerOptions _jsonOptions = new()
{
PropertyNameCaseInsensitive = true
};
[Fact]
public void Create_WhenCalled_ShouldReturnValidGetLibraryMetadataProvidersRequest()
{
// Act
GetLibraryMetadataProvidersRequest sut = _getLibraryMetadataProvidersRequestFixture.Create();
// Assert
Assert.NotNull(sut);
Assert.NotEqual(Guid.Empty, sut.LibraryId);
}
[Fact]
public void Equality_WhenTwoInstancesHaveSameValues_ShouldBeEqual()
{
// Arrange
GetLibraryMetadataProvidersRequest first = _getLibraryMetadataProvidersRequestFixture.Create();
GetLibraryMetadataProvidersRequest second = first with { };
// Act
bool areEqual = first == second;
// Assert
Assert.True(areEqual);
}
[Fact]
public void RoundTrip_WhenSerializingGetLibraryMetadataProvidersRequest_ShouldPreserveValues()
{
// Arrange
Guid libraryId = Guid.NewGuid();
GetLibraryMetadataProvidersRequest expected = new(libraryId);
GetLibraryMetadataProvidersRequest expected = _getLibraryMetadataProvidersRequestFixture.Create();
// Act
string json = JsonSerializer.Serialize(expected, _jsonOptions);
@@ -33,19 +60,4 @@ public class GetLibraryMetadataProvidersRequestTests
Assert.NotNull(actual);
Assert.Equal(expected, actual);
}
[Fact]
public void Equality_WhenTwoInstancesHaveSameValues_ShouldBeEqual()
{
// Arrange
Guid libraryId = Guid.NewGuid();
GetLibraryMetadataProvidersRequest first = new(libraryId);
GetLibraryMetadataProvidersRequest second = new(libraryId);
// Act
bool areEqual = first == second;
// Assert
Assert.True(areEqual);
}
}
@@ -1,4 +1,5 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Contracts.Fixtures.Core.Requests.Plugins;
using Lumina.Contracts.Requests.Plugins;
using System;
using System.Diagnostics.CodeAnalysis;
@@ -13,17 +14,43 @@ namespace Lumina.Contracts.UnitTests.Requests.Plugins;
[ExcludeFromCodeCoverage]
public class GetPluginSettingsRequestTests
{
private readonly GetPluginSettingsRequestFixture _getPluginSettingsRequestFixture = new();
private readonly JsonSerializerOptions _jsonOptions = new()
{
PropertyNameCaseInsensitive = true
};
[Fact]
public void Create_WhenCalled_ShouldReturnValidGetPluginSettingsRequest()
{
// Act
GetPluginSettingsRequest sut = _getPluginSettingsRequestFixture.Create();
// Assert
Assert.NotNull(sut);
Assert.NotEqual(Guid.Empty, sut.PluginId);
}
[Fact]
public void Equality_WhenTwoInstancesHaveSameValues_ShouldBeEqual()
{
// Arrange
GetPluginSettingsRequest first = _getPluginSettingsRequestFixture.Create();
GetPluginSettingsRequest second = first with { };
// Act
bool areEqual = first == second;
// Assert
Assert.True(areEqual);
}
[Fact]
public void RoundTrip_WhenSerializingGetPluginSettingsRequest_ShouldPreserveValues()
{
// Arrange
Guid pluginId = Guid.NewGuid();
GetPluginSettingsRequest expected = new(pluginId);
GetPluginSettingsRequest expected = _getPluginSettingsRequestFixture.Create();
// Act
string json = JsonSerializer.Serialize(expected, _jsonOptions);
@@ -33,19 +60,4 @@ public class GetPluginSettingsRequestTests
Assert.NotNull(actual);
Assert.Equal(expected, actual);
}
[Fact]
public void Equality_WhenTwoInstancesHaveSameValues_ShouldBeEqual()
{
// Arrange
Guid pluginId = Guid.NewGuid();
GetPluginSettingsRequest first = new(pluginId);
GetPluginSettingsRequest second = new(pluginId);
// Act
bool areEqual = first == second;
// Assert
Assert.True(areEqual);
}
}
@@ -1,7 +1,8 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Contracts.Fixtures.Core.Requests.Plugins;
using Lumina.Contracts.Requests.Plugins;
using System;
using System.Collections.Generic;
using System;
using System.Diagnostics.CodeAnalysis;
using System.Text.Json;
#endregion
@@ -14,34 +15,30 @@ namespace Lumina.Contracts.UnitTests.Requests.Plugins;
[ExcludeFromCodeCoverage]
public class ReorderLibraryMetadataProvidersRequestTests
{
private readonly ReorderLibraryMetadataProvidersRequestFixture _reorderLibraryMetadataProvidersRequestFixture = new();
private readonly JsonSerializerOptions _jsonOptions = new()
{
PropertyNameCaseInsensitive = true
};
[Fact]
public void RoundTrip_WhenSerializingReorderLibraryMetadataProvidersRequest_ShouldPreserveValues()
public void Create_WhenCalled_ShouldReturnValidReorderLibraryMetadataProvidersRequest()
{
// Arrange
Guid libraryId = Guid.NewGuid();
List<Guid> pluginIds = [Guid.NewGuid(), Guid.NewGuid()];
ReorderLibraryMetadataProvidersRequest expected = new(libraryId, pluginIds);
// Act
string json = JsonSerializer.Serialize(expected, _jsonOptions);
ReorderLibraryMetadataProvidersRequest? actual = JsonSerializer.Deserialize<ReorderLibraryMetadataProvidersRequest>(json, _jsonOptions);
ReorderLibraryMetadataProvidersRequest sut = _reorderLibraryMetadataProvidersRequestFixture.Create();
// Assert
Assert.NotNull(actual);
Assert.Equivalent(expected, actual);
Assert.NotNull(sut);
Assert.NotEqual(Guid.Empty, sut.LibraryId);
Assert.True(sut.PluginIds.Count > 0);
}
[Fact]
public void Deconstruct_WhenCalled_ShouldReturnAllProperties()
{
// Arrange
Guid libraryId = Guid.NewGuid();
List<Guid> pluginIds = [Guid.NewGuid()];
ReorderLibraryMetadataProvidersRequest sut = new(libraryId, pluginIds);
ReorderLibraryMetadataProvidersRequest sut = _reorderLibraryMetadataProvidersRequestFixture.Create();
// Act
(Guid sutLibraryId, IReadOnlyList<Guid> sutPluginIds) = sut;
@@ -50,4 +47,19 @@ public class ReorderLibraryMetadataProvidersRequestTests
Assert.Equal(sut.LibraryId, sutLibraryId);
Assert.Equal(sut.PluginIds, sutPluginIds);
}
[Fact]
public void RoundTrip_WhenSerializingReorderLibraryMetadataProvidersRequest_ShouldPreserveValues()
{
// Arrange
ReorderLibraryMetadataProvidersRequest expected = _reorderLibraryMetadataProvidersRequestFixture.Create();
// Act
string json = JsonSerializer.Serialize(expected, _jsonOptions);
ReorderLibraryMetadataProvidersRequest? actual = JsonSerializer.Deserialize<ReorderLibraryMetadataProvidersRequest>(json, _jsonOptions);
// Assert
Assert.NotNull(actual);
Assert.Equivalent(expected, actual);
}
}
@@ -0,0 +1,50 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Contracts.Fixtures.Core.Requests.Plugins;
using Lumina.Contracts.Requests.Plugins;
using System;
using System.Diagnostics.CodeAnalysis;
using System.Text.Json;
#endregion
namespace Lumina.Contracts.UnitTests.Requests.Plugins;
/// <summary>
/// Contains unit tests for the <see cref="SetLibraryBookReaderEnabledRequest"/> record.
/// </summary>
[ExcludeFromCodeCoverage]
public class SetLibraryBookReaderEnabledRequestTests
{
private readonly SetLibraryBookReaderEnabledRequestFixture _setLibraryBookReaderEnabledRequestFixture = new();
private readonly JsonSerializerOptions _jsonOptions = new()
{
PropertyNameCaseInsensitive = true
};
[Fact]
public void Create_WhenCalled_ShouldReturnValidSetLibraryBookReaderEnabledRequest()
{
// Act
SetLibraryBookReaderEnabledRequest sut = _setLibraryBookReaderEnabledRequestFixture.Create();
// Assert
Assert.NotNull(sut);
Assert.NotEqual(Guid.Empty, sut.LibraryId);
Assert.NotEqual(Guid.Empty, sut.PluginId);
}
[Fact]
public void RoundTrip_WhenSerializingSetLibraryBookReaderEnabledRequest_ShouldPreserveValues()
{
// Arrange
SetLibraryBookReaderEnabledRequest expected = _setLibraryBookReaderEnabledRequestFixture.Create();
// Act
string json = JsonSerializer.Serialize(expected, _jsonOptions);
SetLibraryBookReaderEnabledRequest? actual = JsonSerializer.Deserialize<SetLibraryBookReaderEnabledRequest>(json, _jsonOptions);
// Assert
Assert.NotNull(actual);
Assert.Equal(expected, actual);
}
}
@@ -1,4 +1,5 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Contracts.Fixtures.Core.Requests.Plugins;
using Lumina.Contracts.Requests.Plugins;
using System;
using System.Diagnostics.CodeAnalysis;
@@ -13,35 +14,30 @@ namespace Lumina.Contracts.UnitTests.Requests.Plugins;
[ExcludeFromCodeCoverage]
public class SetLibraryMetadataProviderEnabledRequestTests
{
private readonly SetLibraryMetadataProviderEnabledRequestFixture _setLibraryMetadataProviderEnabledRequestFixture = new();
private readonly JsonSerializerOptions _jsonOptions = new()
{
PropertyNameCaseInsensitive = true
};
[Fact]
public void RoundTrip_WhenSerializingSetLibraryMetadataProviderEnabledRequest_ShouldPreserveValues()
public void Create_WhenCalled_ShouldReturnValidSetLibraryMetadataProviderEnabledRequest()
{
// Arrange
Guid libraryId = Guid.NewGuid();
Guid pluginId = Guid.NewGuid();
SetLibraryMetadataProviderEnabledRequest expected = new(libraryId, pluginId, true);
// Act
string json = JsonSerializer.Serialize(expected, _jsonOptions);
SetLibraryMetadataProviderEnabledRequest? actual = JsonSerializer.Deserialize<SetLibraryMetadataProviderEnabledRequest>(json, _jsonOptions);
SetLibraryMetadataProviderEnabledRequest sut = _setLibraryMetadataProviderEnabledRequestFixture.Create();
// Assert
Assert.NotNull(actual);
Assert.Equal(expected, actual);
Assert.NotNull(sut);
Assert.NotEqual(Guid.Empty, sut.LibraryId);
Assert.NotEqual(Guid.Empty, sut.PluginId);
}
[Fact]
public void Deconstruct_WhenCalled_ShouldReturnAllProperties()
{
// Arrange
Guid libraryId = Guid.NewGuid();
Guid pluginId = Guid.NewGuid();
SetLibraryMetadataProviderEnabledRequest sut = new(libraryId, pluginId, false);
SetLibraryMetadataProviderEnabledRequest sut = _setLibraryMetadataProviderEnabledRequestFixture.Create();
// Act
(Guid sutLibraryId, Guid sutPluginId, bool isEnabled) = sut;
@@ -51,4 +47,19 @@ public class SetLibraryMetadataProviderEnabledRequestTests
Assert.Equal(sut.PluginId, sutPluginId);
Assert.Equal(sut.IsEnabled, isEnabled);
}
[Fact]
public void RoundTrip_WhenSerializingSetLibraryMetadataProviderEnabledRequest_ShouldPreserveValues()
{
// Arrange
SetLibraryMetadataProviderEnabledRequest expected = _setLibraryMetadataProviderEnabledRequestFixture.Create();
// Act
string json = JsonSerializer.Serialize(expected, _jsonOptions);
SetLibraryMetadataProviderEnabledRequest? actual = JsonSerializer.Deserialize<SetLibraryMetadataProviderEnabledRequest>(json, _jsonOptions);
// Assert
Assert.NotNull(actual);
Assert.Equal(expected, actual);
}
}
@@ -49,11 +49,13 @@ public class UpdateUserSettingsRequestTests
itemsPerPage: 25,
shouldIgnoreThePrefixForAlphaPicker: false,
isThemeCachingEnabled: false,
shouldAggregateMetadataWhenMissing: false
shouldAggregateMetadataWhenMissing: false,
shouldRenderPdfAsImages: true,
shouldPreserveBookStyles: true
);
// Act
(bool isPaginationEnabled, int itemsPerPage, bool shouldIgnoreThePrefixForAlphaPicker, bool isThemeCachingEnabled, bool shouldAggregateMetadataWhenMissing) = sut;
(bool isPaginationEnabled, int itemsPerPage, bool shouldIgnoreThePrefixForAlphaPicker, bool isThemeCachingEnabled, bool shouldAggregateMetadataWhenMissing, bool shouldRenderPdfAsImages, bool shouldPreserveBookStyles) = sut;
// Assert
Assert.Equal(sut.IsPaginationEnabled, isPaginationEnabled);
@@ -61,5 +63,7 @@ public class UpdateUserSettingsRequestTests
Assert.Equal(sut.ShouldIgnoreThePrefixForAlphaPicker, shouldIgnoreThePrefixForAlphaPicker);
Assert.Equal(sut.IsThemeCachingEnabled, isThemeCachingEnabled);
Assert.Equal(sut.ShouldAggregateMetadataWhenMissing, shouldAggregateMetadataWhenMissing);
Assert.Equal(sut.ShouldRenderPdfAsImages, shouldRenderPdfAsImages);
Assert.Equal(sut.ShouldPreserveBookStyles, shouldPreserveBookStyles);
}
}
@@ -0,0 +1,67 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Contracts.Fixtures.Core.Responses.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Reading;
using Lumina.Contracts.Responses.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Reading;
using System.Diagnostics.CodeAnalysis;
using System.Text.Json;
#endregion
namespace Lumina.Contracts.UnitTests.Responses.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Reading;
/// <summary>
/// Contains unit tests for the <see cref="ReadingAvailabilityResponse"/> record.
/// </summary>
[ExcludeFromCodeCoverage]
public class ReadingAvailabilityResponseTests
{
private readonly ReadingAvailabilityResponseFixture _readingAvailabilityResponseFixture = new();
private readonly JsonSerializerOptions _jsonOptions = new()
{
PropertyNameCaseInsensitive = true
};
[Fact]
public void Create_WhenCalled_ShouldReturnValidReadingAvailabilityResponse()
{
// Act
ReadingAvailabilityResponse sut = _readingAvailabilityResponseFixture.Create();
// Assert
Assert.NotNull(sut);
Assert.NotEqual(System.Guid.Empty, sut.BookId);
Assert.NotEqual(System.Guid.Empty, sut.LibraryId);
Assert.True(sut.IsAvailable);
}
[Fact]
public void RoundTrip_WhenSerializingReadingAvailabilityResponse_ShouldPreserveValues()
{
// Arrange
ReadingAvailabilityResponse expected = _readingAvailabilityResponseFixture.Create(isAvailable: true, errorCode: null);
// Act
string json = JsonSerializer.Serialize(expected, _jsonOptions);
ReadingAvailabilityResponse? actual = JsonSerializer.Deserialize<ReadingAvailabilityResponse>(json, _jsonOptions);
// Assert
Assert.NotNull(actual);
Assert.Equal(expected, actual);
}
[Fact]
public void RoundTrip_WhenSerializingReadingAvailabilityResponseWithErrorCode_ShouldPreserveErrorCode()
{
// Arrange
ReadingAvailabilityResponse expected = _readingAvailabilityResponseFixture.Create(isAvailable: false, errorCode: "ReaderDisabled");
// Act
string json = JsonSerializer.Serialize(expected, _jsonOptions);
ReadingAvailabilityResponse? actual = JsonSerializer.Deserialize<ReadingAvailabilityResponse>(json, _jsonOptions);
// Assert
Assert.NotNull(actual);
Assert.Equal(expected, actual);
Assert.False(actual.IsAvailable);
Assert.Equal("ReaderDisabled", actual.ErrorCode);
}
}
@@ -0,0 +1,36 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Contracts.Fixtures.Core.Responses.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Reading;
using Lumina.Contracts.Responses.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Reading;
using System.Diagnostics.CodeAnalysis;
using System.Text.Json;
#endregion
namespace Lumina.Contracts.UnitTests.Responses.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Reading;
/// <summary>
/// Contains unit tests for the <see cref="ReadingManifestResponse"/> record.
/// </summary>
[ExcludeFromCodeCoverage]
public class ReadingManifestResponseTests
{
private readonly ReadingManifestResponseFixture _fixture = new();
private readonly JsonSerializerOptions _jsonOptions = new()
{
PropertyNameCaseInsensitive = true
};
[Fact]
public void RoundTrip_WhenSerializingReadingManifestResponse_ShouldPreserveValues()
{
// Arrange
ReadingManifestResponse expected = _fixture.Create();
// Act
string json = JsonSerializer.Serialize(expected, _jsonOptions);
ReadingManifestResponse? actual = JsonSerializer.Deserialize<ReadingManifestResponse>(json, _jsonOptions);
// Assert
Assert.NotNull(actual);
Assert.Equivalent(expected, actual);
}
}
@@ -0,0 +1,36 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Contracts.Fixtures.Core.Responses.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Reading;
using Lumina.Contracts.Responses.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Reading;
using System.Diagnostics.CodeAnalysis;
using System.Text.Json;
#endregion
namespace Lumina.Contracts.UnitTests.Responses.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Reading;
/// <summary>
/// Contains unit tests for the <see cref="ReadingSpineItemResponse"/> record.
/// </summary>
[ExcludeFromCodeCoverage]
public class ReadingSpineItemResponseTests
{
private readonly ReadingSpineItemResponseFixture _fixture = new();
private readonly JsonSerializerOptions _jsonOptions = new()
{
PropertyNameCaseInsensitive = true
};
[Fact]
public void RoundTrip_WhenSerializingReadingSpineItemResponse_ShouldPreserveValues()
{
// Arrange
ReadingSpineItemResponse expected = _fixture.Create();
// Act
string json = JsonSerializer.Serialize(expected, _jsonOptions);
ReadingSpineItemResponse? actual = JsonSerializer.Deserialize<ReadingSpineItemResponse>(json, _jsonOptions);
// Assert
Assert.NotNull(actual);
Assert.Equal(expected, actual);
}
}
@@ -0,0 +1,36 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Contracts.Fixtures.Core.Responses.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Reading;
using Lumina.Contracts.Responses.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Reading;
using System.Diagnostics.CodeAnalysis;
using System.Text.Json;
#endregion
namespace Lumina.Contracts.UnitTests.Responses.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Reading;
/// <summary>
/// Contains unit tests for the <see cref="ReadingTocEntryResponse"/> record.
/// </summary>
[ExcludeFromCodeCoverage]
public class ReadingTocEntryResponseTests
{
private readonly ReadingTocEntryResponseFixture _fixture = new();
private readonly JsonSerializerOptions _jsonOptions = new()
{
PropertyNameCaseInsensitive = true
};
[Fact]
public void RoundTrip_WhenSerializingReadingTocEntryResponse_ShouldPreserveValues()
{
// Arrange
ReadingTocEntryResponse expected = _fixture.Create();
// Act
string json = JsonSerializer.Serialize(expected, _jsonOptions);
ReadingTocEntryResponse? actual = JsonSerializer.Deserialize<ReadingTocEntryResponse>(json, _jsonOptions);
// Assert
Assert.NotNull(actual);
Assert.Equivalent(expected, actual);
}
}
@@ -0,0 +1,36 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Contracts.Fixtures.Core.Responses.Plugins;
using Lumina.Contracts.Responses.Plugins;
using System.Diagnostics.CodeAnalysis;
using System.Text.Json;
#endregion
namespace Lumina.Contracts.UnitTests.Responses.Plugins;
/// <summary>
/// Contains unit tests for the <see cref="LibraryBookReaderResponse"/> record.
/// </summary>
[ExcludeFromCodeCoverage]
public class LibraryBookReaderResponseTests
{
private readonly LibraryBookReaderResponseFixture _fixture = new();
private readonly JsonSerializerOptions _jsonOptions = new()
{
PropertyNameCaseInsensitive = true
};
[Fact]
public void RoundTrip_WhenSerializingLibraryBookReaderResponse_ShouldPreserveValues()
{
// Arrange
LibraryBookReaderResponse expected = _fixture.Create();
// Act
string json = JsonSerializer.Serialize(expected, _jsonOptions);
LibraryBookReaderResponse? actual = JsonSerializer.Deserialize<LibraryBookReaderResponse>(json, _jsonOptions);
// Assert
Assert.NotNull(actual);
Assert.Equivalent(expected, actual);
}
}
@@ -54,11 +54,13 @@ public class UserSettingsResponseTests
itemsPerPage: 25,
shouldIgnoreThePrefixForAlphaPicker: false,
isThemeCachingEnabled: false,
shouldAggregateMetadataWhenMissing: false
shouldAggregateMetadataWhenMissing: false,
shouldRenderPdfAsImages: true,
shouldPreserveBookStyles: true
);
// Act
(Guid sutUserId, bool isPaginationEnabled, int itemsPerPage, bool shouldIgnoreThePrefixForAlphaPicker, bool isThemeCachingEnabled, bool shouldAggregateMetadataWhenMissing) = sut;
(Guid sutUserId, bool isPaginationEnabled, int itemsPerPage, bool shouldIgnoreThePrefixForAlphaPicker, bool isThemeCachingEnabled, bool shouldAggregateMetadataWhenMissing, bool shouldRenderPdfAsImages, bool shouldPreserveBookStyles) = sut;
// Assert
Assert.Equal(sut.UserId, sutUserId);
@@ -67,5 +69,7 @@ public class UserSettingsResponseTests
Assert.Equal(sut.ShouldIgnoreThePrefixForAlphaPicker, shouldIgnoreThePrefixForAlphaPicker);
Assert.Equal(sut.IsThemeCachingEnabled, isThemeCachingEnabled);
Assert.Equal(sut.ShouldAggregateMetadataWhenMissing, shouldAggregateMetadataWhenMissing);
Assert.Equal(sut.ShouldRenderPdfAsImages, shouldRenderPdfAsImages);
Assert.Equal(sut.ShouldPreserveBookStyles, shouldPreserveBookStyles);
}
}
@@ -0,0 +1,89 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DataAccess.Entities.Plugins;
using Lumina.DataAccess.Core.UoW;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
#endregion
namespace Lumina.DataAccess.UnitTests.Common.Configuration;
/// <summary>
/// Contains unit tests for the <see cref="LibraryBookReaderConfigurationConfiguration"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class LibraryBookReaderConfigurationConfigurationTests
{
private readonly LuminaDbContext _context;
/// <summary>
/// Initializes a new instance of the <see cref="LibraryBookReaderConfigurationConfigurationTests"/> class.
/// </summary>
public LibraryBookReaderConfigurationConfigurationTests()
{
_context = new LuminaDbContext(new DbContextOptionsBuilder<LuminaDbContext>().UseSqlite("Data Source=:memory:").Options);
}
[Fact]
public void Configure_WhenApplied_ShouldSetTableNameAndKey()
{
// Arrange
IEntityType entityType = _context.Model.FindEntityType(typeof(LibraryBookReaderConfigurationEntity))!;
// Act
string? tableName = entityType.GetTableName();
IReadOnlyList<IProperty> keyProperties = entityType.FindPrimaryKey()!.Properties;
// Assert
Assert.Equal("LibraryBookReaderConfigurations", tableName);
Assert.Equal(["Id"], keyProperties.Select(property => property.Name));
}
[Fact]
public void Configure_WhenApplied_ShouldConfigureScalarPropertiesAsRequired()
{
// Arrange
IEntityType entityType = _context.Model.FindEntityType(typeof(LibraryBookReaderConfigurationEntity))!;
// Act
IProperty libraryIdProperty = entityType.GetProperty(nameof(LibraryBookReaderConfigurationEntity.LibraryId));
IProperty pluginIdProperty = entityType.GetProperty(nameof(LibraryBookReaderConfigurationEntity.PluginId));
IProperty isEnabledProperty = entityType.GetProperty(nameof(LibraryBookReaderConfigurationEntity.IsEnabled));
// Assert
Assert.False(libraryIdProperty.IsNullable);
Assert.False(pluginIdProperty.IsNullable);
Assert.False(isEnabledProperty.IsNullable);
}
[Fact]
public void Configure_WhenApplied_ShouldConfigureIndexOnLibraryIdAndPluginId()
{
// Arrange
IEntityType entityType = _context.Model.FindEntityType(typeof(LibraryBookReaderConfigurationEntity))!;
// Act
IIndex index = Assert.Single(entityType.GetIndexes());
// Assert
Assert.Equal([nameof(LibraryBookReaderConfigurationEntity.LibraryId), nameof(LibraryBookReaderConfigurationEntity.PluginId)], index.Properties.Select(property => property.Name));
}
[Fact]
public void Configure_WhenApplied_ShouldConfigureAuditProperties()
{
// Arrange
IEntityType entityType = _context.Model.FindEntityType(typeof(LibraryBookReaderConfigurationEntity))!;
// Act
IProperty createdOnUtcProperty = entityType.GetProperty(nameof(LibraryBookReaderConfigurationEntity.CreatedOnUtc));
IProperty updatedOnUtcProperty = entityType.GetProperty(nameof(LibraryBookReaderConfigurationEntity.UpdatedOnUtc));
// Assert
Assert.False(createdOnUtcProperty.IsNullable);
Assert.Null(updatedOnUtcProperty.GetDefaultValue());
}
}
@@ -0,0 +1,180 @@
#region ========================================================================= USING =====================================================================================
using EntityFrameworkCore.Testing.NSubstitute;
using Lumina.Application.Common.DataAccess.Entities.Plugins;
using Lumina.Application.Fixtures.Common.DataAccess.Entities.Plugins;
using Lumina.DataAccess.Core.Repositories.Plugins;
using Lumina.DataAccess.Core.UoW;
using Lumina.Domain.Common.Primitives;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.DataAccess.UnitTests.Core.Repositories.Plugins;
/// <summary>
/// Contains unit tests for the <see cref="LibraryBookReaderConfigurationRepository"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class LibraryBookReaderConfigurationRepositoryTests
{
private readonly LuminaDbContext _mockContext;
private readonly LibraryBookReaderConfigurationRepository _sut;
private readonly LibraryBookReaderConfigurationEntityFixture _configurationFixture = new();
/// <summary>
/// Initializes a new instance of the <see cref="LibraryBookReaderConfigurationRepositoryTests"/> class.
/// </summary>
public LibraryBookReaderConfigurationRepositoryTests()
{
_mockContext = Create.MockedDbContextFor<LuminaDbContext>();
_sut = new LibraryBookReaderConfigurationRepository(_mockContext);
}
[Fact]
public async Task GetByLibraryIdAsync_WhenCalled_ShouldReturnOnlyConfigurationsOfTheLibrary()
{
// Arrange
Guid libraryId = Guid.NewGuid();
LibraryBookReaderConfigurationEntity configurationOfLibrary = _configurationFixture.Create(libraryId: libraryId);
LibraryBookReaderConfigurationEntity configurationOfAnotherLibrary = _configurationFixture.Create();
_mockContext.LibraryBookReaderConfigurations.AddRange(configurationOfLibrary, configurationOfAnotherLibrary);
await _mockContext.SaveChangesAsync();
// Act
Result<IReadOnlyList<LibraryBookReaderConfigurationEntity>> result = await _sut.GetByLibraryIdAsync(libraryId, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
LibraryBookReaderConfigurationEntity retrievedConfiguration = Assert.Single(result.Value);
Assert.Equal(configurationOfLibrary.PluginId, retrievedConfiguration.PluginId);
}
[Fact]
public async Task GetByLibraryAndPluginIdAsync_WhenConfigurationExists_ShouldReturnIt()
{
// Arrange
LibraryBookReaderConfigurationEntity configuration = _configurationFixture.Create();
_mockContext.LibraryBookReaderConfigurations.Add(configuration);
await _mockContext.SaveChangesAsync();
// Act
Result<LibraryBookReaderConfigurationEntity?> result = await _sut.GetByLibraryAndPluginIdAsync(configuration.LibraryId, configuration.PluginId, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
Assert.Equal(configuration.Id, result.Value!.Id);
}
[Fact]
public async Task GetByLibraryAndPluginIdAsync_WhenConfigurationDoesNotExist_ShouldReturnNull()
{
// Act
Result<LibraryBookReaderConfigurationEntity?> result = await _sut.GetByLibraryAndPluginIdAsync(Guid.NewGuid(), Guid.NewGuid(), CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
Assert.Null(result.Value);
}
[Fact]
public async Task UpsertAsync_WhenConfigurationDoesNotExist_ShouldInsertIt()
{
// Arrange
LibraryBookReaderConfigurationEntity configuration = _configurationFixture.Create();
// Act
Result<Updated> result = await _sut.UpsertAsync(configuration, CancellationToken.None);
await _mockContext.SaveChangesAsync();
// Assert
Assert.False(result.IsFailure);
Assert.Single(_mockContext.LibraryBookReaderConfigurations);
}
[Fact]
public async Task UpsertAsync_WhenConfigurationExists_ShouldUpdateIt()
{
// Arrange
LibraryBookReaderConfigurationEntity configuration = _configurationFixture.Create(isEnabled: false);
_mockContext.LibraryBookReaderConfigurations.Add(configuration);
await _mockContext.SaveChangesAsync();
LibraryBookReaderConfigurationEntity updatedConfiguration = _configurationFixture.Create(libraryId: configuration.LibraryId, pluginId: configuration.PluginId, isEnabled: true);
// Act
Result<Updated> result = await _sut.UpsertAsync(updatedConfiguration, CancellationToken.None);
await _mockContext.SaveChangesAsync();
// Assert
Assert.False(result.IsFailure);
LibraryBookReaderConfigurationEntity retrievedConfiguration = _mockContext.LibraryBookReaderConfigurations.Single();
Assert.True(retrievedConfiguration.IsEnabled);
Assert.Equal(configuration.Id, retrievedConfiguration.Id);
}
[Fact]
public async Task DeleteByLibraryIdAsync_WhenCalled_ShouldRemoveOnlyConfigurationsOfTheLibrary()
{
// Arrange
Guid libraryId = Guid.NewGuid();
LibraryBookReaderConfigurationEntity configurationOfLibrary = _configurationFixture.Create(libraryId: libraryId);
LibraryBookReaderConfigurationEntity configurationOfAnotherLibrary = _configurationFixture.Create();
_mockContext.LibraryBookReaderConfigurations.AddRange(configurationOfLibrary, configurationOfAnotherLibrary);
await _mockContext.SaveChangesAsync();
// Act
Result<Deleted> result = await _sut.DeleteByLibraryIdAsync(libraryId, CancellationToken.None);
await _mockContext.SaveChangesAsync();
// Assert
Assert.False(result.IsFailure);
LibraryBookReaderConfigurationEntity remainingConfiguration = Assert.Single(_mockContext.LibraryBookReaderConfigurations);
Assert.Equal(configurationOfAnotherLibrary.Id, remainingConfiguration.Id);
}
[Fact]
public async Task DeleteByPluginIdAsync_WhenCalled_ShouldRemoveConfigurationsOfThePlugin()
{
// Arrange
Guid pluginId = Guid.NewGuid();
LibraryBookReaderConfigurationEntity configurationOfPlugin = _configurationFixture.Create(pluginId: pluginId);
LibraryBookReaderConfigurationEntity configurationOfAnotherPlugin = _configurationFixture.Create();
_mockContext.LibraryBookReaderConfigurations.AddRange(configurationOfPlugin, configurationOfAnotherPlugin);
await _mockContext.SaveChangesAsync();
// Act
Result<Deleted> result = await _sut.DeleteByPluginIdAsync(pluginId, CancellationToken.None);
await _mockContext.SaveChangesAsync();
// Assert
Assert.False(result.IsFailure);
LibraryBookReaderConfigurationEntity remainingConfiguration = Assert.Single(_mockContext.LibraryBookReaderConfigurations);
Assert.Equal(configurationOfAnotherPlugin.Id, remainingConfiguration.Id);
}
[Fact]
public async Task DeleteByLibraryIdAndPluginIdsAsync_WhenCalled_ShouldRemoveOnlyTheConfigurationsOfTheProvidedPlugins()
{
// Arrange
Guid libraryId = Guid.NewGuid();
Guid removedPluginId = Guid.NewGuid();
Guid keptPluginId = Guid.NewGuid();
LibraryBookReaderConfigurationEntity removedConfiguration = _configurationFixture.Create(libraryId: libraryId, pluginId: removedPluginId);
LibraryBookReaderConfigurationEntity keptConfiguration = _configurationFixture.Create(libraryId: libraryId, pluginId: keptPluginId);
_mockContext.LibraryBookReaderConfigurations.AddRange(removedConfiguration, keptConfiguration);
await _mockContext.SaveChangesAsync();
// Act
Result<Deleted> result = await _sut.DeleteByLibraryIdAndPluginIdsAsync(libraryId, [removedPluginId], CancellationToken.None);
await _mockContext.SaveChangesAsync();
// Assert
Assert.False(result.IsFailure);
LibraryBookReaderConfigurationEntity remainingConfiguration = Assert.Single(_mockContext.LibraryBookReaderConfigurations);
Assert.Equal(keptConfiguration.Id, remainingConfiguration.Id);
}
}
@@ -47,7 +47,7 @@ public class LuminaDbContextTests : IDisposable
// Assert
// The count assertion fails when a table is added or removed, reminding to update the assertions below.
Assert.Equal(28, tableNames.Length);
Assert.Equal(29, tableNames.Length);
Assert.Contains("Books", tableNames);
Assert.Contains("Users", tableNames);
Assert.Contains("UserSettings", tableNames);
@@ -65,6 +65,7 @@ public class LuminaDbContextTests : IDisposable
Assert.Contains("Plugins", tableNames);
Assert.Contains("LibraryMetadataProviderConfigurations", tableNames);
Assert.Contains("LibraryArtworkProviderConfigurations", tableNames);
Assert.Contains("LibraryBookReaderConfigurations", tableNames);
Assert.Contains("Tags", tableNames);
Assert.Contains("Genres", tableNames);
Assert.Contains("LibraryContentLocations", tableNames);
@@ -35,6 +35,8 @@ public class UserSettingsTests
Assert.Equal(48, result.Value.ItemsPerPage);
Assert.False(result.Value.ShouldIgnoreThePrefixForAlphaPicker);
Assert.False(result.Value.ShouldAggregateMetadataWhenMissing);
Assert.False(result.Value.ShouldRenderPdfAsImages);
Assert.True(result.Value.ShouldPreserveBookStyles);
}
[Fact]
@@ -50,6 +52,8 @@ public class UserSettingsTests
Assert.Equal(48, result.Value.ItemsPerPage);
Assert.False(result.Value.ShouldIgnoreThePrefixForAlphaPicker);
Assert.False(result.Value.ShouldAggregateMetadataWhenMissing);
Assert.False(result.Value.ShouldRenderPdfAsImages);
Assert.True(result.Value.ShouldPreserveBookStyles);
}
[Fact]
@@ -73,7 +77,7 @@ public class UserSettingsTests
UserId userId = _userIdFixture.Create();
// Act
Result<UserSettings> result = UserSettings.Create(userId, isPaginationEnabled: false, itemsPerPage: 24, shouldIgnoreThePrefixForAlphaPicker: true, isThemeCachingEnabled: true, shouldAggregateMetadataWhenMissing: true);
Result<UserSettings> result = UserSettings.Create(userId, isPaginationEnabled: false, itemsPerPage: 24, shouldIgnoreThePrefixForAlphaPicker: true, isThemeCachingEnabled: true, shouldAggregateMetadataWhenMissing: true, shouldRenderPdfAsImages: true, shouldPreserveBookStyles: true);
// Assert
Assert.False(result.IsFailure);
@@ -83,6 +87,8 @@ public class UserSettingsTests
Assert.True(result.Value.ShouldIgnoreThePrefixForAlphaPicker);
Assert.True(result.Value.IsThemeCachingEnabled);
Assert.True(result.Value.ShouldAggregateMetadataWhenMissing);
Assert.True(result.Value.ShouldRenderPdfAsImages);
Assert.True(result.Value.ShouldPreserveBookStyles);
}
[Fact]
@@ -108,7 +114,7 @@ public class UserSettingsTests
UserId userId = _userIdFixture.Create();
// Act
Result<UserSettings> result = UserSettings.Create(userId, isPaginationEnabled: true, itemsPerPage: itemsPerPage, shouldIgnoreThePrefixForAlphaPicker: false, isThemeCachingEnabled: true, shouldAggregateMetadataWhenMissing: false);
Result<UserSettings> result = UserSettings.Create(userId, isPaginationEnabled: true, itemsPerPage: itemsPerPage, shouldIgnoreThePrefixForAlphaPicker: false, isThemeCachingEnabled: true, shouldAggregateMetadataWhenMissing: false, shouldRenderPdfAsImages: false, shouldPreserveBookStyles: false);
// Assert
Assert.True(result.IsFailure);
@@ -122,7 +128,7 @@ public class UserSettingsTests
UserSettings userSettings = _userSettingsFixture.Create();
// Act
Result<Updated> result = userSettings.UpdateSettings(isPaginationEnabled: false, itemsPerPage: 12, shouldIgnoreThePrefixForAlphaPicker: true, isThemeCachingEnabled: false, shouldAggregateMetadataWhenMissing: true);
Result<Updated> result = userSettings.UpdateSettings(isPaginationEnabled: false, itemsPerPage: 12, shouldIgnoreThePrefixForAlphaPicker: true, isThemeCachingEnabled: false, shouldAggregateMetadataWhenMissing: true, shouldRenderPdfAsImages: true, shouldPreserveBookStyles: true);
// Assert
Assert.False(result.IsFailure);
@@ -131,6 +137,8 @@ public class UserSettingsTests
Assert.True(userSettings.ShouldIgnoreThePrefixForAlphaPicker);
Assert.False(userSettings.IsThemeCachingEnabled);
Assert.True(userSettings.ShouldAggregateMetadataWhenMissing);
Assert.True(userSettings.ShouldRenderPdfAsImages);
Assert.True(userSettings.ShouldPreserveBookStyles);
}
[Theory]
@@ -142,7 +150,7 @@ public class UserSettingsTests
UserSettings userSettings = _userSettingsFixture.Create();
// Act
Result<Updated> result = userSettings.UpdateSettings(isPaginationEnabled: true, itemsPerPage: itemsPerPage, shouldIgnoreThePrefixForAlphaPicker: false, isThemeCachingEnabled: true, shouldAggregateMetadataWhenMissing: false);
Result<Updated> result = userSettings.UpdateSettings(isPaginationEnabled: true, itemsPerPage: itemsPerPage, shouldIgnoreThePrefixForAlphaPicker: false, isThemeCachingEnabled: true, shouldAggregateMetadataWhenMissing: false, shouldRenderPdfAsImages: false, shouldPreserveBookStyles: false);
// Assert
Assert.True(result.IsFailure);
@@ -7,7 +7,7 @@ using Lumina.Application.Common.DataAccess.Repositories.MediaLibrary;
using Lumina.Application.Common.DataAccess.Repositories.Plugins;
using Lumina.Application.Common.DataAccess.UoW;
using Lumina.Application.Common.Infrastructure.Security;
using Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BooksLibrary.Artwork;
using Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Artwork;
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management;
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary;
using Lumina.Application.Fixtures.Common.DataAccess.Entities.Plugins;
@@ -9,7 +9,7 @@ using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.File
using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.ValueObjects;
using Lumina.Domain.Fixtures.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.ValueObjects;
using Lumina.Domain.SharedKernel.Common.Enums.PhotoLibrary;
using Lumina.Infrastructure.Core.MediaLibrary.WrittenContentLibrary.BooksLibrary.Artwork;
using Lumina.Infrastructure.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Artwork;
using Lumina.Infrastructure.Fixtures.Common.Setup;
using Microsoft.Extensions.Options;
using NSubstitute;
@@ -23,7 +23,7 @@ using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Infrastructure.UnitTests.Core.MediaLibrary.WrittenContentLibrary.BooksLibrary.Artwork;
namespace Lumina.Infrastructure.UnitTests.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Artwork;
/// <summary>
/// Contains unit tests for the <see cref="BookArtworkService"/> class.
@@ -0,0 +1,102 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Infrastructure.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Reading;
using System;
using System.Diagnostics.CodeAnalysis;
#endregion
namespace Lumina.Infrastructure.UnitTests.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Reading;
/// <summary>
/// Contains unit tests for the <see cref="BookReaderEnablementCache"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class BookReaderEnablementCacheTests
{
private readonly BookReaderEnablementCache _sut = new();
[Fact]
public void Get_WhenNothingIsCached_ShouldReturnNull()
{
// Act
bool? result = _sut.Get(Guid.NewGuid(), Guid.NewGuid());
// Assert
Assert.Null(result);
}
[Theory]
[InlineData(true)] // reader enabled
[InlineData(false)] // reader disabled
public void Set_WhenCalled_ThenGetShouldReturnTheCachedValue(bool isEnabled)
{
// Arrange
Guid libraryId = Guid.NewGuid();
Guid pluginId = Guid.NewGuid();
// Act
_sut.Set(libraryId, pluginId, isEnabled);
// Assert
Assert.Equal(isEnabled, _sut.Get(libraryId, pluginId));
}
[Fact]
public void Invalidate_WhenCalled_ShouldRemoveOnlyTheGivenLibraryAndPluginPair()
{
// Arrange
Guid libraryId = Guid.NewGuid();
Guid firstPluginId = Guid.NewGuid();
Guid secondPluginId = Guid.NewGuid();
_sut.Set(libraryId, firstPluginId, isEnabled: true);
_sut.Set(libraryId, secondPluginId, isEnabled: false);
// Act
_sut.Invalidate(libraryId, firstPluginId);
// Assert
Assert.Null(_sut.Get(libraryId, firstPluginId));
Assert.False(_sut.Get(libraryId, secondPluginId));
}
[Fact]
public void InvalidateLibrary_WhenCalled_ShouldRemoveEveryEntryOfTheLibraryAndKeepTheOthers()
{
// Arrange
Guid libraryId = Guid.NewGuid();
Guid otherLibraryId = Guid.NewGuid();
Guid pluginId = Guid.NewGuid();
Guid otherPluginId = Guid.NewGuid();
_sut.Set(libraryId, pluginId, isEnabled: true);
_sut.Set(libraryId, otherPluginId, isEnabled: false);
_sut.Set(otherLibraryId, pluginId, isEnabled: true);
// Act
_sut.InvalidateLibrary(libraryId);
// Assert
Assert.Null(_sut.Get(libraryId, pluginId));
Assert.Null(_sut.Get(libraryId, otherPluginId));
Assert.True(_sut.Get(otherLibraryId, pluginId));
}
[Fact]
public void InvalidatePlugin_WhenCalled_ShouldRemoveEveryEntryOfThePluginAndKeepTheOthers()
{
// Arrange
Guid libraryId = Guid.NewGuid();
Guid otherLibraryId = Guid.NewGuid();
Guid pluginId = Guid.NewGuid();
Guid otherPluginId = Guid.NewGuid();
_sut.Set(libraryId, pluginId, isEnabled: true);
_sut.Set(otherLibraryId, pluginId, isEnabled: false);
_sut.Set(libraryId, otherPluginId, isEnabled: true);
// Act
_sut.InvalidatePlugin(pluginId);
// Assert
Assert.Null(_sut.Get(libraryId, pluginId));
Assert.Null(_sut.Get(otherLibraryId, pluginId));
Assert.True(_sut.Get(libraryId, otherPluginId));
}
}
@@ -0,0 +1,146 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.Infrastructure.Plugins;
using Lumina.Application.Common.Infrastructure.Reading;
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
using Lumina.Infrastructure.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Reading;
using Lumina.Plugins.Contracts.Core.Plugins;
using Lumina.Plugins.Contracts.Core.Reading;
using Microsoft.Extensions.DependencyInjection;
using NSubstitute;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
#endregion
namespace Lumina.Infrastructure.UnitTests.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Reading;
/// <summary>
/// Contains unit tests for the <see cref="BookReaderRegistry"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class BookReaderRegistryTests
{
private readonly IPluginManager _mockPluginManager;
private readonly IServiceProvider _serviceProvider;
private readonly BookReaderRegistry _sut;
private readonly Guid _pluginId = Guid.NewGuid();
/// <summary>
/// Initializes a new instance of the <see cref="BookReaderRegistryTests"/> class.
/// </summary>
public BookReaderRegistryTests()
{
_mockPluginManager = Substitute.For<IPluginManager>();
_serviceProvider = new ServiceCollection().BuildServiceProvider();
_sut = new BookReaderRegistry(_mockPluginManager, _serviceProvider);
}
[Fact]
public void GetSupportedExtensionsByPluginId_WhenReadersAreRegistered_ShouldReturnExtensionsKeyedByPluginId()
{
// Arrange
IPlugin plugin = CreatePlugin(_pluginId, "Test Plugin");
IBookReader reader = CreateReader(".epub", ".EPUB");
_mockPluginManager.GetPlugins().Returns([plugin]);
ServiceProvider serviceProvider = BuildServiceProviderWithReaders(plugin.Id, reader);
// Act
IReadOnlyDictionary<Guid, IReadOnlyList<string>> result = new BookReaderRegistry(_mockPluginManager, serviceProvider).GetSupportedExtensionsByPluginId();
// Assert
IReadOnlyList<string> extensions = Assert.Single(result.Values);
Assert.Equal([".epub"], extensions);
}
[Fact]
public void GetSupportedExtensionsByPluginId_WhenReaderHasNoUsableExtensions_ShouldSkipThePlugin()
{
// Arrange
IPlugin plugin = CreatePlugin(_pluginId, "Test Plugin");
IBookReader reader = CreateReader(string.Empty);
_mockPluginManager.GetPlugins().Returns([plugin]);
ServiceProvider serviceProvider = BuildServiceProviderWithReaders(plugin.Id, reader);
// Act
IReadOnlyDictionary<Guid, IReadOnlyList<string>> result = new BookReaderRegistry(_mockPluginManager, serviceProvider).GetSupportedExtensionsByPluginId();
// Assert
Assert.Empty(result);
}
[Fact]
public void GetSupportedExtensionsByPluginId_WhenNoReadersAreRegistered_ShouldReturnEmptyDictionary()
{
// Arrange
_mockPluginManager.GetPlugins().Returns([]);
// Act
IReadOnlyDictionary<Guid, IReadOnlyList<string>> result = _sut.GetSupportedExtensionsByPluginId();
// Assert
Assert.Empty(result);
}
[Fact]
public void GetSupportedExtensionsByPluginId_WhenMultipleReadersOfOnePlugin_ShouldMergeAndDistinctExtensions()
{
// Arrange
IPlugin plugin = CreatePlugin(_pluginId, "Test Plugin");
IBookReader firstReader = CreateReader(".pdf");
IBookReader secondReader = CreateReader(".pdf", ".epub");
_mockPluginManager.GetPlugins().Returns([plugin]);
ServiceCollection services = new();
services.AddKeyedSingleton(plugin.Id, firstReader);
services.AddKeyedSingleton(plugin.Id, secondReader);
ServiceProvider serviceProvider = services.BuildServiceProvider();
// Act
IReadOnlyDictionary<Guid, IReadOnlyList<string>> result = new BookReaderRegistry(_mockPluginManager, serviceProvider).GetSupportedExtensionsByPluginId();
// Assert
IReadOnlyList<string> extensions = Assert.Single(result.Values);
Assert.Equal([".epub", ".pdf"], extensions);
}
/// <summary>
/// Creates a mocked plugin with the provided identity.
/// </summary>
/// <param name="id">The Id of the plugin.</param>
/// <param name="name">The name of the plugin.</param>
/// <returns>The created plugin mock.</returns>
private static IPlugin CreatePlugin(Guid id, string name)
{
IPlugin plugin = Substitute.For<IPlugin>();
plugin.Id.Returns(id);
plugin.Name.Returns(name);
return plugin;
}
/// <summary>
/// Creates a mocked book reader with the provided extensions.
/// </summary>
/// <param name="extensions">The supported extensions of the reader.</param>
/// <returns>The created reader mock.</returns>
private static IBookReader CreateReader(params string[] extensions)
{
IBookReader reader = Substitute.For<IBookReader>();
reader.SupportedExtensions.Returns(extensions);
reader.SupportedLibraryTypes.Returns([LibraryType.EBook]);
return reader;
}
/// <summary>
/// Builds a service provider in which the provided readers are registered as keyed services of the plugin.
/// </summary>
/// <param name="pluginId">The Id of the plugin providing the readers.</param>
/// <param name="readers">The readers to register.</param>
/// <returns>The built service provider.</returns>
private static ServiceProvider BuildServiceProviderWithReaders(Guid pluginId, params IBookReader[] readers)
{
ServiceCollection services = new();
foreach (IBookReader reader in readers)
services.AddKeyedSingleton<IBookReader>(pluginId, reader);
return services.BuildServiceProvider();
}
}
@@ -0,0 +1,816 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DataAccess.Entities.Plugins;
using Lumina.Application.Common.DataAccess.Repositories.Plugins;
using Lumina.Application.Common.DataAccess.UoW;
using Lumina.Application.Common.Infrastructure.Plugins;
using Lumina.Application.Common.Infrastructure.Reading;
using Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Reading;
using Lumina.Application.Fixtures.Common.DataAccess.Entities.Plugins;
using Lumina.Contracts.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary.Reading;
using Lumina.Contracts.Fixtures.Core.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary.Reading;
using Lumina.Contracts.Responses.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Reading;
using Lumina.Domain.Common.Errors;
using Lumina.Domain.Common.Primitives;
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
using Lumina.Infrastructure.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Reading;
using Lumina.Plugins.Contracts.Core.Plugins;
using Lumina.Plugins.Contracts.Core.Reading;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using NSubstitute;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.IO;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Infrastructure.UnitTests.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Reading;
/// <summary>
/// Contains unit tests for the <see cref="BookReadingService"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class BookReadingServiceTests : IDisposable
{
private readonly IPluginManager _mockPluginManager;
private readonly IPlugin _mockPlugin;
private readonly IBookReader _mockReader;
private readonly IUnitOfWork _mockUnitOfWork;
private readonly ILibraryBookReaderConfigurationRepository _mockConfigurationRepository;
private readonly IServiceProvider _serviceProvider;
private readonly BookReadingService _sut;
private readonly TestBookReaderEnablementCache _enablementCache = new();
private readonly Guid _pluginId = Guid.NewGuid();
private readonly Guid _bookId = Guid.NewGuid();
private readonly Guid _libraryId = Guid.NewGuid();
private readonly string _bookPath;
private readonly ReadingDocumentDtoFixture _readingDocumentDtoFixture = new();
private readonly ReadingSpineItemDtoFixture _readingSpineItemDtoFixture = new();
private readonly ReadingResourceInfoDtoFixture _readingResourceInfoDtoFixture = new();
private readonly LibraryBookReaderConfigurationEntityFixture _configurationEntityFixture = new();
/// <summary>
/// Initializes a new instance of the <see cref="BookReadingServiceTests"/> class.
/// </summary>
public BookReadingServiceTests()
{
_mockReader = Substitute.For<IBookReader>();
_mockReader.SupportedExtensions.Returns([".epub"]);
_mockReader.SupportedLibraryTypes.Returns([LibraryType.EBook]);
_mockPlugin = Substitute.For<IPlugin>();
_mockPlugin.Id.Returns(_pluginId);
_mockPlugin.Name.Returns("Test Reader");
_mockPluginManager = Substitute.For<IPluginManager>();
_mockPluginManager.GetPlugins().Returns([_mockPlugin]);
_mockUnitOfWork = Substitute.For<IUnitOfWork>();
_mockConfigurationRepository = Substitute.For<ILibraryBookReaderConfigurationRepository>();
_mockUnitOfWork.LibraryBookReaderConfigurationRepository.Returns(_mockConfigurationRepository);
LibraryBookReaderConfigurationEntity enabledConfiguration = _configurationEntityFixture.Create(libraryId: _libraryId, pluginId: _pluginId, isEnabled: true);
_mockConfigurationRepository.GetByLibraryAndPluginIdAsync(_libraryId, _pluginId, Arg.Any<CancellationToken>())
.Returns(Result.From<LibraryBookReaderConfigurationEntity?>(enabledConfiguration));
ServiceCollection services = new();
services.AddKeyedSingleton(_pluginId, _mockReader);
services.AddSingleton(_mockUnitOfWork);
_serviceProvider = services.BuildServiceProvider();
IServiceScopeFactory serviceScopeFactory = _serviceProvider.GetRequiredService<IServiceScopeFactory>();
_bookPath = Path.Combine(Path.GetTempPath(), $"lumina-test-book-{Guid.NewGuid():N}.epub");
File.WriteAllText(_bookPath, "test epub content");
_sut = new BookReadingService(_serviceProvider, _mockPluginManager, _enablementCache, serviceScopeFactory, Substitute.For<ILogger<BookReadingService>>());
}
[Fact]
public async Task GetManifestAsync_WhenBookIsNotCached_ShouldExtractAndReturnTheManifest()
{
// Arrange
ReadingDocumentDto document = CreateExtractableDocument();
StubOpenAsyncToExtract(document);
CancellationToken cancellationToken = CancellationToken.None;
// Act
Result<ReadingManifestResponse> result = await _sut.GetManifestAsync(_bookId, _libraryId, _bookPath, LibraryType.EBook, shouldRenderPdfAsImages: false, cancellationToken);
// Assert
Assert.False(result.IsFailure);
Assert.Equal(document.Title, result.Value.Title);
Assert.Equal(document.Author, result.Value.Author);
await _mockReader.Received(1).OpenAsync(_bookPath, Arg.Any<string>(), Arg.Any<bool>(), cancellationToken);
}
[Fact]
public async Task GetManifestAsync_WhenFileIsUnchanged_ShouldReuseTheCachedDocument()
{
// Arrange
ReadingDocumentDto document = CreateExtractableDocument();
StubOpenAsyncToExtract(document);
CancellationToken cancellationToken = CancellationToken.None;
// Act
await _sut.GetManifestAsync(_bookId, _libraryId, _bookPath, LibraryType.EBook, shouldRenderPdfAsImages: false, cancellationToken);
Result<ReadingManifestResponse> secondResult = await _sut.GetManifestAsync(_bookId, _libraryId, _bookPath, LibraryType.EBook, shouldRenderPdfAsImages: false, cancellationToken);
// Assert
Assert.False(secondResult.IsFailure);
await _mockReader.Received(1).OpenAsync(Arg.Any<string>(), Arg.Any<string>(), Arg.Any<bool>(), Arg.Any<CancellationToken>());
}
[Fact]
public async Task GetManifestAsync_WhenFileChanged_ShouldReExtractTheBook()
{
// Arrange
ReadingDocumentDto document = CreateExtractableDocument();
StubOpenAsyncToExtract(document);
CancellationToken cancellationToken = CancellationToken.None;
// Act
await _sut.GetManifestAsync(_bookId, _libraryId, _bookPath, LibraryType.EBook, shouldRenderPdfAsImages: false, cancellationToken);
File.WriteAllText(_bookPath, "modified epub content, longer than before");
Result<ReadingManifestResponse> secondResult = await _sut.GetManifestAsync(_bookId, _libraryId, _bookPath, LibraryType.EBook, shouldRenderPdfAsImages: false, cancellationToken);
// Assert
Assert.False(secondResult.IsFailure);
await _mockReader.Received(2).OpenAsync(Arg.Any<string>(), Arg.Any<string>(), Arg.Any<bool>(), Arg.Any<CancellationToken>());
}
[Fact]
public async Task GetManifestAsync_WhenRenderingPreferenceDiffers_ShouldExtractTheBookTwice()
{
// Arrange
ReadingDocumentDto document = CreateExtractableDocument();
StubOpenAsyncToExtract(document);
CancellationToken cancellationToken = CancellationToken.None;
// Act
await _sut.GetManifestAsync(_bookId, _libraryId, _bookPath, LibraryType.EBook, shouldRenderPdfAsImages: false, cancellationToken);
Result<ReadingManifestResponse> secondResult = await _sut.GetManifestAsync(_bookId, _libraryId, _bookPath, LibraryType.EBook, shouldRenderPdfAsImages: true, cancellationToken);
// Assert
Assert.False(secondResult.IsFailure);
await _mockReader.Received(2).OpenAsync(Arg.Any<string>(), Arg.Any<string>(), Arg.Any<bool>(), Arg.Any<CancellationToken>());
await _mockReader.Received(1).OpenAsync(Arg.Any<string>(), Arg.Any<string>(), false, Arg.Any<CancellationToken>());
await _mockReader.Received(1).OpenAsync(Arg.Any<string>(), Arg.Any<string>(), true, Arg.Any<CancellationToken>());
}
[Fact]
public async Task GetManifestAsync_WhenBothRenderingPreferencesAreExtracted_ShouldKeepTheirWorkingDirectoriesSeparate()
{
// Arrange
ReadingDocumentDto document = CreateExtractableDocument();
StubOpenAsyncToExtract(document);
CancellationToken cancellationToken = CancellationToken.None;
// Act
await _sut.GetManifestAsync(_bookId, _libraryId, _bookPath, LibraryType.EBook, shouldRenderPdfAsImages: false, cancellationToken);
await _sut.GetManifestAsync(_bookId, _libraryId, _bookPath, LibraryType.EBook, shouldRenderPdfAsImages: true, cancellationToken);
// The text extraction must survive the image extraction of the same book, and still be served from the cache.
Result<ReadingManifestResponse> thirdResult = await _sut.GetManifestAsync(_bookId, _libraryId, _bookPath, LibraryType.EBook, shouldRenderPdfAsImages: false, cancellationToken);
// Assert
Assert.False(thirdResult.IsFailure);
string textWorkingDirectory = Path.Combine(ReadingCachePaths.GetRootDirectory(), _bookId.ToString("N"), "text");
string imageWorkingDirectory = Path.Combine(ReadingCachePaths.GetRootDirectory(), _bookId.ToString("N"), "images");
Assert.True(File.Exists(Path.Combine(textWorkingDirectory, "sections", "0.html")));
Assert.True(File.Exists(Path.Combine(imageWorkingDirectory, "sections", "0.html")));
await _mockReader.Received(2).OpenAsync(Arg.Any<string>(), Arg.Any<string>(), Arg.Any<bool>(), Arg.Any<CancellationToken>());
}
[Fact]
public async Task GetManifestAsync_WhenConcurrentRequests_ShouldShareASingleExtraction()
{
// Arrange
ReadingDocumentDto document = CreateExtractableDocument();
TaskCompletionSource<bool> extractionStarted = new();
TaskCompletionSource<bool> allowExtractionToFinish = new();
_mockReader.OpenAsync(Arg.Any<string>(), Arg.Any<string>(), Arg.Any<bool>(), Arg.Any<CancellationToken>())
.Returns(callInfo => Task.Run(async () =>
{
extractionStarted.SetResult(true);
await allowExtractionToFinish.Task;
return document;
}));
// Act
Task<Result<ReadingManifestResponse>> firstTask = _sut.GetManifestAsync(_bookId, _libraryId, _bookPath, LibraryType.EBook, shouldRenderPdfAsImages: false, CancellationToken.None);
await extractionStarted.Task;
Task<Result<ReadingManifestResponse>> secondTask = _sut.GetManifestAsync(_bookId, _libraryId, _bookPath, LibraryType.EBook, shouldRenderPdfAsImages: false, CancellationToken.None);
allowExtractionToFinish.SetResult(true);
Result<ReadingManifestResponse> firstResult = await firstTask;
Result<ReadingManifestResponse> secondResult = await secondTask;
// Assert
Assert.False(firstResult.IsFailure);
Assert.False(secondResult.IsFailure);
await _mockReader.Received(1).OpenAsync(Arg.Any<string>(), Arg.Any<string>(), Arg.Any<bool>(), Arg.Any<CancellationToken>());
}
[Fact]
public async Task GetManifestAsync_WhenNoReaderSupportsTheFormat_ShouldReturnNoReaderAvailableError()
{
// Arrange
_mockPluginManager.GetPlugins().Returns([]);
// Act
Result<ReadingManifestResponse> result = await _sut.GetManifestAsync(_bookId, _libraryId, _bookPath, LibraryType.EBook, shouldRenderPdfAsImages: false, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(Errors.Reading.NoReaderAvailable, result.FirstError);
await _mockReader.DidNotReceive().OpenAsync(Arg.Any<string>(), Arg.Any<string>(), Arg.Any<bool>(), Arg.Any<CancellationToken>());
}
[Fact]
public async Task GetManifestAsync_WhenReaderIsDisabledForTheLibrary_ShouldReturnReaderDisabledError()
{
// Arrange
_mockConfigurationRepository.GetByLibraryAndPluginIdAsync(_libraryId, _pluginId, Arg.Any<CancellationToken>())
.Returns(Result.From<LibraryBookReaderConfigurationEntity?>(null));
// Act
Result<ReadingManifestResponse> result = await _sut.GetManifestAsync(_bookId, _libraryId, _bookPath, LibraryType.EBook, shouldRenderPdfAsImages: false, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(Errors.Reading.ReaderDisabled, result.FirstError);
await _mockReader.DidNotReceive().OpenAsync(Arg.Any<string>(), Arg.Any<string>(), Arg.Any<bool>(), Arg.Any<CancellationToken>());
}
[Fact]
public async Task GetSectionAsync_WhenSectionExists_ShouldReturnSanitizedContent()
{
// Arrange
ReadingDocumentDto document = CreateExtractableDocument();
StubOpenAsyncToExtract(document);
CancellationToken cancellationToken = CancellationToken.None;
// Act
Result<ReadingSectionDto> result = await _sut.GetSectionAsync(_bookId, _libraryId, _bookPath, LibraryType.EBook, "section-1", shouldRenderPdfAsImages: false, shouldPreserveStyles: false, cancellationToken);
// Assert
Assert.False(result.IsFailure);
Assert.Equal("section-1", result.Value.LocationRef);
Assert.Contains("Chapter 1", result.Value.ContentHtml, StringComparison.Ordinal);
}
[Fact]
public async Task GetSectionAsync_WhenSectionDoesNotExist_ShouldReturnSectionNotFoundError()
{
// Arrange
ReadingDocumentDto document = CreateExtractableDocument();
StubOpenAsyncToExtract(document);
// Act
Result<ReadingSectionDto> result = await _sut.GetSectionAsync(_bookId, _libraryId, _bookPath, LibraryType.EBook, "missing-section", shouldRenderPdfAsImages: false, shouldPreserveStyles: false, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(Errors.Reading.SectionNotFound, result.FirstError);
}
[Fact]
public async Task GetSectionAsync_WhenSectionFileDoesNotExist_ShouldReturnSectionNotFoundError()
{
// Arrange
ReadingDocumentDto document = _readingDocumentDtoFixture.Create(
title: "Test Book",
tableOfContents: [],
spine:
[
_readingSpineItemDtoFixture.Create(locationRef: "section-1", title: "Chapter 1", relativeSectionFilePath: "sections/missing.html")
],
resources: new Dictionary<string, ReadingResourceInfoDto>()
);
StubOpenAsyncToExtract(document);
// Act
Result<ReadingSectionDto> result = await _sut.GetSectionAsync(_bookId, _libraryId, _bookPath, LibraryType.EBook, "section-1", shouldRenderPdfAsImages: false, shouldPreserveStyles: false, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(Errors.Reading.SectionNotFound, result.FirstError);
}
[Fact]
public async Task GetSectionAsync_WhenSectionPathEscapesTheWorkingDirectory_ShouldReturnSectionNotFoundError()
{
// Arrange
ReadingDocumentDto document = _readingDocumentDtoFixture.Create(
title: "Test Book",
tableOfContents: [],
spine:
[
_readingSpineItemDtoFixture.Create(locationRef: "section-1", title: "Chapter 1", relativeSectionFilePath: "../../escape.html")
],
resources: new Dictionary<string, ReadingResourceInfoDto>()
);
StubOpenAsyncToExtract(document);
// Act
Result<ReadingSectionDto> result = await _sut.GetSectionAsync(_bookId, _libraryId, _bookPath, LibraryType.EBook, "section-1", shouldRenderPdfAsImages: false, shouldPreserveStyles: false, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(Errors.Reading.SectionNotFound, result.FirstError);
}
[Fact]
public async Task GetResourceAsync_WhenResourceDoesNotExistInTheDocument_ShouldReturnResourceNotFoundError()
{
// Arrange
ReadingDocumentDto document = CreateExtractableDocument();
StubOpenAsyncToExtract(document);
// Act
Result<ReadingResourceDataDto> result = await _sut.GetResourceAsync(_bookId, _libraryId, _bookPath, LibraryType.EBook, "missing-key", shouldRenderPdfAsImages: false, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(Errors.Reading.ResourceNotFound, result.FirstError);
await _mockReader.DidNotReceive().GetResourceAsync(Arg.Any<string>(), Arg.Any<string>(), Arg.Any<string>(), Arg.Any<CancellationToken>());
}
[Fact]
public async Task GetResourceAsync_WhenResourcePathEscapesTheWorkingDirectory_ShouldReturnResourceNotFoundError()
{
// Arrange
ReadingDocumentDto document = _readingDocumentDtoFixture.Create(
title: "Test Book",
tableOfContents: [],
spine: [],
resources: new Dictionary<string, ReadingResourceInfoDto>
{
["escaping"] = _readingResourceInfoDtoFixture.Create(relativeFilePath: "../../escape.png", mimeType: "image/png")
}
);
StubOpenAsyncToExtract(document);
// Act
Result<ReadingResourceDataDto> result = await _sut.GetResourceAsync(_bookId, _libraryId, _bookPath, LibraryType.EBook, "escaping", shouldRenderPdfAsImages: false, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(Errors.Reading.ResourceNotFound, result.FirstError);
await _mockReader.DidNotReceive().GetResourceAsync(Arg.Any<string>(), Arg.Any<string>(), Arg.Any<string>(), Arg.Any<CancellationToken>());
}
[Fact]
public async Task GetResourceAsync_WhenResourceFileAlreadyExists_ShouldServeItFromDiskWithoutCallingTheReader()
{
// Arrange
ReadingDocumentDto document = CreateExtractableDocument();
StubOpenAsyncToExtract(document);
await _sut.GetManifestAsync(_bookId, _libraryId, _bookPath, LibraryType.EBook, shouldRenderPdfAsImages: false, CancellationToken.None);
string workingDirectory = Path.Combine(ReadingCachePaths.GetRootDirectory(), _bookId.ToString("N"), "text");
string resourceFilePath = Path.Combine(workingDirectory, "resources", "cover.png");
Directory.CreateDirectory(Path.GetDirectoryName(resourceFilePath)!);
File.WriteAllBytes(resourceFilePath, [1, 2, 3]);
// Act
Result<ReadingResourceDataDto> result = await _sut.GetResourceAsync(_bookId, _libraryId, _bookPath, LibraryType.EBook, "cover", shouldRenderPdfAsImages: false, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
Assert.Equal(new byte[] { 1, 2, 3 }, result.Value.Data);
Assert.Equal("image/png", result.Value.MimeType);
await _mockReader.DidNotReceive().GetResourceAsync(Arg.Any<string>(), Arg.Any<string>(), Arg.Any<string>(), Arg.Any<CancellationToken>());
}
[Fact]
public async Task GetResourceAsync_WhenResourceFileDoesNotExist_ShouldProduceItAndCacheItToDisk()
{
// Arrange
ReadingDocumentDto document = CreateExtractableDocument();
StubOpenAsyncToExtract(document);
byte[] producedResource = [4, 5, 6];
_mockReader.GetResourceAsync(Arg.Any<string>(), Arg.Any<string>(), "cover", Arg.Any<CancellationToken>()).Returns(producedResource);
// Act
Result<ReadingResourceDataDto> firstResult = await _sut.GetResourceAsync(_bookId, _libraryId, _bookPath, LibraryType.EBook, "cover", shouldRenderPdfAsImages: false, CancellationToken.None);
Result<ReadingResourceDataDto> secondResult = await _sut.GetResourceAsync(_bookId, _libraryId, _bookPath, LibraryType.EBook, "cover", shouldRenderPdfAsImages: false, CancellationToken.None);
// Assert
Assert.False(firstResult.IsFailure);
Assert.Equal(new byte[] { 4, 5, 6 }, firstResult.Value.Data);
Assert.Equal("image/png", firstResult.Value.MimeType);
Assert.False(secondResult.IsFailure);
Assert.Equal(new byte[] { 4, 5, 6 }, secondResult.Value.Data);
Assert.Equal("image/png", secondResult.Value.MimeType);
await _mockReader.Received(1).GetResourceAsync(_bookPath, Arg.Any<string>(), "cover", Arg.Any<CancellationToken>());
string cachedFilePath = Path.Combine(ReadingCachePaths.GetRootDirectory(), _bookId.ToString("N"), "text", "resources", "cover.png");
Assert.True(File.Exists(cachedFilePath));
Assert.Equal(new byte[] { 4, 5, 6 }, File.ReadAllBytes(cachedFilePath));
}
[Fact]
public async Task GetResourceAsync_WhenReaderIsDisabledForTheLibrary_ShouldReturnReaderDisabledError()
{
// Arrange
ReadingDocumentDto document = CreateExtractableDocument();
StubOpenAsyncToExtract(document);
_mockConfigurationRepository.GetByLibraryAndPluginIdAsync(_libraryId, _pluginId, Arg.Any<CancellationToken>())
.Returns(Result.From<LibraryBookReaderConfigurationEntity?>(null));
// The resource already exists on disk, from an earlier extraction, but the enablement is read on every request, so it must not be served.
string workingDirectory = Path.Combine(ReadingCachePaths.GetRootDirectory(), _bookId.ToString("N"), "text");
string resourceFilePath = Path.Combine(workingDirectory, "resources", "cover.png");
Directory.CreateDirectory(Path.GetDirectoryName(resourceFilePath)!);
File.WriteAllBytes(resourceFilePath, [1, 2, 3]);
// Act
Result<ReadingResourceDataDto> result = await _sut.GetResourceAsync(_bookId, _libraryId, _bookPath, LibraryType.EBook, "cover", shouldRenderPdfAsImages: false, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(Errors.Reading.ReaderDisabled, result.FirstError);
await _mockReader.DidNotReceive().GetResourceAsync(Arg.Any<string>(), Arg.Any<string>(), Arg.Any<string>(), Arg.Any<CancellationToken>());
}
[Fact]
public async Task GetResourceAsync_WhenEnablementCacheSaysDisabledAndResourceFileAlreadyExists_ShouldNotServeTheResource()
{
// Arrange
ReadingDocumentDto document = CreateExtractableDocument();
StubOpenAsyncToExtract(document);
// The reader was disabled after the book was extracted, so the enablement cache already knows it; the request must be cut
// off before the already extracted resource on disk is considered, and without consulting the database again.
_enablementCache.Set(_libraryId, _pluginId, isEnabled: false);
string workingDirectory = Path.Combine(ReadingCachePaths.GetRootDirectory(), _bookId.ToString("N"), "text");
string resourceFilePath = Path.Combine(workingDirectory, "resources", "cover.png");
Directory.CreateDirectory(Path.GetDirectoryName(resourceFilePath)!);
File.WriteAllBytes(resourceFilePath, [1, 2, 3]);
// Act
Result<ReadingResourceDataDto> result = await _sut.GetResourceAsync(_bookId, _libraryId, _bookPath, LibraryType.EBook, "cover", shouldRenderPdfAsImages: false, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(Errors.Reading.ReaderDisabled, result.FirstError);
await _mockReader.DidNotReceive().GetResourceAsync(Arg.Any<string>(), Arg.Any<string>(), Arg.Any<string>(), Arg.Any<CancellationToken>());
await _mockConfigurationRepository.DidNotReceive().GetByLibraryAndPluginIdAsync(Arg.Any<Guid>(), Arg.Any<Guid>(), Arg.Any<CancellationToken>());
}
[Fact]
public async Task GetResourceAsync_WhenReaderThrowsWhileProducingTheResource_ShouldReturnResourceProductionFailedError()
{
// Arrange
ReadingDocumentDto document = CreateExtractableDocument();
StubOpenAsyncToExtract(document);
_mockReader.GetResourceAsync(Arg.Any<string>(), Arg.Any<string>(), "cover", Arg.Any<CancellationToken>())
.Returns(Task.FromException<byte[]>(new InvalidOperationException("The page renderer failed")));
// Act
Result<ReadingResourceDataDto> result = await _sut.GetResourceAsync(_bookId, _libraryId, _bookPath, LibraryType.EBook, "cover", shouldRenderPdfAsImages: false, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal("Reading.ResourceProductionFailed", result.FirstError.Code);
await _mockReader.Received(1).GetResourceAsync(Arg.Any<string>(), Arg.Any<string>(), "cover", Arg.Any<CancellationToken>());
}
[Fact]
public async Task GetResourceAsync_WhenReaderProductionIsCancelled_ShouldPropagateTheCancellation()
{
// Arrange
ReadingDocumentDto document = CreateExtractableDocument();
StubOpenAsyncToExtract(document);
_mockReader.GetResourceAsync(Arg.Any<string>(), Arg.Any<string>(), "cover", Arg.Any<CancellationToken>())
.Returns(Task.FromException<byte[]>(new OperationCanceledException()));
// Act
Task<Result<ReadingResourceDataDto>> operationTask = _sut.GetResourceAsync(_bookId, _libraryId, _bookPath, LibraryType.EBook, "cover", shouldRenderPdfAsImages: false, CancellationToken.None);
// Assert
await Assert.ThrowsAnyAsync<OperationCanceledException>(() => operationTask);
}
[Fact]
public async Task GetSectionAsync_WhenStylesArePreserved_ShouldKeepTheStyleAttributeInTheContent()
{
// Arrange
ReadingDocumentDto document = CreateExtractableDocument();
StubOpenAsyncToExtractStyledContent(document);
CancellationToken cancellationToken = CancellationToken.None;
// Act
Result<ReadingSectionDto> result = await _sut.GetSectionAsync(_bookId, _libraryId, _bookPath, LibraryType.EBook, "section-1", shouldRenderPdfAsImages: false, shouldPreserveStyles: true, cancellationToken);
// Assert
Assert.False(result.IsFailure);
Assert.Contains("style", result.Value.ContentHtml, StringComparison.OrdinalIgnoreCase);
}
[Fact]
public async Task GetSectionAsync_WhenStylesAreNotPreserved_ShouldStripTheStyleAttributeFromTheContent()
{
// Arrange
ReadingDocumentDto document = CreateExtractableDocument();
StubOpenAsyncToExtractStyledContent(document);
CancellationToken cancellationToken = CancellationToken.None;
// Act
Result<ReadingSectionDto> result = await _sut.GetSectionAsync(_bookId, _libraryId, _bookPath, LibraryType.EBook, "section-1", shouldRenderPdfAsImages: false, shouldPreserveStyles: false, cancellationToken);
// Assert
Assert.False(result.IsFailure);
Assert.DoesNotContain("style", result.Value.ContentHtml, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("color:red", result.Value.ContentHtml, StringComparison.OrdinalIgnoreCase);
Assert.Contains("Chapter 1", result.Value.ContentHtml, StringComparison.Ordinal);
}
[Fact]
public async Task GetAvailabilityAsync_WhenReaderIsAvailableAndEnabled_ShouldReportAvailable()
{
// Arrange
CancellationToken cancellationToken = CancellationToken.None;
// Act
Result<ReadingAvailabilityResponse> result = await _sut.GetAvailabilityAsync(_bookId, _libraryId, _bookPath, LibraryType.EBook, cancellationToken);
// Assert
Assert.False(result.IsFailure);
Assert.True(result.Value.IsAvailable);
Assert.Null(result.Value.ErrorCode);
await _mockReader.DidNotReceive().OpenAsync(Arg.Any<string>(), Arg.Any<string>(), Arg.Any<bool>(), Arg.Any<CancellationToken>());
}
[Fact]
public async Task GetAvailabilityAsync_WhenNoReaderSupportsTheFormat_ShouldReportUnavailableWithNoReaderAvailable()
{
// Arrange
_mockPluginManager.GetPlugins().Returns([]);
// Act
Result<ReadingAvailabilityResponse> result = await _sut.GetAvailabilityAsync(_bookId, _libraryId, _bookPath, LibraryType.EBook, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
Assert.False(result.Value.IsAvailable);
Assert.Equal(nameof(Errors.Reading.NoReaderAvailable), result.Value.ErrorCode);
}
[Fact]
public async Task GetAvailabilityAsync_WhenReaderIsDisabled_ShouldReportUnavailableWithReaderDisabled()
{
// Arrange
_mockConfigurationRepository.GetByLibraryAndPluginIdAsync(_libraryId, _pluginId, Arg.Any<CancellationToken>())
.Returns(Result.From<LibraryBookReaderConfigurationEntity?>(null));
// Act
Result<ReadingAvailabilityResponse> result = await _sut.GetAvailabilityAsync(_bookId, _libraryId, _bookPath, LibraryType.EBook, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
Assert.False(result.Value.IsAvailable);
Assert.Equal(nameof(Errors.Reading.ReaderDisabled), result.Value.ErrorCode);
}
[Fact]
public async Task GetManifestAsync_WhenReaderOpenThrowsFileNotFoundException_ShouldReturnBookFileNotFoundError()
{
// Arrange
_mockReader.OpenAsync(Arg.Any<string>(), Arg.Any<string>(), Arg.Any<bool>(), Arg.Any<CancellationToken>())
.Returns(Task.FromException<ReadingDocumentDto>(new FileNotFoundException("book missing")));
// Act
Result<ReadingManifestResponse> result = await _sut.GetManifestAsync(_bookId, _libraryId, _bookPath, LibraryType.EBook, shouldRenderPdfAsImages: false, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(Errors.Reading.BookFileNotFound, result.FirstError);
}
[Fact]
public async Task GetManifestAsync_WhenReaderOpenThrowsDirectoryNotFoundException_ShouldReturnBookFileNotFoundError()
{
// Arrange
_mockReader.OpenAsync(Arg.Any<string>(), Arg.Any<string>(), Arg.Any<bool>(), Arg.Any<CancellationToken>())
.Returns(Task.FromException<ReadingDocumentDto>(new DirectoryNotFoundException("directory missing")));
// Act
Result<ReadingManifestResponse> result = await _sut.GetManifestAsync(_bookId, _libraryId, _bookPath, LibraryType.EBook, shouldRenderPdfAsImages: false, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(Errors.Reading.BookFileNotFound, result.FirstError);
}
[Fact]
public async Task GetManifestAsync_WhenReaderOpenThrowsOtherException_ShouldReturnExtractionFailedError()
{
// Arrange
_mockReader.OpenAsync(Arg.Any<string>(), Arg.Any<string>(), Arg.Any<bool>(), Arg.Any<CancellationToken>())
.Returns(Task.FromException<ReadingDocumentDto>(new InvalidDataException("broken book")));
// Act
Result<ReadingManifestResponse> result = await _sut.GetManifestAsync(_bookId, _libraryId, _bookPath, LibraryType.EBook, shouldRenderPdfAsImages: false, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal("Reading.ExtractionFailed", result.FirstError.Code);
}
[Fact]
public async Task GetManifestAsync_WhenReaderOpenIsCancelled_ShouldPropagateTheCancellation()
{
// Arrange
_mockReader.OpenAsync(Arg.Any<string>(), Arg.Any<string>(), Arg.Any<bool>(), Arg.Any<CancellationToken>())
.Returns(Task.FromException<ReadingDocumentDto>(new OperationCanceledException()));
// Act
Task<Result<ReadingManifestResponse>> operationTask = _sut.GetManifestAsync(_bookId, _libraryId, _bookPath, LibraryType.EBook, shouldRenderPdfAsImages: false, CancellationToken.None);
// Assert
await Assert.ThrowsAnyAsync<OperationCanceledException>(() => operationTask);
}
[Fact]
public async Task GetManifestAsync_WhenBookFileIsDeletedAfterExtraction_ShouldReExtractAndFail()
{
// Arrange
ReadingDocumentDto document = CreateExtractableDocument();
StubOpenAsyncToExtract(document);
await _sut.GetManifestAsync(_bookId, _libraryId, _bookPath, LibraryType.EBook, shouldRenderPdfAsImages: false, CancellationToken.None);
_mockReader.OpenAsync(Arg.Any<string>(), Arg.Any<string>(), Arg.Any<bool>(), Arg.Any<CancellationToken>())
.Returns(Task.FromException<ReadingDocumentDto>(new FileNotFoundException("book missing")));
File.Delete(_bookPath);
// Act
Result<ReadingManifestResponse> result = await _sut.GetManifestAsync(_bookId, _libraryId, _bookPath, LibraryType.EBook, shouldRenderPdfAsImages: false, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(Errors.Reading.BookFileNotFound, result.FirstError);
await _mockReader.Received(2).OpenAsync(Arg.Any<string>(), Arg.Any<string>(), Arg.Any<bool>(), Arg.Any<CancellationToken>());
}
[Fact]
public async Task GetManifestAsync_WhenConfigurationsReadFails_ShouldReturnError()
{
// Arrange
_mockConfigurationRepository.GetByLibraryAndPluginIdAsync(_libraryId, _pluginId, Arg.Any<CancellationToken>())
.Returns(Error.Failure("Reading.Error", "Failed to read the configuration"));
// Act
Result<ReadingManifestResponse> result = await _sut.GetManifestAsync(_bookId, _libraryId, _bookPath, LibraryType.EBook, shouldRenderPdfAsImages: false, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal("Reading.Error", result.FirstError.Code);
await _mockReader.DidNotReceive().OpenAsync(Arg.Any<string>(), Arg.Any<string>(), Arg.Any<bool>(), Arg.Any<CancellationToken>());
}
[Fact]
public async Task GetManifestAsync_WhenReaderMatchesExtensionCaseInsensitively_ShouldResolveIt()
{
// Arrange
string uppercaseExtensionPath = Path.Combine(Path.GetTempPath(), $"lumina-test-book-{Guid.NewGuid():N}.EPUB");
File.WriteAllText(uppercaseExtensionPath, "test epub content");
try
{
ReadingDocumentDto document = CreateExtractableDocument();
StubOpenAsyncToExtract(document);
// Act
Result<ReadingManifestResponse> result = await _sut.GetManifestAsync(_bookId, _libraryId, uppercaseExtensionPath, LibraryType.EBook, shouldRenderPdfAsImages: false, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
}
finally
{
File.Delete(uppercaseExtensionPath);
}
}
[Fact]
public async Task GetManifestAsync_WhenReaderSupportsTheLibraryTypeButNotTheExtension_ShouldReturnNoReaderAvailableError()
{
// Arrange
string unsupportedExtensionPath = Path.Combine(Path.GetTempPath(), $"lumina-test-book-{Guid.NewGuid():N}.txt");
File.WriteAllText(unsupportedExtensionPath, "test content");
try
{
// Act
Result<ReadingManifestResponse> result = await _sut.GetManifestAsync(_bookId, _libraryId, unsupportedExtensionPath, LibraryType.EBook, shouldRenderPdfAsImages: false, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(Errors.Reading.NoReaderAvailable, result.FirstError);
await _mockReader.DidNotReceive().OpenAsync(Arg.Any<string>(), Arg.Any<string>(), Arg.Any<bool>(), Arg.Any<CancellationToken>());
}
finally
{
File.Delete(unsupportedExtensionPath);
}
}
/// <summary>
/// Creates a reading document whose spine and resources are extractable into the working directory.
/// </summary>
/// <returns>The created reading document.</returns>
private ReadingDocumentDto CreateExtractableDocument()
{
return _readingDocumentDtoFixture.Create(
title: "Test Book",
author: "Test Author",
tableOfContents: [],
spine:
[
_readingSpineItemDtoFixture.Create(locationRef: "section-1", title: "Chapter 1", relativeSectionFilePath: "sections/0.html")
],
resources: new Dictionary<string, ReadingResourceInfoDto>
{
["cover"] = _readingResourceInfoDtoFixture.Create(relativeFilePath: "resources/cover.png", mimeType: "image/png")
},
hasTextContent: true
);
}
/// <summary>
/// Stubs the reader's OpenAsync to create the extractable files of the document into the working directory.
/// </summary>
/// <param name="document">The document returned by the extraction.</param>
private void StubOpenAsyncToExtract(ReadingDocumentDto document)
{
_mockReader.OpenAsync(Arg.Any<string>(), Arg.Any<string>(), Arg.Any<bool>(), Arg.Any<CancellationToken>())
.Returns(callInfo =>
{
string workingDirectory = callInfo.ArgAt<string>(1);
Directory.CreateDirectory(Path.Combine(workingDirectory, "sections"));
File.WriteAllText(Path.Combine(workingDirectory, "sections", "0.html"), "<section><h1>Chapter 1</h1><p>Some text.</p></section>");
return Task.FromResult(document);
});
}
/// <summary>
/// Stubs the reader's OpenAsync to create a section whose content carries a style attribute, so that the sanitization
/// preference of the service is observable.
/// </summary>
/// <param name="document">The document returned by the extraction.</param>
private void StubOpenAsyncToExtractStyledContent(ReadingDocumentDto document)
{
_mockReader.OpenAsync(Arg.Any<string>(), Arg.Any<string>(), Arg.Any<bool>(), Arg.Any<CancellationToken>())
.Returns(callInfo =>
{
string workingDirectory = callInfo.ArgAt<string>(1);
Directory.CreateDirectory(Path.Combine(workingDirectory, "sections"));
File.WriteAllText(Path.Combine(workingDirectory, "sections", "0.html"), "<section><h1>Chapter 1</h1><p style=\"color:red\">Some text.</p></section>");
return Task.FromResult(document);
});
}
/// <inheritdoc/>
public void Dispose()
{
if (Directory.Exists(ReadingCachePaths.GetRootDirectory()))
Directory.Delete(ReadingCachePaths.GetRootDirectory(), recursive: true);
if (File.Exists(_bookPath))
File.Delete(_bookPath);
(_serviceProvider as IDisposable)?.Dispose();
}
/// <summary>
/// In-memory test double for the <see cref="IBookReaderEnablementCache"/> used by the service under test.
/// </summary>
[ExcludeFromCodeCoverage]
private sealed class TestBookReaderEnablementCache : IBookReaderEnablementCache
{
private readonly Dictionary<(Guid LibraryId, Guid PluginId), bool> _enablements = [];
/// <inheritdoc/>
public bool? Get(Guid libraryId, Guid pluginId)
{
return _enablements.TryGetValue((libraryId, pluginId), out bool isEnabled) ? isEnabled : null;
}
/// <inheritdoc/>
public void Set(Guid libraryId, Guid pluginId, bool isEnabled)
{
_enablements[(libraryId, pluginId)] = isEnabled;
}
/// <inheritdoc/>
public void Invalidate(Guid libraryId, Guid pluginId)
{
_enablements.Remove((libraryId, pluginId));
}
/// <inheritdoc/>
public void InvalidateLibrary(Guid libraryId)
{
foreach (Guid cachedPluginId in _enablements.Keys.Where(cachedPair => cachedPair.LibraryId == libraryId).Select(cachedPair => cachedPair.PluginId).ToList())
_enablements.Remove((libraryId, cachedPluginId));
}
/// <inheritdoc/>
public void InvalidatePlugin(Guid pluginId)
{
foreach (Guid cachedLibraryId in _enablements.Keys.Where(cachedPair => cachedPair.PluginId == pluginId).Select(cachedPair => cachedPair.LibraryId).ToList())
_enablements.Remove((cachedLibraryId, pluginId));
}
}
}
@@ -0,0 +1,32 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Infrastructure.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Reading;
using System;
using System.Diagnostics.CodeAnalysis;
using System.IO;
#endregion
namespace Lumina.Infrastructure.UnitTests.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Reading;
/// <summary>
/// Contains unit tests for the <see cref="ReadingCachePaths"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class ReadingCachePathsTests
{
[Fact]
public void GetRootDirectory_WhenCalled_ShouldReturnBaseDirectoryWithReadingCacheDirectoryName()
{
// Act
string result = ReadingCachePaths.GetRootDirectory();
// Assert
Assert.Equal(Path.Combine(AppContext.BaseDirectory, ReadingCachePaths.DIRECTORY_NAME), result);
}
[Fact]
public void DirectoryName_WhenAccessed_ShouldReturnReadingCache()
{
// Assert
Assert.Equal("reading-cache", ReadingCachePaths.DIRECTORY_NAME);
}
}
@@ -0,0 +1,159 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Infrastructure.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Reading;
using System;
using System.Diagnostics.CodeAnalysis;
#endregion
namespace Lumina.Infrastructure.UnitTests.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Reading;
/// <summary>
/// Contains unit tests for the <see cref="ReadingContentSanitizer"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class ReadingContentSanitizerTests
{
[Fact]
public void Sanitize_WhenHtmlContainsScript_ShouldStripTheScript()
{
// Arrange
string html = "<section><p>Hello</p><script>alert('xss')</script></section>";
// Act
string result = ReadingContentSanitizer.Sanitize(html, shouldPreserveStyles: false);
// Assert
Assert.DoesNotContain("script", result, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("alert", result, StringComparison.OrdinalIgnoreCase);
Assert.Contains("Hello", result, StringComparison.Ordinal);
}
[Fact]
public void Sanitize_WhenHtmlContainsInlineEventHandler_ShouldStripTheHandler()
{
// Arrange
string html = "<p onclick=\"alert('xss')\">Hello</p>";
// Act
string result = ReadingContentSanitizer.Sanitize(html, shouldPreserveStyles: false);
// Assert
Assert.DoesNotContain("onclick", result, StringComparison.OrdinalIgnoreCase);
Assert.Contains("Hello", result, StringComparison.Ordinal);
}
[Fact]
public void Sanitize_WhenHtmlContainsJavascriptUrl_ShouldStripTheReference()
{
// Arrange
string html = "<a href=\"javascript:alert('xss')\">Link</a>";
// Act
string result = ReadingContentSanitizer.Sanitize(html, shouldPreserveStyles: false);
// Assert
Assert.DoesNotContain("javascript", result, StringComparison.OrdinalIgnoreCase);
}
[Fact]
public void Sanitize_WhenHtmlContainsIframe_ShouldStripTheIframe()
{
// Arrange
string html = "<iframe src=\"https://evil.example\"></iframe><p>Hello</p>";
// Act
string result = ReadingContentSanitizer.Sanitize(html, shouldPreserveStyles: false);
// Assert
Assert.DoesNotContain("iframe", result, StringComparison.OrdinalIgnoreCase);
Assert.Contains("Hello", result, StringComparison.Ordinal);
}
[Fact]
public void Sanitize_WhenHtmlContainsDataLuminaResourceMarker_ShouldKeepTheMarker()
{
// Arrange
string html = $"<img {ReadingContentSanitizer.RESOURCE_ATTRIBUTE}=\"page:1\" alt=\"Page\" />";
// Act
string result = ReadingContentSanitizer.Sanitize(html, shouldPreserveStyles: false);
// Assert
Assert.Contains(ReadingContentSanitizer.RESOURCE_ATTRIBUTE, result, StringComparison.Ordinal);
Assert.Contains("page:1", result, StringComparison.Ordinal);
}
[Fact]
public void Sanitize_WhenHtmlContainsPlainContent_ShouldKeepTheContent()
{
// Arrange
string html = "<section><h1>Chapter 1</h1><p>Some text.</p></section>";
// Act
string result = ReadingContentSanitizer.Sanitize(html, shouldPreserveStyles: false);
// Assert
Assert.Contains("Chapter 1", result, StringComparison.Ordinal);
Assert.Contains("Some text.", result, StringComparison.Ordinal);
}
[Fact]
public void Sanitize_WhenShouldPreserveStylesIsTrue_ShouldKeepTheStyleAttribute()
{
// Arrange
string html = "<p style=\"color:red\">Hello</p>";
// Act
string result = ReadingContentSanitizer.Sanitize(html, shouldPreserveStyles: true);
// Assert
Assert.Contains("style", result, StringComparison.OrdinalIgnoreCase);
Assert.Contains("Hello", result, StringComparison.Ordinal);
}
[Fact]
public void Sanitize_WhenShouldPreserveStylesIsFalse_ShouldStripTheStyleAttribute()
{
// Arrange
string html = "<p style=\"color:red\">Hello</p>";
// Act
string result = ReadingContentSanitizer.Sanitize(html, shouldPreserveStyles: false);
// Assert
Assert.DoesNotContain("style", result, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("color:red", result, StringComparison.OrdinalIgnoreCase);
Assert.Contains("Hello", result, StringComparison.Ordinal);
}
[Theory]
[InlineData(true)] // preserve styles
[InlineData(false)] // strip styles
public void Sanitize_WhenHtmlContainsActiveContent_ShouldStripItRegardlessOfTheStylePreference(bool shouldPreserveStyles)
{
// Arrange
string html = "<section><p style=\"color:red\">Hello</p><script>alert('xss')</script><p onclick=\"alert('xss')\">World</p></section>";
// Act
string result = ReadingContentSanitizer.Sanitize(html, shouldPreserveStyles);
// Assert
Assert.DoesNotContain("script", result, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("alert", result, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("onclick", result, StringComparison.OrdinalIgnoreCase);
Assert.Contains("Hello", result, StringComparison.Ordinal);
Assert.Contains("World", result, StringComparison.Ordinal);
}
[Theory]
[InlineData(null)] // null input
[InlineData("")] // empty input
[InlineData(" ")] // whitespace input
public void Sanitize_WhenInputIsBlank_ShouldReturnEmptyString(string? html)
{
// Act
string result = ReadingContentSanitizer.Sanitize(html!, shouldPreserveStyles: false);
// Assert
Assert.Equal(string.Empty, result);
}
}
@@ -1,14 +1,16 @@
#region ========================================================================= USING =====================================================================================
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DataAccess.Entities.Plugins;
using Lumina.Application.Common.DataAccess.Repositories.Plugins;
using Lumina.Application.Common.DataAccess.UoW;
using Lumina.Application.Common.Infrastructure.Plugins;
using Lumina.Application.Common.Infrastructure.Reading;
using Lumina.Application.Fixtures.Common.DataAccess.Entities.Plugins;
using Lumina.Domain.Common.Primitives;
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
using Lumina.Infrastructure.Core.Plugins;
using Lumina.Plugins.Contracts.Core.Metadata;
using Lumina.Plugins.Contracts.Core.Plugins;
using Lumina.Plugins.Contracts.Core.Reading;
using Microsoft.Extensions.DependencyInjection;
using NSubstitute;
using System;
@@ -30,9 +32,12 @@ public class MediaLibraryProviderConfigurationStoreTests
private readonly IUnitOfWork _mockUnitOfWork;
private readonly ILibraryMetadataProviderConfigurationRepository _mockMetadataConfigurationRepository;
private readonly IArtworkProviderConfigurationRepository _mockArtworkConfigurationRepository;
private readonly ILibraryBookReaderConfigurationRepository _mockBookReaderConfigurationRepository;
private readonly IPluginManager _mockPluginManager;
private readonly IBookReaderEnablementCache _mockEnablementCache;
private readonly LibraryMetadataProviderConfigurationEntityFixture _metadataConfigurationFixture = new();
private readonly LibraryArtworkProviderConfigurationEntityFixture _artworkConfigurationFixture = new();
private readonly LibraryBookReaderConfigurationEntityFixture _bookReaderConfigurationFixture = new();
/// <summary>
/// Initializes a new instance of the <see cref="MediaLibraryProviderConfigurationStoreTests"/> class.
@@ -42,10 +47,13 @@ public class MediaLibraryProviderConfigurationStoreTests
_mockUnitOfWork = Substitute.For<IUnitOfWork>();
_mockMetadataConfigurationRepository = Substitute.For<ILibraryMetadataProviderConfigurationRepository>();
_mockArtworkConfigurationRepository = Substitute.For<IArtworkProviderConfigurationRepository>();
_mockBookReaderConfigurationRepository = Substitute.For<ILibraryBookReaderConfigurationRepository>();
_mockUnitOfWork.LibraryMetadataProviderConfigurationRepository.Returns(_mockMetadataConfigurationRepository);
_mockUnitOfWork.ArtworkProviderConfigurationRepository.Returns(_mockArtworkConfigurationRepository);
_mockUnitOfWork.LibraryBookReaderConfigurationRepository.Returns(_mockBookReaderConfigurationRepository);
_mockPluginManager = Substitute.For<IPluginManager>();
_mockPluginManager.GetPlugins().Returns([]);
_mockEnablementCache = Substitute.For<IBookReaderEnablementCache>();
}
[Fact]
@@ -77,8 +85,8 @@ public class MediaLibraryProviderConfigurationStoreTests
IPlugin betaPlugin = CreatePlugin(betaPluginId, "Beta");
_mockPluginManager.GetPlugins().Returns([alphaPlugin, betaPlugin]);
MediaLibraryProviderConfigurationStore sut = CreateSut(
(alphaPluginId, CreateMetadataProvider(LibraryType.Book), null),
(betaPluginId, CreateMetadataProvider(LibraryType.Book), CreateArtworkProvider(LibraryType.Book)));
(alphaPluginId, CreateMetadataProvider(LibraryType.Book), null, null),
(betaPluginId, CreateMetadataProvider(LibraryType.Book), CreateArtworkProvider(LibraryType.Book), null));
_mockMetadataConfigurationRepository.GetByLibraryIdAsync(libraryId, Arg.Any<CancellationToken>())
.Returns(Result.From<IReadOnlyList<LibraryMetadataProviderConfigurationEntity>>([]));
_mockArtworkConfigurationRepository.GetByLibraryIdAsync(libraryId, Arg.Any<CancellationToken>())
@@ -112,7 +120,7 @@ public class MediaLibraryProviderConfigurationStoreTests
Guid pluginId = Guid.NewGuid();
IPlugin plugin = CreatePlugin(pluginId, "Plugin");
_mockPluginManager.GetPlugins().Returns([plugin]);
MediaLibraryProviderConfigurationStore sut = CreateSut((pluginId, CreateMetadataProvider(LibraryType.Book), null));
MediaLibraryProviderConfigurationStore sut = CreateSut((pluginId, CreateMetadataProvider(LibraryType.Book), null, null));
LibraryMetadataProviderConfigurationEntity existingConfiguration = _metadataConfigurationFixture.Create(libraryId, pluginId, 4);
_mockMetadataConfigurationRepository.GetByLibraryIdAsync(libraryId, Arg.Any<CancellationToken>())
.Returns(Result.From<IReadOnlyList<LibraryMetadataProviderConfigurationEntity>>([existingConfiguration]));
@@ -133,7 +141,7 @@ public class MediaLibraryProviderConfigurationStoreTests
Guid pluginId = Guid.NewGuid();
IPlugin plugin = CreatePlugin(pluginId, "Plugin");
_mockPluginManager.GetPlugins().Returns([plugin]);
MediaLibraryProviderConfigurationStore sut = CreateSut((pluginId, CreateMetadataProvider(LibraryType.Movie), null));
MediaLibraryProviderConfigurationStore sut = CreateSut((pluginId, CreateMetadataProvider(LibraryType.Movie), null, null));
// Act
Result<Success> result = await sut.EnsureProviderConfigurationsAsync(libraryId, LibraryType.Book, CancellationToken.None);
@@ -152,7 +160,7 @@ public class MediaLibraryProviderConfigurationStoreTests
Guid pluginId = Guid.NewGuid();
IPlugin plugin = CreatePlugin(pluginId, "Plugin");
_mockPluginManager.GetPlugins().Returns([plugin]);
MediaLibraryProviderConfigurationStore sut = CreateSut((pluginId, CreateMetadataProvider(LibraryType.Book), null));
MediaLibraryProviderConfigurationStore sut = CreateSut((pluginId, CreateMetadataProvider(LibraryType.Book), null, null));
_mockMetadataConfigurationRepository.GetByLibraryIdAsync(libraryId, Arg.Any<CancellationToken>())
.Returns(Error.Failure(description: "Failed to read configurations"));
@@ -174,13 +182,15 @@ public class MediaLibraryProviderConfigurationStoreTests
IPlugin betaPlugin = CreatePlugin(betaPluginId, "Beta");
_mockPluginManager.GetPlugins().Returns([alphaPlugin, betaPlugin]);
MediaLibraryProviderConfigurationStore sut = CreateSut(
(alphaPluginId, CreateMetadataProvider(LibraryType.Book), null),
(betaPluginId, CreateMetadataProvider(LibraryType.EBook), null));
(alphaPluginId, CreateMetadataProvider(LibraryType.Book), null, null),
(betaPluginId, CreateMetadataProvider(LibraryType.EBook), null, null));
LibraryMetadataProviderConfigurationEntity existingConfiguration = _metadataConfigurationFixture.Create(libraryId, alphaPluginId, 1);
_mockMetadataConfigurationRepository.GetByLibraryIdAsync(libraryId, Arg.Any<CancellationToken>())
.Returns(Result.From<IReadOnlyList<LibraryMetadataProviderConfigurationEntity>>([existingConfiguration]));
_mockArtworkConfigurationRepository.GetByLibraryIdAsync(libraryId, Arg.Any<CancellationToken>())
.Returns(Result.From<IReadOnlyList<LibraryArtworkProviderConfigurationEntity>>([]));
_mockBookReaderConfigurationRepository.GetByLibraryIdAsync(libraryId, Arg.Any<CancellationToken>())
.Returns(Result.From<IReadOnlyList<LibraryBookReaderConfigurationEntity>>([]));
_mockMetadataConfigurationRepository.DeleteByLibraryIdAndPluginIdsAsync(libraryId, Arg.Any<IEnumerable<Guid>>(), Arg.Any<CancellationToken>())
.Returns(Result.Deleted);
_mockMetadataConfigurationRepository.UpsertAsync(Arg.Any<LibraryMetadataProviderConfigurationEntity>(), Arg.Any<CancellationToken>())
@@ -198,6 +208,7 @@ public class MediaLibraryProviderConfigurationStoreTests
Arg.Any<CancellationToken>());
await _mockMetadataConfigurationRepository.DidNotReceive().UpsertAsync(
Arg.Is<LibraryMetadataProviderConfigurationEntity>(configuration => configuration.PluginId == alphaPluginId), Arg.Any<CancellationToken>());
await _mockBookReaderConfigurationRepository.DidNotReceive().UpsertAsync(Arg.Any<LibraryBookReaderConfigurationEntity>(), Arg.Any<CancellationToken>());
}
[Fact]
@@ -209,6 +220,8 @@ public class MediaLibraryProviderConfigurationStoreTests
.Returns(Result.Deleted);
_mockArtworkConfigurationRepository.DeleteByLibraryIdAsync(libraryId, Arg.Any<CancellationToken>())
.Returns(Result.Deleted);
_mockBookReaderConfigurationRepository.DeleteByLibraryIdAsync(libraryId, Arg.Any<CancellationToken>())
.Returns(Result.Deleted);
MediaLibraryProviderConfigurationStore sut = CreateSut();
// Act
@@ -218,6 +231,8 @@ public class MediaLibraryProviderConfigurationStoreTests
Assert.False(result.IsFailure);
await _mockMetadataConfigurationRepository.Received(1).DeleteByLibraryIdAsync(libraryId, Arg.Any<CancellationToken>());
await _mockArtworkConfigurationRepository.Received(1).DeleteByLibraryIdAsync(libraryId, Arg.Any<CancellationToken>());
await _mockBookReaderConfigurationRepository.Received(1).DeleteByLibraryIdAsync(libraryId, Arg.Any<CancellationToken>());
_mockEnablementCache.Received(1).InvalidateLibrary(libraryId);
}
[Fact]
@@ -229,6 +244,8 @@ public class MediaLibraryProviderConfigurationStoreTests
.Returns(Result.Deleted);
_mockArtworkConfigurationRepository.DeleteByPluginIdAsync(pluginId, Arg.Any<CancellationToken>())
.Returns(Result.Deleted);
_mockBookReaderConfigurationRepository.DeleteByPluginIdAsync(pluginId, Arg.Any<CancellationToken>())
.Returns(Result.Deleted);
MediaLibraryProviderConfigurationStore sut = CreateSut();
// Act
@@ -238,24 +255,505 @@ public class MediaLibraryProviderConfigurationStoreTests
Assert.False(result.IsFailure);
await _mockMetadataConfigurationRepository.Received(1).DeleteByPluginIdAsync(pluginId, Arg.Any<CancellationToken>());
await _mockArtworkConfigurationRepository.Received(1).DeleteByPluginIdAsync(pluginId, Arg.Any<CancellationToken>());
await _mockBookReaderConfigurationRepository.Received(1).DeleteByPluginIdAsync(pluginId, Arg.Any<CancellationToken>());
_mockEnablementCache.Received(1).InvalidatePlugin(pluginId);
}
[Fact]
public async Task RemoveProviderConfigurationsForLibraryAsync_WhenDeletingMetadataFails_ShouldReturnError()
{
// Arrange
Guid libraryId = Guid.NewGuid();
_mockMetadataConfigurationRepository.DeleteByLibraryIdAsync(libraryId, Arg.Any<CancellationToken>())
.Returns(Error.Failure(description: "Failed to delete the configurations"));
MediaLibraryProviderConfigurationStore sut = CreateSut();
// Act
Result<Deleted> result = await sut.RemoveProviderConfigurationsForLibraryAsync(libraryId, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
await _mockArtworkConfigurationRepository.DidNotReceive().DeleteByLibraryIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
await _mockBookReaderConfigurationRepository.DidNotReceive().DeleteByLibraryIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
_mockEnablementCache.DidNotReceive().InvalidateLibrary(Arg.Any<Guid>());
}
[Fact]
public async Task RemoveProviderConfigurationsForLibraryAsync_WhenDeletingArtworkFails_ShouldReturnError()
{
// Arrange
Guid libraryId = Guid.NewGuid();
_mockMetadataConfigurationRepository.DeleteByLibraryIdAsync(libraryId, Arg.Any<CancellationToken>())
.Returns(Result.Deleted);
_mockArtworkConfigurationRepository.DeleteByLibraryIdAsync(libraryId, Arg.Any<CancellationToken>())
.Returns(Error.Failure(description: "Failed to delete the configurations"));
MediaLibraryProviderConfigurationStore sut = CreateSut();
// Act
Result<Deleted> result = await sut.RemoveProviderConfigurationsForLibraryAsync(libraryId, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
await _mockBookReaderConfigurationRepository.DidNotReceive().DeleteByLibraryIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
_mockEnablementCache.DidNotReceive().InvalidateLibrary(Arg.Any<Guid>());
}
[Fact]
public async Task RemoveProviderConfigurationsAsync_WhenDeletingMetadataFails_ShouldReturnError()
{
// Arrange
Guid pluginId = Guid.NewGuid();
_mockMetadataConfigurationRepository.DeleteByPluginIdAsync(pluginId, Arg.Any<CancellationToken>())
.Returns(Error.Failure(description: "Failed to delete the configurations"));
MediaLibraryProviderConfigurationStore sut = CreateSut();
// Act
Result<Deleted> result = await sut.RemoveProviderConfigurationsAsync(pluginId, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
await _mockArtworkConfigurationRepository.DidNotReceive().DeleteByPluginIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
await _mockBookReaderConfigurationRepository.DidNotReceive().DeleteByPluginIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
_mockEnablementCache.DidNotReceive().InvalidatePlugin(Arg.Any<Guid>());
}
[Fact]
public async Task RemoveProviderConfigurationsAsync_WhenDeletingArtworkFails_ShouldReturnError()
{
// Arrange
Guid pluginId = Guid.NewGuid();
_mockMetadataConfigurationRepository.DeleteByPluginIdAsync(pluginId, Arg.Any<CancellationToken>())
.Returns(Result.Deleted);
_mockArtworkConfigurationRepository.DeleteByPluginIdAsync(pluginId, Arg.Any<CancellationToken>())
.Returns(Error.Failure(description: "Failed to delete the configurations"));
MediaLibraryProviderConfigurationStore sut = CreateSut();
// Act
Result<Deleted> result = await sut.RemoveProviderConfigurationsAsync(pluginId, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
await _mockBookReaderConfigurationRepository.DidNotReceive().DeleteByPluginIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
_mockEnablementCache.DidNotReceive().InvalidatePlugin(Arg.Any<Guid>());
}
[Fact]
public async Task EnsureBookReaderConfigurationsAsync_WhenBookReaderSupportsTheLibraryType_ShouldAddDisabledConfiguration()
{
// Arrange
Guid libraryId = Guid.NewGuid();
Guid pluginId = Guid.NewGuid();
IPlugin plugin = CreatePlugin(pluginId, "Reader Plugin");
_mockPluginManager.GetPlugins().Returns([plugin]);
MediaLibraryProviderConfigurationStore sut = CreateSut((pluginId, null, null, CreateBookReader(LibraryType.EBook, ".epub")));
_mockBookReaderConfigurationRepository.GetByLibraryIdAsync(libraryId, Arg.Any<CancellationToken>())
.Returns(Result.From<IReadOnlyList<LibraryBookReaderConfigurationEntity>>([]));
_mockBookReaderConfigurationRepository.UpsertAsync(Arg.Any<LibraryBookReaderConfigurationEntity>(), Arg.Any<CancellationToken>())
.Returns(Result.Updated);
// Act
Result<Success> result = await sut.EnsureBookReaderConfigurationsAsync(libraryId, LibraryType.EBook, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
await _mockBookReaderConfigurationRepository.Received(1).UpsertAsync(
Arg.Is<LibraryBookReaderConfigurationEntity>(configuration => configuration.PluginId == pluginId && !configuration.IsEnabled),
Arg.Any<CancellationToken>());
}
[Fact]
public async Task EnsureBookReaderConfigurationsAsync_WhenConfigurationAlreadyExists_ShouldNotAddAnotherOne()
{
// Arrange
Guid libraryId = Guid.NewGuid();
Guid pluginId = Guid.NewGuid();
IPlugin plugin = CreatePlugin(pluginId, "Reader Plugin");
_mockPluginManager.GetPlugins().Returns([plugin]);
MediaLibraryProviderConfigurationStore sut = CreateSut((pluginId, null, null, CreateBookReader(LibraryType.EBook, ".epub")));
LibraryBookReaderConfigurationEntity existingConfiguration = _bookReaderConfigurationFixture.Create(libraryId: libraryId, pluginId: pluginId);
_mockBookReaderConfigurationRepository.GetByLibraryIdAsync(libraryId, Arg.Any<CancellationToken>())
.Returns(Result.From<IReadOnlyList<LibraryBookReaderConfigurationEntity>>([existingConfiguration]));
// Act
Result<Success> result = await sut.EnsureBookReaderConfigurationsAsync(libraryId, LibraryType.EBook, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
await _mockBookReaderConfigurationRepository.DidNotReceive().UpsertAsync(Arg.Any<LibraryBookReaderConfigurationEntity>(), Arg.Any<CancellationToken>());
}
[Fact]
public async Task EnsureBookReaderConfigurationsAsync_WhenNoBookReaderSupportsTheLibraryType_ShouldNotAddConfiguration()
{
// Arrange
Guid libraryId = Guid.NewGuid();
Guid pluginId = Guid.NewGuid();
IPlugin plugin = CreatePlugin(pluginId, "Reader Plugin");
_mockPluginManager.GetPlugins().Returns([plugin]);
MediaLibraryProviderConfigurationStore sut = CreateSut((pluginId, null, null, CreateBookReader(LibraryType.Movie, ".epub")));
// Act
Result<Success> result = await sut.EnsureBookReaderConfigurationsAsync(libraryId, LibraryType.EBook, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
await _mockBookReaderConfigurationRepository.DidNotReceive().UpsertAsync(Arg.Any<LibraryBookReaderConfigurationEntity>(), Arg.Any<CancellationToken>());
await _mockBookReaderConfigurationRepository.DidNotReceive().GetByLibraryIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
}
[Fact]
public async Task EnsureBookReaderConfigurationsAsync_WhenReaderDeclaresNoExtension_ShouldNotAddConfiguration()
{
// Arrange
Guid libraryId = Guid.NewGuid();
Guid pluginId = Guid.NewGuid();
IPlugin plugin = CreatePlugin(pluginId, "Reader Plugin");
_mockPluginManager.GetPlugins().Returns([plugin]);
MediaLibraryProviderConfigurationStore sut = CreateSut((pluginId, null, null, CreateBookReader(LibraryType.EBook, supportedExtension: null)));
// Act
Result<Success> result = await sut.EnsureBookReaderConfigurationsAsync(libraryId, LibraryType.EBook, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
await _mockBookReaderConfigurationRepository.DidNotReceive().UpsertAsync(Arg.Any<LibraryBookReaderConfigurationEntity>(), Arg.Any<CancellationToken>());
}
[Fact]
public async Task EnsureBookReaderConfigurationsAsync_WhenReadingConfigurationsFails_ShouldReturnError()
{
// Arrange
Guid libraryId = Guid.NewGuid();
Guid pluginId = Guid.NewGuid();
IPlugin plugin = CreatePlugin(pluginId, "Reader Plugin");
_mockPluginManager.GetPlugins().Returns([plugin]);
MediaLibraryProviderConfigurationStore sut = CreateSut((pluginId, null, null, CreateBookReader(LibraryType.EBook, ".epub")));
_mockBookReaderConfigurationRepository.GetByLibraryIdAsync(libraryId, Arg.Any<CancellationToken>())
.Returns(Error.Failure(description: "Failed to read configurations"));
// Act
Result<Success> result = await sut.EnsureBookReaderConfigurationsAsync(libraryId, LibraryType.EBook, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
}
[Fact]
public async Task EnsureBookReaderConfigurationsAsync_WhenUpsertFails_ShouldReturnError()
{
// Arrange
Guid libraryId = Guid.NewGuid();
Guid pluginId = Guid.NewGuid();
IPlugin plugin = CreatePlugin(pluginId, "Reader Plugin");
_mockPluginManager.GetPlugins().Returns([plugin]);
MediaLibraryProviderConfigurationStore sut = CreateSut((pluginId, null, null, CreateBookReader(LibraryType.EBook, ".epub")));
_mockBookReaderConfigurationRepository.GetByLibraryIdAsync(libraryId, Arg.Any<CancellationToken>())
.Returns(Result.From<IReadOnlyList<LibraryBookReaderConfigurationEntity>>([]));
_mockBookReaderConfigurationRepository.UpsertAsync(Arg.Any<LibraryBookReaderConfigurationEntity>(), Arg.Any<CancellationToken>())
.Returns(Error.Failure(description: "Failed to persist the configuration"));
// Act
Result<Success> result = await sut.EnsureBookReaderConfigurationsAsync(libraryId, LibraryType.EBook, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
}
[Fact]
public async Task ReconcileBookReaderConfigurationsAsync_WhenCalled_ShouldRemoveStaleAndAddTheSupportedBookReaders()
{
// Arrange
Guid libraryId = Guid.NewGuid();
Guid alphaPluginId = Guid.NewGuid();
Guid betaPluginId = Guid.NewGuid();
IPlugin alphaPlugin = CreatePlugin(alphaPluginId, "Alpha Reader");
IPlugin betaPlugin = CreatePlugin(betaPluginId, "Beta Reader");
_mockPluginManager.GetPlugins().Returns([alphaPlugin, betaPlugin]);
MediaLibraryProviderConfigurationStore sut = CreateSut(
(alphaPluginId, null, null, CreateBookReader(LibraryType.Book, ".pdf")),
(betaPluginId, null, null, CreateBookReader(LibraryType.EBook, ".epub")));
LibraryBookReaderConfigurationEntity existingConfiguration = _bookReaderConfigurationFixture.Create(libraryId: libraryId, pluginId: alphaPluginId);
_mockBookReaderConfigurationRepository.GetByLibraryIdAsync(libraryId, Arg.Any<CancellationToken>())
.Returns(Result.From<IReadOnlyList<LibraryBookReaderConfigurationEntity>>([existingConfiguration]));
_mockBookReaderConfigurationRepository.DeleteByLibraryIdAndPluginIdsAsync(libraryId, Arg.Any<IEnumerable<Guid>>(), Arg.Any<CancellationToken>())
.Returns(Result.Deleted);
_mockBookReaderConfigurationRepository.UpsertAsync(Arg.Any<LibraryBookReaderConfigurationEntity>(), Arg.Any<CancellationToken>())
.Returns(Result.Updated);
// Act
Result<Success> result = await sut.ReconcileBookReaderConfigurationsAsync(libraryId, LibraryType.EBook, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
await _mockBookReaderConfigurationRepository.Received(1).DeleteByLibraryIdAndPluginIdsAsync(
libraryId, Arg.Is<IEnumerable<Guid>>(pluginIds => pluginIds.SequenceEqual(new[] { alphaPluginId })), Arg.Any<CancellationToken>());
await _mockBookReaderConfigurationRepository.Received(1).UpsertAsync(
Arg.Is<LibraryBookReaderConfigurationEntity>(configuration => configuration.PluginId == betaPluginId && !configuration.IsEnabled),
Arg.Any<CancellationToken>());
await _mockBookReaderConfigurationRepository.DidNotReceive().UpsertAsync(
Arg.Is<LibraryBookReaderConfigurationEntity>(configuration => configuration.PluginId == alphaPluginId), Arg.Any<CancellationToken>());
}
[Fact]
public async Task ReconcileBookReaderConfigurationsAsync_WhenReadingConfigurationsFails_ShouldReturnError()
{
// Arrange
Guid libraryId = Guid.NewGuid();
Guid pluginId = Guid.NewGuid();
IPlugin plugin = CreatePlugin(pluginId, "Reader Plugin");
_mockPluginManager.GetPlugins().Returns([plugin]);
MediaLibraryProviderConfigurationStore sut = CreateSut((pluginId, null, null, CreateBookReader(LibraryType.EBook, ".epub")));
_mockBookReaderConfigurationRepository.GetByLibraryIdAsync(libraryId, Arg.Any<CancellationToken>())
.Returns(Error.Failure(description: "Failed to read configurations"));
// Act
Result<Success> result = await sut.ReconcileBookReaderConfigurationsAsync(libraryId, LibraryType.EBook, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
}
[Fact]
public async Task ReconcileBookReaderConfigurationsAsync_WhenDeletingStaleConfigurationsFails_ShouldReturnError()
{
// Arrange
Guid libraryId = Guid.NewGuid();
Guid pluginId = Guid.NewGuid();
Guid stalePluginId = Guid.NewGuid();
IPlugin plugin = CreatePlugin(pluginId, "Reader Plugin");
_mockPluginManager.GetPlugins().Returns([plugin]);
MediaLibraryProviderConfigurationStore sut = CreateSut((pluginId, null, null, CreateBookReader(LibraryType.EBook, ".epub")));
LibraryBookReaderConfigurationEntity staleConfiguration = _bookReaderConfigurationFixture.Create(libraryId: libraryId, pluginId: stalePluginId);
_mockBookReaderConfigurationRepository.GetByLibraryIdAsync(libraryId, Arg.Any<CancellationToken>())
.Returns(Result.From<IReadOnlyList<LibraryBookReaderConfigurationEntity>>([staleConfiguration]));
_mockBookReaderConfigurationRepository.DeleteByLibraryIdAndPluginIdsAsync(libraryId, Arg.Any<IEnumerable<Guid>>(), Arg.Any<CancellationToken>())
.Returns(Error.Failure(description: "Failed to delete the configurations"));
// Act
Result<Success> result = await sut.ReconcileBookReaderConfigurationsAsync(libraryId, LibraryType.EBook, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
}
[Fact]
public async Task ReconcileBookReaderConfigurationsAsync_WhenUpsertFails_ShouldReturnError()
{
// Arrange
Guid libraryId = Guid.NewGuid();
Guid pluginId = Guid.NewGuid();
IPlugin plugin = CreatePlugin(pluginId, "Reader Plugin");
_mockPluginManager.GetPlugins().Returns([plugin]);
MediaLibraryProviderConfigurationStore sut = CreateSut((pluginId, null, null, CreateBookReader(LibraryType.EBook, ".epub")));
_mockBookReaderConfigurationRepository.GetByLibraryIdAsync(libraryId, Arg.Any<CancellationToken>())
.Returns(Result.From<IReadOnlyList<LibraryBookReaderConfigurationEntity>>([]));
_mockBookReaderConfigurationRepository.UpsertAsync(Arg.Any<LibraryBookReaderConfigurationEntity>(), Arg.Any<CancellationToken>())
.Returns(Error.Failure(description: "Failed to persist the configuration"));
// Act
Result<Success> result = await sut.ReconcileBookReaderConfigurationsAsync(libraryId, LibraryType.EBook, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
}
[Fact]
public async Task RemoveBookReaderConfigurationsForLibraryAsync_WhenCalled_ShouldDeleteTheConfigurationsOfTheLibrary()
{
// Arrange
Guid libraryId = Guid.NewGuid();
_mockBookReaderConfigurationRepository.DeleteByLibraryIdAsync(libraryId, Arg.Any<CancellationToken>())
.Returns(Result.Deleted);
MediaLibraryProviderConfigurationStore sut = CreateSut();
// Act
Result<Deleted> result = await sut.RemoveBookReaderConfigurationsForLibraryAsync(libraryId, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
await _mockBookReaderConfigurationRepository.Received(1).DeleteByLibraryIdAsync(libraryId, Arg.Any<CancellationToken>());
_mockEnablementCache.Received(1).InvalidateLibrary(libraryId);
}
[Fact]
public async Task RemoveBookReaderConfigurationsForLibraryAsync_WhenDeletionFails_ShouldReturnError()
{
// Arrange
Guid libraryId = Guid.NewGuid();
_mockBookReaderConfigurationRepository.DeleteByLibraryIdAsync(libraryId, Arg.Any<CancellationToken>())
.Returns(Error.Failure(description: "Failed to delete the configurations"));
MediaLibraryProviderConfigurationStore sut = CreateSut();
// Act
Result<Deleted> result = await sut.RemoveBookReaderConfigurationsForLibraryAsync(libraryId, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
_mockEnablementCache.DidNotReceive().InvalidateLibrary(Arg.Any<Guid>());
}
[Fact]
public async Task RemoveBookReaderConfigurationsAsync_WhenCalled_ShouldDeleteTheConfigurationsOfThePlugin()
{
// Arrange
Guid pluginId = Guid.NewGuid();
_mockBookReaderConfigurationRepository.DeleteByPluginIdAsync(pluginId, Arg.Any<CancellationToken>())
.Returns(Result.Deleted);
MediaLibraryProviderConfigurationStore sut = CreateSut();
// Act
Result<Deleted> result = await sut.RemoveBookReaderConfigurationsAsync(pluginId, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
await _mockBookReaderConfigurationRepository.Received(1).DeleteByPluginIdAsync(pluginId, Arg.Any<CancellationToken>());
_mockEnablementCache.Received(1).InvalidatePlugin(pluginId);
}
[Fact]
public async Task RemoveBookReaderConfigurationsAsync_WhenDeletionFails_ShouldReturnError()
{
// Arrange
Guid pluginId = Guid.NewGuid();
_mockBookReaderConfigurationRepository.DeleteByPluginIdAsync(pluginId, Arg.Any<CancellationToken>())
.Returns(Error.Failure(description: "Failed to delete the configurations"));
MediaLibraryProviderConfigurationStore sut = CreateSut();
// Act
Result<Deleted> result = await sut.RemoveBookReaderConfigurationsAsync(pluginId, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
_mockEnablementCache.DidNotReceive().InvalidatePlugin(Arg.Any<Guid>());
}
[Fact]
public async Task ReconcileProviderConfigurationsAsync_WhenArtworkConfigurationsAreStale_ShouldDeleteAndAddThem()
{
// Arrange
Guid libraryId = Guid.NewGuid();
Guid alphaPluginId = Guid.NewGuid();
Guid betaPluginId = Guid.NewGuid();
IPlugin alphaPlugin = CreatePlugin(alphaPluginId, "Alpha");
IPlugin betaPlugin = CreatePlugin(betaPluginId, "Beta");
_mockPluginManager.GetPlugins().Returns([alphaPlugin, betaPlugin]);
MediaLibraryProviderConfigurationStore sut = CreateSut(
(alphaPluginId, null, CreateArtworkProvider(LibraryType.Book), null),
(betaPluginId, null, CreateArtworkProvider(LibraryType.EBook), null));
LibraryArtworkProviderConfigurationEntity existingArtworkConfiguration = _artworkConfigurationFixture.Create(libraryId, alphaPluginId, 1);
_mockMetadataConfigurationRepository.GetByLibraryIdAsync(libraryId, Arg.Any<CancellationToken>())
.Returns(Result.From<IReadOnlyList<LibraryMetadataProviderConfigurationEntity>>([]));
_mockArtworkConfigurationRepository.GetByLibraryIdAsync(libraryId, Arg.Any<CancellationToken>())
.Returns(Result.From<IReadOnlyList<LibraryArtworkProviderConfigurationEntity>>([existingArtworkConfiguration]));
_mockBookReaderConfigurationRepository.GetByLibraryIdAsync(libraryId, Arg.Any<CancellationToken>())
.Returns(Result.From<IReadOnlyList<LibraryBookReaderConfigurationEntity>>([]));
_mockArtworkConfigurationRepository.DeleteByLibraryIdAndPluginIdsAsync(libraryId, Arg.Any<IEnumerable<Guid>>(), Arg.Any<CancellationToken>())
.Returns(Result.Deleted);
_mockArtworkConfigurationRepository.UpsertAsync(Arg.Any<LibraryArtworkProviderConfigurationEntity>(), Arg.Any<CancellationToken>())
.Returns(Result.Updated);
// Act
Result<Success> result = await sut.ReconcileProviderConfigurationsAsync(libraryId, LibraryType.EBook, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
await _mockArtworkConfigurationRepository.Received(1).DeleteByLibraryIdAndPluginIdsAsync(
libraryId, Arg.Is<IEnumerable<Guid>>(pluginIds => pluginIds.SequenceEqual(new[] { alphaPluginId })), Arg.Any<CancellationToken>());
await _mockArtworkConfigurationRepository.Received(1).UpsertAsync(
Arg.Is<LibraryArtworkProviderConfigurationEntity>(configuration => configuration.PluginId == betaPluginId && configuration.Rank == 2 && !configuration.IsEnabled),
Arg.Any<CancellationToken>());
}
[Fact]
public async Task ReconcileProviderConfigurationsAsync_WhenDeletingStaleArtworkConfigurationsFails_ShouldReturnError()
{
// Arrange
Guid libraryId = Guid.NewGuid();
Guid alphaPluginId = Guid.NewGuid();
IPlugin alphaPlugin = CreatePlugin(alphaPluginId, "Alpha");
_mockPluginManager.GetPlugins().Returns([alphaPlugin]);
MediaLibraryProviderConfigurationStore sut = CreateSut((alphaPluginId, null, CreateArtworkProvider(LibraryType.Movie), null));
LibraryArtworkProviderConfigurationEntity staleArtworkConfiguration = _artworkConfigurationFixture.Create(libraryId, alphaPluginId, 1);
_mockMetadataConfigurationRepository.GetByLibraryIdAsync(libraryId, Arg.Any<CancellationToken>())
.Returns(Result.From<IReadOnlyList<LibraryMetadataProviderConfigurationEntity>>([]));
_mockArtworkConfigurationRepository.GetByLibraryIdAsync(libraryId, Arg.Any<CancellationToken>())
.Returns(Result.From<IReadOnlyList<LibraryArtworkProviderConfigurationEntity>>([staleArtworkConfiguration]));
_mockArtworkConfigurationRepository.DeleteByLibraryIdAndPluginIdsAsync(libraryId, Arg.Any<IEnumerable<Guid>>(), Arg.Any<CancellationToken>())
.Returns(Error.Failure(description: "Failed to delete the configurations"));
// Act
Result<Success> result = await sut.ReconcileProviderConfigurationsAsync(libraryId, LibraryType.EBook, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
}
[Fact]
public async Task EnsureProviderConfigurationsAsync_WhenArtworkConfigurationAlreadyExists_ShouldNotAddAnotherOne()
{
// Arrange
Guid libraryId = Guid.NewGuid();
Guid pluginId = Guid.NewGuid();
IPlugin plugin = CreatePlugin(pluginId, "Plugin");
_mockPluginManager.GetPlugins().Returns([plugin]);
MediaLibraryProviderConfigurationStore sut = CreateSut((pluginId, null, CreateArtworkProvider(LibraryType.Book), null));
LibraryArtworkProviderConfigurationEntity existingConfiguration = _artworkConfigurationFixture.Create(libraryId, pluginId, 3);
_mockMetadataConfigurationRepository.GetByLibraryIdAsync(libraryId, Arg.Any<CancellationToken>())
.Returns(Result.From<IReadOnlyList<LibraryMetadataProviderConfigurationEntity>>([]));
_mockArtworkConfigurationRepository.GetByLibraryIdAsync(libraryId, Arg.Any<CancellationToken>())
.Returns(Result.From<IReadOnlyList<LibraryArtworkProviderConfigurationEntity>>([existingConfiguration]));
_mockBookReaderConfigurationRepository.GetByLibraryIdAsync(libraryId, Arg.Any<CancellationToken>())
.Returns(Result.From<IReadOnlyList<LibraryBookReaderConfigurationEntity>>([]));
// Act
Result<Success> result = await sut.EnsureProviderConfigurationsAsync(libraryId, LibraryType.Book, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
await _mockArtworkConfigurationRepository.DidNotReceive().UpsertAsync(Arg.Any<LibraryArtworkProviderConfigurationEntity>(), Arg.Any<CancellationToken>());
}
[Fact]
public async Task EnsureProviderConfigurationsAsync_WhenArtworkUpsertFails_ShouldReturnError()
{
// Arrange
Guid libraryId = Guid.NewGuid();
Guid pluginId = Guid.NewGuid();
IPlugin plugin = CreatePlugin(pluginId, "Plugin");
_mockPluginManager.GetPlugins().Returns([plugin]);
MediaLibraryProviderConfigurationStore sut = CreateSut((pluginId, null, CreateArtworkProvider(LibraryType.Book), null));
_mockMetadataConfigurationRepository.GetByLibraryIdAsync(libraryId, Arg.Any<CancellationToken>())
.Returns(Result.From<IReadOnlyList<LibraryMetadataProviderConfigurationEntity>>([]));
_mockArtworkConfigurationRepository.GetByLibraryIdAsync(libraryId, Arg.Any<CancellationToken>())
.Returns(Result.From<IReadOnlyList<LibraryArtworkProviderConfigurationEntity>>([]));
_mockArtworkConfigurationRepository.UpsertAsync(Arg.Any<LibraryArtworkProviderConfigurationEntity>(), Arg.Any<CancellationToken>())
.Returns(Error.Failure(description: "Failed to persist the configuration"));
// Act
Result<Success> result = await sut.EnsureProviderConfigurationsAsync(libraryId, LibraryType.Book, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
}
/// <summary>
/// Creates the store under test wired to the mocked dependencies, optionally registering the providers of the loaded plugins.
/// Creates the store under test wired to the mocked dependencies, optionally registering the providers and book readers of the loaded plugins.
/// </summary>
/// <param name="pluginProviders">The providers registered by the loaded plugins, keyed by their plugin, when any.</param>
/// <param name="pluginServices">The providers and book readers registered by the loaded plugins, keyed by their plugin, when any.</param>
/// <returns>The created store.</returns>
private MediaLibraryProviderConfigurationStore CreateSut(params (Guid pluginId, IMetadataProvider? metadataProvider, IArtworkProvider? artworkProvider)[] pluginProviders)
private MediaLibraryProviderConfigurationStore CreateSut(params (Guid pluginId, IMetadataProvider? metadataProvider, IArtworkProvider? artworkProvider, IBookReader? bookReader)[] pluginServices)
{
ServiceCollection services = new();
foreach ((Guid pluginId, IMetadataProvider? metadataProvider, IArtworkProvider? artworkProvider) in pluginProviders)
foreach ((Guid pluginId, IMetadataProvider? metadataProvider, IArtworkProvider? artworkProvider, IBookReader? bookReader) in pluginServices)
{
if (metadataProvider is not null)
services.AddKeyedSingleton<IMetadataProvider>(pluginId, (_, _) => metadataProvider);
if (artworkProvider is not null)
services.AddKeyedSingleton<IArtworkProvider>(pluginId, (_, _) => artworkProvider);
if (bookReader is not null)
services.AddKeyedSingleton<IBookReader>(pluginId, (_, _) => bookReader);
}
return new MediaLibraryProviderConfigurationStore(_mockUnitOfWork, _mockPluginManager, services.BuildServiceProvider());
return new MediaLibraryProviderConfigurationStore(_mockUnitOfWork, _mockPluginManager, services.BuildServiceProvider(), _mockEnablementCache);
}
/// <summary>
@@ -295,4 +793,19 @@ public class MediaLibraryProviderConfigurationStoreTests
provider.SupportedLibraryTypes.Returns([supportedLibraryType]);
return provider;
}
/// <summary>
/// Creates a mocked book reader supporting the provided library type and file extension.
/// </summary>
/// <param name="supportedLibraryType">The library type supported by the reader.</param>
/// <param name="supportedExtension">The file extension supported by the reader, or <see langword="null"/> for none.</param>
/// <returns>The created book reader mock.</returns>
private static IBookReader CreateBookReader(LibraryType supportedLibraryType, string? supportedExtension = ".epub")
{
IBookReader reader = Substitute.For<IBookReader>();
reader.SupportedLibraryTypes.Returns([supportedLibraryType]);
reader.SupportedExtensions.Returns(supportedExtension is null ? [] : [supportedExtension]);
return reader;
}
}
@@ -71,6 +71,8 @@ public class PluginDetectionSyncJobTests
.Returns(Result.Deleted);
_mockProviderConfigurationStore.EnsureProviderConfigurationsAsync(Arg.Any<Guid>(), Arg.Any<LibraryType>(), Arg.Any<CancellationToken>())
.Returns(Result.Success);
_mockProviderConfigurationStore.EnsureBookReaderConfigurationsAsync(Arg.Any<Guid>(), Arg.Any<LibraryType>(), Arg.Any<CancellationToken>())
.Returns(Result.Success);
_mockServiceProvider.GetService(typeof(IUnitOfWork)).Returns(_mockUnitOfWork);
_mockServiceProvider.GetService(typeof(IMediaLibraryProviderConfigurationStore)).Returns(_mockProviderConfigurationStore);
@@ -222,6 +224,7 @@ public class PluginDetectionSyncJobTests
// Assert
await _mockProviderConfigurationStore.Received(1).EnsureProviderConfigurationsAsync(bookLibrary.Id, LibraryType.Book, Arg.Any<CancellationToken>());
await _mockProviderConfigurationStore.Received(1).EnsureBookReaderConfigurationsAsync(bookLibrary.Id, LibraryType.Book, Arg.Any<CancellationToken>());
await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any<CancellationToken>());
}
@@ -50,6 +50,24 @@ public class PluginLoaderTests
Assert.Contains("invalid.dll", error.ErrorMessage);
}
[Fact]
public void LoadPlugins_WhenDirectoryContainsNativeLibrary_ShouldSkipItSilently()
{
// Arrange
using TemporaryPluginDirectory temporaryPluginDirectory = new();
// A native library (like pdfium.dll) is a valid PE image starting with the DOS signature, but it is not a managed assembly.
temporaryPluginDirectory.CreateFile("native.dll", "MZ\u0001\u0000\u0000\u0000garbage native library content");
IServiceCollection services = new ServiceCollection();
// Act
PluginLoadResultDto result = PluginLoader.LoadPlugins(temporaryPluginDirectory.Path, services);
// Assert
Assert.Empty(result.Plugins);
Assert.Empty(result.Errors);
Assert.Empty(result.LoadContexts);
}
[Fact]
public void LoadPlugins_WhenDirectoryContainsAssemblyWithoutPluginDescriptors_ShouldReturnNoPluginsAndNoErrors()
{
@@ -85,6 +103,104 @@ public class PluginLoaderTests
Assert.Contains(services, descriptor => descriptor.ImplementationInstance as string == "plugin-services-registered");
}
[Fact]
public void LoadPlugins_WhenDirectoryContainsValidPluginAssembly_ShouldRetainTheLoadContextOfThePlugin()
{
// Arrange
using TemporaryPluginDirectory temporaryPluginDirectory = new();
temporaryPluginDirectory.CopyDll(GetTestPluginAssemblyPath());
IServiceCollection services = new ServiceCollection();
// Act
PluginLoadResultDto result = PluginLoader.LoadPlugins(temporaryPluginDirectory.Path, services);
// Assert
Assert.Single(result.Plugins);
// A collectible load context is only kept alive by a direct reference to the context object itself, so the context of every loaded plugin is retained
// for the lifetime of the host, keeping the plugin assemblies from being unloaded by the garbage collector.
Assert.Single(result.LoadContexts);
}
[Fact]
public void LoadPlugins_WhenDirectoryContainsManagedDependencyAssemblyAlongsideAPlugin_ShouldSkipTheDependencyAndLoadOnlyThePlugin()
{
// Arrange
using TemporaryPluginDirectory temporaryPluginDirectory = new();
temporaryPluginDirectory.CopyDll(GetTestPluginAssemblyPath());
// A plugin ships its managed dependencies into the plugins directory (like PdfPig.dll and SkiaSharp.dll next to the PDF plugin). A managed dependency is a valid
// assembly that does not reference the plugin contracts, so it is not a plugin and must be skipped without reflecting over its types, which would otherwise surface
// spurious load errors for a file that is not a plugin.
temporaryPluginDirectory.CopyDll(GetDependencyAssemblyPath());
IServiceCollection services = new ServiceCollection();
// Act
PluginLoadResultDto result = PluginLoader.LoadPlugins(temporaryPluginDirectory.Path, services);
// Assert
IPlugin loadedPlugin = Assert.Single(result.Plugins);
Assert.Equal(Guid.Parse("7B5A3E5D-9B7F-4A1E-8D9C-2F3A4B5C6D7E"), loadedPlugin.Id);
Assert.Equal("Test Plugin", loadedPlugin.Name);
Assert.Empty(result.Errors);
Assert.Single(result.LoadContexts);
}
[Fact]
public void LoadPlugins_WhenDirectoryContainsFileShorterThanDosSignature_ShouldRecordInvalidAssemblyError()
{
// Arrange
using TemporaryPluginDirectory temporaryPluginDirectory = new();
// A single-character file is not long enough to carry the two-byte DOS signature "MZ", so it is not a PE image.
temporaryPluginDirectory.CreateFile("tiny.dll", "M");
IServiceCollection services = new ServiceCollection();
// Act
PluginLoadResultDto result = PluginLoader.LoadPlugins(temporaryPluginDirectory.Path, services);
// Assert
Assert.Empty(result.Plugins);
PluginLoadErrorDto error = Assert.Single(result.Errors);
Assert.Equal("tiny", error.AssemblyName);
Assert.Contains("tiny.dll", error.ErrorMessage);
}
[Fact]
public void LoadPlugins_WhenDirectoryContainsFileWithWrongDosSignature_ShouldRecordInvalidAssemblyError()
{
// Arrange
using TemporaryPluginDirectory temporaryPluginDirectory = new();
// The file starts with the wrong DOS signature, so it is not a PE image at all.
temporaryPluginDirectory.CreateFile("notpe.dll", "XY\u0000\u0000\u0000some content that is not a PE image");
IServiceCollection services = new ServiceCollection();
// Act
PluginLoadResultDto result = PluginLoader.LoadPlugins(temporaryPluginDirectory.Path, services);
// Assert
Assert.Empty(result.Plugins);
PluginLoadErrorDto error = Assert.Single(result.Errors);
Assert.Equal("notpe", error.AssemblyName);
Assert.Contains("notpe.dll", error.ErrorMessage);
}
[Fact]
public void LoadPlugins_WhenDirectoryContainsLockedNativeLibrary_ShouldNotThrowAndRecordError()
{
// Arrange
using TemporaryPluginDirectory temporaryPluginDirectory = new();
string nativePath = temporaryPluginDirectory.CreateFileReturningPath("locked.dll", "MZ\u0000\u0000\u0000locked native library content");
using FileStream lockStream = new(nativePath, FileMode.Open, FileAccess.Read, FileShare.None);
IServiceCollection services = new ServiceCollection();
// Act
PluginLoadResultDto result = PluginLoader.LoadPlugins(temporaryPluginDirectory.Path, services);
// Assert
Assert.Empty(result.Plugins);
// The file cannot be read to verify its PE signature, so it is reported as not loadable rather than crashing the loader.
PluginLoadErrorDto error = Assert.Single(result.Errors);
Assert.Equal("locked", error.AssemblyName);
}
/// <summary>
/// Gets the path of the <c>Lumina.TestPlugin</c> assembly from the test output directory.
/// The assembly is referenced by the test project but no type from it is used, so it is not loaded
@@ -96,6 +212,18 @@ public class PluginLoaderTests
return Path.Combine(AppContext.BaseDirectory, "Lumina.TestPlugin.dll");
}
/// <summary>
/// Gets the path of a managed dependency assembly from the test output directory, standing in for the managed dependencies
/// a plugin ships next to itself (like PdfPig.dll and SkiaSharp.dll next to the PDF plugin). The <c>Microsoft.AspNetCore.SignalR.Core</c>
/// assembly is used because it does not reference the plugin contracts assembly, and reflecting over its types inside a plugin load
/// context throws, which reproduces the spurious load errors the loader used to record for dependency assemblies.
/// </summary>
/// <returns>The path of the managed dependency assembly.</returns>
private static string GetDependencyAssemblyPath()
{
return Path.Combine(AppContext.BaseDirectory, "Microsoft.AspNetCore.SignalR.Core.dll");
}
/// <summary>
/// Test helper managing a temporary plugins directory, deleted when the test finishes.
/// </summary>
@@ -116,6 +244,13 @@ public class PluginLoaderTests
File.WriteAllText(System.IO.Path.Combine(Path, fileName), content);
}
public string CreateFileReturningPath(string fileName, string content)
{
string filePath = System.IO.Path.Combine(Path, fileName);
File.WriteAllText(filePath, content);
return filePath;
}
public void CopyDll(string sourceDllPath)
{
File.Copy(sourceDllPath, System.IO.Path.Combine(Path, System.IO.Path.GetFileName(sourceDllPath)));
@@ -5,7 +5,6 @@ using NSubstitute;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
#endregion
namespace Lumina.Infrastructure.UnitTests.Core.Plugins;
@@ -22,7 +21,7 @@ public class PluginManagerTests
// Arrange
IPlugin firstPlugin = CreatePlugin(Guid.NewGuid(), "First Plugin");
IPlugin secondPlugin = CreatePlugin(Guid.NewGuid(), "Second Plugin");
PluginManager sut = new([firstPlugin, secondPlugin]);
PluginManager sut = new([firstPlugin, secondPlugin], []);
// Act
IReadOnlyList<IPlugin> result = sut.GetPlugins();
@@ -37,7 +36,7 @@ public class PluginManagerTests
public void GetPlugins_WhenNoPluginsWereLoaded_ShouldReturnEmptyList()
{
// Arrange
PluginManager sut = new([]);
PluginManager sut = new([], []);
// Act
IReadOnlyList<IPlugin> result = sut.GetPlugins();
@@ -52,7 +51,7 @@ public class PluginManagerTests
// Arrange
Guid pluginId = Guid.NewGuid();
IPlugin expectedPlugin = CreatePlugin(pluginId, "Expected Plugin");
PluginManager sut = new([expectedPlugin, CreatePlugin(Guid.NewGuid(), "Other Plugin")]);
PluginManager sut = new([expectedPlugin, CreatePlugin(Guid.NewGuid(), "Other Plugin")], []);
// Act
IPlugin? result = sut.GetPlugin(pluginId);
@@ -65,7 +64,7 @@ public class PluginManagerTests
public void GetPlugin_WhenPluginWithIdWasNotLoaded_ShouldReturnNull()
{
// Arrange
PluginManager sut = new([CreatePlugin(Guid.NewGuid(), "Loaded Plugin")]);
PluginManager sut = new([CreatePlugin(Guid.NewGuid(), "Loaded Plugin")], []);
// Act
IPlugin? result = sut.GetPlugin(Guid.NewGuid());
@@ -0,0 +1,152 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Contracts.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary.Reading;
using Lumina.Contracts.Fixtures.Core.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary.Reading;
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
using Lumina.Plugins.Contracts.Core.Reading;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Plugins.Contracts.UnitTests.Core.Reading;
/// <summary>
/// Contains unit tests for the <see cref="IBookReader"/> interface.
/// </summary>
[ExcludeFromCodeCoverage]
public class IBookReaderGenericTests
{
private readonly ReadingDocumentDtoFixture _readingDocumentDtoFixture = new();
[Fact]
public async Task OpenAsync_WhenCalled_ShouldForwardArgumentsToTheReaderImplementation()
{
// Arrange
string path = "/books/test.epub";
string workingDirectory = "/tmp/reading-cache";
bool shouldRenderPdfAsImages = true;
CancellationToken cancellationToken = CancellationToken.None;
ReadingDocumentDto expectedDocument = _readingDocumentDtoFixture.Create();
TestBookReader reader = new(expectedDocument, [1, 2, 3]);
// Act
ReadingDocumentDto result = await reader.OpenAsync(path, workingDirectory, shouldRenderPdfAsImages, cancellationToken);
// Assert
Assert.Equal(expectedDocument, result);
Assert.Equal(path, reader.ReceivedPath);
Assert.Equal(workingDirectory, reader.ReceivedWorkingDirectory);
Assert.Equal(shouldRenderPdfAsImages, reader.ReceivedShouldRenderPdfAsImages);
Assert.Equal(cancellationToken, reader.ReceivedCancellationToken);
}
[Fact]
public async Task GetResourceAsync_WhenCalled_ShouldForwardArgumentsToTheReaderImplementation()
{
// Arrange
string path = "/books/test.epub";
string workingDirectory = "/tmp/reading-cache";
string resourceKey = "resources/cover.png";
CancellationToken cancellationToken = CancellationToken.None;
byte[] expectedResource = [0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A];
TestBookReader reader = new(_readingDocumentDtoFixture.Create(), expectedResource);
// Act
byte[] result = await reader.GetResourceAsync(path, workingDirectory, resourceKey, cancellationToken);
// Assert
Assert.Equal(expectedResource, result);
Assert.Equal(path, reader.ReceivedResourcePath);
Assert.Equal(workingDirectory, reader.ReceivedResourceWorkingDirectory);
Assert.Equal(resourceKey, reader.ReceivedResourceKey);
Assert.Equal(cancellationToken, reader.ReceivedResourceCancellationToken);
}
/// <summary>
/// Test double for the book reader interface that records the forwarded arguments.
/// </summary>
[ExcludeFromCodeCoverage]
private sealed class TestBookReader : IBookReader
{
private readonly ReadingDocumentDto _document;
private readonly byte[] _resource;
/// <summary>
/// Gets the path that was forwarded to the OpenAsync implementation.
/// </summary>
public string? ReceivedPath { get; private set; }
/// <summary>
/// Gets the working directory that was forwarded to the OpenAsync implementation.
/// </summary>
public string? ReceivedWorkingDirectory { get; private set; }
/// <summary>
/// Gets the rendering preference that was forwarded to the OpenAsync implementation.
/// </summary>
public bool ReceivedShouldRenderPdfAsImages { get; private set; }
/// <summary>
/// Gets the cancellation token that was forwarded to the OpenAsync implementation.
/// </summary>
public CancellationToken ReceivedCancellationToken { get; private set; }
/// <summary>
/// Gets the path that was forwarded to the GetResourceAsync implementation.
/// </summary>
public string? ReceivedResourcePath { get; private set; }
/// <summary>
/// Gets the working directory that was forwarded to the GetResourceAsync implementation.
/// </summary>
public string? ReceivedResourceWorkingDirectory { get; private set; }
/// <summary>
/// Gets the resource key that was forwarded to the GetResourceAsync implementation.
/// </summary>
public string? ReceivedResourceKey { get; private set; }
/// <summary>
/// Gets the cancellation token that was forwarded to the GetResourceAsync implementation.
/// </summary>
public CancellationToken ReceivedResourceCancellationToken { get; private set; }
/// <summary>
/// Initializes a new instance of the <see cref="TestBookReader"/> class.
/// </summary>
/// <param name="document">The document returned by the OpenAsync implementation.</param>
/// <param name="resource">The resource data returned by the GetResourceAsync implementation.</param>
public TestBookReader(ReadingDocumentDto document, byte[] resource)
{
_document = document;
_resource = resource;
}
/// <inheritdoc/>
public IReadOnlyList<string> SupportedExtensions => [".epub"];
/// <inheritdoc/>
public IReadOnlyList<LibraryType> SupportedLibraryTypes => [LibraryType.EBook];
/// <inheritdoc/>
public Task<ReadingDocumentDto> OpenAsync(string path, string workingDirectory, bool shouldRenderPdfAsImages, CancellationToken cancellationToken)
{
ReceivedPath = path;
ReceivedWorkingDirectory = workingDirectory;
ReceivedShouldRenderPdfAsImages = shouldRenderPdfAsImages;
ReceivedCancellationToken = cancellationToken;
return Task.FromResult(_document);
}
/// <inheritdoc/>
public Task<byte[]> GetResourceAsync(string path, string workingDirectory, string resourceKey, CancellationToken cancellationToken)
{
ReceivedResourcePath = path;
ReceivedResourceWorkingDirectory = workingDirectory;
ReceivedResourceKey = resourceKey;
ReceivedResourceCancellationToken = cancellationToken;
return Task.FromResult(_resource);
}
}
}
@@ -0,0 +1,58 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Plugins.Contracts.Core.Reading;
using Lumina.Plugins.Epub.Common.DependencyInjection;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Diagnostics.CodeAnalysis;
#endregion
namespace Lumina.Plugins.Epub.UnitTests.Common.DependencyInjection;
/// <summary>
/// Contains unit tests for the <see cref="EpubServices"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class EpubServicesTests
{
[Fact]
public void AddEpubReader_WhenServicesIsNull_ShouldThrowArgumentNullException()
{
// Arrange
IServiceCollection services = null!;
// Act
Action act = () => services.AddEpubReader(pluginId: Guid.NewGuid());
// Assert
Assert.Throws<ArgumentNullException>(act);
}
[Fact]
public void AddEpubReader_WhenCalled_ShouldReturnTheSameServiceCollection()
{
// Arrange
ServiceCollection services = new();
// Act
IServiceCollection result = services.AddEpubReader(pluginId: Guid.NewGuid());
// Assert
Assert.Same(services, result);
}
[Fact]
public void AddEpubReader_WhenCalled_ShouldRegisterTheBookReaderForKeyedResolution()
{
// Arrange
Guid pluginId = Guid.NewGuid();
ServiceCollection services = new();
// Act
services.AddEpubReader(pluginId: pluginId);
ServiceProvider serviceProvider = services.BuildServiceProvider();
// Assert
Assert.NotNull(serviceProvider.GetKeyedService<IBookReader>(pluginId));
Assert.Null(serviceProvider.GetKeyedService<IBookReader>(Guid.NewGuid()));
}
}
@@ -0,0 +1,635 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Contracts.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary.Reading;
using Lumina.Plugins.Epub.Core.Epub;
using Lumina.Plugins.Epub.Fixtures.Core.Epub;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.IO;
using System.IO.Compression;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Threading;
#endregion
namespace Lumina.Plugins.Epub.UnitTests.Core.Epub;
/// <summary>
/// Contains unit tests for the <see cref="EpubDocumentParser"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class EpubDocumentParserTests : IDisposable
{
private readonly string _temporaryDirectory = Path.Combine(Path.GetTempPath(), $"lumina-epub-tests-{Guid.NewGuid():N}");
private readonly string _epubPath;
/// <summary>
/// Initializes a new instance of the <see cref="EpubDocumentParserTests"/> class.
/// </summary>
public EpubDocumentParserTests()
{
Directory.CreateDirectory(_temporaryDirectory);
_epubPath = Path.Combine(_temporaryDirectory, "minimal.epub");
}
[Fact]
public void Parse_WhenCalledOnValidEpub_ShouldReturnDocumentWithTitleAuthorAndSpine()
{
// Arrange
TestEpubFileFactory.CreateMinimalEpub(_epubPath);
string workingDirectory = Path.Combine(_temporaryDirectory, "work");
// Act
ReadingDocumentDto result = EpubDocumentParser.Parse(_epubPath, workingDirectory, CancellationToken.None);
// Assert
Assert.Equal("Minimal EPUB Book", result.Title);
Assert.Equal("Test Author", result.Author);
Assert.Equal(2, result.Spine.Count);
Assert.Equal("chapter1", result.Spine[0].LocationRef);
Assert.Equal("chapter2", result.Spine[1].LocationRef);
Assert.True(result.HasTextContent);
}
[Fact]
public void Parse_WhenCalledOnValidEpub_ShouldExtractResourcesAndRewriteReferences()
{
// Arrange
TestEpubFileFactory.CreateMinimalEpub(_epubPath);
string workingDirectory = Path.Combine(_temporaryDirectory, "work");
// Act
ReadingDocumentDto result = EpubDocumentParser.Parse(_epubPath, workingDirectory, CancellationToken.None);
// Assert
string expectedKey = CreateResourceKey("images/cover.png");
KeyValuePair<string, ReadingResourceInfoDto> resource = Assert.Single(result.Resources);
Assert.Equal(expectedKey, resource.Key);
Assert.Equal("image/png", resource.Value.MimeType);
Assert.True(File.Exists(Path.Combine(workingDirectory, resource.Value.RelativeFilePath)));
string sectionContent = File.ReadAllText(Path.Combine(workingDirectory, result.Spine[0].RelativeSectionFilePath));
Assert.Contains($"data-lumina-resource=\"{expectedKey}\"", sectionContent, StringComparison.Ordinal);
Assert.DoesNotContain("src=\"images/cover.png\"", sectionContent, StringComparison.Ordinal);
}
[Fact]
public void Parse_WhenSectionDeclaresADoctypeAndNamedEntities_ShouldRewriteItsReferencesAndResolveTheEntities()
{
// Arrange
TestEpubFileFactory.CreateEpubWithDoctypeAndNamedEntities(_epubPath);
string workingDirectory = Path.Combine(_temporaryDirectory, "work");
// Act
ReadingDocumentDto result = EpubDocumentParser.Parse(_epubPath, workingDirectory, CancellationToken.None);
// Assert
ReadingSpineItemDto spineItem = Assert.Single(result.Spine);
string sectionContent = File.ReadAllText(Path.Combine(workingDirectory, spineItem.RelativeSectionFilePath));
string expectedKey = CreateResourceKey("images/cover.png");
// The DTD declaration was tolerated and the named character references resolved, so the section was rewritten instead of
// being served "as-is": the internal image reference became the resource marker and the non-breaking spaces were decoded.
Assert.Contains($"data-lumina-resource=\"{expectedKey}\"", sectionContent, StringComparison.Ordinal);
Assert.DoesNotContain("src=\"images/cover.png\"", sectionContent, StringComparison.Ordinal);
Assert.DoesNotContain("<!DOCTYPE", sectionContent, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("&nbsp;", sectionContent, StringComparison.Ordinal);
Assert.Contains("Chapter\u00A0One", sectionContent, StringComparison.Ordinal);
}
[Fact]
public void Parse_WhenCalledOnValidEpub_ShouldBuildTableOfContentsFromTheNavigationDocument()
{
// Arrange
TestEpubFileFactory.CreateMinimalEpub(_epubPath);
string workingDirectory = Path.Combine(_temporaryDirectory, "work");
// Act
ReadingDocumentDto result = EpubDocumentParser.Parse(_epubPath, workingDirectory, CancellationToken.None);
// Assert
// The parser collects every list item of the navigation document, including the nested ones, so the nested
// "Part One" entry is present both at the top level and as a child of its parent entry; the anchor-less item
// yields a non-navigable entry.
Assert.Equal(4, result.TableOfContents.Count);
ReadingTocEntryDto firstEntry = result.TableOfContents[0];
Assert.Equal("Chapter One", firstEntry.Label);
Assert.Equal("chapter1", firstEntry.LocationRef);
ReadingTocEntryDto childEntry = Assert.Single(firstEntry.Children);
Assert.Equal("Part One", childEntry.Label);
Assert.Equal("chapter1", childEntry.LocationRef);
Assert.Equal("Part One", result.TableOfContents[1].Label);
Assert.Equal("chapter1", result.TableOfContents[1].LocationRef);
Assert.Equal("Chapter Two", result.TableOfContents[2].Label);
Assert.Equal("chapter2", result.TableOfContents[2].LocationRef);
Assert.Equal(string.Empty, result.TableOfContents[3].Label);
Assert.Equal(string.Empty, result.TableOfContents[3].LocationRef);
Assert.Equal("Chapter One", result.Spine[0].Title);
Assert.Equal("Chapter Two", result.Spine[1].Title);
}
[Fact]
public void Parse_WhenCalledOnValidEpub_ShouldExposeTheCoverResourceKey()
{
// Arrange
TestEpubFileFactory.CreateMinimalEpub(_epubPath);
string workingDirectory = Path.Combine(_temporaryDirectory, "work");
// Act
ReadingDocumentDto result = EpubDocumentParser.Parse(_epubPath, workingDirectory, CancellationToken.None);
// Assert
Assert.Equal(CreateResourceKey("images/cover.png"), result.CoverResourceKey);
}
[Fact]
public void Parse_WhenEpubHasNoContainerDocument_ShouldThrowInvalidDataException()
{
// Arrange
TestEpubFileFactory.CreateEpubWithoutContainer(_epubPath);
string workingDirectory = Path.Combine(_temporaryDirectory, "work");
// Act
Action act = () => EpubDocumentParser.Parse(_epubPath, workingDirectory, CancellationToken.None);
// Assert
InvalidDataException exception = Assert.Throws<InvalidDataException>(act);
Assert.Contains("OPF", exception.Message, StringComparison.Ordinal);
}
[Fact]
public void Parse_WhenEpubHasNoSpine_ShouldThrowInvalidDataException()
{
// Arrange
TestEpubFileFactory.CreateEpubWithoutSpine(_epubPath);
string workingDirectory = Path.Combine(_temporaryDirectory, "work");
// Act
Action act = () => EpubDocumentParser.Parse(_epubPath, workingDirectory, CancellationToken.None);
// Assert
InvalidDataException exception = Assert.Throws<InvalidDataException>(act);
Assert.Contains("reading sections", exception.Message, StringComparison.Ordinal);
}
[Fact]
public void Parse_WhenEpubHasTraversalHref_ShouldSkipTheBrokenItemAndKeepTheRest()
{
// Arrange
TestEpubFileFactory.CreateEpubWithTraversalHref(_epubPath);
string workingDirectory = Path.Combine(_temporaryDirectory, "work");
// Act
ReadingDocumentDto result = EpubDocumentParser.Parse(_epubPath, workingDirectory, CancellationToken.None);
// Assert
// The broken manifest item is skipped, while the resolvable section is still parsed.
Assert.Equal("Traversal Href", result.Title);
ReadingSpineItemDto spineItem = Assert.Single(result.Spine);
Assert.Equal("chapter2", spineItem.LocationRef);
}
[Fact]
public void Parse_WhenSectionIsNotWellFormedXml_ShouldServeTheSectionAsIs()
{
// Arrange
TestEpubFileFactory.CreateEpubWithBrokenSection(_epubPath);
string workingDirectory = Path.Combine(_temporaryDirectory, "work");
// Act
ReadingDocumentDto result = EpubDocumentParser.Parse(_epubPath, workingDirectory, CancellationToken.None);
// Assert
ReadingSpineItemDto spineItem = Assert.Single(result.Spine);
string sectionContent = File.ReadAllText(Path.Combine(workingDirectory, spineItem.RelativeSectionFilePath));
Assert.Contains("Not well formed", sectionContent, StringComparison.Ordinal);
}
[Fact]
public void Parse_WhenEpub2HasNcxToc_ShouldBuildTableOfContentsFromTheNcxDocument()
{
// Arrange
TestEpubFileFactory.CreateEpubWithNcxToc(_epubPath);
string workingDirectory = Path.Combine(_temporaryDirectory, "work");
// Act
ReadingDocumentDto result = EpubDocumentParser.Parse(_epubPath, workingDirectory, CancellationToken.None);
// Assert
Assert.Equal("EPUB 2 Book", result.Title);
// The NCX entries: Chapter One (with its nested Part One), Chapter Two, the anchor-less entry whose target is
// missing, and the entry with a blank label and no content source.
Assert.Equal(4, result.TableOfContents.Count);
ReadingTocEntryDto firstEntry = result.TableOfContents[0];
Assert.Equal("NCX Chapter One", firstEntry.Label);
Assert.Equal("chapter1", firstEntry.LocationRef);
ReadingTocEntryDto childEntry = Assert.Single(firstEntry.Children);
Assert.Equal("NCX Part One", childEntry.Label);
Assert.Equal("chapter1", childEntry.LocationRef);
Assert.Equal("NCX Chapter Two", result.TableOfContents[1].Label);
Assert.Equal("chapter2", result.TableOfContents[1].LocationRef);
// A navigation point without a label and pointing at an unknown file yields a non-navigable entry.
Assert.Equal(string.Empty, result.TableOfContents[2].Label);
Assert.Equal(string.Empty, result.TableOfContents[2].LocationRef);
// A navigation point with a blank label and no content source also yields a non-navigable entry.
Assert.Equal(string.Empty, result.TableOfContents[3].Label);
Assert.Equal(string.Empty, result.TableOfContents[3].LocationRef);
Assert.Equal("NCX Chapter One", result.Spine[0].Title);
Assert.Equal("NCX Chapter Two", result.Spine[1].Title);
// The cover is declared with an EPUB 2 meta element, and is still exposed.
Assert.Equal(CreateResourceKey("images/cover.png"), result.CoverResourceKey);
}
[Fact]
public void Parse_WhenEpub2HasNcxTocAndNoNavigationDocument_ShouldUseTheNcxDocument()
{
// Arrange
TestEpubFileFactory.CreateEpubWithNcxToc(_epubPath);
string workingDirectory = Path.Combine(_temporaryDirectory, "work");
// Act
ReadingDocumentDto result = EpubDocumentParser.Parse(_epubPath, workingDirectory, CancellationToken.None);
// Assert
// No EPUB 3 navigation document is present, so every named entry comes from the NCX document.
Assert.Equal("NCX Chapter One", result.TableOfContents[0].Label);
Assert.Equal("NCX Chapter Two", result.TableOfContents[1].Label);
}
[Fact]
public void Parse_WhenManifestCarriesVariedMediaTypes_ShouldExtractOnlyTheUsableResources()
{
// Arrange
TestEpubFileFactory.CreateEpubWithVariedMediaTypes(_epubPath);
string workingDirectory = Path.Combine(_temporaryDirectory, "work");
// Act
ReadingDocumentDto result = EpubDocumentParser.Parse(_epubPath, workingDirectory, CancellationToken.None);
// Assert
// The font, audio, video, and CSS items are extracted as resources; the script is not a resource the reader serves.
Assert.Equal(6, result.Resources.Count);
Assert.Contains(result.Resources, resource => resource.Value.MimeType == "font/woff2");
Assert.Contains(result.Resources, resource => resource.Value.MimeType == "application/vnd.ms-opentype");
Assert.Contains(result.Resources, resource => resource.Value.MimeType == "application/x-font-ttf");
Assert.Contains(result.Resources, resource => resource.Value.MimeType == "audio/mpeg");
Assert.Contains(result.Resources, resource => resource.Value.MimeType == "video/mp4");
Assert.DoesNotContain(result.Resources, resource => resource.Value.MimeType == "application/javascript");
Assert.Contains(result.Resources, resource => resource.Value.MimeType == "text/css");
// The section is the only spine item, so the document still reads.
Assert.Single(result.Spine);
}
[Fact]
public void Parse_WhenContainerDocumentIsMalformed_ShouldThrowInvalidDataException()
{
// Arrange
TestEpubFileFactory.CreateEpubWithMalformedContainer(_epubPath);
string workingDirectory = Path.Combine(_temporaryDirectory, "work");
// Act
Action act = () => EpubDocumentParser.Parse(_epubPath, workingDirectory, CancellationToken.None);
// Assert
InvalidDataException exception = Assert.Throws<InvalidDataException>(act);
Assert.Contains("OPF", exception.Message, StringComparison.Ordinal);
}
[Fact]
public void Parse_WhenNavigationDocumentHasNoTocNav_ShouldReturnEmptyTableOfContents()
{
// Arrange
TestEpubFileFactory.CreateEpubWithNonTocNav(_epubPath);
string workingDirectory = Path.Combine(_temporaryDirectory, "work");
// Act
ReadingDocumentDto result = EpubDocumentParser.Parse(_epubPath, workingDirectory, CancellationToken.None);
// Assert
Assert.Empty(result.TableOfContents);
Assert.Single(result.Spine);
}
[Fact]
public void Parse_WhenEpubHasNoTitle_ShouldUseTheFileNameAsTheTitle()
{
// Arrange
TestEpubFileFactory.CreateEpubWithoutTitle(_epubPath);
string workingDirectory = Path.Combine(_temporaryDirectory, "work");
// Act
ReadingDocumentDto result = EpubDocumentParser.Parse(_epubPath, workingDirectory, CancellationToken.None);
// Assert
Assert.Equal("minimal", result.Title);
Assert.Null(result.Author);
}
[Fact]
public void Parse_WhenManifestContainsBrokenItems_ShouldSkipThemAndKeepTheValidSections()
{
// Arrange
TestEpubFileFactory.CreateEpubWithBrokenManifest(_epubPath);
string workingDirectory = Path.Combine(_temporaryDirectory, "work");
// Act
ReadingDocumentDto result = EpubDocumentParser.Parse(_epubPath, workingDirectory, CancellationToken.None);
// Assert
// The two valid spine items are kept, and the reference to the unknown Id is dropped.
Assert.Equal(2, result.Spine.Count);
Assert.Equal("chapter1", result.Spine[0].LocationRef);
Assert.Equal("chapter2", result.Spine[1].LocationRef);
// The plain item (no properties) is not extracted as a resource because it is not a spine section and not a usable media type.
Assert.Empty(result.Resources);
}
[Fact]
public void Parse_WhenArchiveHasTooManyEntries_ShouldThrowInvalidDataException()
{
// Arrange
TestEpubFileFactory.CreateEpubWithTooManyEntries(_epubPath);
string workingDirectory = Path.Combine(_temporaryDirectory, "work");
// Act
Action act = () => EpubDocumentParser.Parse(_epubPath, workingDirectory, CancellationToken.None);
// Assert
InvalidDataException exception = Assert.Throws<InvalidDataException>(act);
Assert.Contains("too many entries", exception.Message, StringComparison.OrdinalIgnoreCase);
}
[Fact]
public void Parse_WhenArchiveExpandsBeyondTheLimit_ShouldThrowInvalidDataException()
{
// Arrange
TestEpubFileFactory.CreateEpubWithTooLargeExpandedSize(_epubPath);
string workingDirectory = Path.Combine(_temporaryDirectory, "work");
// Act
Action act = () => EpubDocumentParser.Parse(_epubPath, workingDirectory, CancellationToken.None);
// Assert
InvalidDataException exception = Assert.Throws<InvalidDataException>(act);
Assert.Contains("too large", exception.Message, StringComparison.OrdinalIgnoreCase);
}
[Fact]
public void Parse_WhenRootfileHasNoFullPath_ShouldThrowInvalidDataException()
{
// Arrange
TestEpubFileFactory.CreateEpubWithRootfileWithoutPath(_epubPath);
string workingDirectory = Path.Combine(_temporaryDirectory, "work");
// Act
Action act = () => EpubDocumentParser.Parse(_epubPath, workingDirectory, CancellationToken.None);
// Assert
InvalidDataException exception = Assert.Throws<InvalidDataException>(act);
Assert.Contains("OPF", exception.Message, StringComparison.Ordinal);
}
[Fact]
public void Parse_WhenArchiveFilesAreMissing_ShouldSkipTheBrokenItemsAndKeepTheReadableSection()
{
// Arrange
TestEpubFileFactory.CreateEpubWithMissingArchiveFiles(_epubPath);
string workingDirectory = Path.Combine(_temporaryDirectory, "work");
// Act
ReadingDocumentDto result = EpubDocumentParser.Parse(_epubPath, workingDirectory, CancellationToken.None);
// Assert
// The section whose file is missing from the archive is skipped, while the readable one is kept.
Assert.Single(result.Spine);
Assert.Equal("chapter1", result.Spine[0].LocationRef);
// The resource whose file is missing from the archive is not extracted.
Assert.Empty(result.Resources);
}
[Fact]
public void Parse_WhenTwoItemsShareAHref_ShouldExtractTheResourceOnce()
{
// Arrange
TestEpubFileFactory.CreateEpubWithDuplicateResource(_epubPath);
string workingDirectory = Path.Combine(_temporaryDirectory, "work");
// Act
ReadingDocumentDto result = EpubDocumentParser.Parse(_epubPath, workingDirectory, CancellationToken.None);
// Assert
string expectedKey = CreateResourceKey("images/cover.png");
KeyValuePair<string, ReadingResourceInfoDto> resource = Assert.Single(result.Resources);
Assert.Equal(expectedKey, resource.Key);
}
[Fact]
public void Parse_WhenNavigationDocumentIsMalformed_ShouldReturnEmptyTableOfContents()
{
// Arrange
TestEpubFileFactory.CreateEpubWithMalformedNavigationDocument(_epubPath);
string workingDirectory = Path.Combine(_temporaryDirectory, "work");
// Act
ReadingDocumentDto result = EpubDocumentParser.Parse(_epubPath, workingDirectory, CancellationToken.None);
// Assert
Assert.Empty(result.TableOfContents);
Assert.Single(result.Spine);
}
[Fact]
public void Parse_WhenNcxDocumentIsMalformed_ShouldReturnEmptyTableOfContents()
{
// Arrange
TestEpubFileFactory.CreateEpubWithMalformedNcx(_epubPath);
string workingDirectory = Path.Combine(_temporaryDirectory, "work");
// Act
ReadingDocumentDto result = EpubDocumentParser.Parse(_epubPath, workingDirectory, CancellationToken.None);
// Assert
Assert.Empty(result.TableOfContents);
Assert.Single(result.Spine);
}
[Fact]
public void Parse_WhenSectionCarriesVariedReferences_ShouldRewriteOnlyTheResolvableOnes()
{
// Arrange
TestEpubFileFactory.CreateEpubWithVariedReferences(_epubPath);
string workingDirectory = Path.Combine(_temporaryDirectory, "work");
// Act
ReadingDocumentDto result = EpubDocumentParser.Parse(_epubPath, workingDirectory, CancellationToken.None);
// Assert
string sectionContent = File.ReadAllText(Path.Combine(workingDirectory, result.Spine[0].RelativeSectionFilePath));
string expectedKey = CreateResourceKey("images/cover.png");
// The resolvable internal image is rewritten to the resource marker; the fragment variant resolves to the same image.
Assert.Contains($"data-lumina-resource=\"{expectedKey}\"", sectionContent, StringComparison.Ordinal);
Assert.Equal(2, CountOccurrences(sectionContent, "data-lumina-resource"));
// The same-page anchor, data URI, absolute links, mailto, and broken path keep their original value.
Assert.Contains("href=\"#part\"", sectionContent, StringComparison.Ordinal);
Assert.Contains("data:image/png;base64,AAAA", sectionContent, StringComparison.Ordinal);
Assert.Contains("href=\"http://example.com\"", sectionContent, StringComparison.Ordinal);
Assert.Contains("href=\"https://example.com\"", sectionContent, StringComparison.Ordinal);
Assert.Contains("href=\"mailto:a@b.com\"", sectionContent, StringComparison.Ordinal);
Assert.Contains("href=\"tel:+123\"", sectionContent, StringComparison.Ordinal);
Assert.Contains("src=\"missing/image.png\"", sectionContent, StringComparison.Ordinal);
}
[Fact]
public void Parse_WhenEpubHasNoMetadataElement_ShouldUseTheFileNameAsTheTitleAndLeaveAuthorNull()
{
// Arrange
TestEpubFileFactory.CreateEpubWithoutMetadataElement(_epubPath);
string workingDirectory = Path.Combine(_temporaryDirectory, "work");
// Act
ReadingDocumentDto result = EpubDocumentParser.Parse(_epubPath, workingDirectory, CancellationToken.None);
// Assert
Assert.Equal("minimal", result.Title);
Assert.Null(result.Author);
Assert.Single(result.Spine);
}
[Fact]
public void Parse_WhenOpfFileIsMissing_ShouldThrowInvalidDataException()
{
// Arrange
TestEpubFileFactory.CreateEpubWithMissingOpf(_epubPath);
string workingDirectory = Path.Combine(_temporaryDirectory, "work");
// Act
Action act = () => EpubDocumentParser.Parse(_epubPath, workingDirectory, CancellationToken.None);
// Assert
Assert.Throws<InvalidDataException>(act);
}
[Fact]
public void Parse_WhenOpfSitsAtTheArchiveRoot_ShouldResolveSectionsRelativeToIt()
{
// Arrange
TestEpubFileFactory.CreateEpubWithRootLevelOpf(_epubPath);
string workingDirectory = Path.Combine(_temporaryDirectory, "work");
// Act
ReadingDocumentDto result = EpubDocumentParser.Parse(_epubPath, workingDirectory, CancellationToken.None);
// Assert
Assert.Equal("Root Level OPF", result.Title);
ReadingSpineItemDto spineItem = Assert.Single(result.Spine);
Assert.Equal("chapter1", spineItem.LocationRef);
}
[Fact]
public void Parse_WhenResourceHrefEscapesTheArchive_ShouldSkipTheResource()
{
// Arrange
TestEpubFileFactory.CreateEpubWithEscapingResourceHref(_epubPath);
string workingDirectory = Path.Combine(_temporaryDirectory, "work");
// Act
ReadingDocumentDto result = EpubDocumentParser.Parse(_epubPath, workingDirectory, CancellationToken.None);
// Assert
Assert.Equal("Escaping Resource", result.Title);
Assert.Empty(result.Resources);
Assert.Single(result.Spine);
}
[Fact]
public void Parse_WhenResourceExceedsTheSizeCap_ShouldThrowInvalidDataException()
{
// Arrange
TestEpubFileFactory.CreateEpubWithOversizedResource(_epubPath);
string workingDirectory = Path.Combine(_temporaryDirectory, "work");
// Act
Action act = () => EpubDocumentParser.Parse(_epubPath, workingDirectory, CancellationToken.None);
// Assert
InvalidDataException exception = Assert.Throws<InvalidDataException>(act);
Assert.Contains("too large", exception.Message, StringComparison.OrdinalIgnoreCase);
}
[Fact]
public void Parse_WhenEntriesFitPerEntryCapsButActualExpandedBytesExceedTheTotalCap_ShouldThrowInvalidDataException()
{
// Arrange
// The entries each declare a tiny uncompressed size and each actual one is under its per-entry cap, so only the budget
// that counts the bytes actually read while the entries are streamed can reject the archive.
TestEpubFileFactory.CreateEpubWithUnderPerEntryCapsButOversizedExpandedSize(_epubPath);
string workingDirectory = Path.Combine(_temporaryDirectory, "work");
// The declared sizes stay well under the 256 MB cap, so the declared-size quick guard in ValidateArchive cannot be
// what rejects the archive; the rejection can only come from counting the bytes actually read.
long declaredTotalBytes;
using (FileStream fileStream = File.OpenRead(_epubPath))
using (ZipArchive zipArchive = new(fileStream, ZipArchiveMode.Read))
declaredTotalBytes = zipArchive.Entries.Sum(entry => entry.Length);
Assert.True(declaredTotalBytes <= 256 * 1024 * 1024);
// Act
Action act = () => EpubDocumentParser.Parse(_epubPath, workingDirectory, CancellationToken.None);
// Assert
// The total-expanded message is specific to the archive-wide cap, unlike the per-entry "too large" message.
InvalidDataException exception = Assert.Throws<InvalidDataException>(act);
Assert.Contains("expanded EPUB archive", exception.Message, StringComparison.OrdinalIgnoreCase);
}
[Fact]
public void Parse_WhenManifestItemHasNoMediaType_ShouldSkipIt()
{
// Arrange
TestEpubFileFactory.CreateEpubWithMissingMediaType(_epubPath);
string workingDirectory = Path.Combine(_temporaryDirectory, "work");
// Act
ReadingDocumentDto result = EpubDocumentParser.Parse(_epubPath, workingDirectory, CancellationToken.None);
// Assert
// A manifest item without a media type cannot be classified as an extractable resource, so it is skipped.
Assert.Empty(result.Resources);
Assert.Single(result.Spine);
}
/// <summary>
/// Counts the occurrences of <paramref name="needle"/> in <paramref name="haystack"/>.
/// </summary>
/// <param name="haystack">The text to search.</param>
/// <param name="needle">The substring to count.</param>
/// <returns>The number of occurrences of the substring.</returns>
private static int CountOccurrences(string haystack, string needle)
{
int count = 0;
int index = 0;
while ((index = haystack.IndexOf(needle, index, StringComparison.Ordinal)) >= 0)
{
count++;
index += needle.Length;
}
return count;
}
/// <summary>
/// Computes the resource key the parser derives from a manifest href.
/// </summary>
/// <param name="href">The manifest href.</param>
/// <returns>The resource key of the href.</returns>
private static string CreateResourceKey(string href)
{
return Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes(href)))[..32].ToLowerInvariant();
}
/// <inheritdoc/>
public void Dispose()
{
if (Directory.Exists(_temporaryDirectory))
Directory.Delete(_temporaryDirectory, recursive: true);
}
}
@@ -0,0 +1,96 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Plugins.Contracts.Common.Models.DTO.Settings;
using Lumina.Plugins.Contracts.Core.Reading;
using Lumina.Plugins.Epub.Core;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
#endregion
namespace Lumina.Plugins.Epub.UnitTests.Core;
/// <summary>
/// Contains unit tests for the <see cref="EpubPlugin"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class EpubPluginTests
{
private readonly EpubPlugin _sut = new();
[Fact]
public void Id_WhenCalled_ShouldReturnStablePluginIdentifier()
{
// Act
Guid result = _sut.Id;
// Assert
Assert.Equal(EpubPlugin.s_pluginId, result);
Assert.Equal(new Guid("b1e8a8e0-4f3a-4d2c-9a1e-6d3f8a9b2c3d"), result);
}
[Fact]
public void Name_WhenCalled_ShouldReturnPluginDisplayName()
{
// Act
string result = _sut.Name;
// Assert
Assert.Equal("EPUB Reader", result);
}
[Fact]
public void Author_WhenCalled_ShouldReturnPluginAuthor()
{
// Act
string result = _sut.Author;
// Assert
Assert.Equal("Lumina", result);
}
[Fact]
public void Version_WhenCalled_ShouldReturnPluginVersion()
{
// Act
Version result = _sut.Version;
// Assert
Assert.Equal(new Version(1, 0, 0), result);
}
[Fact]
public void Description_WhenCalled_ShouldReturnPluginDescription()
{
// Act
string result = _sut.Description;
// Assert
Assert.Equal("Allows reading of EPUB format books.", result);
}
[Fact]
public void GetSettingsSchema_WhenCalled_ShouldReturnEmptySettingsSchema()
{
// Act
IReadOnlyList<PluginSettingDescriptorDto> result = _sut.GetSettingsSchema();
// Assert
Assert.Empty(result);
}
[Fact]
public void RegisterServices_WhenCalled_ShouldRegisterTheKeyedBookReader()
{
// Arrange
ServiceCollection services = new();
// Act
_sut.RegisterServices(services);
ServiceProvider serviceProvider = services.BuildServiceProvider();
// Assert
Assert.NotNull(serviceProvider.GetKeyedService<IBookReader>(EpubPlugin.s_pluginId));
Assert.Null(serviceProvider.GetKeyedService<IBookReader>(Guid.NewGuid()));
}
}
@@ -0,0 +1,88 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Contracts.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary.Reading;
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
using Lumina.Plugins.Epub.Core;
using Lumina.Plugins.Epub.Fixtures.Core.Epub;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.IO;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Plugins.Epub.UnitTests.Core;
/// <summary>
/// Contains unit tests for the <see cref="EpubReader"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class EpubReaderTests : IDisposable
{
private readonly string _temporaryDirectory = Path.Combine(Path.GetTempPath(), $"lumina-epub-reader-{Guid.NewGuid():N}");
private readonly string _epubPath;
private readonly EpubReader _sut = new();
/// <summary>
/// Initializes a new instance of the <see cref="EpubReaderTests"/> class.
/// </summary>
public EpubReaderTests()
{
Directory.CreateDirectory(_temporaryDirectory);
_epubPath = Path.Combine(_temporaryDirectory, "minimal.epub");
TestEpubFileFactory.CreateMinimalEpub(_epubPath);
}
[Fact]
public void SupportedExtensions_WhenAccessed_ShouldOnlyContainEpub()
{
// Assert
Assert.Equal([".epub"], _sut.SupportedExtensions);
}
[Fact]
public void SupportedLibraryTypes_WhenAccessed_ShouldContainEBookAndBook()
{
// Assert
Assert.Equal([LibraryType.EBook, LibraryType.Book], _sut.SupportedLibraryTypes);
}
[Fact]
public async Task OpenAsync_WhenCalled_ShouldReturnTheParsedDocument()
{
// Arrange
string workingDirectory = Path.Combine(_temporaryDirectory, "work");
// Act
ReadingDocumentDto result = await _sut.OpenAsync(_epubPath, workingDirectory, shouldRenderPdfAsImages: false, CancellationToken.None);
// Assert
Assert.Equal("Minimal EPUB Book", result.Title);
Assert.Equal(2, result.Spine.Count);
}
[Fact]
public async Task GetResourceAsync_WhenResourceWasExtracted_ShouldReturnItsBytes()
{
// Arrange
string workingDirectory = Path.Combine(_temporaryDirectory, "work");
ReadingDocumentDto document = await _sut.OpenAsync(_epubPath, workingDirectory, shouldRenderPdfAsImages: false, CancellationToken.None);
string resourceKey = document.Resources.Keys.Single();
// Act
byte[] result = await _sut.GetResourceAsync(_epubPath, workingDirectory, resourceKey, CancellationToken.None);
// Assert
Assert.NotNull(result);
Assert.NotEmpty(result);
}
/// <inheritdoc/>
public void Dispose()
{
if (Directory.Exists(_temporaryDirectory))
Directory.Delete(_temporaryDirectory, recursive: true);
}
}
@@ -0,0 +1,48 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net10.0</TargetFramework>
<ImplicitUsings>disable</ImplicitUsings>
<Nullable>enable</Nullable>
<IsPackable>false</IsPackable>
<IsTestProject>true</IsTestProject>
</PropertyGroup>
<ItemGroup>
<AssemblyAttribute Include="Xunit.CollectionBehaviorAttribute">
<_Parameter1>DisableTestParallelization = true</_Parameter1>
<_Parameter1_IsLiteral>true</_Parameter1_IsLiteral>
</AssemblyAttribute>
</ItemGroup>
<ItemGroup>
<PackageReference Include="AutoFixture.AutoNSubstitute" />
<PackageReference Include="AutoFixture.Xunit2" />
<PackageReference Include="Bogus" />
<PackageReference Include="coverlet.collector">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
<PackageReference Include="Microsoft.Extensions.DependencyInjection" />
<PackageReference Include="Microsoft.NET.Test.Sdk" />
<PackageReference Include="NSubstitute" />
<PackageReference Include="xunit" />
<PackageReference Include="xunit.runner.visualstudio">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
</ItemGroup>
<ItemGroup>
<Using Include="Xunit" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\..\..\plugins\Lumina.Plugins.Epub\Lumina.Plugins.Epub.csproj" />
<ProjectReference Include="..\..\..\src\Lumina.Plugins.Contracts\Lumina.Plugins.Contracts.csproj" />
<ProjectReference Include="..\..\Common\Lumina.Contracts.Fixtures\Lumina.Contracts.Fixtures.csproj" />
<ProjectReference Include="..\..\Common\Lumina.Plugins.Epub.Fixtures\Lumina.Plugins.Epub.Fixtures.csproj" />
</ItemGroup>
</Project>
@@ -0,0 +1,58 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Plugins.Contracts.Core.Reading;
using Lumina.Plugins.Pdf.Common.DependencyInjection;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Diagnostics.CodeAnalysis;
#endregion
namespace Lumina.Plugins.Pdf.UnitTests.Common.DependencyInjection;
/// <summary>
/// Contains unit tests for the <see cref="PdfServices"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class PdfServicesTests
{
[Fact]
public void AddPdfReader_WhenServicesIsNull_ShouldThrowArgumentNullException()
{
// Arrange
IServiceCollection services = null!;
// Act
Action act = () => services.AddPdfReader(pluginId: Guid.NewGuid());
// Assert
Assert.Throws<ArgumentNullException>(act);
}
[Fact]
public void AddPdfReader_WhenCalled_ShouldReturnTheSameServiceCollection()
{
// Arrange
ServiceCollection services = new();
// Act
IServiceCollection result = services.AddPdfReader(pluginId: Guid.NewGuid());
// Assert
Assert.Same(services, result);
}
[Fact]
public void AddPdfReader_WhenCalled_ShouldRegisterTheBookReaderForKeyedResolution()
{
// Arrange
Guid pluginId = Guid.NewGuid();
ServiceCollection services = new();
// Act
services.AddPdfReader(pluginId: pluginId);
ServiceProvider serviceProvider = services.BuildServiceProvider();
// Assert
Assert.NotNull(serviceProvider.GetKeyedService<IBookReader>(pluginId));
Assert.Null(serviceProvider.GetKeyedService<IBookReader>(Guid.NewGuid()));
}
}
@@ -0,0 +1,241 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Contracts.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary.Reading;
using Lumina.Plugins.Pdf.Core.Pdf;
using Lumina.Plugins.Pdf.Fixtures.Core.Pdf;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.IO;
using System.Runtime.Versioning;
using System.Threading;
#endregion
namespace Lumina.Plugins.Pdf.UnitTests.Core.Pdf;
/// <summary>
/// Contains unit tests for the <see cref="PdfDocumentParser"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class PdfDocumentParserTests : IDisposable
{
private readonly string _temporaryDirectory = Path.Combine(Path.GetTempPath(), $"lumina-pdf-tests-{Guid.NewGuid():N}");
private readonly string _pdfPath;
/// <summary>
/// Initializes a new instance of the <see cref="PdfDocumentParserTests"/> class.
/// </summary>
public PdfDocumentParserTests()
{
Directory.CreateDirectory(_temporaryDirectory);
_pdfPath = Path.Combine(_temporaryDirectory, "minimal.pdf");
TestPdfFileFactory.CreateMinimalPdf(_pdfPath);
}
[Fact]
public void Parse_WhenCalledOnPdfWithTextLayer_ShouldReturnDocumentWithTextSections()
{
// Arrange
string workingDirectory = Path.Combine(_temporaryDirectory, "work");
// Act
ReadingDocumentDto result = PdfDocumentParser.Parse(_pdfPath, workingDirectory, shouldRenderPdfAsImages: false, CancellationToken.None);
// Assert
Assert.Equal("minimal", result.Title);
Assert.True(result.HasTextContent);
ReadingSpineItemDto spineItem = Assert.Single(result.Spine);
Assert.Equal("page:1", spineItem.LocationRef);
string sectionContent = File.ReadAllText(Path.Combine(workingDirectory, spineItem.RelativeSectionFilePath));
Assert.Contains("<p>Hello PDF Page 1</p>", sectionContent, StringComparison.Ordinal);
Assert.Empty(result.Resources);
}
[Fact]
public void Parse_WhenCalledWithRenderAsImages_ShouldReturnDocumentWithImageSectionsAndNoTextContent()
{
// Arrange
string workingDirectory = Path.Combine(_temporaryDirectory, "work");
// Act
ReadingDocumentDto result = PdfDocumentParser.Parse(_pdfPath, workingDirectory, shouldRenderPdfAsImages: true, CancellationToken.None);
// Assert
Assert.Equal("minimal", result.Title);
Assert.False(result.HasTextContent);
ReadingSpineItemDto spineItem = Assert.Single(result.Spine);
Assert.Equal("page:1", spineItem.LocationRef);
KeyValuePair<string, ReadingResourceInfoDto> resource = Assert.Single(result.Resources);
Assert.Equal("page:1", resource.Key);
Assert.Equal("image/png", resource.Value.MimeType);
string sectionContent = File.ReadAllText(Path.Combine(workingDirectory, spineItem.RelativeSectionFilePath));
Assert.Contains("data-lumina-resource=\"page:1\"", sectionContent, StringComparison.Ordinal);
}
[Fact]
public void Parse_WhenPdfFileDoesNotExist_ShouldThrowFileNotFoundException()
{
// Arrange
string missingPdfPath = Path.Combine(_temporaryDirectory, "missing.pdf");
string workingDirectory = Path.Combine(_temporaryDirectory, "work");
// Act
Action act = () => PdfDocumentParser.Parse(missingPdfPath, workingDirectory, shouldRenderPdfAsImages: false, CancellationToken.None);
// Assert
Assert.Throws<FileNotFoundException>(act);
}
[SupportedOSPlatform("windows")]
[Fact]
public void RenderResource_WhenResourceKeyDoesNotIdentifyAPage_ShouldThrowInvalidDataException()
{
// Act
Action act = () => PdfDocumentParser.RenderResource(_pdfPath, "not-a-page", CancellationToken.None);
// Assert
Assert.Throws<InvalidDataException>(act);
}
[SupportedOSPlatform("windows")]
[Fact]
public void RenderResource_WhenResourceKeyNamesAPageBeyondThePageCap_ShouldThrowInvalidDataException()
{
// Act
// The minimal PDF has a single page, but the key is rejected by the page cap before the document is even opened.
Action act = () => PdfDocumentParser.RenderResource(_pdfPath, "page:10001", CancellationToken.None);
// Assert
Assert.Throws<InvalidDataException>(act);
}
[SupportedOSPlatform("windows")]
[Fact]
public void RenderResource_WhenResourceKeyNamesAPageBeyondTheDocument_ShouldThrowInvalidDataException()
{
// Act
// The minimal PDF has a single page, so page 2 is rejected against the page count of the document without rendering it.
Action act = () => PdfDocumentParser.RenderResource(_pdfPath, "page:2", CancellationToken.None);
// Assert
Assert.Throws<InvalidDataException>(act);
}
[Fact]
public void Parse_WhenPdfHasBookmarks_ShouldBuildTableOfContentsFromTheOutline()
{
// Arrange
string outlinedPdfPath = Path.Combine(_temporaryDirectory, "outlined.pdf");
TestPdfFileFactory.CreatePdfWithOutline(outlinedPdfPath);
string workingDirectory = Path.Combine(_temporaryDirectory, "work");
// Act
ReadingDocumentDto result = PdfDocumentParser.Parse(outlinedPdfPath, workingDirectory, shouldRenderPdfAsImages: false, CancellationToken.None);
// Assert
// PdfPig does not surface a bookmark without a title, so only the three titled top-level entries appear.
Assert.Equal(3, result.TableOfContents.Count);
ReadingTocEntryDto chapterOne = result.TableOfContents[0];
Assert.Equal("Chapter One", chapterOne.Label);
Assert.Equal("page:1", chapterOne.LocationRef);
ReadingTocEntryDto partOne = Assert.Single(chapterOne.Children);
Assert.Equal("Part One", partOne.Label);
Assert.Equal("page:1", partOne.LocationRef);
Assert.Equal("Chapter Two", result.TableOfContents[1].Label);
Assert.Equal("page:2", result.TableOfContents[1].LocationRef);
// A bookmark pointing at a URI instead of a page yields an entry that is not navigable.
Assert.Equal("External Link", result.TableOfContents[2].Label);
Assert.Equal(string.Empty, result.TableOfContents[2].LocationRef);
}
[Fact]
public void Parse_WhenPdfIsTooLarge_ShouldThrowInvalidDataException()
{
// Arrange
string oversizedPdfPath = Path.Combine(_temporaryDirectory, "oversized.pdf");
// A sparse file larger than the 500 MB cap, without allocating disk space.
using (FileStream fileStream = new(oversizedPdfPath, FileMode.Create, FileAccess.Write))
fileStream.SetLength(501L * 1024 * 1024);
string workingDirectory = Path.Combine(_temporaryDirectory, "work");
// Act
Action act = () => PdfDocumentParser.Parse(oversizedPdfPath, workingDirectory, shouldRenderPdfAsImages: false, CancellationToken.None);
// Assert
Assert.Throws<InvalidDataException>(act);
}
[Fact]
public void Parse_WhenPdfHasABlankTextLine_ShouldSkipTheBlankLineAndKeepTheOthers()
{
// Arrange
string blankLinePdfPath = Path.Combine(_temporaryDirectory, "blankline.pdf");
TestPdfFileFactory.CreatePdfWithBlankLine(blankLinePdfPath);
string workingDirectory = Path.Combine(_temporaryDirectory, "work");
// Act
ReadingDocumentDto result = PdfDocumentParser.Parse(blankLinePdfPath, workingDirectory, shouldRenderPdfAsImages: false, CancellationToken.None);
// Assert
string sectionContent = File.ReadAllText(Path.Combine(workingDirectory, result.Spine[0].RelativeSectionFilePath));
Assert.Contains("<p>First line</p>", sectionContent, StringComparison.Ordinal);
Assert.Contains("<p>Third line</p>", sectionContent, StringComparison.Ordinal);
Assert.DoesNotContain("<p></p>", sectionContent, StringComparison.Ordinal);
}
[Fact]
public void Parse_WhenPdfOutlineIsMalformed_ShouldSkipTheTableOfContentsAndKeepThePages()
{
// Arrange
string malformedOutlinePdfPath = Path.Combine(_temporaryDirectory, "malformed-outline.pdf");
TestPdfFileFactory.CreatePdfWithMalformedOutline(malformedOutlinePdfPath);
string workingDirectory = Path.Combine(_temporaryDirectory, "work");
// Act
ReadingDocumentDto result = PdfDocumentParser.Parse(malformedOutlinePdfPath, workingDirectory, shouldRenderPdfAsImages: false, CancellationToken.None);
// Assert
// The malformed bookmarks are best effort: the table of contents is skipped, but the pages are still readable.
Assert.Empty(result.TableOfContents);
Assert.Single(result.Spine);
}
[Fact]
public void Parse_WhenPdfExceedsThePageCap_ShouldStopAtTheCap()
{
// Arrange
string manyPagesPdfPath = Path.Combine(_temporaryDirectory, "many-pages.pdf");
TestPdfFileFactory.CreatePdfWithMorePagesThanAllowed(manyPagesPdfPath);
string workingDirectory = Path.Combine(_temporaryDirectory, "work");
// Act
ReadingDocumentDto result = PdfDocumentParser.Parse(manyPagesPdfPath, workingDirectory, shouldRenderPdfAsImages: false, CancellationToken.None);
// Assert
// The parser stops enumerating after the page cap instead of reading every page.
Assert.Equal(10_000, result.Spine.Count);
}
[Fact]
public void ParseAsImages_WhenPdfExceedsThePageCap_ShouldStopAtTheCap()
{
// Arrange
string manyPagesPdfPath = Path.Combine(_temporaryDirectory, "many-pages-images.pdf");
TestPdfFileFactory.CreatePdfWithMorePagesThanAllowed(manyPagesPdfPath);
string workingDirectory = Path.Combine(_temporaryDirectory, "work");
// Act
ReadingDocumentDto result = PdfDocumentParser.Parse(manyPagesPdfPath, workingDirectory, shouldRenderPdfAsImages: true, CancellationToken.None);
// Assert
Assert.Equal(10_000, result.Spine.Count);
Assert.Equal(10_000, result.Resources.Count);
}
/// <inheritdoc/>
public void Dispose()
{
if (Directory.Exists(_temporaryDirectory))
Directory.Delete(_temporaryDirectory, recursive: true);
}
}
@@ -0,0 +1,96 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Plugins.Contracts.Common.Models.DTO.Settings;
using Lumina.Plugins.Contracts.Core.Reading;
using Lumina.Plugins.Pdf.Core;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
#endregion
namespace Lumina.Plugins.Pdf.UnitTests.Core;
/// <summary>
/// Contains unit tests for the <see cref="PdfPlugin"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class PdfPluginTests
{
private readonly PdfPlugin _sut = new();
[Fact]
public void Id_WhenCalled_ShouldReturnStablePluginIdentifier()
{
// Act
Guid result = _sut.Id;
// Assert
Assert.Equal(PdfPlugin.s_pluginId, result);
Assert.Equal(new Guid("c2f9b8f0-5a4b-4e3d-8b2f-7e4a9c1d3e5f"), result);
}
[Fact]
public void Name_WhenCalled_ShouldReturnPluginDisplayName()
{
// Act
string result = _sut.Name;
// Assert
Assert.Equal("PDF Reader", result);
}
[Fact]
public void Author_WhenCalled_ShouldReturnPluginAuthor()
{
// Act
string result = _sut.Author;
// Assert
Assert.Equal("Lumina", result);
}
[Fact]
public void Version_WhenCalled_ShouldReturnPluginVersion()
{
// Act
Version result = _sut.Version;
// Assert
Assert.Equal(new Version(1, 0, 0), result);
}
[Fact]
public void Description_WhenCalled_ShouldReturnPluginDescription()
{
// Act
string result = _sut.Description;
// Assert
Assert.Equal("Allows reading of PDF format books.", result);
}
[Fact]
public void GetSettingsSchema_WhenCalled_ShouldReturnEmptySettingsSchema()
{
// Act
IReadOnlyList<PluginSettingDescriptorDto> result = _sut.GetSettingsSchema();
// Assert
Assert.Empty(result);
}
[Fact]
public void RegisterServices_WhenCalled_ShouldRegisterTheKeyedBookReader()
{
// Arrange
ServiceCollection services = new();
// Act
_sut.RegisterServices(services);
ServiceProvider serviceProvider = services.BuildServiceProvider();
// Assert
Assert.NotNull(serviceProvider.GetKeyedService<IBookReader>(PdfPlugin.s_pluginId));
Assert.Null(serviceProvider.GetKeyedService<IBookReader>(Guid.NewGuid()));
}
}
@@ -0,0 +1,86 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Contracts.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary.Reading;
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
using Lumina.Plugins.Pdf.Core;
using Lumina.Plugins.Pdf.Fixtures.Core.Pdf;
using System;
using System.Diagnostics.CodeAnalysis;
using System.IO;
using System.Runtime.Versioning;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Plugins.Pdf.UnitTests.Core;
/// <summary>
/// Contains unit tests for the <see cref="PdfReader"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class PdfReaderTests : IDisposable
{
private readonly string _temporaryDirectory = Path.Combine(Path.GetTempPath(), $"lumina-pdf-reader-{Guid.NewGuid():N}");
private readonly string _pdfPath;
private readonly PdfReader _sut = new();
/// <summary>
/// Initializes a new instance of the <see cref="PdfReaderTests"/> class.
/// </summary>
public PdfReaderTests()
{
Directory.CreateDirectory(_temporaryDirectory);
_pdfPath = Path.Combine(_temporaryDirectory, "minimal.pdf");
TestPdfFileFactory.CreateMinimalPdf(_pdfPath);
}
[Fact]
public void SupportedExtensions_WhenAccessed_ShouldOnlyContainPdf()
{
// Assert
Assert.Equal([".pdf"], _sut.SupportedExtensions);
}
[Fact]
public void SupportedLibraryTypes_WhenAccessed_ShouldContainEBookAndBook()
{
// Assert
Assert.Equal([LibraryType.EBook, LibraryType.Book], _sut.SupportedLibraryTypes);
}
[Fact]
public async Task OpenAsync_WhenCalled_ShouldReturnTheParsedDocument()
{
// Arrange
string workingDirectory = Path.Combine(_temporaryDirectory, "work");
// Act
ReadingDocumentDto result = await _sut.OpenAsync(_pdfPath, workingDirectory, shouldRenderPdfAsImages: false, CancellationToken.None);
// Assert
Assert.Equal("minimal", result.Title);
Assert.Single(result.Spine);
}
[SupportedOSPlatform("windows")]
[Fact]
public async Task GetResourceAsync_WhenCalledForAPage_ShouldRenderThePageImage()
{
// Arrange
string workingDirectory = Path.Combine(_temporaryDirectory, "work");
// Act
byte[] result = await _sut.GetResourceAsync(_pdfPath, workingDirectory, "page:1", CancellationToken.None);
// Assert
Assert.NotNull(result);
Assert.NotEmpty(result);
}
/// <inheritdoc/>
public void Dispose()
{
if (Directory.Exists(_temporaryDirectory))
Directory.Delete(_temporaryDirectory, recursive: true);
}
}
@@ -0,0 +1,48 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net10.0</TargetFramework>
<ImplicitUsings>disable</ImplicitUsings>
<Nullable>enable</Nullable>
<IsPackable>false</IsPackable>
<IsTestProject>true</IsTestProject>
</PropertyGroup>
<ItemGroup>
<AssemblyAttribute Include="Xunit.CollectionBehaviorAttribute">
<_Parameter1>DisableTestParallelization = true</_Parameter1>
<_Parameter1_IsLiteral>true</_Parameter1_IsLiteral>
</AssemblyAttribute>
</ItemGroup>
<ItemGroup>
<PackageReference Include="AutoFixture.AutoNSubstitute" />
<PackageReference Include="AutoFixture.Xunit2" />
<PackageReference Include="Bogus" />
<PackageReference Include="coverlet.collector">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
<PackageReference Include="Microsoft.Extensions.DependencyInjection" />
<PackageReference Include="Microsoft.NET.Test.Sdk" />
<PackageReference Include="NSubstitute" />
<PackageReference Include="xunit" />
<PackageReference Include="xunit.runner.visualstudio">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
</ItemGroup>
<ItemGroup>
<Using Include="Xunit" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\..\..\plugins\Lumina.Plugins.Pdf\Lumina.Plugins.Pdf.csproj" />
<ProjectReference Include="..\..\..\src\Lumina.Plugins.Contracts\Lumina.Plugins.Contracts.csproj" />
<ProjectReference Include="..\..\Common\Lumina.Contracts.Fixtures\Lumina.Contracts.Fixtures.csproj" />
<ProjectReference Include="..\..\Common\Lumina.Plugins.Pdf.Fixtures\Lumina.Plugins.Pdf.Fixtures.csproj" />
</ItemGroup>
</Project>
@@ -1,7 +1,7 @@
#region ========================================================================= USING =====================================================================================
using FastEndpoints;
using Lumina.Application.Common.CQRS;
using Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BooksLibrary.Books.Queries.GetBooks;
using Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Queries.GetBooks;
using Lumina.Contracts.Fixtures.Core.Requests.MediaLibrary.WrittenContentLibrary.BookLibrary.Books;
using Lumina.Contracts.Fixtures.Core.Responses.MediaLibrary.WrittenContentLibrary.BookLibrary.Books;
using Lumina.Contracts.Fixtures.Responses.Common;
@@ -1,7 +1,7 @@
#region ========================================================================= USING =====================================================================================
using FastEndpoints;
using Lumina.Application.Common.CQRS;
using Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BooksLibrary.Books.Queries.GetBooksLite;
using Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Queries.GetBooksLite;
using Lumina.Contracts.Fixtures.Core.Requests.MediaLibrary.WrittenContentLibrary.BookLibrary.Books;
using Lumina.Contracts.Fixtures.Core.Responses.MediaLibrary.WrittenContentLibrary.BookLibrary.Books;
using Lumina.Contracts.Fixtures.Responses.Common;
@@ -0,0 +1,147 @@
#region ========================================================================= USING =====================================================================================
using FastEndpoints;
using Lumina.Application.Common.CQRS;
using Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Reading.Queries.GetReadingAvailability;
using Lumina.Contracts.Fixtures.Core.Requests.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Reading;
using Lumina.Contracts.Fixtures.Core.Responses.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Reading;
using Lumina.Contracts.Requests.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Reading;
using Lumina.Contracts.Responses.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Reading;
using Lumina.Domain.Common.Primitives;
using Lumina.Presentation.Api.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.Books.Reading.GetReadingAvailability;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Http.HttpResults;
using NSubstitute;
using System;
using System.Diagnostics.CodeAnalysis;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Presentation.Api.UnitTests.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.Books.Reading.GetReadingAvailability;
/// <summary>
/// Contains unit tests for the <see cref="GetReadingAvailabilityEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetReadingAvailabilityEndpointTests
{
private readonly IQueryHandler<GetReadingAvailabilityQuery, Result<ReadingAvailabilityResponse>> _mockHandler;
private readonly GetReadingAvailabilityEndpoint _sut;
private readonly GetReadingAvailabilityRequestFixture _getReadingAvailabilityRequestFixture = new();
private readonly ReadingAvailabilityResponseFixture _readingAvailabilityResponseFixture = new();
/// <summary>
/// Initializes a new instance of the <see cref="GetReadingAvailabilityEndpointTests"/> class.
/// </summary>
public GetReadingAvailabilityEndpointTests()
{
_mockHandler = Substitute.For<IQueryHandler<GetReadingAvailabilityQuery, Result<ReadingAvailabilityResponse>>>();
_sut = Factory.Create<GetReadingAvailabilityEndpoint>(_mockHandler);
}
[Fact]
public async Task ExecuteAsync_WhenSuccessful_ShouldReturnOkResultWithReadingAvailability()
{
// Arrange
GetReadingAvailabilityRequest request = _getReadingAvailabilityRequestFixture.Create();
CancellationToken cancellationToken = CancellationToken.None;
ReadingAvailabilityResponse expectedResponse = _readingAvailabilityResponseFixture.Create(bookId: request.BookId, isAvailable: true, errorCode: null);
_mockHandler.HandleAsync(Arg.Any<GetReadingAvailabilityQuery>(), Arg.Any<CancellationToken>())
.Returns(Result.From(expectedResponse));
// Act
IResult result = await _sut.ExecuteAsync(request, cancellationToken);
// Assert
Ok<ReadingAvailabilityResponse> okResult = Assert.IsType<Ok<ReadingAvailabilityResponse>>(result);
Assert.Equal(expectedResponse, okResult.Value);
}
[Fact]
public async Task ExecuteAsync_WhenBookIsNotAvailable_ShouldReturnOkResultWithUnavailableReadingAvailability()
{
// Arrange
GetReadingAvailabilityRequest request = _getReadingAvailabilityRequestFixture.Create();
CancellationToken cancellationToken = CancellationToken.None;
ReadingAvailabilityResponse expectedResponse = _readingAvailabilityResponseFixture.Create(bookId: request.BookId, isAvailable: false, errorCode: "ReaderDisabled");
_mockHandler.HandleAsync(Arg.Any<GetReadingAvailabilityQuery>(), Arg.Any<CancellationToken>())
.Returns(Result.From(expectedResponse));
// Act
IResult result = await _sut.ExecuteAsync(request, cancellationToken);
// Assert
Ok<ReadingAvailabilityResponse> okResult = Assert.IsType<Ok<ReadingAvailabilityResponse>>(result);
Assert.Equal(expectedResponse, okResult.Value);
Assert.False(okResult.Value.IsAvailable);
Assert.Equal("ReaderDisabled", okResult.Value.ErrorCode);
}
[Fact]
public async Task ExecuteAsync_WhenHandlerReturnsError_ShouldReturnProblemResult()
{
// Arrange
GetReadingAvailabilityRequest request = _getReadingAvailabilityRequestFixture.Create();
CancellationToken cancellationToken = CancellationToken.None;
Error expectedError = Error.NotFound("Reading.BookNotFound", "BookNotFound");
_mockHandler.HandleAsync(Arg.Any<GetReadingAvailabilityQuery>(), Arg.Any<CancellationToken>())
.Returns(expectedError);
// Act
IResult result = await _sut.ExecuteAsync(request, cancellationToken);
// Assert
ProblemHttpResult problemResult = Assert.IsType<ProblemHttpResult>(result);
Assert.Equal(StatusCodes.Status404NotFound, problemResult.StatusCode);
Assert.Equal("application/problem+json", problemResult.ContentType);
Assert.Equal("Reading.BookNotFound", problemResult.ProblemDetails.Title);
Assert.Equal("BookNotFound", problemResult.ProblemDetails.Detail);
}
[Fact]
public async Task ExecuteAsync_WhenCalled_ShouldSendGetReadingAvailabilityQueryToSender()
{
// Arrange
GetReadingAvailabilityRequest request = _getReadingAvailabilityRequestFixture.Create();
CancellationToken cancellationToken = CancellationToken.None;
ReadingAvailabilityResponse response = _readingAvailabilityResponseFixture.Create(bookId: request.BookId, isAvailable: true, errorCode: null);
_mockHandler.HandleAsync(Arg.Any<GetReadingAvailabilityQuery>(), Arg.Any<CancellationToken>())
.Returns(Result.From(response));
// Act
await _sut.ExecuteAsync(request, cancellationToken);
// Assert
await _mockHandler.Received(1).HandleAsync(
Arg.Is<GetReadingAvailabilityQuery>(query => query.BookId == request.BookId),
Arg.Is(cancellationToken));
}
[Fact]
public async Task ExecuteAsync_WhenCancellationRequested_ShouldCancelOperation()
{
// Arrange
GetReadingAvailabilityRequest request = _getReadingAvailabilityRequestFixture.Create();
CancellationTokenSource cts = new();
TaskCompletionSource<bool> operationStarted = new();
TaskCompletionSource<bool> cancellationRequested = new();
_mockHandler.HandleAsync(Arg.Any<GetReadingAvailabilityQuery>(), Arg.Any<CancellationToken>())
.Returns(info => Task.Run(async () =>
{
operationStarted.SetResult(true);
await cancellationRequested.Task;
info.Arg<CancellationToken>().ThrowIfCancellationRequested();
return Result.From(_readingAvailabilityResponseFixture.Create(bookId: request.BookId, isAvailable: true, errorCode: null));
}, info.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);
}
}
@@ -0,0 +1,127 @@
#region ========================================================================= USING =====================================================================================
using FastEndpoints;
using Lumina.Application.Common.CQRS;
using Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Reading.Queries.GetReadingManifest;
using Lumina.Contracts.Fixtures.Core.Requests.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Reading;
using Lumina.Contracts.Fixtures.Core.Responses.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Reading;
using Lumina.Contracts.Requests.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Reading;
using Lumina.Contracts.Responses.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Reading;
using Lumina.Domain.Common.Primitives;
using Lumina.Presentation.Api.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.Books.Reading.GetReadingManifest;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Http.HttpResults;
using NSubstitute;
using System;
using System.Diagnostics.CodeAnalysis;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Presentation.Api.UnitTests.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.Books.Reading.GetReadingManifest;
/// <summary>
/// Contains unit tests for the <see cref="GetReadingManifestEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetReadingManifestEndpointTests
{
private readonly IQueryHandler<GetReadingManifestQuery, Result<ReadingManifestResponse>> _mockHandler;
private readonly GetReadingManifestEndpoint _sut;
private readonly GetReadingManifestRequestFixture _getReadingManifestRequestFixture = new();
private readonly ReadingManifestResponseFixture _readingManifestResponseFixture = new();
/// <summary>
/// Initializes a new instance of the <see cref="GetReadingManifestEndpointTests"/> class.
/// </summary>
public GetReadingManifestEndpointTests()
{
_mockHandler = Substitute.For<IQueryHandler<GetReadingManifestQuery, Result<ReadingManifestResponse>>>();
_sut = Factory.Create<GetReadingManifestEndpoint>(_mockHandler);
}
[Fact]
public async Task ExecuteAsync_WhenSuccessful_ShouldReturnOkResultWithReadingManifest()
{
// Arrange
GetReadingManifestRequest request = _getReadingManifestRequestFixture.Create();
CancellationToken cancellationToken = CancellationToken.None;
ReadingManifestResponse expectedResponse = _readingManifestResponseFixture.Create();
_mockHandler.HandleAsync(Arg.Any<GetReadingManifestQuery>(), Arg.Any<CancellationToken>())
.Returns(Result.From(expectedResponse));
// Act
IResult result = await _sut.ExecuteAsync(request, cancellationToken);
// Assert
Ok<ReadingManifestResponse> okResult = Assert.IsType<Ok<ReadingManifestResponse>>(result);
Assert.Equal(expectedResponse, okResult.Value);
}
[Fact]
public async Task ExecuteAsync_WhenHandlerReturnsError_ShouldReturnProblemResult()
{
// Arrange
GetReadingManifestRequest request = _getReadingManifestRequestFixture.Create();
CancellationToken cancellationToken = CancellationToken.None;
Error expectedError = Error.NotFound("Reading.BookNotFound", "BookNotFound");
_mockHandler.HandleAsync(Arg.Any<GetReadingManifestQuery>(), Arg.Any<CancellationToken>())
.Returns(expectedError);
// Act
IResult result = await _sut.ExecuteAsync(request, cancellationToken);
// Assert
ProblemHttpResult problemResult = Assert.IsType<ProblemHttpResult>(result);
Assert.Equal(StatusCodes.Status404NotFound, problemResult.StatusCode);
Assert.Equal("application/problem+json", problemResult.ContentType);
Assert.Equal("Reading.BookNotFound", problemResult.ProblemDetails.Title);
Assert.Equal("BookNotFound", problemResult.ProblemDetails.Detail);
}
[Fact]
public async Task ExecuteAsync_WhenCalled_ShouldSendGetReadingManifestQueryToSender()
{
// Arrange
GetReadingManifestRequest request = _getReadingManifestRequestFixture.Create();
CancellationToken cancellationToken = CancellationToken.None;
ReadingManifestResponse response = _readingManifestResponseFixture.Create();
_mockHandler.HandleAsync(Arg.Any<GetReadingManifestQuery>(), Arg.Any<CancellationToken>())
.Returns(Result.From(response));
// Act
await _sut.ExecuteAsync(request, cancellationToken);
// Assert
await _mockHandler.Received(1).HandleAsync(
Arg.Is<GetReadingManifestQuery>(query => query.BookId == request.BookId),
Arg.Is(cancellationToken));
}
[Fact]
public async Task ExecuteAsync_WhenCancellationRequested_ShouldCancelOperation()
{
// Arrange
GetReadingManifestRequest request = _getReadingManifestRequestFixture.Create();
CancellationTokenSource cts = new();
TaskCompletionSource<bool> operationStarted = new();
TaskCompletionSource<bool> cancellationRequested = new();
_mockHandler.HandleAsync(Arg.Any<GetReadingManifestQuery>(), Arg.Any<CancellationToken>())
.Returns(info => Task.Run(async () =>
{
operationStarted.SetResult(true);
await cancellationRequested.Task;
info.Arg<CancellationToken>().ThrowIfCancellationRequested();
return Result.From(_readingManifestResponseFixture.Create());
}, info.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);
}
}
@@ -0,0 +1,128 @@
#region ========================================================================= USING =====================================================================================
using FastEndpoints;
using Lumina.Application.Common.CQRS;
using Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Reading.Queries.GetReadingResource;
using Lumina.Contracts.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary.Reading;
using Lumina.Contracts.Fixtures.Core.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary.Reading;
using Lumina.Contracts.Fixtures.Core.Requests.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Reading;
using Lumina.Contracts.Requests.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Reading;
using Lumina.Domain.Common.Primitives;
using Lumina.Presentation.Api.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.Books.Reading.GetReadingResource;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Http.HttpResults;
using NSubstitute;
using System;
using System.Diagnostics.CodeAnalysis;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Presentation.Api.UnitTests.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.Books.Reading.GetReadingResource;
/// <summary>
/// Contains unit tests for the <see cref="GetReadingResourceEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetReadingResourceEndpointTests
{
private readonly IQueryHandler<GetReadingResourceQuery, Result<ReadingResourceDataDto>> _mockHandler;
private readonly GetReadingResourceEndpoint _sut;
private readonly GetReadingResourceRequestFixture _getReadingResourceRequestFixture = new();
private readonly ReadingResourceDataDtoFixture _readingResourceDataDtoFixture = new();
/// <summary>
/// Initializes a new instance of the <see cref="GetReadingResourceEndpointTests"/> class.
/// </summary>
public GetReadingResourceEndpointTests()
{
_mockHandler = Substitute.For<IQueryHandler<GetReadingResourceQuery, Result<ReadingResourceDataDto>>>();
_sut = Factory.Create<GetReadingResourceEndpoint>(_mockHandler);
}
[Fact]
public async Task ExecuteAsync_WhenSuccessful_ShouldReturnBytesResultWithResourceData()
{
// Arrange
GetReadingResourceRequest request = _getReadingResourceRequestFixture.Create();
CancellationToken cancellationToken = CancellationToken.None;
ReadingResourceDataDto expectedResponse = _readingResourceDataDtoFixture.Create();
_mockHandler.HandleAsync(Arg.Any<GetReadingResourceQuery>(), Arg.Any<CancellationToken>())
.Returns(Result.From(expectedResponse));
// Act
IResult result = await _sut.ExecuteAsync(request, cancellationToken);
// Assert
FileContentHttpResult bytesResult = Assert.IsType<FileContentHttpResult>(result);
Assert.Equal(expectedResponse.Data, bytesResult.FileContents);
Assert.Equal(expectedResponse.MimeType, bytesResult.ContentType);
}
[Fact]
public async Task ExecuteAsync_WhenHandlerReturnsError_ShouldReturnProblemResult()
{
// Arrange
GetReadingResourceRequest request = _getReadingResourceRequestFixture.Create();
CancellationToken cancellationToken = CancellationToken.None;
Error expectedError = Error.NotFound("Reading.ResourceNotFound", "ResourceNotFound");
_mockHandler.HandleAsync(Arg.Any<GetReadingResourceQuery>(), Arg.Any<CancellationToken>())
.Returns(expectedError);
// Act
IResult result = await _sut.ExecuteAsync(request, cancellationToken);
// Assert
ProblemHttpResult problemResult = Assert.IsType<ProblemHttpResult>(result);
Assert.Equal(StatusCodes.Status404NotFound, problemResult.StatusCode);
Assert.Equal("application/problem+json", problemResult.ContentType);
Assert.Equal("Reading.ResourceNotFound", problemResult.ProblemDetails.Title);
Assert.Equal("ResourceNotFound", problemResult.ProblemDetails.Detail);
}
[Fact]
public async Task ExecuteAsync_WhenCalled_ShouldSendGetReadingResourceQueryToSender()
{
// Arrange
GetReadingResourceRequest request = _getReadingResourceRequestFixture.Create();
CancellationToken cancellationToken = CancellationToken.None;
ReadingResourceDataDto response = _readingResourceDataDtoFixture.Create();
_mockHandler.HandleAsync(Arg.Any<GetReadingResourceQuery>(), Arg.Any<CancellationToken>())
.Returns(Result.From(response));
// Act
await _sut.ExecuteAsync(request, cancellationToken);
// Assert
await _mockHandler.Received(1).HandleAsync(
Arg.Is<GetReadingResourceQuery>(query => query.BookId == request.BookId && query.ResourceKey == request.ResourceKey),
Arg.Is(cancellationToken));
}
[Fact]
public async Task ExecuteAsync_WhenCancellationRequested_ShouldCancelOperation()
{
// Arrange
GetReadingResourceRequest request = _getReadingResourceRequestFixture.Create();
CancellationTokenSource cts = new();
TaskCompletionSource<bool> operationStarted = new();
TaskCompletionSource<bool> cancellationRequested = new();
_mockHandler.HandleAsync(Arg.Any<GetReadingResourceQuery>(), Arg.Any<CancellationToken>())
.Returns(info => Task.Run(async () =>
{
operationStarted.SetResult(true);
await cancellationRequested.Task;
info.Arg<CancellationToken>().ThrowIfCancellationRequested();
return Result.From(_readingResourceDataDtoFixture.Create());
}, info.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);
}
}
@@ -0,0 +1,127 @@
#region ========================================================================= USING =====================================================================================
using FastEndpoints;
using Lumina.Application.Common.CQRS;
using Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Reading.Queries.GetReadingSection;
using Lumina.Contracts.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary.Reading;
using Lumina.Contracts.Fixtures.Core.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary.Reading;
using Lumina.Contracts.Fixtures.Core.Requests.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Reading;
using Lumina.Contracts.Requests.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Reading;
using Lumina.Domain.Common.Primitives;
using Lumina.Presentation.Api.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.Books.Reading.GetReadingSection;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Http.HttpResults;
using NSubstitute;
using System;
using System.Diagnostics.CodeAnalysis;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Presentation.Api.UnitTests.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.Books.Reading.GetReadingSection;
/// <summary>
/// Contains unit tests for the <see cref="GetReadingSectionEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetReadingSectionEndpointTests
{
private readonly IQueryHandler<GetReadingSectionQuery, Result<ReadingSectionDto>> _mockHandler;
private readonly GetReadingSectionEndpoint _sut;
private readonly GetReadingSectionRequestFixture _getReadingSectionRequestFixture = new();
private readonly ReadingSectionDtoFixture _readingSectionDtoFixture = new();
/// <summary>
/// Initializes a new instance of the <see cref="GetReadingSectionEndpointTests"/> class.
/// </summary>
public GetReadingSectionEndpointTests()
{
_mockHandler = Substitute.For<IQueryHandler<GetReadingSectionQuery, Result<ReadingSectionDto>>>();
_sut = Factory.Create<GetReadingSectionEndpoint>(_mockHandler);
}
[Fact]
public async Task ExecuteAsync_WhenSuccessful_ShouldReturnOkResultWithReadingSection()
{
// Arrange
GetReadingSectionRequest request = _getReadingSectionRequestFixture.Create();
CancellationToken cancellationToken = CancellationToken.None;
ReadingSectionDto expectedResponse = _readingSectionDtoFixture.Create(locationRef: request.LocationRef);
_mockHandler.HandleAsync(Arg.Any<GetReadingSectionQuery>(), Arg.Any<CancellationToken>())
.Returns(Result.From(expectedResponse));
// Act
IResult result = await _sut.ExecuteAsync(request, cancellationToken);
// Assert
Ok<ReadingSectionDto> okResult = Assert.IsType<Ok<ReadingSectionDto>>(result);
Assert.Equal(expectedResponse, okResult.Value);
}
[Fact]
public async Task ExecuteAsync_WhenHandlerReturnsError_ShouldReturnProblemResult()
{
// Arrange
GetReadingSectionRequest request = _getReadingSectionRequestFixture.Create();
CancellationToken cancellationToken = CancellationToken.None;
Error expectedError = Error.NotFound("Reading.SectionNotFound", "SectionNotFound");
_mockHandler.HandleAsync(Arg.Any<GetReadingSectionQuery>(), Arg.Any<CancellationToken>())
.Returns(expectedError);
// Act
IResult result = await _sut.ExecuteAsync(request, cancellationToken);
// Assert
ProblemHttpResult problemResult = Assert.IsType<ProblemHttpResult>(result);
Assert.Equal(StatusCodes.Status404NotFound, problemResult.StatusCode);
Assert.Equal("application/problem+json", problemResult.ContentType);
Assert.Equal("Reading.SectionNotFound", problemResult.ProblemDetails.Title);
Assert.Equal("SectionNotFound", problemResult.ProblemDetails.Detail);
}
[Fact]
public async Task ExecuteAsync_WhenCalled_ShouldSendGetReadingSectionQueryToSender()
{
// Arrange
GetReadingSectionRequest request = _getReadingSectionRequestFixture.Create();
CancellationToken cancellationToken = CancellationToken.None;
ReadingSectionDto response = _readingSectionDtoFixture.Create(locationRef: request.LocationRef);
_mockHandler.HandleAsync(Arg.Any<GetReadingSectionQuery>(), Arg.Any<CancellationToken>())
.Returns(Result.From(response));
// Act
await _sut.ExecuteAsync(request, cancellationToken);
// Assert
await _mockHandler.Received(1).HandleAsync(
Arg.Is<GetReadingSectionQuery>(query => query.BookId == request.BookId && query.LocationRef == request.LocationRef),
Arg.Is(cancellationToken));
}
[Fact]
public async Task ExecuteAsync_WhenCancellationRequested_ShouldCancelOperation()
{
// Arrange
GetReadingSectionRequest request = _getReadingSectionRequestFixture.Create();
CancellationTokenSource cts = new();
TaskCompletionSource<bool> operationStarted = new();
TaskCompletionSource<bool> cancellationRequested = new();
_mockHandler.HandleAsync(Arg.Any<GetReadingSectionQuery>(), Arg.Any<CancellationToken>())
.Returns(info => Task.Run(async () =>
{
operationStarted.SetResult(true);
await cancellationRequested.Task;
info.Arg<CancellationToken>().ThrowIfCancellationRequested();
return Result.From(_readingSectionDtoFixture.Create(locationRef: request.LocationRef));
}, info.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);
}
}
Loaded 100 of 192 files, more files were not shown because too many files have changed in this diff. Show more