mirror of
https://github.com/BinaryAlley/Nemera.git
synced 2026-12-02 18:11:10 +00:00
Adds tests for the book reading feature
This commit is contained in:
1 parent
f7ccdf3d1c
commit
3a3c0c047c
192 files changed
+14104
-342
No files matched your search
+1
-1
@@ -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;
|
||||
|
||||
+2
-2
@@ -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.
|
||||
+102
@@ -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));
|
||||
}
|
||||
}
|
||||
+146
@@ -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();
|
||||
}
|
||||
}
|
||||
+816
@@ -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));
|
||||
}
|
||||
}
|
||||
}
|
||||
+32
@@ -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);
|
||||
}
|
||||
}
|
||||
+159
@@ -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);
|
||||
}
|
||||
}
|
||||
+526
-13
@@ -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;
|
||||
}
|
||||
}
|
||||
|
||||
+3
@@ -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());
|
||||
|
||||
Reference in new issue
Block a user