Relocates real-resource tests into integration projects and improves data access unit tests

This commit is contained in:
BinaryAlley committed 2026-09-02 09:49:58 -07:00
1 parent 551259ad81
commit 042c5e4729
56 files changed
+5642 -4136

No files matched your search

@@ -2,17 +2,16 @@
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management;
using Lumina.Application.Common.DataAccess.Repositories.MediaLibrary;
using Lumina.Application.Common.DataAccess.UoW;
using Lumina.Domain.Common.Errors;
using Lumina.Domain.Common.Events;
using Lumina.Domain.Common.Primitives;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Events;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Jobs;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects;
using Lumina.Domain.Core.BoundedContexts.UserManagementBoundedContext.UserAggregate.ValueObjects;
using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects;
using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects;
using Lumina.Domain.Fixtures.Core.BoundedContexts.UserManagementBoundedContext.UserAggregate.ValueObjects;
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management;
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
using Lumina.Infrastructure.Core.MediaLibrary.Management.Scanning.Jobs.WrittenContent.Books;
using Microsoft.Extensions.DependencyInjection;
@@ -20,8 +19,6 @@ 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
@@ -40,14 +37,11 @@ public class BooksFileSystemDiscoveryJobTests
private readonly IUnitOfWork _mockUnitOfWork;
private readonly ILibraryRepository _mockLibraryRepository;
private readonly ILibraryScanStagingResultsRepository _mockStagingResultsRepository;
private readonly IDirectoryScanFingerprintRepository _mockDirectoryScanFingerprintRepository;
private readonly IDomainEventPublisher _mockDomainEventPublisher;
private readonly BooksFileSystemDiscoveryJob _sut;
private readonly ScanIdFixture _scanIdFixture = new();
private readonly UserIdFixture _userIdFixture = new();
private readonly LibraryIdFixture _libraryIdFixture = new();
private readonly LibraryEntityFixture _libraryEntityFixture = new();
private readonly DirectoryScanFingerprintEntityFixture _directoryScanFingerprintEntityFixture = new();
private readonly ScanId _scanId;
private readonly UserId _userId;
private readonly LibraryId _libraryId;
@@ -66,10 +60,8 @@ public class BooksFileSystemDiscoveryJobTests
_mockUnitOfWork = Substitute.For<IUnitOfWork>();
_mockLibraryRepository = Substitute.For<ILibraryRepository>();
_mockStagingResultsRepository = Substitute.For<ILibraryScanStagingResultsRepository>();
_mockDirectoryScanFingerprintRepository = Substitute.For<IDirectoryScanFingerprintRepository>();
_mockUnitOfWork.LibraryRepository.Returns(_mockLibraryRepository);
_mockUnitOfWork.LibraryScanStagingResultsRepository.Returns(_mockStagingResultsRepository);
_mockUnitOfWork.DirectoryScanFingerprintRepository.Returns(_mockDirectoryScanFingerprintRepository);
_mockServiceProvider.GetService(typeof(IUnitOfWork)).Returns(_mockUnitOfWork);
_mockDomainEventPublisher = Substitute.For<IDomainEventPublisher>();
@@ -88,47 +80,6 @@ public class BooksFileSystemDiscoveryJobTests
};
}
[Fact]
public async Task ExecuteAsync_WhenContentLocationContainsBookFiles_ShouldDiscoverAndStageThemAndComplete()
{
// Arrange
using TemporaryLibraryDirectory temporaryLibraryDirectory = new();
temporaryLibraryDirectory.CreateFile("book1.pdf", "book content");
temporaryLibraryDirectory.CreateFile("notes.log", "not a book");
string subdirectoryPath = temporaryLibraryDirectory.CreateSubdirectory("sub");
File.WriteAllText(Path.Combine(subdirectoryPath, "book2.epub"), "another book content");
LibraryEntity libraryEntity = _libraryEntityFixture.Create(
id: _libraryId.Value,
userId: _userId.Value,
title: "Test Library",
libraryType: LibraryType.Book,
contentLocations: [temporaryLibraryDirectory.Path],
shouldSkipUnchangedDirectoriesDuringScan: false);
_mockLibraryRepository.GetByIdAsync(_libraryId.Value, Arg.Any<CancellationToken>())
.Returns(Result.From<LibraryEntity?>(libraryEntity));
_mockStagingResultsRepository.InsertRangeAsync(Arg.Any<IReadOnlyCollection<LibraryScanStagingResultsEntity>>(), Arg.Any<CancellationToken>())
.Returns(Result.From(Result.Created));
_mockDirectoryScanFingerprintRepository.UpsertRangeAsync(Arg.Any<IReadOnlyCollection<DirectoryScanFingerprintEntity>>(), Arg.Any<CancellationToken>())
.Returns(Result.From(Result.Updated));
// Act
await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None);
// Assert
Assert.Equal(LibraryScanJobStatus.Completed, _sut.Status);
IReadOnlyList<LibraryScanStagingResultsEntity>? actualEntities = _mockStagingResultsRepository.ReceivedCalls()
.Where(call => call.GetMethodInfo().Name == nameof(ILibraryScanStagingResultsRepository.InsertRangeAsync))
.Select(call => call.GetArguments().FirstOrDefault() as IReadOnlyList<LibraryScanStagingResultsEntity>)
.FirstOrDefault();
Assert.True(actualEntities is not null, $"InsertRangeAsync was not called. Received: {string.Join(", ", _mockStagingResultsRepository.ReceivedCalls().Select(call => call.GetMethodInfo().Name))}");
Assert.Equal(
["book1.pdf", "book2.epub"],
actualEntities!.Select(entity => Path.GetFileName(entity.Path)).OrderBy(name => name, StringComparer.Ordinal));
await _mockDirectoryScanFingerprintRepository.DidNotReceive().UpsertRangeAsync(Arg.Any<IReadOnlyCollection<DirectoryScanFingerprintEntity>>(), Arg.Any<CancellationToken>());
await _mockDomainEventPublisher.Received(1).PublishAsync(Arg.Is<LibraryScanProgressChangedDomainEvent>(domainEvent => domainEvent.LibraryId == _libraryId), Arg.Any<CancellationToken>());
}
[Fact]
public async Task ExecuteAsync_WhenGettingTheLibraryFails_ShouldMarkJobAsFailedAndPublishFailureEvent()
{
@@ -178,227 +129,4 @@ public class BooksFileSystemDiscoveryJobTests
await Assert.ThrowsAnyAsync<OperationCanceledException>(() => operation);
Assert.Equal(LibraryScanJobStatus.Canceled, _sut.Status);
}
[Fact]
public async Task ExecuteAsync_WhenFastSkipIsEnabledAndDirectoryDidNotChange_ShouldSkipTheDirectoryAndUpsertOnlyChangedFingerprints()
{
// Arrange
using TemporaryLibraryDirectory temporaryLibraryDirectory = new();
string unchangedDirectoryPath = temporaryLibraryDirectory.CreateSubdirectory("unchanged");
File.WriteAllText(Path.Combine(unchangedDirectoryPath, "skip.pdf"), "unchanged book content");
string changedDirectoryPath = temporaryLibraryDirectory.CreateSubdirectory("changed");
File.WriteAllText(Path.Combine(changedDirectoryPath, "book.pdf"), "changed book content");
DirectoryInfo unchangedDirectory = new(unchangedDirectoryPath);
string unchangedDirectoryFullName = unchangedDirectory.FullName;
DateTime unchangedDirectoryLastWriteTimeUtc = unchangedDirectory.LastWriteTimeUtc;
DirectoryInfo changedDirectory = new(changedDirectoryPath);
string changedDirectoryFullName = changedDirectory.FullName;
DirectoryInfo rootDirectory = new(temporaryLibraryDirectory.Path);
string rootDirectoryFullName = rootDirectory.FullName;
LibraryEntity libraryEntity = _libraryEntityFixture.Create(
id: _libraryId.Value,
userId: _userId.Value,
title: "Test Library",
libraryType: LibraryType.Book,
contentLocations: [temporaryLibraryDirectory.Path],
shouldSkipUnchangedDirectoriesDuringScan: true);
_mockLibraryRepository.GetByIdAsync(_libraryId.Value, Arg.Any<CancellationToken>())
.Returns(Result.From<LibraryEntity?>(libraryEntity));
_mockDirectoryScanFingerprintRepository.GetMappedByLibraryIdAsync(_libraryId.Value, Arg.Any<CancellationToken>())
.Returns(Result.From(new Dictionary<string, DirectoryScanFingerprintEntity>
{
[unchangedDirectoryFullName] = _directoryScanFingerprintEntityFixture.Create(
libraryId: _libraryId.Value,
path: unchangedDirectoryFullName,
lastWriteTimeUtc: unchangedDirectoryLastWriteTimeUtc)
}));
_mockStagingResultsRepository.InsertRangeAsync(Arg.Any<IReadOnlyCollection<LibraryScanStagingResultsEntity>>(), Arg.Any<CancellationToken>())
.Returns(Result.From(Result.Created));
_mockDirectoryScanFingerprintRepository.UpsertRangeAsync(Arg.Any<IReadOnlyCollection<DirectoryScanFingerprintEntity>>(), Arg.Any<CancellationToken>())
.Returns(Result.From(Result.Updated));
// Act
await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None);
// Assert
Assert.Equal(LibraryScanJobStatus.Completed, _sut.Status);
await _mockStagingResultsRepository.Received(1).InsertRangeAsync(
Arg.Is<IReadOnlyCollection<LibraryScanStagingResultsEntity>>(entities =>
entities.Count == 1 && Path.GetFileName(entities.Single().Path) == "book.pdf"),
Arg.Any<CancellationToken>());
await _mockDirectoryScanFingerprintRepository.Received(1).UpsertRangeAsync(
Arg.Is<IReadOnlyCollection<DirectoryScanFingerprintEntity>>(entities =>
entities.Count == 2
&& entities.Any(entity => entity.Path == rootDirectoryFullName)
&& entities.Any(entity => entity.Path == changedDirectoryFullName)
&& entities.All(entity => entity.Path != unchangedDirectoryFullName)
&& entities.All(entity => entity.LibraryId == _libraryId.Value)),
Arg.Any<CancellationToken>());
}
[Fact]
public async Task ExecuteAsync_WhenLoadingDirectoryScanFingerprintsFails_ShouldMarkJobAsFailedAndPublishFailureEvent()
{
// Arrange
using TemporaryLibraryDirectory temporaryLibraryDirectory = new();
LibraryEntity libraryEntity = _libraryEntityFixture.Create(
id: _libraryId.Value,
userId: _userId.Value,
title: "Test Library",
libraryType: LibraryType.Book,
contentLocations: [temporaryLibraryDirectory.Path],
shouldSkipUnchangedDirectoriesDuringScan: true);
_mockLibraryRepository.GetByIdAsync(_libraryId.Value, Arg.Any<CancellationToken>())
.Returns(Result.From<LibraryEntity?>(libraryEntity));
_mockDirectoryScanFingerprintRepository.GetMappedByLibraryIdAsync(_libraryId.Value, Arg.Any<CancellationToken>())
.Returns(Error.Failure("Database.Error", "Failed to load the directory scan fingerprints"));
// Act
await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None);
// Assert
Assert.Equal(LibraryScanJobStatus.Failed, _sut.Status);
await _mockStagingResultsRepository.DidNotReceive().InsertRangeAsync(Arg.Any<IReadOnlyCollection<LibraryScanStagingResultsEntity>>(), Arg.Any<CancellationToken>());
await _mockDomainEventPublisher.Received(1).PublishAsync(Arg.Is<LibraryScanFailedDomainEvent>(domainEvent =>
domainEvent.LibraryId == _libraryId), Arg.Any<CancellationToken>());
}
[Fact]
public async Task ExecuteAsync_WhenUpsertingDirectoryScanFingerprintsFails_ShouldMarkJobAsFailedAndPublishFailureEvent()
{
// Arrange
using TemporaryLibraryDirectory temporaryLibraryDirectory = new();
temporaryLibraryDirectory.CreateSubdirectory("changed");
LibraryEntity libraryEntity = _libraryEntityFixture.Create(
id: _libraryId.Value,
userId: _userId.Value,
title: "Test Library",
libraryType: LibraryType.Book,
contentLocations: [temporaryLibraryDirectory.Path],
shouldSkipUnchangedDirectoriesDuringScan: true);
_mockLibraryRepository.GetByIdAsync(_libraryId.Value, Arg.Any<CancellationToken>())
.Returns(Result.From<LibraryEntity?>(libraryEntity));
_mockDirectoryScanFingerprintRepository.GetMappedByLibraryIdAsync(_libraryId.Value, Arg.Any<CancellationToken>())
.Returns(Result.From(new Dictionary<string, DirectoryScanFingerprintEntity>()));
_mockDirectoryScanFingerprintRepository.UpsertRangeAsync(Arg.Any<IReadOnlyCollection<DirectoryScanFingerprintEntity>>(), Arg.Any<CancellationToken>())
.Returns(Error.Failure("Database.Error", "Failed to upsert the directory scan fingerprints"));
// Act
await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None);
// Assert
Assert.Equal(LibraryScanJobStatus.Failed, _sut.Status);
await _mockDomainEventPublisher.Received(1).PublishAsync(Arg.Is<LibraryScanFailedDomainEvent>(domainEvent =>
domainEvent.LibraryId == _libraryId), Arg.Any<CancellationToken>());
await _mockDomainEventPublisher.DidNotReceive().PublishAsync(Arg.Is<LibraryScanProgressChangedDomainEvent>(domainEvent =>
domainEvent.LibraryId == _libraryId), Arg.Any<CancellationToken>());
}
[Fact]
public async Task ExecuteAsync_WhenInsertingStagingResultsFails_ShouldMarkJobAsFailedAndPublishFailureEvent()
{
// Arrange
using TemporaryLibraryDirectory temporaryLibraryDirectory = new();
temporaryLibraryDirectory.CreateFile("book.pdf", "book content");
LibraryEntity libraryEntity = _libraryEntityFixture.Create(
id: _libraryId.Value,
userId: _userId.Value,
title: "Test Library",
libraryType: LibraryType.Book,
contentLocations: [temporaryLibraryDirectory.Path],
shouldSkipUnchangedDirectoriesDuringScan: false);
_mockLibraryRepository.GetByIdAsync(_libraryId.Value, Arg.Any<CancellationToken>())
.Returns(Result.From<LibraryEntity?>(libraryEntity));
_mockStagingResultsRepository.InsertRangeAsync(Arg.Any<IReadOnlyCollection<LibraryScanStagingResultsEntity>>(), Arg.Any<CancellationToken>())
.Returns(Error.Failure("Database.Error", "Failed to insert the staging results"));
// Act
await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None);
// Assert
Assert.Equal(LibraryScanJobStatus.Failed, _sut.Status);
await _mockDirectoryScanFingerprintRepository.DidNotReceive().UpsertRangeAsync(Arg.Any<IReadOnlyCollection<DirectoryScanFingerprintEntity>>(), Arg.Any<CancellationToken>());
await _mockDomainEventPublisher.Received(1).PublishAsync(Arg.Is<LibraryScanFailedDomainEvent>(domainEvent =>
domainEvent.LibraryId == _libraryId), Arg.Any<CancellationToken>());
await _mockDomainEventPublisher.DidNotReceive().PublishAsync(Arg.Is<LibraryScanProgressChangedDomainEvent>(domainEvent =>
domainEvent.LibraryId == _libraryId), Arg.Any<CancellationToken>());
}
[Fact]
public async Task ExecuteAsync_WhenJobHasLinkedChildren_ShouldExecuteEachChildAndComplete()
{
// Arrange
using TemporaryLibraryDirectory temporaryLibraryDirectory = new();
temporaryLibraryDirectory.CreateFile("book1.pdf", "book content");
LibraryEntity libraryEntity = _libraryEntityFixture.Create(
id: _libraryId.Value,
userId: _userId.Value,
title: "Test Library",
libraryType: LibraryType.Book,
contentLocations: [temporaryLibraryDirectory.Path],
shouldSkipUnchangedDirectoriesDuringScan: false);
_mockLibraryRepository.GetByIdAsync(_libraryId.Value, Arg.Any<CancellationToken>())
.Returns(Result.From<LibraryEntity?>(libraryEntity));
_mockStagingResultsRepository.InsertRangeAsync(Arg.Any<IReadOnlyCollection<LibraryScanStagingResultsEntity>>(), Arg.Any<CancellationToken>())
.Returns(Result.From(Result.Created));
IMediaLibraryScanJob mockChild = Substitute.For<IMediaLibraryScanJob>();
mockChild.ExecuteAsync(Arg.Any<Guid>(), Arg.Any<object>(), Arg.Any<CancellationToken>())
.Returns(Task.CompletedTask);
_sut.AddChild(mockChild);
object input = new();
// Act
await _sut.ExecuteAsync(Guid.NewGuid(), input, CancellationToken.None);
// Assert
Assert.Equal(LibraryScanJobStatus.Completed, _sut.Status);
await mockChild.Received(1).ExecuteAsync(Arg.Any<Guid>(), Arg.Is<object>(executedInput => executedInput == input), Arg.Any<CancellationToken>());
}
/// <summary>
/// Test helper managing a temporary library directory, deleted when the test finishes.
/// </summary>
private sealed class TemporaryLibraryDirectory : IDisposable
{
private bool _disposed;
public TemporaryLibraryDirectory()
{
Path = System.IO.Path.Combine(System.IO.Path.GetTempPath(), $"lumina-books-discovery-{Guid.NewGuid()}");
Directory.CreateDirectory(Path);
}
public string Path { get; }
public void CreateFile(string fileName, string content)
{
File.WriteAllText(System.IO.Path.Combine(Path, fileName), content);
}
public string CreateSubdirectory(string name)
{
string subdirectoryPath = System.IO.Path.Combine(Path, name);
Directory.CreateDirectory(subdirectoryPath);
return subdirectoryPath;
}
public void Dispose()
{
if (!_disposed)
{
try
{
Directory.Delete(Path, recursive: true);
}
catch (IOException)
{
// best effort cleanup of the temporary library directory
}
_disposed = true;
}
}
}
}
@@ -8,16 +8,13 @@ using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.File
using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Strategies.Environment;
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.BookLibrary.Artwork;
using Lumina.Infrastructure.Fixtures.Common.Setup;
using Microsoft.Extensions.Options;
using NSubstitute;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.IO;
using System.Net;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
@@ -31,8 +28,6 @@ namespace Lumina.Infrastructure.UnitTests.Core.MediaLibrary.WrittenContentLibrar
[ExcludeFromCodeCoverage]
public class BookArtworkServiceTests
{
private const long MAX_ARTWORK_SIZE_BYTES = 10 * 1024 * 1024;
private readonly IEnvironmentContext _mockEnvironmentContext;
private readonly IFileTypeService _mockFileTypeService;
private readonly IFileProviderService _mockFileProviderService;
@@ -45,7 +40,6 @@ public class BookArtworkServiceTests
private readonly PathSegmentFixture _pathSegmentFixture = new();
private readonly ArtworkDtoFixture _artworkDtoFixture = new();
private readonly MediaSettingsDtoFixture _mediaSettingsDtoFixture = new();
private readonly StubHttpMessageHandler _stubHttpMessageHandler = new();
/// <summary>
/// Initializes a new instance of the <see cref="BookArtworkServiceTests"/> class.
@@ -64,7 +58,6 @@ public class BookArtworkServiceTests
_mockPathService.PathSeparator.Returns('\\');
_mockHttpClientFactory = Substitute.For<IHttpClientFactory>();
_mockHttpClientFactory.CreateClient().Returns(new HttpClient(_stubHttpMessageHandler));
MediaSettingsDto mediaSettings = _mediaSettingsDtoFixture.Create(rootDirectory: "media", librariesDirectory: "libraries", booksDirectory: "books");
_mockMediaSettingsOptions = Substitute.For<IOptions<MediaSettingsDto>>();
@@ -73,91 +66,6 @@ public class BookArtworkServiceTests
_sut = new BookArtworkService(_mockEnvironmentContext, _mockPathService, _mockHttpClientFactory, _mockMediaSettingsOptions);
}
[Fact]
public async Task SaveBookArtworkAsync_WhenLocalArtworkExists_ShouldCopyItAndReturnARelativePath()
{
// Arrange
Guid libraryId = Guid.NewGuid();
Guid bookId = Guid.NewGuid();
string libraryName = "Test Library";
string authorName = "Test Author";
string bookTitle = "Test Book";
string sourcePath = CreateTempImageFile(smallImageBytes: 1024);
try
{
_mockFileProviderService.FileExists(Arg.Any<FileSystemPathId>()).Returns(Result.From(true));
_mockFileTypeService.GetImageTypeAsync(Arg.Any<FileSystemPathId>(), Arg.Any<CancellationToken>())
.Returns(Result.From(ImageType.JPEG));
string artworkDirectoryPath = BuildArtworkDirectoryPath(libraryId, bookId, libraryName, authorName, bookTitle);
MockArtworkDirectoryStubs(artworkDirectoryPath);
FileSystemPathId copiedFileId = _fileSystemPathIdFixture.Create(Path.Combine(artworkDirectoryPath, "cover.jpg"));
_mockFileProviderService.CopyFile(Arg.Any<FileSystemPathId>(), Arg.Any<FileSystemPathId>(), true)
.Returns(Result.From(copiedFileId));
string renamedFilePath = Path.Combine(artworkDirectoryPath, "cover.jpeg");
FileSystemPathId renamedFileId = _fileSystemPathIdFixture.Create(renamedFilePath);
_mockFileProviderService.RenameFile(Arg.Any<FileSystemPathId>(), "cover.jpeg")
.Returns(Result.From(renamedFileId));
// Act
Result<string> result = await _sut.SaveBookArtworkAsync(libraryId, bookId, libraryName, authorName, bookTitle, _artworkDtoFixture.Create(localPath: sourcePath), CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
Assert.Equal(renamedFilePath[AppContext.BaseDirectory.Length..].Insert(0, "\\"), result.Value);
_mockFileProviderService.Received(1).CopyFile(
Arg.Is<FileSystemPathId>(pathId => pathId.Path == sourcePath),
Arg.Any<FileSystemPathId>(),
true);
_mockFileProviderService.Received(1).RenameFile(Arg.Any<FileSystemPathId>(), "cover.jpeg");
}
finally
{
File.Delete(sourcePath);
}
}
[Fact]
public async Task SaveBookArtworkAsync_WhenAuthorNameIsMissing_ShouldUseUnknownForTheDirectorySegment()
{
// Arrange
Guid libraryId = Guid.NewGuid();
Guid bookId = Guid.NewGuid();
string libraryName = "Test Library";
string bookTitle = "Test Book";
string sourcePath = CreateTempImageFile(smallImageBytes: 1024);
try
{
_mockFileProviderService.FileExists(Arg.Any<FileSystemPathId>()).Returns(Result.From(true));
_mockFileTypeService.GetImageTypeAsync(Arg.Any<FileSystemPathId>(), Arg.Any<CancellationToken>())
.Returns(Result.From(ImageType.JPEG));
string artworkDirectoryPath = BuildArtworkDirectoryPath(libraryId, bookId, libraryName, authorName: "Unknown", bookTitle);
MockArtworkDirectoryStubs(artworkDirectoryPath);
FileSystemPathId renamedFileId = _fileSystemPathIdFixture.Create(Path.Combine(artworkDirectoryPath, "cover.jpeg"));
_mockFileProviderService.CopyFile(Arg.Any<FileSystemPathId>(), Arg.Any<FileSystemPathId>(), true)
.Returns(Result.From(_fileSystemPathIdFixture.Create(Path.Combine(artworkDirectoryPath, "cover.jpg"))));
_mockFileProviderService.RenameFile(Arg.Any<FileSystemPathId>(), "cover.jpeg")
.Returns(Result.From(renamedFileId));
// Act
Result<string> result = await _sut.SaveBookArtworkAsync(libraryId, bookId, libraryName, authorName: " ", bookTitle, _artworkDtoFixture.Create(localPath: sourcePath), CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
_mockPathService.Received(1).SanitizeSegment("Unknown");
}
finally
{
File.Delete(sourcePath);
}
}
[Fact]
public async Task SaveBookArtworkAsync_WhenLocalArtworkDoesNotExist_ShouldReturnFileNotFound()
{
@@ -174,90 +82,6 @@ public class BookArtworkServiceTests
await _mockFileTypeService.DidNotReceive().GetImageTypeAsync(Arg.Any<FileSystemPathId>(), Arg.Any<CancellationToken>());
}
[Fact]
public async Task SaveBookArtworkAsync_WhenLocalArtworkIsALink_ShouldReturnInvalidPath()
{
// Arrange
string targetDirectory = Path.Combine(Path.GetTempPath(), $"lumina-junction-target-{Guid.NewGuid():N}");
Directory.CreateDirectory(targetDirectory);
string linkPath = Path.Combine(Path.GetTempPath(), $"lumina-junction-link-{Guid.NewGuid():N}");
if (!TryCreateJunction(linkPath, targetDirectory))
{
Directory.Delete(targetDirectory, true);
return; // the environment does not support creating reparse points
}
try
{
_mockFileProviderService.FileExists(Arg.Any<FileSystemPathId>()).Returns(Result.From(true));
// Act
Result<string> result = await _sut.SaveBookArtworkAsync(Guid.NewGuid(), Guid.NewGuid(), "Library", "Author", "Title", _artworkDtoFixture.Create(localPath: linkPath), CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(Errors.FileSystemManagement.InvalidPath, result.FirstError);
_mockFileProviderService.DidNotReceive().CopyFile(Arg.Any<FileSystemPathId>(), Arg.Any<FileSystemPathId>(), true);
}
finally
{
// Windows removes a junction with Directory.Delete, while Unix-like platforms unlink the symbolic link with File.Delete
if (OperatingSystem.IsWindows())
Directory.Delete(linkPath, true);
else
File.Delete(linkPath);
Directory.Delete(targetDirectory, true);
}
}
[Fact]
public async Task SaveBookArtworkAsync_WhenLocalArtworkExceedsMaxSize_ShouldReturnFileTooLarge()
{
// Arrange
string sourcePath = CreateTempImageFile(smallImageBytes: (int)MAX_ARTWORK_SIZE_BYTES + 1);
try
{
_mockFileProviderService.FileExists(Arg.Any<FileSystemPathId>()).Returns(Result.From(true));
// Act
Result<string> result = await _sut.SaveBookArtworkAsync(Guid.NewGuid(), Guid.NewGuid(), "Library", "Author", "Title", _artworkDtoFixture.Create(localPath: sourcePath), CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(Errors.FileSystemManagement.FileTooLarge, result.FirstError);
await _mockFileTypeService.DidNotReceive().GetImageTypeAsync(Arg.Any<FileSystemPathId>(), Arg.Any<CancellationToken>());
}
finally
{
File.Delete(sourcePath);
}
}
[Fact]
public async Task SaveBookArtworkAsync_WhenLocalArtworkIsNotAnImage_ShouldReturnCoverFileMustBeAnImage()
{
// Arrange
string sourcePath = CreateTempImageFile(smallImageBytes: 1024);
try
{
_mockFileProviderService.FileExists(Arg.Any<FileSystemPathId>()).Returns(Result.From(true));
_mockFileTypeService.GetImageTypeAsync(Arg.Any<FileSystemPathId>(), Arg.Any<CancellationToken>())
.Returns(Result.From(ImageType.None));
// Act
Result<string> result = await _sut.SaveBookArtworkAsync(Guid.NewGuid(), Guid.NewGuid(), "Library", "Author", "Title", _artworkDtoFixture.Create(localPath: sourcePath), CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(Errors.Library.CoverFileMustBeAnImage, result.FirstError);
_mockFileProviderService.DidNotReceive().CopyFile(Arg.Any<FileSystemPathId>(), Arg.Any<FileSystemPathId>(), true);
}
finally
{
File.Delete(sourcePath);
}
}
[Fact]
public async Task SaveBookArtworkAsync_WhenArtworkHasNeitherLocalPathNorRemoteUrl_ShouldReturnFileNotFound()
{
@@ -269,130 +93,6 @@ public class BookArtworkServiceTests
Assert.Equal(Errors.FileSystemManagement.FileNotFound, result.FirstError);
}
[Fact]
public async Task SaveBookArtworkAsync_WhenRemoteUrlIsProvided_ShouldDownloadAndStoreTheArtwork()
{
// Arrange
byte[] imageBytes = new byte[1024];
_stubHttpMessageHandler.SetResponse(HttpStatusCode.OK, imageBytes);
Guid libraryId = Guid.NewGuid();
Guid bookId = Guid.NewGuid();
string libraryName = "Test Library";
string authorName = "Test Author";
string bookTitle = "Test Book";
_mockFileProviderService.FileExists(Arg.Any<FileSystemPathId>()).Returns(Result.From(true));
_mockFileTypeService.GetImageTypeAsync(Arg.Any<FileSystemPathId>(), Arg.Any<CancellationToken>())
.Returns(Result.From(ImageType.JPEG));
string artworkDirectoryPath = BuildArtworkDirectoryPath(libraryId, bookId, libraryName, authorName, bookTitle);
MockArtworkDirectoryStubs(artworkDirectoryPath);
_mockFileProviderService.CopyFile(Arg.Any<FileSystemPathId>(), Arg.Any<FileSystemPathId>(), true)
.Returns(Result.From(_fileSystemPathIdFixture.Create(Path.Combine(artworkDirectoryPath, "cover.jpg"))));
FileSystemPathId renamedFileId = _fileSystemPathIdFixture.Create(Path.Combine(artworkDirectoryPath, "cover.jpeg"));
_mockFileProviderService.RenameFile(Arg.Any<FileSystemPathId>(), "cover.jpeg")
.Returns(Result.From(renamedFileId));
// Act
Result<string> result = await _sut.SaveBookArtworkAsync(libraryId, bookId, libraryName, authorName, bookTitle, _artworkDtoFixture.Create(remoteUrl: "http://artwork.example/cover.jpg"), CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
_mockFileProviderService.Received(1).CopyFile(
Arg.Is<FileSystemPathId>(pathId => pathId.Path.StartsWith(Path.GetTempPath())),
Arg.Any<FileSystemPathId>(),
true);
}
[Fact]
public async Task SaveBookArtworkAsync_WhenRemoteDownloadReturnsAnErrorStatus_ShouldReturnFileNotFound()
{
// Arrange
_stubHttpMessageHandler.SetResponse(HttpStatusCode.NotFound, []);
// Act
Result<string> result = await _sut.SaveBookArtworkAsync(Guid.NewGuid(), Guid.NewGuid(), "Library", "Author", "Title", _artworkDtoFixture.Create(remoteUrl: "http://artwork.example/cover.jpg"), CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(Errors.FileSystemManagement.FileNotFound, result.FirstError);
}
[Fact]
public async Task SaveBookArtworkAsync_WhenRemoteDownloadExceedsMaxSize_ShouldReturnFileTooLarge()
{
// Arrange
_stubHttpMessageHandler.SetResponse(HttpStatusCode.OK, new byte[MAX_ARTWORK_SIZE_BYTES + 1]);
// Act
Result<string> result = await _sut.SaveBookArtworkAsync(Guid.NewGuid(), Guid.NewGuid(), "Library", "Author", "Title", _artworkDtoFixture.Create(remoteUrl: "http://artwork.example/cover.jpg"), CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(Errors.FileSystemManagement.FileTooLarge, result.FirstError);
}
[Fact]
public async Task SaveBookArtworkAsync_WhenArtworkHasBothLocalPathAndRemoteUrl_ShouldUseTheLocalFileWithoutDeletingIt()
{
// Arrange
Guid libraryId = Guid.NewGuid();
Guid bookId = Guid.NewGuid();
string libraryName = "Test Library";
string authorName = "Test Author";
string bookTitle = "Test Book";
string sourcePath = CreateTempImageFile(smallImageBytes: 1024);
try
{
_mockFileProviderService.FileExists(Arg.Any<FileSystemPathId>()).Returns(Result.From(true));
_mockFileTypeService.GetImageTypeAsync(Arg.Any<FileSystemPathId>(), Arg.Any<CancellationToken>())
.Returns(Result.From(ImageType.JPEG));
string artworkDirectoryPath = BuildArtworkDirectoryPath(libraryId, bookId, libraryName, authorName, bookTitle);
MockArtworkDirectoryStubs(artworkDirectoryPath);
FileSystemPathId renamedFileId = _fileSystemPathIdFixture.Create(Path.Combine(artworkDirectoryPath, "cover.jpeg"));
_mockFileProviderService.CopyFile(Arg.Any<FileSystemPathId>(), Arg.Any<FileSystemPathId>(), true)
.Returns(Result.From(_fileSystemPathIdFixture.Create(Path.Combine(artworkDirectoryPath, "cover.jpg"))));
_mockFileProviderService.RenameFile(Arg.Any<FileSystemPathId>(), "cover.jpeg")
.Returns(Result.From(renamedFileId));
// Act
Result<string> result = await _sut.SaveBookArtworkAsync(libraryId, bookId, libraryName, authorName, bookTitle, _artworkDtoFixture.Create(localPath: sourcePath, remoteUrl: "http://artwork.example/cover.jpg"), CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
Assert.True(File.Exists(sourcePath));
_mockFileProviderService.Received(1).CopyFile(
Arg.Is<FileSystemPathId>(pathId => pathId.Path == sourcePath),
Arg.Any<FileSystemPathId>(),
true);
}
finally
{
File.Delete(sourcePath);
}
}
[Fact]
public async Task SaveBookArtworkAsync_WhenRemoteDownloadIsCancelled_ShouldRethrowCancellation()
{
// Arrange
CancellationTokenSource cancellationTokenSource = new();
cancellationTokenSource.Cancel();
// Act
async Task Act()
{
await _sut.SaveBookArtworkAsync(Guid.NewGuid(), Guid.NewGuid(), "Library", "Author", "Title", _artworkDtoFixture.Create(remoteUrl: "http://artwork.example/cover.jpg"), cancellationTokenSource.Token);
}
// Assert
await Assert.ThrowsAnyAsync<OperationCanceledException>(Act);
}
[Fact]
public async Task SaveBookArtworkAsync_WhenFileExistenceCheckFails_ShouldReturnTheError()
{
@@ -409,223 +109,6 @@ public class BookArtworkServiceTests
Assert.Equal("FileSystem.Error", result.FirstError.Code);
}
[Fact]
public async Task SaveBookArtworkAsync_WhenImageTypeDetectionFails_ShouldReturnTheError()
{
// Arrange
string sourcePath = CreateTempImageFile(smallImageBytes: 1024);
try
{
_mockFileProviderService.FileExists(Arg.Any<FileSystemPathId>()).Returns(Result.From(true));
_mockFileTypeService.GetImageTypeAsync(Arg.Any<FileSystemPathId>(), Arg.Any<CancellationToken>())
.Returns(Error.Failure("FileSystem.Error", "Failed to detect the image type"));
// Act
Result<string> result = await _sut.SaveBookArtworkAsync(Guid.NewGuid(), Guid.NewGuid(), "Library", "Author", "Title", _artworkDtoFixture.Create(localPath: sourcePath), CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal("FileSystem.Error", result.FirstError.Code);
_mockFileProviderService.DidNotReceive().CopyFile(Arg.Any<FileSystemPathId>(), Arg.Any<FileSystemPathId>(), true);
}
finally
{
File.Delete(sourcePath);
}
}
[Fact]
public async Task SaveBookArtworkAsync_WhenCreatingTheArtworkDirectoryFails_ShouldReturnTheError()
{
// Arrange
Guid libraryId = Guid.NewGuid();
Guid bookId = Guid.NewGuid();
string libraryName = "Test Library";
string authorName = "Test Author";
string bookTitle = "Test Book";
string sourcePath = CreateTempImageFile(smallImageBytes: 1024);
try
{
_mockFileProviderService.FileExists(Arg.Any<FileSystemPathId>()).Returns(Result.From(true));
_mockFileTypeService.GetImageTypeAsync(Arg.Any<FileSystemPathId>(), Arg.Any<CancellationToken>())
.Returns(Result.From(ImageType.JPEG));
string artworkDirectoryPath = BuildArtworkDirectoryPath(libraryId, bookId, libraryName, authorName, bookTitle);
MockArtworkDirectoryStubs(artworkDirectoryPath);
_mockDirectoryProviderService.CreateDirectory(Arg.Any<FileSystemPathId>(), Arg.Any<string>())
.Returns(Error.Failure("Directory.Error", "Failed to create the artwork directory"));
// Act
Result<string> result = await _sut.SaveBookArtworkAsync(libraryId, bookId, libraryName, authorName, bookTitle, _artworkDtoFixture.Create(localPath: sourcePath), CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal("Directory.Error", result.FirstError.Code);
_mockFileProviderService.DidNotReceive().CopyFile(Arg.Any<FileSystemPathId>(), Arg.Any<FileSystemPathId>(), true);
}
finally
{
File.Delete(sourcePath);
}
}
[Fact]
public async Task SaveBookArtworkAsync_WhenDirectoryExistenceCheckFails_ShouldReturnTheError()
{
// Arrange
Guid libraryId = Guid.NewGuid();
Guid bookId = Guid.NewGuid();
string libraryName = "Test Library";
string authorName = "Test Author";
string bookTitle = "Test Book";
string sourcePath = CreateTempImageFile(smallImageBytes: 1024);
try
{
_mockFileProviderService.FileExists(Arg.Any<FileSystemPathId>()).Returns(Result.From(true));
_mockFileTypeService.GetImageTypeAsync(Arg.Any<FileSystemPathId>(), Arg.Any<CancellationToken>())
.Returns(Result.From(ImageType.JPEG));
string artworkDirectoryPath = BuildArtworkDirectoryPath(libraryId, bookId, libraryName, authorName, bookTitle);
MockArtworkDirectoryStubs(artworkDirectoryPath);
_mockDirectoryProviderService.DirectoryExists(Arg.Any<FileSystemPathId>())
.Returns(Error.Failure("Directory.Error", "Failed to check the artwork directory"));
// Act
Result<string> result = await _sut.SaveBookArtworkAsync(libraryId, bookId, libraryName, authorName, bookTitle, _artworkDtoFixture.Create(localPath: sourcePath), CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal("Directory.Error", result.FirstError.Code);
_mockFileProviderService.DidNotReceive().CopyFile(Arg.Any<FileSystemPathId>(), Arg.Any<FileSystemPathId>(), true);
}
finally
{
File.Delete(sourcePath);
}
}
[Fact]
public async Task SaveBookArtworkAsync_WhenCopyingTheArtworkFails_ShouldReturnTheError()
{
// Arrange
Guid libraryId = Guid.NewGuid();
Guid bookId = Guid.NewGuid();
string libraryName = "Test Library";
string authorName = "Test Author";
string bookTitle = "Test Book";
string sourcePath = CreateTempImageFile(smallImageBytes: 1024);
try
{
_mockFileProviderService.FileExists(Arg.Any<FileSystemPathId>()).Returns(Result.From(true));
_mockFileTypeService.GetImageTypeAsync(Arg.Any<FileSystemPathId>(), Arg.Any<CancellationToken>())
.Returns(Result.From(ImageType.JPEG));
string artworkDirectoryPath = BuildArtworkDirectoryPath(libraryId, bookId, libraryName, authorName, bookTitle);
MockArtworkDirectoryStubs(artworkDirectoryPath);
_mockFileProviderService.CopyFile(Arg.Any<FileSystemPathId>(), Arg.Any<FileSystemPathId>(), true)
.Returns(Error.Failure("FileSystem.Error", "Failed to copy the artwork"));
// Act
Result<string> result = await _sut.SaveBookArtworkAsync(libraryId, bookId, libraryName, authorName, bookTitle, _artworkDtoFixture.Create(localPath: sourcePath), CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal("FileSystem.Error", result.FirstError.Code);
_mockFileProviderService.DidNotReceive().RenameFile(Arg.Any<FileSystemPathId>(), Arg.Any<string>());
}
finally
{
File.Delete(sourcePath);
}
}
[Fact]
public async Task SaveBookArtworkAsync_WhenRenamingTheCopiedArtworkFails_ShouldReturnTheError()
{
// Arrange
Guid libraryId = Guid.NewGuid();
Guid bookId = Guid.NewGuid();
string libraryName = "Test Library";
string authorName = "Test Author";
string bookTitle = "Test Book";
string sourcePath = CreateTempImageFile(smallImageBytes: 1024);
try
{
_mockFileProviderService.FileExists(Arg.Any<FileSystemPathId>()).Returns(Result.From(true));
_mockFileTypeService.GetImageTypeAsync(Arg.Any<FileSystemPathId>(), Arg.Any<CancellationToken>())
.Returns(Result.From(ImageType.JPEG));
string artworkDirectoryPath = BuildArtworkDirectoryPath(libraryId, bookId, libraryName, authorName, bookTitle);
MockArtworkDirectoryStubs(artworkDirectoryPath);
_mockFileProviderService.CopyFile(Arg.Any<FileSystemPathId>(), Arg.Any<FileSystemPathId>(), true)
.Returns(Result.From(_fileSystemPathIdFixture.Create(Path.Combine(artworkDirectoryPath, "cover.jpg"))));
_mockFileProviderService.RenameFile(Arg.Any<FileSystemPathId>(), "cover.jpeg")
.Returns(Error.Failure("FileSystem.Error", "Failed to rename the artwork"));
// Act
Result<string> result = await _sut.SaveBookArtworkAsync(libraryId, bookId, libraryName, authorName, bookTitle, _artworkDtoFixture.Create(localPath: sourcePath), CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal("FileSystem.Error", result.FirstError.Code);
_mockFileProviderService.DidNotReceive().DeleteFile(Arg.Any<FileSystemPathId>());
}
finally
{
File.Delete(sourcePath);
}
}
[Fact]
public async Task SaveBookArtworkAsync_WhenAuthorNameCannotBeSanitized_ShouldReturnInvalidPath()
{
// Arrange
Guid libraryId = Guid.NewGuid();
Guid bookId = Guid.NewGuid();
string libraryName = "Test Library";
string authorName = "Test Author";
string bookTitle = "Test Book";
string sourcePath = CreateTempImageFile(smallImageBytes: 1024);
try
{
_mockFileProviderService.FileExists(Arg.Any<FileSystemPathId>()).Returns(Result.From(true));
_mockFileTypeService.GetImageTypeAsync(Arg.Any<FileSystemPathId>(), Arg.Any<CancellationToken>())
.Returns(Result.From(ImageType.JPEG));
string mediaRoot = Path.Combine(AppContext.BaseDirectory, "media");
string booksPath = Path.Combine(mediaRoot, "books");
_mockPathService.CombinePath(AppContext.BaseDirectory, "media").Returns(Result.From(mediaRoot));
_mockPathService.CombinePath(mediaRoot, "books").Returns(Result.From(booksPath));
_mockPathService.CombinePath(Arg.Any<string>(), Arg.Any<string>())
.Returns(callInfo => Result.From(Path.Combine(callInfo.ArgAt<string>(0), callInfo.ArgAt<string>(1))));
_mockPathService.SanitizeSegment(Arg.Any<string>())
.Returns(callInfo =>
{
string name = callInfo.Arg<string>();
return name == $"{libraryName}-{libraryId}"
? Result.From(_pathSegmentFixture.Create(name: name, isDirectory: true, isDrive: false))
: Errors.FileSystemManagement.InvalidPath;
});
// Act
Result<string> result = await _sut.SaveBookArtworkAsync(libraryId, bookId, libraryName, authorName, bookTitle, _artworkDtoFixture.Create(localPath: sourcePath), CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(Errors.FileSystemManagement.InvalidPath, result.FirstError);
_mockFileProviderService.DidNotReceive().CopyFile(Arg.Any<FileSystemPathId>(), Arg.Any<FileSystemPathId>(), true);
}
finally
{
File.Delete(sourcePath);
}
}
[Fact]
public void DeleteBookArtwork_WhenListingTheCoverFilesFails_ShouldReturnSuccessAndDeleteNothing()
{
@@ -712,7 +195,7 @@ public class BookArtworkServiceTests
_mockPathService.CombinePath(Arg.Any<string>(), Arg.Any<string>())
.Returns(callInfo => Result.From(Path.Combine(callInfo.ArgAt<string>(0), callInfo.ArgAt<string>(1))));
// every directory except the artwork directory itself already exists, so that only the final directory is created
// Every directory except the artwork directory itself already exists, so that only the final directory is created.
_mockDirectoryProviderService.DirectoryExists(Arg.Any<FileSystemPathId>())
.Returns(callInfo => Result.From(!string.Equals(callInfo.Arg<FileSystemPathId>().Path, artworkDirectoryPath, StringComparison.OrdinalIgnoreCase)));
_mockDirectoryProviderService.CreateDirectory(Arg.Any<FileSystemPathId>(), Arg.Any<string>())
@@ -741,57 +224,4 @@ public class BookArtworkServiceTests
authorName,
$"{bookTitle}-{bookId}");
}
/// <summary>
/// Creates a temporary image file with the given size and returns its path.
/// </summary>
/// <param name="smallImageBytes">The size of the temporary image file, in bytes.</param>
/// <returns>The file system path of the created temporary image file.</returns>
private static string CreateTempImageFile(int smallImageBytes)
{
string sourcePath = Path.Combine(Path.GetTempPath(), $"lumina-artwork-source-{Guid.NewGuid():N}.jpg");
File.WriteAllBytes(sourcePath, new byte[smallImageBytes]);
return sourcePath;
}
/// <summary>
/// Creates a file system link that points to the target directory: a junction on Windows, and a symbolic link on Unix-like platforms.
/// </summary>
/// <param name="linkPath">The file system path of the link to create.</param>
/// <param name="targetDirectory">The file system path of the directory the link points to.</param>
/// <returns><see langword="true"/> when the link was created, <see langword="false"/> otherwise.</returns>
private static bool TryCreateJunction(string linkPath, string targetDirectory)
{
try
{
System.Diagnostics.ProcessStartInfo startInfo = OperatingSystem.IsWindows()
? new()
{
FileName = "cmd.exe",
Arguments = $"/c mklink /J \"{linkPath}\" \"{targetDirectory}\"",
CreateNoWindow = true,
UseShellExecute = false
}
: new()
{
FileName = "ln",
CreateNoWindow = true,
UseShellExecute = false
};
if (!OperatingSystem.IsWindows())
{
startInfo.ArgumentList.Add("-s");
startInfo.ArgumentList.Add(targetDirectory);
startInfo.ArgumentList.Add(linkPath);
}
System.Diagnostics.Process process = System.Diagnostics.Process.Start(startInfo)!;
process.WaitForExit(5000);
return process.ExitCode == 0;
}
catch (Exception)
{
return false;
}
}
}
@@ -3,11 +3,8 @@ 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;
@@ -19,10 +16,7 @@ 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
@@ -33,7 +27,7 @@ namespace Lumina.Infrastructure.UnitTests.Core.MediaLibrary.WrittenContentLibrar
/// Contains unit tests for the <see cref="BookReadingService"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class BookReadingServiceTests : IDisposable
public class BookReadingServiceTests
{
private readonly IPluginManager _mockPluginManager;
private readonly IPlugin _mockPlugin;
@@ -42,14 +36,11 @@ public class BookReadingServiceTests : IDisposable
private readonly ILibraryBookReaderConfigurationRepository _mockConfigurationRepository;
private readonly IServiceProvider _serviceProvider;
private readonly BookReadingService _sut;
private readonly TestBookReaderEnablementCache _enablementCache = new();
private readonly BookReaderEnablementCache _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>
@@ -79,136 +70,12 @@ public class BookReadingServiceTests : IDisposable
_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");
// The resolution and enablement guards under test stop before the book file is probed, so no real file is needed.
_bookPath = $"lumina-test-book-{Guid.NewGuid():N}.epub";
_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()
{
@@ -241,284 +108,34 @@ public class BookReadingServiceTests : IDisposable
}
[Fact]
public async Task GetSectionAsync_WhenSectionExists_ShouldReturnSanitizedContent()
public async Task GetManifestAsync_WhenConfigurationsReadFails_ShouldReturnError()
{
// 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]);
.Returns(Error.Failure("Reading.Error", "Failed to read the configuration"));
// Act
Result<ReadingResourceDataDto> result = await _sut.GetResourceAsync(_bookId, _libraryId, _bookPath, LibraryType.EBook, "cover", shouldRenderPdfAsImages: false, CancellationToken.None);
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().GetResourceAsync(Arg.Any<string>(), Arg.Any<string>(), Arg.Any<string>(), Arg.Any<CancellationToken>());
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 GetResourceAsync_WhenEnablementCacheSaysDisabledAndResourceFileAlreadyExists_ShouldNotServeTheResource()
public async Task GetSectionAsync_WhenNoReaderSupportsTheFormat_ShouldReturnNoReaderAvailableError()
{
// 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]);
_mockPluginManager.GetPlugins().Returns([]);
// Act
Result<ReadingResourceDataDto> result = await _sut.GetResourceAsync(_bookId, _libraryId, _bookPath, LibraryType.EBook, "cover", shouldRenderPdfAsImages: false, CancellationToken.None);
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.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);
Assert.Equal(Errors.Reading.NoReaderAvailable, result.FirstError);
await _mockReader.DidNotReceive().OpenAsync(Arg.Any<string>(), Arg.Any<string>(), Arg.Any<bool>(), Arg.Any<CancellationToken>());
}
[Fact]
@@ -567,325 +184,4 @@ public class BookReadingServiceTests : IDisposable
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);
}
}
[Fact]
public async Task GetSectionAsync_WhenNoReaderSupportsTheFormat_ShouldReturnNoReaderAvailableError()
{
// Arrange
_mockPluginManager.GetPlugins().Returns([]);
// 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.NoReaderAvailable, result.FirstError);
await _mockReader.DidNotReceive().OpenAsync(Arg.Any<string>(), Arg.Any<string>(), Arg.Any<bool>(), Arg.Any<CancellationToken>());
}
[Fact]
public async Task GetManifestAsync_WhenAReaderDeclaresABlankExtension_ShouldSkipItAndStillResolveTheFormat()
{
// Arrange
ReadingDocumentDto document = CreateExtractableDocument();
StubOpenAsyncToExtract(document);
IBookReader blankExtensionReader = Substitute.For<IBookReader>();
blankExtensionReader.SupportedExtensions.Returns([" "]);
blankExtensionReader.SupportedLibraryTypes.Returns([LibraryType.EBook]);
ServiceCollection services = new();
services.AddKeyedSingleton(_pluginId, blankExtensionReader);
services.AddKeyedSingleton(_pluginId, _mockReader);
services.AddSingleton(_mockUnitOfWork);
using (ServiceProvider serviceProvider = services.BuildServiceProvider())
{
IServiceScopeFactory serviceScopeFactory = serviceProvider.GetRequiredService<IServiceScopeFactory>();
BookReadingService sut = new(serviceProvider, _mockPluginManager, _enablementCache, serviceScopeFactory, Substitute.For<ILogger<BookReadingService>>());
// Act
Result<ReadingManifestResponse> result = await sut.GetManifestAsync(_bookId, _libraryId, _bookPath, LibraryType.EBook, shouldRenderPdfAsImages: false, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
Assert.Equal(document.Title, result.Value.Title);
}
}
[Fact]
public async Task GetResourceAsync_WhenTwoRequestsMissTheSameResourceConcurrently_ShouldProduceItOnceAndBothServeIt()
{
// Arrange
ReadingDocumentDto document = CreateExtractableDocument();
StubOpenAsyncToExtract(document);
byte[] producedResource = [7, 8, 9];
TaskCompletionSource<bool> productionStarted = new();
TaskCompletionSource<bool> allowProductionToFinish = new();
_mockReader.GetResourceAsync(Arg.Any<string>(), Arg.Any<string>(), "cover", Arg.Any<CancellationToken>())
.Returns(async callInfo =>
{
productionStarted.SetResult(true);
await allowProductionToFinish.Task;
return producedResource;
});
// Act
Task<Result<ReadingResourceDataDto>> firstTask = _sut.GetResourceAsync(_bookId, _libraryId, _bookPath, LibraryType.EBook, "cover", shouldRenderPdfAsImages: false, CancellationToken.None);
await productionStarted.Task;
Task<Result<ReadingResourceDataDto>> secondTask = _sut.GetResourceAsync(_bookId, _libraryId, _bookPath, LibraryType.EBook, "cover", shouldRenderPdfAsImages: false, CancellationToken.None);
allowProductionToFinish.SetResult(true);
Result<ReadingResourceDataDto> firstResult = await firstTask;
Result<ReadingResourceDataDto> secondResult = await secondTask;
// Assert
Assert.False(firstResult.IsFailure);
Assert.False(secondResult.IsFailure);
Assert.Equal(new byte[] { 7, 8, 9 }, firstResult.Value.Data);
Assert.Equal(new byte[] { 7, 8, 9 }, secondResult.Value.Data);
await _mockReader.Received(1).GetResourceAsync(_bookPath, Arg.Any<string>(), "cover", Arg.Any<CancellationToken>());
}
/// <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));
}
}
}