Renames project paths from Lumina to Nemera

This commit is contained in:
BinaryAlley committed 2026-11-27 15:34:43 +02:00
1 parent ce6fddb4c9
commit 0f659a4877
6450 files changed

No files matched your search

@@ -0,0 +1,740 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Infrastructure.Common.Caching;
using Lumina.Infrastructure.Common.Models.DTO.MediaLibrary.AudioLibrary.MusicLibrary.Playback;
using Lumina.Infrastructure.Core.MediaLibrary.AudioLibrary.MusicLibrary.Playback;
using Lumina.Infrastructure.Fixtures.Common.Models.DTO.MediaLibrary.AudioLibrary.MusicLibrary.Playback;
using System;
using System.Diagnostics.CodeAnalysis;
using System.IO;
using System.Threading;
#endregion
namespace Lumina.Infrastructure.IntegrationTests.Core.MediaLibrary.AudioLibrary.MusicLibrary.Playback;
/// <summary>
/// Contains integration tests for the <see cref="TranscodingCacheCoordinator"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class TranscodingCacheCoordinatorTests : IDisposable
{
private readonly string _temporaryDirectory;
private readonly string _cacheRoot;
private readonly TranscodingCacheCoordinator _sut;
private readonly NormalizedTrackIndexDtoFixture _normalizedTrackIndexDtoFixture = new();
/// <summary>
/// Initializes a new instance of the <see cref="TranscodingCacheCoordinatorTests"/> class.
/// </summary>
public TranscodingCacheCoordinatorTests()
{
_temporaryDirectory = Path.Combine(Path.GetTempPath(), $"lumina-transcoding-cache-coordinator-{Guid.NewGuid():N}");
_cacheRoot = Path.Combine(_temporaryDirectory, "cache");
Directory.CreateDirectory(_cacheRoot);
_sut = TranscodingCacheCoordinator.AcquireForRoot(_cacheRoot);
}
[Fact]
public void AcquireForRoot_WhenCalledTwiceForTheSameRoot_ShouldReturnTheSameInstance()
{
// Arrange
string cacheRoot = Path.Combine(_temporaryDirectory, "shared-cache");
// Act
TranscodingCacheCoordinator firstCoordinator = TranscodingCacheCoordinator.AcquireForRoot(cacheRoot);
TranscodingCacheCoordinator secondCoordinator = TranscodingCacheCoordinator.AcquireForRoot(cacheRoot);
// Assert
try
{
Assert.Same(firstCoordinator, secondCoordinator);
}
finally
{
firstCoordinator.Release();
secondCoordinator.Release();
}
}
[Fact]
public void Release_WhenOneReferenceRemains_ShouldKeepTheCoordinatorRegistered()
{
// Arrange
string cacheRoot = Path.Combine(_temporaryDirectory, "partially-released-cache");
TranscodingCacheCoordinator firstCoordinator = TranscodingCacheCoordinator.AcquireForRoot(cacheRoot);
TranscodingCacheCoordinator secondCoordinator = TranscodingCacheCoordinator.AcquireForRoot(cacheRoot);
try
{
// Act
firstCoordinator.Release();
TranscodingCacheCoordinator acquiredAfterRelease = TranscodingCacheCoordinator.AcquireForRoot(cacheRoot);
// Assert
try
{
Assert.Same(firstCoordinator, acquiredAfterRelease);
}
finally
{
acquiredAfterRelease.Release();
}
}
finally
{
firstCoordinator.Release();
secondCoordinator.Release();
}
}
[Fact]
public void Release_WhenTheLastReferenceIsReleased_ShouldMakeALaterAcquireReturnANewInstance()
{
// Arrange
string cacheRoot = Path.Combine(_temporaryDirectory, "fully-released-cache");
TranscodingCacheCoordinator firstCoordinator = TranscodingCacheCoordinator.AcquireForRoot(cacheRoot);
TranscodingCacheCoordinator secondCoordinator = TranscodingCacheCoordinator.AcquireForRoot(cacheRoot);
// Act
firstCoordinator.Release();
secondCoordinator.Release();
TranscodingCacheCoordinator laterCoordinator = TranscodingCacheCoordinator.AcquireForRoot(cacheRoot);
// Assert
try
{
Assert.NotSame(firstCoordinator, laterCoordinator);
}
finally
{
laterCoordinator.Release();
}
}
[Theory]
[InlineData(0)] // A zero sized output.
[InlineData(-1)] // A negative sized output.
public void TryReserve_WhenTheRequestedSizeIsNotPositive_ShouldReturnFalse(int requestedBytes)
{
// Act
bool result = _sut.TryReserve(requestedBytes, 100, TimeSpan.Zero, out TranscodingCacheReservation? reservation);
// Assert
Assert.False(result);
Assert.Null(reservation);
}
[Theory]
[InlineData(0)] // A zero maximum cache size.
[InlineData(-1)] // A negative maximum cache size.
public void TryReserve_WhenTheMaximumCacheSizeIsNotPositive_ShouldReturnFalse(int maxCacheBytes)
{
// Act
bool result = _sut.TryReserve(50, maxCacheBytes, TimeSpan.Zero, out TranscodingCacheReservation? reservation);
// Assert
Assert.False(result);
Assert.Null(reservation);
}
[Fact]
public void TryReserve_WhenTheRequestExceedsTheMaximum_ShouldReturnFalse()
{
// Act
bool result = _sut.TryReserve(101, 100, TimeSpan.Zero, out TranscodingCacheReservation? reservation);
// Assert
Assert.False(result);
Assert.Null(reservation);
}
[Fact]
public void TryReserve_WhenTheRequestFits_ShouldReserveCapacity()
{
// Act
bool result = _sut.TryReserve(50, 100, TimeSpan.Zero, out TranscodingCacheReservation? reservation);
// Assert
Assert.True(result);
Assert.NotNull(reservation);
reservation!.Dispose();
}
[Fact]
public void TryReserve_WhenTheCacheAlreadyHoldsAReservation_ShouldCountItAgainstTheLimit()
{
// Arrange
Assert.True(_sut.TryReserve(60, 100, TimeSpan.Zero, out TranscodingCacheReservation? firstReservation));
Assert.NotNull(firstReservation);
try
{
// Act
bool result = _sut.TryReserve(50, 100, TimeSpan.Zero, out TranscodingCacheReservation? secondReservation);
// Assert
Assert.False(result);
Assert.Null(secondReservation);
}
finally
{
firstReservation.Dispose();
}
}
[Fact]
public void TryGrow_WhenTheReservationIsUnknown_ShouldReturnFalse()
{
// Act
bool result = _sut.TryGrow(Guid.NewGuid().ToString("N"), 50, 100, TimeSpan.Zero);
// Assert
Assert.False(result);
}
[Fact]
public void TryGrow_WhenTheActualSizeIsNotLargerThanTheReservation_ShouldKeepTheReservedSize()
{
// Arrange
Assert.True(_sut.TryReserve(100, 150, TimeSpan.Zero, out TranscodingCacheReservation? reservation));
Assert.NotNull(reservation);
try
{
// Act
bool result = _sut.TryGrow(reservation.Id, 50, 150, TimeSpan.Zero);
// Assert
Assert.True(result);
Assert.False(_sut.TryReserve(60, 150, TimeSpan.Zero, out _));
}
finally
{
reservation!.Dispose();
}
}
[Fact]
public void TryGrow_WhenTheGrownSizeFits_ShouldIncreaseTheReservation()
{
// Arrange
Assert.True(_sut.TryReserve(40, 100, TimeSpan.Zero, out TranscodingCacheReservation? reservation));
Assert.NotNull(reservation);
try
{
// Act
bool result = _sut.TryGrow(reservation.Id, 80, 100, TimeSpan.Zero);
// Assert
Assert.True(result);
Assert.False(_sut.TryReserve(30, 100, TimeSpan.Zero, out _));
Assert.True(_sut.TryReserve(20, 100, TimeSpan.Zero, out TranscodingCacheReservation? remainingReservation));
remainingReservation!.Dispose();
}
finally
{
reservation!.Dispose();
}
}
[Fact]
public void TryGrow_WhenTheGrownSizeExceedsTheMaximum_ShouldReturnFalse()
{
// Arrange
Assert.True(_sut.TryReserve(40, 100, TimeSpan.Zero, out TranscodingCacheReservation? reservation));
Assert.NotNull(reservation);
try
{
// Act
bool result = _sut.TryGrow(reservation.Id, 101, 100, TimeSpan.Zero);
// Assert
Assert.False(result);
}
finally
{
reservation!.Dispose();
}
}
[Fact]
public void TryGrow_WhenTheActualSizeIsNegative_ShouldReturnFalse()
{
// Arrange
Assert.True(_sut.TryReserve(40, 100, TimeSpan.Zero, out TranscodingCacheReservation? reservation));
Assert.NotNull(reservation);
try
{
// Act
bool result = _sut.TryGrow(reservation.Id, -1, 100, TimeSpan.Zero);
// Assert
Assert.False(result);
}
finally
{
reservation!.Dispose();
}
}
[Fact]
public void TryPublish_WhenTheEntryFits_ShouldMoveTheProducedEntryAndRegisterIt()
{
// Arrange
string cacheId = CreateCacheId();
string temporaryPath = CreateTemporaryOutput(128);
NormalizedTrackIndexDto index = _normalizedTrackIndexDtoFixture.Create();
Assert.True(_sut.TryReserve(128, 1024, TimeSpan.Zero, out TranscodingCacheReservation? reservation));
Assert.NotNull(reservation);
// Act
bool result = _sut.TryPublish(reservation.Id, cacheId, temporaryPath, 128, index, 1024, TimeSpan.Zero, out bool isKeptOverCapacity, out bool isEntryInUse);
// Assert
Assert.True(result);
Assert.False(isKeptOverCapacity);
Assert.False(isEntryInUse);
string cachePath = Path.Combine(_cacheRoot, cacheId);
Assert.True(Directory.Exists(cachePath));
Assert.False(Directory.Exists(temporaryPath));
Assert.Equal(128, TranscodingCacheCoordinator.GetDirectorySize(cachePath));
Assert.True(_sut.TryGetIndex(cacheId, out NormalizedTrackIndexDto? cachedIndex));
Assert.Same(index, cachedIndex);
}
[Fact]
public void TryPublish_WhenTheSameCacheIdIsPublishedAgain_ShouldReplaceThePreviousEntry()
{
// Arrange
string cacheId = CreateCacheId();
PublishEntry(cacheId, 30, 100);
string replacementPath = CreateTemporaryOutput(40, "replacement.m4s");
NormalizedTrackIndexDto replacementIndex = _normalizedTrackIndexDtoFixture.Create();
Assert.True(_sut.TryReserve(40, 100, TimeSpan.Zero, out TranscodingCacheReservation? reservation));
Assert.NotNull(reservation);
// Act
bool result = _sut.TryPublish(reservation.Id, cacheId, replacementPath, 40, replacementIndex, 100, TimeSpan.Zero, out bool isKeptOverCapacity, out bool isEntryInUse);
// Assert
Assert.True(result);
Assert.False(isKeptOverCapacity);
Assert.False(isEntryInUse);
string cachePath = Path.Combine(_cacheRoot, cacheId);
Assert.True(File.Exists(Path.Combine(cachePath, "replacement.m4s")));
Assert.False(File.Exists(Path.Combine(cachePath, "segment.m4s")));
Assert.True(_sut.TryGetIndex(cacheId, out NormalizedTrackIndexDto? cachedIndex));
Assert.Same(replacementIndex, cachedIndex);
Assert.True(_sut.TryReserve(60, 100, TimeSpan.FromHours(1), out TranscodingCacheReservation? accountingProbe));
accountingProbe!.Dispose();
}
[Fact]
public void TryPublish_WhenAReaderHoldsThePreviousEntry_ShouldReturnFalseAndKeepThePreviousEntry()
{
// Arrange
string cacheId = CreateCacheId();
NormalizedTrackIndexDto originalIndex = PublishEntry(cacheId, 50, 200);
using (TranscodingCacheReaderLease lease = _sut.AcquireReaderLease(cacheId))
{
string temporaryPath = CreateTemporaryOutput(50);
Assert.True(_sut.TryReserve(50, 200, TimeSpan.Zero, out TranscodingCacheReservation? reservation));
Assert.NotNull(reservation);
// Act
bool result = _sut.TryPublish(reservation.Id, cacheId, temporaryPath, 50, _normalizedTrackIndexDtoFixture.Create(), 200, TimeSpan.Zero, out bool isKeptOverCapacity, out bool isEntryInUse);
// Assert
Assert.False(result);
Assert.True(isEntryInUse);
Assert.False(isKeptOverCapacity);
Assert.True(Directory.Exists(temporaryPath));
Assert.True(Directory.Exists(Path.Combine(_cacheRoot, cacheId)));
Assert.True(_sut.TryGetIndex(cacheId, out NormalizedTrackIndexDto? cachedIndex));
Assert.Same(originalIndex, cachedIndex);
}
}
[Fact]
public void TryPublish_WhenTheProducedEntryAloneExceedsTheMaximum_ShouldKeepItOverCapacity()
{
// Arrange
string cacheId = CreateCacheId();
string temporaryPath = CreateTemporaryOutput(150);
Assert.True(_sut.TryReserve(50, 100, TimeSpan.Zero, out TranscodingCacheReservation? reservation));
Assert.NotNull(reservation);
// Act
bool result = _sut.TryPublish(reservation.Id, cacheId, temporaryPath, 150, _normalizedTrackIndexDtoFixture.Create(), 100, TimeSpan.Zero, out bool isKeptOverCapacity, out bool isEntryInUse);
// Assert
Assert.True(result);
Assert.True(isKeptOverCapacity);
Assert.False(isEntryInUse);
Assert.True(Directory.Exists(Path.Combine(_cacheRoot, cacheId)));
Assert.True(_sut.TryGetIndex(cacheId, out _));
}
[Fact]
public void TryPublish_WhenTheTemporaryDirectoryDoesNotExist_ShouldReturnFalseAndConsumeTheReservation()
{
// Arrange
Assert.True(_sut.TryReserve(50, 100, TimeSpan.Zero, out TranscodingCacheReservation? reservation));
Assert.NotNull(reservation);
string missingTemporaryPath = Path.Combine(_temporaryDirectory, "missing-output");
// Act
bool result = _sut.TryPublish(reservation.Id, CreateCacheId(), missingTemporaryPath, 50, _normalizedTrackIndexDtoFixture.Create(), 100, TimeSpan.Zero, out bool isKeptOverCapacity, out bool isEntryInUse);
// Assert
Assert.False(result);
Assert.False(isKeptOverCapacity);
Assert.False(isEntryInUse);
Assert.False(reservation.TryUpdate(50, 100, TimeSpan.Zero));
Assert.True(_sut.TryReserve(100, 100, TimeSpan.Zero, out TranscodingCacheReservation? replacementReservation));
replacementReservation!.Dispose();
}
[Fact]
public void ReleaseReservation_WhenCalled_ShouldFreeTheReservedCapacity()
{
// Arrange
Assert.True(_sut.TryReserve(100, 100, TimeSpan.Zero, out TranscodingCacheReservation? firstReservation));
Assert.NotNull(firstReservation);
Assert.False(_sut.TryReserve(100, 100, TimeSpan.Zero, out _));
// Act
_sut.ReleaseReservation(firstReservation.Id);
// Assert
Assert.True(_sut.TryReserve(100, 100, TimeSpan.Zero, out TranscodingCacheReservation? secondReservation));
secondReservation!.Dispose();
firstReservation.Dispose();
}
[Fact]
public void Touch_WhenTheCacheIdIsUnknown_ShouldBeIgnored()
{
// Act
Exception? exception = Record.Exception(() => _sut.Touch(CreateCacheId(), TimeSpan.Zero));
// Assert
Assert.Null(exception);
}
[Fact]
public void Touch_WhenTheThrottleIntervalHasNotElapsed_ShouldNotChangeTheEntry()
{
// Arrange
string cacheId = CreateCacheId();
string cachePath = Path.Combine(_cacheRoot, cacheId);
PublishEntry(cacheId, 50, 100);
Thread.Sleep(200);
// Act
_sut.Touch(cacheId, TimeSpan.FromDays(1));
bool result = _sut.TryReserve(80, 100, TimeSpan.FromMilliseconds(100), out _);
// Assert
Assert.True(result);
Assert.False(Directory.Exists(cachePath));
}
[Fact]
public void Touch_WhenTheThrottleIntervalHasElapsed_ShouldUpdateTheEntry()
{
// Arrange
string cacheId = CreateCacheId();
string cachePath = Path.Combine(_cacheRoot, cacheId);
PublishEntry(cacheId, 50, 100);
// The entry must be older than the grace period before the touch, and the touch must still be inside it when the reservation
// runs. A grace period of seconds keeps the second condition true on slow CI runners, where a few hundred milliseconds can pass between the two calls.
Thread.Sleep(2100);
// Act
_sut.Touch(cacheId, TimeSpan.Zero);
bool result = _sut.TryReserve(80, 100, TimeSpan.FromSeconds(2), out _);
// Assert
Assert.False(result);
Assert.True(Directory.Exists(cachePath));
}
[Fact]
public void TryReserve_WhenTheOnlyEntryIsLeased_ShouldNotEvictItUntilTheLeaseIsReleased()
{
// Arrange
string cacheId = CreateCacheId();
string cachePath = Path.Combine(_cacheRoot, cacheId);
PublishEntry(cacheId, 50, 100);
TranscodingCacheReaderLease lease = _sut.AcquireReaderLease(cacheId);
try
{
// Act
bool result = _sut.TryReserve(80, 100, TimeSpan.Zero, out _);
// Assert
Assert.False(result);
Assert.True(Directory.Exists(cachePath));
}
finally
{
lease.Dispose();
}
Assert.False(Directory.Exists(cachePath));
Assert.True(_sut.TryReserve(80, 100, TimeSpan.Zero, out TranscodingCacheReservation? reservation));
reservation!.Dispose();
}
[Fact]
public void TryReserve_WhenTheCacheIsFull_ShouldEvictTheLeastRecentlyUsedEntriesInOrder()
{
// Arrange
string firstCacheId = CreateCacheId();
string secondCacheId = CreateCacheId();
string thirdCacheId = CreateCacheId();
PublishEntry(firstCacheId, 50, 150);
Thread.Sleep(30);
PublishEntry(secondCacheId, 50, 150);
Thread.Sleep(30);
PublishEntry(thirdCacheId, 50, 150);
// Act
bool result = _sut.TryReserve(60, 150, TimeSpan.Zero, out TranscodingCacheReservation? reservation);
// Assert
Assert.True(result);
Assert.False(Directory.Exists(Path.Combine(_cacheRoot, firstCacheId)));
Assert.False(Directory.Exists(Path.Combine(_cacheRoot, secondCacheId)));
Assert.True(Directory.Exists(Path.Combine(_cacheRoot, thirdCacheId)));
reservation!.Dispose();
}
[Fact]
public void TryReserve_WhenAnEntryIsInsideTheGracePeriod_ShouldNotEvictIt()
{
// Arrange
string cacheId = CreateCacheId();
string cachePath = Path.Combine(_cacheRoot, cacheId);
PublishEntry(cacheId, 50, 100);
// Act
bool result = _sut.TryReserve(80, 100, TimeSpan.FromHours(1), out TranscodingCacheReservation? reservation);
// Assert
Assert.False(result);
Assert.Null(reservation);
Assert.True(Directory.Exists(cachePath));
}
[Fact]
public void TryReserve_WhenTheGracePeriodHasElapsed_ShouldEvictTheEntry()
{
// Arrange
string cacheId = CreateCacheId();
string cachePath = Path.Combine(_cacheRoot, cacheId);
PublishEntry(cacheId, 50, 100);
// Act
bool result = _sut.TryReserve(80, 100, TimeSpan.Zero, out TranscodingCacheReservation? reservation);
// Assert
Assert.True(result);
Assert.False(Directory.Exists(cachePath));
reservation!.Dispose();
}
[Fact]
public void TryPublish_WhenOnlyUnprotectedEntriesAreLeased_ShouldNeverEvictThePublishedEntry()
{
// Arrange
string firstCacheId = CreateCacheId();
string secondCacheId = CreateCacheId();
string publishedCacheId = CreateCacheId();
PublishEntry(firstCacheId, 50, 200);
PublishEntry(secondCacheId, 50, 200);
Assert.True(_sut.TryReserve(50, 200, TimeSpan.Zero, out TranscodingCacheReservation? reservation));
Assert.NotNull(reservation);
TranscodingCacheReaderLease firstLease = _sut.AcquireReaderLease(firstCacheId);
TranscodingCacheReaderLease secondLease = _sut.AcquireReaderLease(secondCacheId);
try
{
// Act
bool result = _sut.TryPublish(reservation.Id, publishedCacheId, CreateTemporaryOutput(50), 50, _normalizedTrackIndexDtoFixture.Create(), 100, TimeSpan.Zero, out bool isKeptOverCapacity, out bool isEntryInUse);
// Assert
Assert.True(result);
Assert.True(isKeptOverCapacity);
Assert.False(isEntryInUse);
Assert.True(Directory.Exists(Path.Combine(_cacheRoot, publishedCacheId)));
}
finally
{
firstLease.Dispose();
secondLease.Dispose();
}
Assert.False(Directory.Exists(Path.Combine(_cacheRoot, firstCacheId)));
Assert.False(Directory.Exists(Path.Combine(_cacheRoot, secondCacheId)));
Assert.True(Directory.Exists(Path.Combine(_cacheRoot, publishedCacheId)));
}
[Fact]
public void TryReserve_WhenTheRootAlreadyHoldsEntries_ShouldAccountForThem()
{
// Arrange
string existingCacheId = CreateCacheId();
string entryPath = Path.Combine(_cacheRoot, existingCacheId);
Directory.CreateDirectory(entryPath);
File.WriteAllBytes(Path.Combine(entryPath, "segment.m4s"), new byte[60]);
// Act
bool result = _sut.TryReserve(50, 100, TimeSpan.FromHours(1), out TranscodingCacheReservation? reservation);
// Assert
Assert.False(result);
Assert.Null(reservation);
}
[Fact]
public void TryReserve_WhenTheRootHoldsNamesThatAreNotCacheIds_ShouldIgnoreThem()
{
// Arrange
string unrelatedDirectoryPath = Path.Combine(_cacheRoot, "not-a-cache-id");
Directory.CreateDirectory(unrelatedDirectoryPath);
File.WriteAllBytes(Path.Combine(unrelatedDirectoryPath, "payload.bin"), new byte[200]);
// Act
bool result = _sut.TryReserve(100, 100, TimeSpan.FromHours(1), out TranscodingCacheReservation? reservation);
// Assert
Assert.True(result);
reservation!.Dispose();
}
[Fact]
public void TryReserve_WhenTheRootHoldsTombstones_ShouldHandThemToTheSweeper()
{
// Arrange
string tombstonePath = Path.Combine(_cacheRoot, TranscodingCachePaths.DELETION_DIRECTORY_PREFIX + Guid.NewGuid().ToString("N"));
Directory.CreateDirectory(tombstonePath);
File.WriteAllBytes(Path.Combine(tombstonePath, "segment.m4s"), new byte[200]);
// Act
bool result = _sut.TryReserve(100, 100, TimeSpan.FromHours(1), out TranscodingCacheReservation? reservation);
// Assert
Assert.True(result);
reservation!.Dispose();
Assert.True(WaitUntil(() => !Directory.Exists(tombstonePath), TimeSpan.FromSeconds(2)));
}
[Fact]
public void GetDirectorySize_WhenTheDirectoryHasNestedFiles_ShouldReturnTheirTotalSize()
{
// Arrange
string directoryPath = Path.Combine(_temporaryDirectory, "size-root");
Directory.CreateDirectory(Path.Combine(directoryPath, "nested", "deeper"));
File.WriteAllBytes(Path.Combine(directoryPath, "first.bin"), new byte[10]);
File.WriteAllBytes(Path.Combine(directoryPath, "nested", "second.bin"), new byte[20]);
File.WriteAllBytes(Path.Combine(directoryPath, "nested", "deeper", "third.bin"), new byte[30]);
// Act
long result = TranscodingCacheCoordinator.GetDirectorySize(directoryPath);
// Assert
Assert.Equal(60, result);
}
[Fact]
public void GetDirectorySize_WhenTheDirectoryDoesNotExist_ShouldReturnZero()
{
// Arrange
string directoryPath = Path.Combine(_temporaryDirectory, "missing-size-root");
// Act
long result = TranscodingCacheCoordinator.GetDirectorySize(directoryPath);
// Assert
Assert.Equal(0, result);
}
/// <summary>
/// Creates a well formed opaque cache identifier.
/// </summary>
/// <returns>A 64 character lowercase hexadecimal identifier.</returns>
private static string CreateCacheId()
{
return $"{Guid.NewGuid():N}{Guid.NewGuid():N}";
}
/// <summary>
/// Creates a temporary output directory with a single file of the requested size.
/// </summary>
/// <param name="size">The size of the produced file, in bytes.</param>
/// <param name="fileName">The name of the produced file.</param>
/// <returns>The path of the created temporary output directory.</returns>
private string CreateTemporaryOutput(int size, string fileName = "segment.m4s")
{
string temporaryPath = Path.Combine(_temporaryDirectory, TranscodingCachePaths.TEMPORARY_DIRECTORY_PREFIX + Guid.NewGuid().ToString("N"));
Directory.CreateDirectory(temporaryPath);
File.WriteAllBytes(Path.Combine(temporaryPath, fileName), new byte[size]);
return temporaryPath;
}
/// <summary>
/// Reserves capacity and publishes a produced entry under the requested cache identifier.
/// </summary>
/// <param name="cacheId">The identifier of the produced cache entry.</param>
/// <param name="size">The total size of the produced cache entry, in bytes.</param>
/// <param name="maxCacheBytes">The maximum total size of the cache, in bytes.</param>
/// <returns>The index that was published with the entry.</returns>
private NormalizedTrackIndexDto PublishEntry(string cacheId, int size, long maxCacheBytes)
{
string temporaryPath = CreateTemporaryOutput(size);
NormalizedTrackIndexDto index = _normalizedTrackIndexDtoFixture.Create();
Assert.True(_sut.TryReserve(size, maxCacheBytes, TimeSpan.Zero, out TranscodingCacheReservation? reservation));
Assert.NotNull(reservation);
Assert.True(_sut.TryPublish(reservation.Id, cacheId, temporaryPath, size, index, maxCacheBytes, TimeSpan.Zero, out _, out _));
return index;
}
/// <summary>
/// Waits, for a bounded period, until the condition becomes true.
/// </summary>
/// <param name="condition">The condition to wait for.</param>
/// <param name="timeout">The maximum period to wait.</param>
/// <returns><see langword="true"/> when the condition became true within the timeout, otherwise <see langword="false"/>.</returns>
private static bool WaitUntil(Func<bool> condition, TimeSpan timeout)
{
DateTime deadline = DateTime.UtcNow + timeout;
while (DateTime.UtcNow < deadline)
{
if (condition())
return true;
Thread.Sleep(20);
}
return condition();
}
/// <summary>
/// Releases the coordinator and removes the temporary directory created for the test.
/// </summary>
public void Dispose()
{
_sut.Release();
try
{
if (Directory.Exists(_temporaryDirectory))
Directory.Delete(_temporaryDirectory, recursive: true);
}
catch (Exception exception) when (exception is IOException or UnauthorizedAccessException)
{
// A background sweeper can still be removing a tombstone that was detached by the test.
}
GC.SuppressFinalize(this);
}
}
@@ -0,0 +1,479 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Infrastructure.Core.MediaLibrary.AudioLibrary.MusicLibrary.Playback;
using Lumina.Infrastructure.Fixtures.Common.Models.DTO.MediaLibrary.AudioLibrary.MusicLibrary.Playback;
using NSubstitute;
using System;
using System.Diagnostics.CodeAnalysis;
using System.IO;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Infrastructure.IntegrationTests.Core.MediaLibrary.AudioLibrary.MusicLibrary.Playback;
/// <summary>
/// Contains integration tests for the <see cref="TranscodingCacheLeaseStream"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class TranscodingCacheLeaseStreamTests : IDisposable
{
private readonly string _temporaryDirectory;
private readonly string _cacheRoot;
private readonly TranscodingCacheCoordinator _coordinator;
private readonly NormalizedTrackIndexDtoFixture _normalizedTrackIndexDtoFixture = new();
/// <summary>
/// Initializes a new instance of the <see cref="TranscodingCacheLeaseStreamTests"/> class.
/// </summary>
public TranscodingCacheLeaseStreamTests()
{
_temporaryDirectory = Path.Combine(Path.GetTempPath(), $"lumina-transcoding-cache-stream-{Guid.NewGuid():N}");
_cacheRoot = Path.Combine(_temporaryDirectory, "cache");
Directory.CreateDirectory(_cacheRoot);
_coordinator = TranscodingCacheCoordinator.AcquireForRoot(_cacheRoot);
}
[Fact]
public void CanRead_WhenAccessed_ShouldReturnTheInnerValue()
{
// Arrange
Stream innerStream = Substitute.For<Stream>();
innerStream.CanRead.Returns(true);
// Act
bool result;
using (TranscodingCacheLeaseStream leaseStream = CreateSut(innerStream))
result = leaseStream.CanRead;
// Assert
Assert.True(result);
}
[Fact]
public void CanSeek_WhenAccessed_ShouldReturnTheInnerValue()
{
// Arrange
Stream innerStream = Substitute.For<Stream>();
innerStream.CanSeek.Returns(false);
// Act
bool result;
using (TranscodingCacheLeaseStream leaseStream = CreateSut(innerStream))
result = leaseStream.CanSeek;
// Assert
Assert.False(result);
}
[Fact]
public void CanWrite_WhenAccessed_ShouldReturnTheInnerValue()
{
// Arrange
Stream innerStream = Substitute.For<Stream>();
innerStream.CanWrite.Returns(true);
// Act
bool result;
using (TranscodingCacheLeaseStream leaseStream = CreateSut(innerStream))
result = leaseStream.CanWrite;
// Assert
Assert.True(result);
}
[Fact]
public void Length_WhenAccessed_ShouldReturnTheInnerValue()
{
// Arrange
using (MemoryStream innerStream = new([1, 2, 3, 4, 5]))
using (TranscodingCacheLeaseStream leaseStream = CreateSut(innerStream))
{
// Act
long result = leaseStream.Length;
// Assert
Assert.Equal(5L, result);
}
}
[Fact]
public void Position_WhenAccessed_ShouldReturnAndSetTheInnerValue()
{
// Arrange
using (MemoryStream innerStream = new([1, 2, 3, 4, 5, 6, 7, 8]))
using (TranscodingCacheLeaseStream leaseStream = CreateSut(innerStream))
{
innerStream.Position = 5L;
// Act
long position = leaseStream.Position;
leaseStream.Position = 7L;
// Assert
Assert.Equal(5L, position);
Assert.Equal(7L, innerStream.Position);
}
}
[Fact]
public void Flush_WhenCalled_ShouldFlushTheInnerStream()
{
// Arrange
Stream innerStream = Substitute.For<Stream>();
// Act
using (TranscodingCacheLeaseStream leaseStream = CreateSut(innerStream))
leaseStream.Flush();
// Assert
innerStream.Received(1).Flush();
}
[Fact]
public void Read_WhenCalled_ShouldReadFromTheInnerStream()
{
// Arrange
byte[] buffer = new byte[8];
using (MemoryStream innerStream = new([1, 2, 3, 4, 5]))
using (TranscodingCacheLeaseStream leaseStream = CreateSut(innerStream))
{
// Act
int result = leaseStream.Read(buffer, 1, 4);
// Assert
Assert.Equal(4, result);
Assert.Equal(new byte[] { 0, 1, 2, 3, 4, 0, 0, 0 }, buffer);
Assert.Equal(4L, innerStream.Position);
}
}
[Fact]
public void Read_WhenCalledWithASpan_ShouldReadFromTheInnerStream()
{
// Arrange
using (MemoryStream innerStream = new([1, 2, 3, 4]))
using (TranscodingCacheLeaseStream leaseStream = CreateSut(innerStream))
{
Span<byte> buffer = stackalloc byte[2];
// Act
int result = leaseStream.Read(buffer);
// Assert
Assert.Equal(2, result);
Assert.Equal(1, buffer[0]);
Assert.Equal(2, buffer[1]);
}
}
[Fact]
public async Task ReadAsync_WhenCalledWithMemory_ShouldReadFromTheInnerStream()
{
// Arrange
byte[] buffer = new byte[8];
using (MemoryStream innerStream = new([4, 5, 6, 7]))
using (TranscodingCacheLeaseStream leaseStream = CreateSut(innerStream))
{
// Act
int result = await leaseStream.ReadAsync(buffer.AsMemory(), CancellationToken.None);
// Assert
Assert.Equal(4, result);
Assert.Equal(new byte[] { 4, 5, 6, 7, 0, 0, 0, 0 }, buffer);
Assert.Equal(4L, innerStream.Position);
}
}
[Fact]
public void Seek_WhenCalled_ShouldSeekTheInnerStream()
{
// Arrange
using (MemoryStream innerStream = new([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]))
using (TranscodingCacheLeaseStream leaseStream = CreateSut(innerStream))
{
// Act
long result = leaseStream.Seek(3L, SeekOrigin.Begin);
// Assert
Assert.Equal(3L, result);
Assert.Equal(3L, innerStream.Position);
}
}
[Fact]
public void SetLength_WhenCalled_ShouldSetTheInnerLength()
{
// Arrange
using (MemoryStream innerStream = new())
using (TranscodingCacheLeaseStream leaseStream = CreateSut(innerStream))
{
// Act
leaseStream.SetLength(10L);
// Assert
Assert.Equal(10L, innerStream.Length);
}
}
[Fact]
public void Write_WhenCalled_ShouldWriteToTheInnerStream()
{
// Arrange
using (MemoryStream innerStream = new())
using (TranscodingCacheLeaseStream leaseStream = CreateSut(innerStream))
{
byte[] buffer = [1, 2, 3, 4, 5, 6];
// Act
leaseStream.Write(buffer, 1, 4);
// Assert
Assert.Equal(new byte[] { 2, 3, 4, 5 }, innerStream.ToArray());
}
}
[Fact]
public void Write_WhenCalledWithASpan_ShouldWriteToTheInnerStream()
{
// Arrange
using (MemoryStream innerStream = new())
using (TranscodingCacheLeaseStream leaseStream = CreateSut(innerStream))
{
// Act
leaseStream.Write([5, 6, 7]);
// Assert
Assert.Equal(3L, innerStream.Length);
Assert.Equal(new byte[] { 5, 6, 7 }, innerStream.ToArray());
}
}
[Fact]
public async Task WriteAsync_WhenCalledWithMemory_ShouldWriteToTheInnerStream()
{
// Arrange
using (MemoryStream innerStream = new())
using (TranscodingCacheLeaseStream leaseStream = CreateSut(innerStream))
{
// Act
await leaseStream.WriteAsync(new byte[] { 1, 2 }.AsMemory(), CancellationToken.None);
// Assert
Assert.Equal(new byte[] { 1, 2 }, innerStream.ToArray());
}
}
[Fact]
public void Dispose_WhenCalled_ShouldDisposeTheInnerStreamAndReleaseTheLease()
{
// Arrange
string cacheId = CreateCacheId();
PublishEntry(cacheId, 50, 100);
string cachePath = Path.Combine(_cacheRoot, cacheId);
TranscodingCacheReaderLease lease = _coordinator.AcquireReaderLease(cacheId);
using (MemoryStream innerStream = new())
{
TranscodingCacheLeaseStream leaseStream = new(innerStream, lease);
Assert.False(_coordinator.TryReserve(80, 100, TimeSpan.Zero, out _));
Assert.True(Directory.Exists(cachePath));
// Act
leaseStream.Dispose();
// Assert
Assert.Throws<ObjectDisposedException>(() =>
{
_ = innerStream.Length;
});
Assert.False(Directory.Exists(cachePath));
Assert.True(_coordinator.TryReserve(80, 100, TimeSpan.Zero, out TranscodingCacheReservation? reservation));
reservation!.Dispose();
}
}
[Fact]
public void Dispose_WhenCalledTwice_ShouldDisposeTheInnerStreamAndReleaseTheLeaseOnce()
{
// Arrange
string cacheId = CreateCacheId();
PublishEntry(cacheId, 50, 100);
string cachePath = Path.Combine(_cacheRoot, cacheId);
TranscodingCacheReaderLease firstLease = _coordinator.AcquireReaderLease(cacheId);
TranscodingCacheReaderLease secondLease = _coordinator.AcquireReaderLease(cacheId);
using (MemoryStream firstInnerStream = new())
using (MemoryStream secondInnerStream = new())
{
TranscodingCacheLeaseStream firstStream = new(firstInnerStream, firstLease);
TranscodingCacheLeaseStream secondStream = new(secondInnerStream, secondLease);
// Act
firstStream.Dispose();
firstStream.Dispose();
// Assert
Assert.Throws<ObjectDisposedException>(() =>
{
_ = firstInnerStream.Length;
});
Assert.Equal(0L, secondInnerStream.Length);
Assert.False(_coordinator.TryReserve(80, 100, TimeSpan.Zero, out _));
Assert.True(Directory.Exists(cachePath));
secondStream.Dispose();
Assert.False(Directory.Exists(cachePath));
Assert.Throws<ObjectDisposedException>(() =>
{
_ = secondInnerStream.Length;
});
}
}
[Fact]
public void Dispose_WhenDisposingTheInnerStreamThrows_ShouldStillReleaseTheLease()
{
// Arrange
string cacheId = CreateCacheId();
PublishEntry(cacheId, 50, 100);
string cachePath = Path.Combine(_cacheRoot, cacheId);
TranscodingCacheReaderLease lease = _coordinator.AcquireReaderLease(cacheId);
Stream innerStream = new ThrowingDisposeStream(new IOException("The inner stream cannot be disposed."));
TranscodingCacheLeaseStream leaseStream = new(innerStream, lease);
Assert.False(_coordinator.TryReserve(80, 100, TimeSpan.Zero, out _));
// Act
Assert.Throws<IOException>(() => leaseStream.Dispose());
// Assert
Assert.False(Directory.Exists(cachePath));
}
[Fact]
public async Task DisposeAsync_WhenCalled_ShouldDisposeTheInnerStreamAndReleaseTheLease()
{
// Arrange
string cacheId = CreateCacheId();
PublishEntry(cacheId, 50, 100);
string cachePath = Path.Combine(_cacheRoot, cacheId);
TranscodingCacheReaderLease lease = _coordinator.AcquireReaderLease(cacheId);
Stream innerStream = Substitute.For<Stream>();
TranscodingCacheLeaseStream leaseStream = new(innerStream, lease);
Assert.False(_coordinator.TryReserve(80, 100, TimeSpan.Zero, out _));
// Act
await leaseStream.DisposeAsync();
// Assert
await innerStream.Received(1).DisposeAsync();
Assert.False(Directory.Exists(cachePath));
}
[Fact]
public async Task DisposeAsync_WhenDisposingTheInnerStreamThrows_ShouldStillReleaseTheLease()
{
// Arrange
string cacheId = CreateCacheId();
PublishEntry(cacheId, 50, 100);
string cachePath = Path.Combine(_cacheRoot, cacheId);
TranscodingCacheReaderLease lease = _coordinator.AcquireReaderLease(cacheId);
Stream innerStream = new ThrowingDisposeStream(new IOException("The inner stream cannot be disposed."));
TranscodingCacheLeaseStream leaseStream = new(innerStream, lease);
Assert.False(_coordinator.TryReserve(80, 100, TimeSpan.Zero, out _));
// Act
await Assert.ThrowsAsync<IOException>(async () => await leaseStream.DisposeAsync());
// Assert
Assert.False(Directory.Exists(cachePath));
}
/// <summary>
/// Creates the stream under test over the provided inner stream.
/// </summary>
/// <param name="innerStream">The stream over the cached segment.</param>
/// <returns>The created <see cref="TranscodingCacheLeaseStream"/>.</returns>
private TranscodingCacheLeaseStream CreateSut(Stream innerStream)
{
TranscodingCacheReaderLease lease = _coordinator.AcquireReaderLease(CreateCacheId());
return new TranscodingCacheLeaseStream(innerStream, lease);
}
/// <summary>
/// Creates a well formed opaque cache identifier.
/// </summary>
/// <returns>A 64 character lowercase hexadecimal identifier.</returns>
private static string CreateCacheId()
{
return $"{Guid.NewGuid():N}{Guid.NewGuid():N}";
}
/// <summary>
/// Reserves capacity and publishes a produced entry under the requested cache identifier.
/// </summary>
/// <param name="cacheId">The identifier of the produced cache entry.</param>
/// <param name="size">The total size of the produced cache entry, in bytes.</param>
/// <param name="maxCacheBytes">The maximum total size of the cache, in bytes.</param>
private void PublishEntry(string cacheId, int size, long maxCacheBytes)
{
string temporaryPath = Path.Combine(_temporaryDirectory, $"tmp-{Guid.NewGuid():N}");
Directory.CreateDirectory(temporaryPath);
File.WriteAllBytes(Path.Combine(temporaryPath, "segment.m4s"), new byte[size]);
Assert.True(_coordinator.TryReserve(size, maxCacheBytes, TimeSpan.Zero, out TranscodingCacheReservation? reservation));
Assert.NotNull(reservation);
Assert.True(_coordinator.TryPublish(reservation.Id, cacheId, temporaryPath, size, _normalizedTrackIndexDtoFixture.Create(), maxCacheBytes, TimeSpan.Zero, out _, out _));
}
/// <summary>
/// Releases the coordinator and removes the temporary directory created for the test.
/// </summary>
public void Dispose()
{
_coordinator.Release();
try
{
if (Directory.Exists(_temporaryDirectory))
Directory.Delete(_temporaryDirectory, recursive: true);
}
catch (Exception exception) when (exception is IOException or UnauthorizedAccessException)
{
// A background sweeper can still be removing a tombstone that was detached by the test.
}
GC.SuppressFinalize(this);
}
/// <summary>
/// A memory stream whose disposal always fails, used to verify that a cache entry lease is released even when the inner stream cannot be disposed.
/// </summary>
private sealed class ThrowingDisposeStream : MemoryStream
{
private readonly IOException _exception;
/// <summary>
/// Initializes a new instance of the <see cref="ThrowingDisposeStream"/> class.
/// </summary>
/// <param name="exception">The exception thrown when the stream is disposed.</param>
internal ThrowingDisposeStream(IOException exception)
{
_exception = exception;
}
/// <summary>
/// Releases the resources of the stream and then throws the configured exception.
/// </summary>
/// <param name="disposing">Whether the method is called from the <see cref="IDisposable.Dispose"/> method.</param>
protected override void Dispose(bool disposing)
{
base.Dispose(disposing);
throw _exception;
}
/// <summary>
/// Gets a failed value task that carries the configured exception.
/// </summary>
/// <returns>A failed <see cref="ValueTask"/>.</returns>
public override ValueTask DisposeAsync()
{
return ValueTask.FromException(_exception);
}
}
}
@@ -0,0 +1,123 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Infrastructure.Core.MediaLibrary.AudioLibrary.MusicLibrary.Playback;
using Lumina.Infrastructure.Fixtures.Common.Models.DTO.MediaLibrary.AudioLibrary.MusicLibrary.Playback;
using System;
using System.Diagnostics.CodeAnalysis;
using System.IO;
#endregion
namespace Lumina.Infrastructure.IntegrationTests.Core.MediaLibrary.AudioLibrary.MusicLibrary.Playback;
/// <summary>
/// Contains integration tests for the <see cref="TranscodingCacheReaderLease"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class TranscodingCacheReaderLeaseTests : IDisposable
{
private readonly string _temporaryDirectory;
private readonly string _cacheRoot;
private readonly TranscodingCacheCoordinator _sut;
private readonly NormalizedTrackIndexDtoFixture _normalizedTrackIndexDtoFixture = new();
/// <summary>
/// Initializes a new instance of the <see cref="TranscodingCacheReaderLeaseTests"/> class.
/// </summary>
public TranscodingCacheReaderLeaseTests()
{
_temporaryDirectory = Path.Combine(Path.GetTempPath(), $"lumina-transcoding-cache-lease-{Guid.NewGuid():N}");
_cacheRoot = Path.Combine(_temporaryDirectory, "cache");
Directory.CreateDirectory(_cacheRoot);
_sut = TranscodingCacheCoordinator.AcquireForRoot(_cacheRoot);
}
[Fact]
public void Dispose_WhenCalled_ShouldReleaseTheLeaseSoTheEntryCanBeEvicted()
{
// Arrange
string cacheId = CreateCacheId();
PublishEntry(cacheId, 50, 100);
string cachePath = Path.Combine(_cacheRoot, cacheId);
TranscodingCacheReaderLease lease = _sut.AcquireReaderLease(cacheId);
Assert.False(_sut.TryReserve(80, 100, TimeSpan.Zero, out _));
Assert.True(Directory.Exists(cachePath));
// Act
lease.Dispose();
// Assert
Assert.False(Directory.Exists(cachePath));
Assert.True(_sut.TryReserve(80, 100, TimeSpan.Zero, out TranscodingCacheReservation? reservation));
reservation!.Dispose();
}
[Fact]
public void Dispose_WhenCalledTwiceAcrossTwoLeases_ShouldReleaseOnlyOncePerLease()
{
// Arrange
string cacheId = CreateCacheId();
PublishEntry(cacheId, 50, 100);
string cachePath = Path.Combine(_cacheRoot, cacheId);
TranscodingCacheReaderLease firstLease = _sut.AcquireReaderLease(cacheId);
TranscodingCacheReaderLease secondLease = _sut.AcquireReaderLease(cacheId);
try
{
// Act
firstLease.Dispose();
firstLease.Dispose();
// Assert
Assert.False(_sut.TryReserve(80, 100, TimeSpan.Zero, out _));
Assert.True(Directory.Exists(cachePath));
}
finally
{
firstLease.Dispose();
secondLease.Dispose();
}
Assert.False(Directory.Exists(cachePath));
}
/// <summary>
/// Creates a well formed opaque cache identifier.
/// </summary>
/// <returns>A 64 character lowercase hexadecimal identifier.</returns>
private static string CreateCacheId()
{
return $"{Guid.NewGuid():N}{Guid.NewGuid():N}";
}
/// <summary>
/// Reserves capacity and publishes a produced entry under the requested cache identifier.
/// </summary>
/// <param name="cacheId">The identifier of the produced cache entry.</param>
/// <param name="size">The total size of the produced cache entry, in bytes.</param>
/// <param name="maxCacheBytes">The maximum total size of the cache, in bytes.</param>
private void PublishEntry(string cacheId, int size, long maxCacheBytes)
{
string temporaryPath = Path.Combine(_temporaryDirectory, $"tmp-{Guid.NewGuid():N}");
Directory.CreateDirectory(temporaryPath);
File.WriteAllBytes(Path.Combine(temporaryPath, "segment.m4s"), new byte[size]);
Assert.True(_sut.TryReserve(size, maxCacheBytes, TimeSpan.Zero, out TranscodingCacheReservation? reservation));
Assert.NotNull(reservation);
Assert.True(_sut.TryPublish(reservation.Id, cacheId, temporaryPath, size, _normalizedTrackIndexDtoFixture.Create(), maxCacheBytes, TimeSpan.Zero, out _, out _));
}
/// <summary>
/// Releases the coordinator and removes the temporary directory created for the test.
/// </summary>
public void Dispose()
{
_sut.Release();
try
{
if (Directory.Exists(_temporaryDirectory))
Directory.Delete(_temporaryDirectory, recursive: true);
}
catch (Exception exception) when (exception is IOException or UnauthorizedAccessException)
{
// A background sweeper can still be removing a tombstone that was detached by the test.
}
GC.SuppressFinalize(this);
}
}
@@ -0,0 +1,230 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Infrastructure.Common.Models.DTO.MediaLibrary.AudioLibrary.MusicLibrary.Playback;
using Lumina.Infrastructure.Core.MediaLibrary.AudioLibrary.MusicLibrary.Playback;
using Lumina.Infrastructure.Fixtures.Common.Models.DTO.MediaLibrary.AudioLibrary.MusicLibrary.Playback;
using System;
using System.Diagnostics.CodeAnalysis;
using System.IO;
using System.Threading;
#endregion
namespace Lumina.Infrastructure.IntegrationTests.Core.MediaLibrary.AudioLibrary.MusicLibrary.Playback;
/// <summary>
/// Contains integration tests for the <see cref="TranscodingCacheReservation"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class TranscodingCacheReservationTests : IDisposable
{
private readonly string _temporaryDirectory;
private readonly string _cacheRoot;
private readonly TranscodingCacheCoordinator _sut;
private readonly NormalizedTrackIndexDtoFixture _normalizedTrackIndexDtoFixture = new();
/// <summary>
/// Initializes a new instance of the <see cref="TranscodingCacheReservationTests"/> class.
/// </summary>
public TranscodingCacheReservationTests()
{
_temporaryDirectory = Path.Combine(Path.GetTempPath(), $"lumina-transcoding-cache-reservation-{Guid.NewGuid():N}");
_cacheRoot = Path.Combine(_temporaryDirectory, "cache");
Directory.CreateDirectory(_cacheRoot);
_sut = TranscodingCacheCoordinator.AcquireForRoot(_cacheRoot);
}
[Fact]
public void TryUpdate_WhenTheReservationIsUnfinished_ShouldGrowTheReservation()
{
// Arrange
Assert.True(_sut.TryReserve(40, 100, TimeSpan.Zero, out TranscodingCacheReservation? reservation));
Assert.NotNull(reservation);
try
{
// Act
bool result = reservation.TryUpdate(80, 100, TimeSpan.Zero);
// Assert
Assert.True(result);
Assert.False(_sut.TryReserve(30, 100, TimeSpan.Zero, out _));
}
finally
{
reservation.Dispose();
}
}
[Fact]
public void TryUpdate_WhenTheReservationIsCompleted_ShouldReturnFalse()
{
// Arrange
Assert.True(_sut.TryReserve(50, 200, TimeSpan.Zero, out TranscodingCacheReservation? reservation));
Assert.NotNull(reservation);
Assert.True(reservation.TryComplete(CreateCacheId(), CreateTemporaryOutput(50), 50, _normalizedTrackIndexDtoFixture.Create(), 200, TimeSpan.Zero, out _, out _));
try
{
// Act
bool result = reservation.TryUpdate(60, 200, TimeSpan.Zero);
// Assert
Assert.False(result);
}
finally
{
reservation.Dispose();
}
}
[Fact]
public void TryUpdate_WhenTheReservationIsDisposed_ShouldReturnFalse()
{
// Arrange
Assert.True(_sut.TryReserve(50, 100, TimeSpan.Zero, out TranscodingCacheReservation? reservation));
Assert.NotNull(reservation);
reservation.Dispose();
// Act
bool result = reservation.TryUpdate(50, 100, TimeSpan.Zero);
// Assert
Assert.False(result);
}
[Fact]
public void TryComplete_WhenTheReservationIsCompleted_ShouldReturnFalse()
{
// Arrange
string cacheId = CreateCacheId();
NormalizedTrackIndexDto index = _normalizedTrackIndexDtoFixture.Create();
Assert.True(_sut.TryReserve(50, 200, TimeSpan.Zero, out TranscodingCacheReservation? reservation));
Assert.NotNull(reservation);
Assert.True(reservation.TryComplete(cacheId, CreateTemporaryOutput(50), 50, index, 200, TimeSpan.Zero, out _, out _));
string secondTemporaryPath = CreateTemporaryOutput(50);
try
{
// Act
bool result = reservation.TryComplete(cacheId, secondTemporaryPath, 50, _normalizedTrackIndexDtoFixture.Create(), 200, TimeSpan.Zero, out bool isKeptOverCapacity, out bool isEntryInUse);
// Assert
Assert.False(result);
Assert.False(isKeptOverCapacity);
Assert.False(isEntryInUse);
Assert.True(Directory.Exists(secondTemporaryPath));
Assert.True(_sut.TryGetIndex(cacheId, out NormalizedTrackIndexDto? cachedIndex));
Assert.Same(index, cachedIndex);
}
finally
{
reservation.Dispose();
}
}
[Fact]
public void TryComplete_WhenTheReservationIsDisposed_ShouldReturnFalse()
{
// Arrange
Assert.True(_sut.TryReserve(50, 100, TimeSpan.Zero, out TranscodingCacheReservation? reservation));
Assert.NotNull(reservation);
reservation.Dispose();
string temporaryPath = CreateTemporaryOutput(50);
// Act
bool result = reservation.TryComplete(CreateCacheId(), temporaryPath, 50, _normalizedTrackIndexDtoFixture.Create(), 100, TimeSpan.Zero, out _, out _);
// Assert
Assert.False(result);
Assert.True(Directory.Exists(temporaryPath));
}
[Fact]
public void Dispose_WhenTheReservationIsNotCompleted_ShouldReleaseTheReservedCapacity()
{
// Arrange
Assert.True(_sut.TryReserve(100, 100, TimeSpan.Zero, out TranscodingCacheReservation? reservation));
Assert.NotNull(reservation);
Assert.False(_sut.TryReserve(100, 100, TimeSpan.Zero, out _));
// Act
reservation.Dispose();
// Assert
Assert.True(_sut.TryReserve(100, 100, TimeSpan.Zero, out TranscodingCacheReservation? laterReservation));
laterReservation!.Dispose();
}
[Fact]
public void Dispose_WhenTheReservationIsCompleted_ShouldKeepThePublishedEntryAccounted()
{
// Arrange
string cacheId = CreateCacheId();
Assert.True(_sut.TryReserve(100, 100, TimeSpan.Zero, out TranscodingCacheReservation? reservation));
Assert.NotNull(reservation);
Assert.True(reservation.TryComplete(cacheId, CreateTemporaryOutput(100), 100, _normalizedTrackIndexDtoFixture.Create(), 100, TimeSpan.Zero, out _, out _));
// Act
reservation.Dispose();
reservation.Dispose();
// Assert
Assert.True(_sut.TryGetIndex(cacheId, out _));
Assert.False(_sut.TryReserve(100, 100, TimeSpan.FromHours(1), out _));
}
[Fact]
public void Dispose_WhenCalledTwice_ShouldReleaseTheReservedCapacityOnce()
{
// Arrange
Assert.True(_sut.TryReserve(100, 100, TimeSpan.Zero, out TranscodingCacheReservation? reservation));
Assert.NotNull(reservation);
// Act
reservation.Dispose();
reservation.Dispose();
// Assert
Assert.True(_sut.TryReserve(100, 100, TimeSpan.Zero, out TranscodingCacheReservation? laterReservation));
laterReservation!.Dispose();
}
/// <summary>
/// Creates a well formed opaque cache identifier.
/// </summary>
/// <returns>A 64 character lowercase hexadecimal identifier.</returns>
private static string CreateCacheId()
{
return $"{Guid.NewGuid():N}{Guid.NewGuid():N}";
}
/// <summary>
/// Creates a temporary output directory with a single file of the requested size.
/// </summary>
/// <param name="size">The size of the produced file, in bytes.</param>
/// <returns>The path of the created temporary output directory.</returns>
private string CreateTemporaryOutput(int size)
{
string temporaryPath = Path.Combine(_temporaryDirectory, $"tmp-{Guid.NewGuid():N}");
Directory.CreateDirectory(temporaryPath);
File.WriteAllBytes(Path.Combine(temporaryPath, "segment.m4s"), new byte[size]);
return temporaryPath;
}
/// <summary>
/// Releases the coordinator and removes the temporary directory created for the test.
/// </summary>
public void Dispose()
{
_sut.Release();
try
{
if (Directory.Exists(_temporaryDirectory))
Directory.Delete(_temporaryDirectory, recursive: true);
}
catch (Exception exception) when (exception is IOException or UnauthorizedAccessException)
{
// A background sweeper can still be removing a tombstone that was detached by the test.
}
GC.SuppressFinalize(this);
}
}
@@ -0,0 +1,216 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Infrastructure.Core.MediaLibrary.AudioLibrary.MusicLibrary.Playback;
using System;
using System.Diagnostics.CodeAnalysis;
using System.IO;
#endregion
namespace Lumina.Infrastructure.IntegrationTests.Core.MediaLibrary.AudioLibrary.MusicLibrary.Playback;
/// <summary>
/// Contains integration tests for the <see cref="TranscodingOutputSizeTracker"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class TranscodingOutputSizeTrackerTests : IDisposable
{
private const string SEGMENT_FILE_PREFIX = "segment";
private const string SEGMENT_FILE_EXTENSION = ".m4s";
private const string SEGMENT_LIST_FILE_NAME = "index.m3u8";
private readonly string _temporaryDirectory;
private readonly TranscodingOutputSizeTracker _sut;
/// <summary>
/// Initializes a new instance of the <see cref="TranscodingOutputSizeTrackerTests"/> class.
/// </summary>
public TranscodingOutputSizeTrackerTests()
{
_temporaryDirectory = Path.Combine(Path.GetTempPath(), $"lumina-transcoding-output-size-{Guid.NewGuid():N}");
Directory.CreateDirectory(_temporaryDirectory);
_sut = new TranscodingOutputSizeTracker(_temporaryDirectory, SEGMENT_FILE_PREFIX, SEGMENT_FILE_EXTENSION, SEGMENT_LIST_FILE_NAME);
}
[Fact]
public void GetCurrentSize_WhenCalledForTheFirstTime_ShouldCountTheSegmentListAndTheExistingSegments()
{
// Arrange
CreateSegmentList(10);
CreateSegment(0, 100);
CreateSegment(1, 50);
// Act
long result = _sut.GetCurrentSize();
// Assert
Assert.Equal(160L, result);
}
[Fact]
public void GetCurrentSize_WhenTheCurrentSegmentGrows_ShouldCountOnlyTheGrowth()
{
// Arrange
CreateSegmentList(10);
CreateSegment(0, 100);
Assert.Equal(110L, _sut.GetCurrentSize());
// Act
AppendToSegment(0, 40);
long result = _sut.GetCurrentSize();
// Assert
Assert.Equal(150L, result);
}
[Fact]
public void GetCurrentSize_WhenTheSegmentListGrows_ShouldCountOnlyTheGrowth()
{
// Arrange
CreateSegmentList(10);
CreateSegment(0, 10);
Assert.Equal(20L, _sut.GetCurrentSize());
// Act
AppendToFile(Path.Combine(_temporaryDirectory, SEGMENT_LIST_FILE_NAME), 5);
long result = _sut.GetCurrentSize();
// Assert
Assert.Equal(25L, result);
}
[Fact]
public void GetCurrentSize_WhenASegmentIsFinishedAndANewOneStarts_ShouldDiscoverEachSegmentOnce()
{
// Arrange
CreateSegmentList(10);
CreateSegment(0, 100);
Assert.Equal(110L, _sut.GetCurrentSize());
AppendToSegment(0, 50);
CreateSegment(1, 30);
// Act
long resultAfterTheNewSegment = _sut.GetCurrentSize();
AppendToSegment(1, 20);
long resultAfterTheNewSegmentGrows = _sut.GetCurrentSize();
// Assert
Assert.Equal(190L, resultAfterTheNewSegment);
Assert.Equal(210L, resultAfterTheNewSegmentGrows);
}
[Fact]
public void GetCurrentSize_WhenFilesDoNotFollowTheSegmentNamePattern_ShouldIgnoreThem()
{
// Arrange
CreateSegmentList(5);
CreateSegment(0, 10);
File.WriteAllBytes(Path.Combine(_temporaryDirectory, "segment000001.bak"), new byte[1000]);
File.WriteAllBytes(Path.Combine(_temporaryDirectory, "other000000.m4s"), new byte[1000]);
File.WriteAllBytes(Path.Combine(_temporaryDirectory, "segment-1.m4s"), new byte[1000]);
File.WriteAllBytes(Path.Combine(_temporaryDirectory, "segment000000.txt"), new byte[1000]);
// Act
long result = _sut.GetCurrentSize();
// Assert
Assert.Equal(15L, result);
}
[Fact]
public void GetCurrentSize_WhenTheLastSegmentDisappears_ShouldKeepItsLastMeasuredLength()
{
// Arrange
CreateSegmentList(10);
CreateSegment(0, 100);
Assert.Equal(110L, _sut.GetCurrentSize());
// Act
File.Delete(GetSegmentPath(0));
long result = _sut.GetCurrentSize();
// Assert
Assert.Equal(110L, result);
}
[Fact]
public void GetCurrentSize_WhenTheSegmentListDisappears_ShouldKeepItsLastMeasuredLength()
{
// Arrange
CreateSegmentList(10);
CreateSegment(0, 100);
Assert.Equal(110L, _sut.GetCurrentSize());
// Act
File.Delete(Path.Combine(_temporaryDirectory, SEGMENT_LIST_FILE_NAME));
long result = _sut.GetCurrentSize();
// Assert
Assert.Equal(110L, result);
}
/// <summary>
/// Creates the segment list file with the requested size.
/// </summary>
/// <param name="size">The size of the segment list, in bytes.</param>
private void CreateSegmentList(int size)
{
File.WriteAllBytes(Path.Combine(_temporaryDirectory, SEGMENT_LIST_FILE_NAME), new byte[size]);
}
/// <summary>
/// Creates a segment file with the requested zero based index and size.
/// </summary>
/// <param name="segmentIndex">The zero based index of the segment.</param>
/// <param name="size">The size of the segment, in bytes.</param>
private void CreateSegment(int segmentIndex, int size)
{
File.WriteAllBytes(GetSegmentPath(segmentIndex), new byte[size]);
}
/// <summary>
/// Appends the requested number of bytes to a segment file.
/// </summary>
/// <param name="segmentIndex">The zero based index of the segment.</param>
/// <param name="size">The number of bytes to append.</param>
private void AppendToSegment(int segmentIndex, int size)
{
AppendToFile(GetSegmentPath(segmentIndex), size);
}
/// <summary>
/// Appends the requested number of bytes to a file.
/// </summary>
/// <param name="filePath">The file to append to.</param>
/// <param name="size">The number of bytes to append.</param>
private static void AppendToFile(string filePath, int size)
{
using (FileStream stream = new(filePath, FileMode.Append, FileAccess.Write))
stream.Write(new byte[size], 0, size);
}
/// <summary>
/// Gets the path of the segment file of the requested zero based index.
/// </summary>
/// <param name="segmentIndex">The zero based index of the segment.</param>
/// <returns>The path of the segment file.</returns>
private string GetSegmentPath(int segmentIndex)
{
return Path.Combine(_temporaryDirectory, $"{SEGMENT_FILE_PREFIX}{segmentIndex:D6}{SEGMENT_FILE_EXTENSION}");
}
/// <summary>
/// Removes the temporary directory created for the test.
/// </summary>
public void Dispose()
{
try
{
if (Directory.Exists(_temporaryDirectory))
Directory.Delete(_temporaryDirectory, recursive: true);
}
catch (Exception exception) when (exception is IOException or UnauthorizedAccessException)
{
// The directory is under the process temporary directory.
}
GC.SuppressFinalize(this);
}
}
@@ -0,0 +1,278 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Infrastructure.Common.Caching;
using Lumina.Infrastructure.Common.Models.DTO.Configuration;
using Lumina.Infrastructure.Core.MediaLibrary.AudioLibrary.MusicLibrary.Playback;
using Lumina.Infrastructure.Fixtures.Common.Models.DTO.Configuration;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using NSubstitute;
using System;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.IO;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Infrastructure.IntegrationTests.Core.MediaLibrary.AudioLibrary.MusicLibrary.Playback;
/// <summary>
/// Contains integration tests for the <see cref="TranscodingStartupInitializer"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class TranscodingStartupInitializerTests : IDisposable
{
private readonly string _temporaryDirectory;
private readonly string _cacheDirectory;
private readonly TranscodingSettingsDto _settings;
private readonly TranscodingToolchainStatus _toolchainStatus;
private readonly ILogger<TranscodingStartupInitializer> _mockLogger;
private readonly TranscodingStartupInitializer _sut;
private readonly TranscodingSettingsDtoFixture _transcodingSettingsDtoFixture = new();
/// <summary>
/// Initializes a new instance of the <see cref="TranscodingStartupInitializerTests"/> class.
/// </summary>
public TranscodingStartupInitializerTests()
{
_temporaryDirectory = Path.Combine(Path.GetTempPath(), $"lumina-transcoding-startup-{Guid.NewGuid():N}");
Directory.CreateDirectory(_temporaryDirectory);
_cacheDirectory = Path.Combine(_temporaryDirectory, "cache");
string missingFfmpegPath = Path.Combine(_temporaryDirectory, "missing-ffmpeg-binary");
_settings = _transcodingSettingsDtoFixture.Create(ffmpegPath: missingFfmpegPath, cacheDirectory: _cacheDirectory);
_toolchainStatus = new TranscodingToolchainStatus();
_mockLogger = Substitute.For<ILogger<TranscodingStartupInitializer>>();
_mockLogger.IsEnabled(Arg.Any<LogLevel>()).Returns(true);
_sut = new TranscodingStartupInitializer(Options.Create(_settings), _toolchainStatus, _mockLogger);
}
[Fact]
public async Task StartAsync_WhenTheConfiguredDirectoryDoesNotExist_ShouldCreateAndMarkItAndRecordTheToolchainUnavailable()
{
// Act
await _sut.StartAsync(CancellationToken.None);
// Assert
Assert.True(Directory.Exists(_cacheDirectory));
Assert.True(TranscodingCachePaths.HasCacheMarker(_cacheDirectory));
Assert.False(_toolchainStatus.IsTranscoderAvailable);
}
[Fact]
public async Task StartAsync_WhenTheDirectoryExistsButIsEmptyWithoutTheMarker_ShouldAdoptItByWritingTheMarker()
{
// Arrange
Directory.CreateDirectory(_cacheDirectory);
Assert.False(TranscodingCachePaths.HasCacheMarker(_cacheDirectory));
// Act
await _sut.StartAsync(CancellationToken.None);
// Assert
Assert.True(Directory.Exists(_cacheDirectory));
Assert.True(TranscodingCachePaths.HasCacheMarker(_cacheDirectory));
}
[Fact]
public async Task StartAsync_WhenTheDirectoryExistsNonEmptyWithoutTheMarker_ShouldLeaveItUntouchedAndLogAnError()
{
// Arrange
Directory.CreateDirectory(_cacheDirectory);
string operatorFilePath = Path.Combine(_cacheDirectory, "operator-data.txt");
File.WriteAllText(operatorFilePath, "operator data");
string operatorDirectoryPath = Path.Combine(_cacheDirectory, "operator-directory");
Directory.CreateDirectory(operatorDirectoryPath);
string nestedFilePath = Path.Combine(operatorDirectoryPath, "nested.txt");
File.WriteAllText(nestedFilePath, "nested data");
// Act
await _sut.StartAsync(CancellationToken.None);
// Assert
Assert.True(Directory.Exists(_cacheDirectory));
Assert.Equal("operator data", File.ReadAllText(operatorFilePath));
Assert.True(File.Exists(nestedFilePath));
Assert.False(TranscodingCachePaths.HasCacheMarker(_cacheDirectory));
Assert.False(_toolchainStatus.IsTranscoderAvailable);
_mockLogger.Received(1).Log(
LogLevel.Error,
Arg.Any<EventId>(),
Arg.Any<object>(),
Arg.Any<Exception?>(),
Arg.Any<Func<object, Exception?, string>>());
}
[Fact]
public async Task StartAsync_WhenLoggingIsDisabledAndTheDirectoryExistsNonEmptyWithoutTheMarker_ShouldNotLogAnError()
{
// Arrange
_mockLogger.IsEnabled(Arg.Any<LogLevel>()).Returns(false);
Directory.CreateDirectory(_cacheDirectory);
File.WriteAllText(Path.Combine(_cacheDirectory, "operator-data.txt"), "operator data");
// Act
await _sut.StartAsync(CancellationToken.None);
// Assert
Assert.False(TranscodingCachePaths.HasCacheMarker(_cacheDirectory));
Assert.False(_toolchainStatus.IsTranscoderAvailable);
_mockLogger.DidNotReceive().Log(
LogLevel.Error,
Arg.Any<EventId>(),
Arg.Any<object>(),
Arg.Any<Exception?>(),
Arg.Any<Func<object, Exception?, string>>());
}
[Fact]
public async Task StartAsync_WhenTheDirectoryIsMarked_ShouldRemoveOnlyTheEntriesOfTheCacheNamespace()
{
// Arrange
Directory.CreateDirectory(_cacheDirectory);
TranscodingCachePaths.WriteCacheMarker(_cacheDirectory);
string cacheEntryPath = Path.Combine(_cacheDirectory, CreateCacheId());
Directory.CreateDirectory(Path.Combine(cacheEntryPath, "nested"));
File.WriteAllText(Path.Combine(cacheEntryPath, "nested", "segment.m4s"), "cache data");
string temporaryEntryPath = Path.Combine(_cacheDirectory, "tmp-0123456789abcdef");
Directory.CreateDirectory(temporaryEntryPath);
string deletionEntryPath = Path.Combine(_cacheDirectory, "del-0123456789abcdef");
Directory.CreateDirectory(deletionEntryPath);
string unrelatedDirectoryPath = Path.Combine(_cacheDirectory, "operator-directory");
Directory.CreateDirectory(unrelatedDirectoryPath);
File.WriteAllText(Path.Combine(unrelatedDirectoryPath, "keep.txt"), "keep");
string unrelatedFilePath = Path.Combine(_cacheDirectory, "operator-note.txt");
File.WriteAllText(unrelatedFilePath, "keep");
// Act
await _sut.StartAsync(CancellationToken.None);
// Assert
Assert.True(Directory.Exists(_cacheDirectory));
Assert.False(Directory.Exists(cacheEntryPath));
Assert.False(Directory.Exists(temporaryEntryPath));
Assert.False(Directory.Exists(deletionEntryPath));
Assert.True(Directory.Exists(unrelatedDirectoryPath));
Assert.Equal("keep", File.ReadAllText(Path.Combine(unrelatedDirectoryPath, "keep.txt")));
Assert.Equal("keep", File.ReadAllText(unrelatedFilePath));
Assert.True(TranscodingCachePaths.HasCacheMarker(_cacheDirectory));
}
[Fact]
public async Task StartAsync_WhenTheCacheDirectoryIsAReparsePoint_ShouldNotThrowAndShouldRecordTheToolchainUnavailable()
{
// Arrange
string junctionTargetPath = Path.Combine(_temporaryDirectory, "junction-target");
Directory.CreateDirectory(junctionTargetPath);
string targetFilePath = Path.Combine(junctionTargetPath, "keep.txt");
File.WriteAllText(targetFilePath, "keep");
if (!TryCreateJunction(_cacheDirectory, junctionTargetPath)) // The platform refused to create a reparse point, so the scenario cannot be exercised here.
return;
Assert.NotNull(new DirectoryInfo(_cacheDirectory).LinkTarget);
// Act
Exception? exception = await Record.ExceptionAsync(() => _sut.StartAsync(CancellationToken.None));
// Assert
Assert.Null(exception);
Assert.False(_toolchainStatus.IsTranscoderAvailable);
Assert.True(Directory.Exists(junctionTargetPath));
Assert.Equal("keep", File.ReadAllText(targetFilePath));
}
[Fact]
public async Task StartAsync_WhenTheProbeFails_ShouldRecordTheOutcomeInTheProvidedToolchainStatusInstance()
{
// Act
await _sut.StartAsync(CancellationToken.None);
// Assert
// The instance passed to the initializer is the one that changes. A copied status would leave this instance available.
Assert.False(_toolchainStatus.IsTranscoderAvailable);
Assert.All(
[.. PlaybackFormatCatalog.Formats.Select(format => format.EncoderName).Distinct(StringComparer.OrdinalIgnoreCase)],
encoderName => Assert.False(_toolchainStatus.IsEncoderAvailable(encoderName)));
}
[Fact]
public async Task StopAsync_WhenCalled_ShouldReturnACompletedTask()
{
// Act
Task result = _sut.StopAsync(CancellationToken.None);
// Assert
Assert.True(result.IsCompletedSuccessfully);
await result;
}
/// <summary>
/// Creates a well formed opaque cache identifier.
/// </summary>
/// <returns>A 64 character lowercase hexadecimal identifier.</returns>
private static string CreateCacheId()
{
return $"{Guid.NewGuid():N}{Guid.NewGuid():N}";
}
/// <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
{
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);
}
using (Process process = Process.Start(startInfo)!)
{
process.WaitForExit(5000);
return process.ExitCode == 0;
}
}
catch (Exception)
{
return false;
}
}
/// <summary>
/// Removes the temporary directory created for the test.
/// </summary>
public void Dispose()
{
try
{
if (Directory.Exists(_cacheDirectory) && new DirectoryInfo(_cacheDirectory).LinkTarget is not null)
Directory.Delete(_cacheDirectory);
if (Directory.Exists(_temporaryDirectory))
Directory.Delete(_temporaryDirectory, recursive: true);
}
catch (Exception exception) when (exception is IOException or UnauthorizedAccessException)
{
// A reparse point may be held by the platform on some systems; the directory is under the process temporary directory.
}
GC.SuppressFinalize(this);
}
}
@@ -0,0 +1,309 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary;
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management;
using Lumina.Application.Common.DataAccess.Repositories.MediaLibrary;
using Lumina.Application.Common.DataAccess.Repositories.MusicLibrary;
using Lumina.Application.Common.DataAccess.UoW;
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management;
using Lumina.Domain.Common.Events;
using Lumina.Domain.Common.Primitives;
using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Services;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Jobs;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.PathTemplate;
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.Domain.SharedKernel.Common.Enums.MediaLibrary;
using Lumina.Infrastructure.Core.MediaLibrary.Management.Scanning.Jobs.Audio.Music;
using Microsoft.Extensions.DependencyInjection;
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.IntegrationTests.Core.MediaLibrary.Management.Scanning.Jobs.Audio.Music;
/// <summary>
/// Contains integration tests for the <see cref="MusicMetadataExtractionJob"/> class, probing real audio containers through the tagging library.
/// </summary>
[ExcludeFromCodeCoverage]
public class MusicMetadataExtractionJobTests
{
private readonly IServiceScopeFactory _mockServiceScopeFactory;
private readonly IServiceScope _mockServiceScope;
private readonly IServiceProvider _mockServiceProvider;
private readonly IUnitOfWork _mockUnitOfWork;
private readonly ILibraryRepository _mockLibraryRepository;
private readonly IMusicLibraryScanItemMetadataRepository _mockMusicMetadataRepository;
private readonly ILibraryScanStagingResultsRepository _mockStagingResultsRepository;
private readonly ILibraryPathTemplateService _mockPathTemplateService;
private readonly IPathService _mockPathService;
private readonly IDomainEventPublisher _mockDomainEventPublisher;
private readonly MusicMetadataExtractionJob _sut;
private readonly LibraryEntityFixture _libraryEntityFixture = new();
private readonly LibraryPathTemplateFixture _libraryPathTemplateFixture = new();
private readonly LibraryIdFixture _libraryIdFixture = new();
private readonly ScanIdFixture _scanIdFixture = new();
private readonly UserIdFixture _userIdFixture = new();
private readonly LibraryId _libraryId;
private readonly ScanId _scanId;
private readonly UserId _userId;
/// <summary>
/// Initializes a new instance of the <see cref="MusicMetadataExtractionJobTests"/> class.
/// </summary>
public MusicMetadataExtractionJobTests()
{
_mockServiceScopeFactory = Substitute.For<IServiceScopeFactory>();
_mockServiceScope = Substitute.For<IServiceScope>();
_mockServiceProvider = Substitute.For<IServiceProvider>();
_mockServiceScopeFactory.CreateScope().Returns(_mockServiceScope);
_mockServiceScope.ServiceProvider.Returns(_mockServiceProvider);
_mockUnitOfWork = Substitute.For<IUnitOfWork>();
_mockUnitOfWork.SaveChangesAsync(Arg.Any<CancellationToken>()).Returns(Result.Success);
_mockLibraryRepository = Substitute.For<ILibraryRepository>();
_mockMusicMetadataRepository = Substitute.For<IMusicLibraryScanItemMetadataRepository>();
_mockStagingResultsRepository = Substitute.For<ILibraryScanStagingResultsRepository>();
_mockUnitOfWork.LibraryRepository.Returns(_mockLibraryRepository);
_mockUnitOfWork.MusicLibraryScanItemMetadataRepository.Returns(_mockMusicMetadataRepository);
_mockUnitOfWork.LibraryScanStagingResultsRepository.Returns(_mockStagingResultsRepository);
_mockServiceProvider.GetService(typeof(IUnitOfWork)).Returns(_mockUnitOfWork);
_mockPathTemplateService = Substitute.For<ILibraryPathTemplateService>();
_mockPathService = Substitute.For<IPathService>();
_mockPathService.PathSeparator.Returns('\\');
_mockServiceProvider.GetService(typeof(ILibraryPathTemplateService)).Returns(_mockPathTemplateService);
_mockServiceProvider.GetService(typeof(IPathService)).Returns(_mockPathService);
_mockDomainEventPublisher = Substitute.For<IDomainEventPublisher>();
_mockDomainEventPublisher.PublishAsync(Arg.Any<IDomainEvent>(), Arg.Any<CancellationToken>())
.Returns(ValueTask.CompletedTask);
_mockServiceProvider.GetService(typeof(IDomainEventPublisher)).Returns(_mockDomainEventPublisher);
// Default stubs that keep the happy path working, overridden per test where needed.
_mockMusicMetadataRepository.InsertRangeAsync(Arg.Any<IReadOnlyCollection<MusicLibraryScanItemMetadataEntity>>(), Arg.Any<CancellationToken>()).Returns(Result.Created);
_mockPathTemplateService.ResolveTemplate(Arg.Any<LibraryType>(), Arg.Any<IReadOnlyList<LibraryPathPart>>()).Returns(Result.From(_libraryPathTemplateFixture.Create()));
_mockPathTemplateService.Parse(Arg.Any<LibraryType>(), Arg.Any<LibraryPathTemplate>(), Arg.Any<string>(), Arg.Any<char>()).Returns(Result.From<Optional<ParsedLibraryPath>>(Optional<ParsedLibraryPath>.None()));
_mockPathService.IsPathWithin(Arg.Any<string>(), Arg.Any<string>()).Returns(true);
_mockPathService.GetFileNameWithoutExtension(Arg.Any<string>()).Returns("tone");
_mockPathService.GetFileName(Arg.Any<string>()).Returns("tone.wav");
_libraryId = _libraryIdFixture.Create();
_scanId = _scanIdFixture.Create();
_userId = _userIdFixture.Create();
_sut = new MusicMetadataExtractionJob(_mockServiceScopeFactory, Substitute.For<Microsoft.Extensions.Logging.ILogger<MusicMetadataExtractionJob>>())
{
ScanId = _scanId,
UserId = _userId,
LibraryId = _libraryId
};
}
[Fact]
public async Task ExecuteAsync_WhenTheFileIsARealAudioFile_ShouldCaptureItsContainerAndAudioProperties()
{
// Arrange
using TemporaryMediaDirectory temporaryMediaDirectory = new();
string audioFilePath = temporaryMediaDirectory.CreateWavFile("tone.wav");
LibraryEntity library = _libraryEntityFixture.Create(
id: _libraryId.Value,
libraryType: LibraryType.Music,
contentLocations: [temporaryMediaDirectory.Path]);
_mockLibraryRepository.GetByIdAsync(_libraryId.Value, cancellationToken: Arg.Any<CancellationToken>())
.Returns(Result.From<LibraryEntity?>(library));
_mockStagingResultsRepository.GetPathsNeedingRehashAsync(_scanId.Value, Arg.Any<CancellationToken>())
.Returns(Result.From<IReadOnlyList<string>>([audioFilePath]));
// Act
await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None);
// Assert
Assert.Equal(LibraryScanJobStatus.Completed, _sut.Status);
await _mockMusicMetadataRepository.Received(1).InsertRangeAsync(
Arg.Is<IReadOnlyCollection<MusicLibraryScanItemMetadataEntity>>(items => items.Count == 1
&& items.First().Container == "WAV"
&& items.First().SampleRate == 8000
&& items.First().Channels == 1
&& items.First().BitDepth == 16),
Arg.Any<CancellationToken>());
}
[Fact]
public async Task ExecuteAsync_WhenTheContainerHasNoDedicatedParser_ShouldFallBackToTheMimeTypeName()
{
// Arrange
using TemporaryMediaDirectory temporaryMediaDirectory = new();
string imageFilePath = temporaryMediaDirectory.CreatePngFile("cover.png");
LibraryEntity library = _libraryEntityFixture.Create(
id: _libraryId.Value,
libraryType: LibraryType.Music,
contentLocations: [temporaryMediaDirectory.Path]);
_mockLibraryRepository.GetByIdAsync(_libraryId.Value, cancellationToken: Arg.Any<CancellationToken>())
.Returns(Result.From<LibraryEntity?>(library));
_mockStagingResultsRepository.GetPathsNeedingRehashAsync(_scanId.Value, Arg.Any<CancellationToken>())
.Returns(Result.From<IReadOnlyList<string>>([imageFilePath]));
// Act
await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None);
// Assert
Assert.Equal(LibraryScanJobStatus.Completed, _sut.Status);
await _mockMusicMetadataRepository.Received(1).InsertRangeAsync(
Arg.Is<IReadOnlyCollection<MusicLibraryScanItemMetadataEntity>>(items => items.Count == 1
&& items.First().Container == "PNG"),
Arg.Any<CancellationToken>());
}
[Fact]
public async Task ExecuteAsync_WhenTheFileIsAReparsePoint_ShouldNotReadTheLinkedFile()
{
// Arrange
using TemporaryMediaDirectory temporaryMediaDirectory = new();
using TemporaryMediaDirectory outsideMediaDirectory = new();
string targetFilePath = outsideMediaDirectory.CreateWavFile("target.wav");
string linkFilePath = System.IO.Path.Combine(temporaryMediaDirectory.Path, "link.wav");
if (!TryCreateFileSymbolicLink(linkFilePath, targetFilePath))
return; // The environment does not support creating file symbolic links.
LibraryEntity library = _libraryEntityFixture.Create(
id: _libraryId.Value,
libraryType: LibraryType.Music,
contentLocations: [temporaryMediaDirectory.Path]);
_mockLibraryRepository.GetByIdAsync(_libraryId.Value, cancellationToken: Arg.Any<CancellationToken>())
.Returns(Result.From<LibraryEntity?>(library));
_mockStagingResultsRepository.GetPathsNeedingRehashAsync(_scanId.Value, Arg.Any<CancellationToken>())
.Returns(Result.From<IReadOnlyList<string>>([linkFilePath]));
// Act
await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None);
// Assert
// The linked file lives outside the content location, so its audio metadata must not be read: the container stays unrecognized.
await _mockMusicMetadataRepository.Received(1).InsertRangeAsync(
Arg.Is<IReadOnlyCollection<MusicLibraryScanItemMetadataEntity>>(items => items.Count == 1
&& items.First().Container == null
&& items.First().SampleRate == 0),
Arg.Any<CancellationToken>());
}
/// <summary>
/// Creates a file system symbolic link that points to the target file.
/// </summary>
/// <param name="linkPath">The file system path of the symbolic link to create.</param>
/// <param name="targetPath">The file system path of the file the link points to.</param>
/// <returns><see langword="true"/> when the link was created, <see langword="false"/> otherwise.</returns>
private static bool TryCreateFileSymbolicLink(string linkPath, string targetPath)
{
try
{
File.CreateSymbolicLink(linkPath, targetPath);
return true;
}
catch (Exception)
{
// Creating a file symbolic link requires elevated privileges on Windows, so the environment may not support it.
return false;
}
}
/// <summary>
/// Test helper managing a temporary directory holding real media files, deleted when the test finishes.
/// </summary>
private sealed class TemporaryMediaDirectory : IDisposable
{
/// <summary>
/// A minimal, valid, one by one pixel PNG image, used to exercise a container that has no dedicated parser.
/// </summary>
private const string PNG_BYTES = "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAAAANSURBVBhXY2BgYGAAAAAFAAGKM+MAAAAAAElFTkSuQmCC";
private bool _disposed;
/// <summary>
/// Initializes a new instance of the <see cref="TemporaryMediaDirectory"/> class.
/// </summary>
public TemporaryMediaDirectory()
{
Path = System.IO.Path.Combine(System.IO.Path.GetTempPath(), $"lumina-music-probe-{Guid.NewGuid():N}");
Directory.CreateDirectory(Path);
}
/// <summary>
/// Gets the full path of the temporary directory.
/// </summary>
public string Path { get; }
/// <summary>
/// Writes a minimal, valid, one second long 16 bit PCM mono 8000 Hz WAV file into the temporary directory.
/// </summary>
/// <param name="fileName">The name of the WAV file to create.</param>
/// <returns>The full path of the created WAV file.</returns>
public string CreateWavFile(string fileName)
{
const int SAMPLE_RATE = 8000;
const short CHANNELS = 1;
const short BITS_PER_SAMPLE = 16;
int blockAlign = CHANNELS * (BITS_PER_SAMPLE / 8);
int dataSize = SAMPLE_RATE * blockAlign;
string filePath = System.IO.Path.Combine(Path, fileName);
using (FileStream stream = new(filePath, FileMode.Create, FileAccess.Write))
using (BinaryWriter writer = new(stream))
{
writer.Write("RIFF"u8.ToArray());
writer.Write(36 + dataSize);
writer.Write("WAVE"u8.ToArray());
writer.Write("fmt "u8.ToArray());
writer.Write(16);
writer.Write((short)1);
writer.Write(CHANNELS);
writer.Write(SAMPLE_RATE);
writer.Write(SAMPLE_RATE * blockAlign);
writer.Write((short)blockAlign);
writer.Write(BITS_PER_SAMPLE);
writer.Write("data"u8.ToArray());
writer.Write(dataSize);
writer.Write(new byte[dataSize]);
}
return filePath;
}
/// <summary>
/// Writes a minimal, valid PNG image into the temporary directory.
/// </summary>
/// <param name="fileName">The name of the PNG file to create.</param>
/// <returns>The full path of the created PNG file.</returns>
public string CreatePngFile(string fileName)
{
string filePath = System.IO.Path.Combine(Path, fileName);
File.WriteAllBytes(filePath, Convert.FromBase64String(PNG_BYTES));
return filePath;
}
/// <summary>
/// Deletes the temporary directory, ignoring the failures of the files that are still in use.
/// </summary>
public void Dispose()
{
if (_disposed)
return;
try
{
Directory.Delete(Path, recursive: true);
}
catch (IOException)
{
// Best effort cleanup of the temporary directory.
}
_disposed = true;
}
}
}
@@ -0,0 +1,412 @@
#region ========================================================================= USING =====================================================================================
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.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;
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.IntegrationTests.Core.MediaLibrary.Management.Scanning.Jobs.WrittenContent.Books;
/// <summary>
/// Contains integration tests for the <see cref="BooksFileSystemDiscoveryJob"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class BooksFileSystemDiscoveryJobTests
{
private readonly IServiceScopeFactory _mockServiceScopeFactory;
private readonly IServiceScope _mockServiceScope;
private readonly IServiceProvider _mockServiceProvider;
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;
/// <summary>
/// Initializes a new instance of the <see cref="BooksFileSystemDiscoveryJobTests"/> class.
/// </summary>
public BooksFileSystemDiscoveryJobTests()
{
_mockServiceScopeFactory = Substitute.For<IServiceScopeFactory>();
_mockServiceScope = Substitute.For<IServiceScope>();
_mockServiceProvider = Substitute.For<IServiceProvider>();
_mockServiceScopeFactory.CreateScope().Returns(_mockServiceScope);
_mockServiceScope.ServiceProvider.Returns(_mockServiceProvider);
_mockUnitOfWork = Substitute.For<IUnitOfWork>();
_mockUnitOfWork.SaveChangesAsync(Arg.Any<CancellationToken>()).Returns(Result.Success);
_mockLibraryRepository = Substitute.For<ILibraryRepository>();
_mockStagingResultsRepository = Substitute.For<ILibraryScanStagingResultsRepository>();
_mockDirectoryScanFingerprintRepository = Substitute.For<IDirectoryScanFingerprintRepository>();
_mockUnitOfWork.LibraryRepository.Returns(_mockLibraryRepository);
_mockUnitOfWork.LibraryScanStagingResultsRepository.Returns(_mockStagingResultsRepository);
_mockUnitOfWork.DirectoryScanFingerprintRepository.Returns(_mockDirectoryScanFingerprintRepository);
_mockServiceProvider.GetService(typeof(IUnitOfWork)).Returns(_mockUnitOfWork);
_mockDomainEventPublisher = Substitute.For<IDomainEventPublisher>();
_mockDomainEventPublisher.PublishAsync(Arg.Any<IDomainEvent>(), Arg.Any<CancellationToken>())
.Returns(ValueTask.CompletedTask);
_mockServiceProvider.GetService(typeof(IDomainEventPublisher)).Returns(_mockDomainEventPublisher);
_scanId = _scanIdFixture.Create();
_userId = _userIdFixture.Create();
_libraryId = _libraryIdFixture.Create();
_sut = new BooksFileSystemDiscoveryJob(_mockServiceScopeFactory, Substitute.For<Microsoft.Extensions.Logging.ILogger<BooksFileSystemDiscoveryJob>>())
{
ScanId = _scanId,
UserId = _userId,
LibraryId = _libraryId
};
}
[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");
temporaryLibraryDirectory.CreateFile(".hidden.pdf", "hidden book content");
SetHiddenAttribute(Path.Combine(temporaryLibraryDirectory.Path, ".hidden.pdf"));
string subdirectoryPath = temporaryLibraryDirectory.CreateSubdirectory("sub");
File.WriteAllText(Path.Combine(subdirectoryPath, "book2.epub"), "another book content");
string hiddenSubdirectoryPath = temporaryLibraryDirectory.CreateSubdirectory(".hidden");
SetHiddenAttribute(hiddenSubdirectoryPath);
File.WriteAllText(Path.Combine(hiddenSubdirectoryPath, "hidden.epub"), "hidden book content");
LibraryEntity libraryEntity = _libraryEntityFixture.Create(
id: _libraryId.Value,
userId: _userId.Value,
title: "Test Library",
libraryType: LibraryType.Book,
contentLocations: [temporaryLibraryDirectory.Path],
shouldSkipUnchangedDirectoriesDuringScan: false,
isContentOnSsd: true);
_mockLibraryRepository.GetByIdAsync(_libraryId.Value, cancellationToken: Arg.Any<CancellationToken>())
.Returns(Result.From<LibraryEntity?>(libraryEntity));
_mockStagingResultsRepository.InsertRangeAsync(Arg.Any<IReadOnlyCollection<LibraryScanStagingResultsEntity>>(), Arg.Any<CancellationToken>())
.Returns(Result.From(Result.Created));
_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(
[".hidden.pdf", "book1.pdf", "book2.epub", "hidden.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_WhenHiddenFilesAndDirectoriesAreSkipped_ShouldNotDiscoverThem()
{
// Arrange
using TemporaryLibraryDirectory temporaryLibraryDirectory = new();
temporaryLibraryDirectory.CreateFile("visible.pdf", "visible book content");
temporaryLibraryDirectory.CreateFile(".hidden.pdf", "hidden book content");
string hiddenFileName = Path.Combine(temporaryLibraryDirectory.Path, ".hidden.pdf");
SetHiddenAttribute(hiddenFileName);
string visibleSubdirectoryPath = temporaryLibraryDirectory.CreateSubdirectory("visible");
File.WriteAllText(Path.Combine(visibleSubdirectoryPath, "nested.epub"), "nested book content");
string hiddenSubdirectoryPath = temporaryLibraryDirectory.CreateSubdirectory(".hidden");
SetHiddenAttribute(hiddenSubdirectoryPath);
File.WriteAllText(Path.Combine(hiddenSubdirectoryPath, "secret.epub"), "secret book content");
LibraryEntity libraryEntity = _libraryEntityFixture.Create(
id: _libraryId.Value,
userId: _userId.Value,
title: "Test Library",
libraryType: LibraryType.Book,
contentLocations: [temporaryLibraryDirectory.Path],
shouldSkipHiddenFilesAndDirectoriesDuringScan: true);
_mockLibraryRepository.GetByIdAsync(_libraryId.Value, cancellationToken: Arg.Any<CancellationToken>())
.Returns(Result.From<LibraryEntity?>(libraryEntity));
_mockStagingResultsRepository.InsertRangeAsync(Arg.Any<IReadOnlyCollection<LibraryScanStagingResultsEntity>>(), Arg.Any<CancellationToken>())
.Returns(Result.From(Result.Created));
// 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 == 2
&& entities.Select(entity => Path.GetFileName(entity.Path)).OrderBy(name => name, StringComparer.Ordinal).SequenceEqual(new[] { "nested.epub", "visible.pdf" })),
Arg.Any<CancellationToken>());
}
[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, cancellationToken: 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, cancellationToken: Arg.Any<CancellationToken>())
.Returns(Result.From<LibraryEntity?>(libraryEntity));
_mockDirectoryScanFingerprintRepository.GetMappedByLibraryIdAsync(_libraryId.Value, Arg.Any<CancellationToken>())
.Returns(Error.Failure("Database.Error", "Failed to load the directory scan fingerprints"));
// 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, cancellationToken: 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, cancellationToken: Arg.Any<CancellationToken>())
.Returns(Result.From<LibraryEntity?>(libraryEntity));
_mockStagingResultsRepository.InsertRangeAsync(Arg.Any<IReadOnlyCollection<LibraryScanStagingResultsEntity>>(), Arg.Any<CancellationToken>())
.Returns(Error.Failure("Database.Error", "Failed to insert the staging results"));
// 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, cancellationToken: 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>
/// Marks the file system entry at <paramref name="path"/> as hidden on Windows, where the dot prefix alone is not enough.
/// </summary>
/// <param name="path">The path of the file or directory to mark as hidden.</param>
private static void SetHiddenAttribute(string path)
{
if (OperatingSystem.IsWindows())
File.SetAttributes(path, File.GetAttributes(path) | FileAttributes.Hidden);
}
/// <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;
}
}
}
}
@@ -0,0 +1,699 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.Infrastructure.Models.DTO.Configuration;
using Lumina.Application.Fixtures.Common.Infrastructure.Models.DTO.Configuration;
using Lumina.Contracts.Fixtures.Core.DTO.Common;
using Lumina.Domain.Common.Errors;
using Lumina.Domain.Common.Primitives;
using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Services;
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;
using System.Diagnostics.CodeAnalysis;
using System.IO;
using System.Net;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Infrastructure.IntegrationTests.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Artwork;
/// <summary>
/// Contains integration tests for the <see cref="BookArtworkService"/> class.
/// </summary>
[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;
private readonly IDirectoryProviderService _mockDirectoryProviderService;
private readonly IPathService _mockPathService;
private readonly IHttpClientFactory _mockHttpClientFactory;
private readonly IOptions<MediaSettingsDto> _mockMediaSettingsOptions;
private readonly BookArtworkService _sut;
private readonly FileSystemPathIdFixture _fileSystemPathIdFixture = new();
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.
/// </summary>
public BookArtworkServiceTests()
{
_mockEnvironmentContext = Substitute.For<IEnvironmentContext>();
_mockFileTypeService = Substitute.For<IFileTypeService>();
_mockFileProviderService = Substitute.For<IFileProviderService>();
_mockDirectoryProviderService = Substitute.For<IDirectoryProviderService>();
_mockEnvironmentContext.FileTypeService.Returns(_mockFileTypeService);
_mockEnvironmentContext.FileProviderService.Returns(_mockFileProviderService);
_mockEnvironmentContext.DirectoryProviderService.Returns(_mockDirectoryProviderService);
_mockPathService = Substitute.For<IPathService>();
_mockPathService.PathSeparator.Returns('\\');
_mockHttpClientFactory = Substitute.For<IHttpClientFactory>();
_mockHttpClientFactory.CreateClient(Arg.Any<string>()).Returns(new HttpClient(_stubHttpMessageHandler));
MediaSettingsDto mediaSettings = _mediaSettingsDtoFixture.Create(rootDirectory: "media", librariesDirectory: "libraries", booksDirectory: "books");
_mockMediaSettingsOptions = Substitute.For<IOptions<MediaSettingsDto>>();
_mockMediaSettingsOptions.Value.Returns(mediaSettings);
_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.jpg");
FileSystemPathId renamedFileId = _fileSystemPathIdFixture.Create(renamedFilePath);
_mockFileProviderService.RenameFile(Arg.Any<FileSystemPathId>(), "cover.jpg")
.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.jpg");
}
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.jpg"));
_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.jpg")
.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_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_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.jpg"));
_mockFileProviderService.RenameFile(Arg.Any<FileSystemPathId>(), "cover.jpg")
.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.jpg"));
_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.jpg")
.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_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.jpg")
.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.SanitizeCompositeSegment(Arg.Any<string>(), Arg.Any<string>())
.Returns(callInfo =>
{
string name = callInfo.ArgAt<string>(0);
string identifier = callInfo.ArgAt<string>(1);
return Result.From(_pathSegmentFixture.Create(name: $"{name}-{identifier}", isDirectory: true, isDrive: false));
});
_mockPathService.SanitizeSegment(Arg.Any<string>())
.Returns(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);
}
}
/// <summary>
/// Stubs the path and file system services so that the artwork is stored into the given directory.
/// </summary>
/// <param name="artworkDirectoryPath">The file system path of the directory into which the artwork is stored.</param>
private void MockArtworkDirectoryStubs(string artworkDirectoryPath)
{
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.SanitizeSegment(Arg.Any<string>())
.Returns(callInfo =>
{
string name = callInfo.Arg<string>();
return Result.From(_pathSegmentFixture.Create(name: name, isDirectory: true, isDrive: false));
});
_mockPathService.SanitizeCompositeSegment(Arg.Any<string>(), Arg.Any<string>())
.Returns(callInfo =>
{
string name = callInfo.ArgAt<string>(0);
string identifier = callInfo.ArgAt<string>(1);
return Result.From(_pathSegmentFixture.Create(name: $"{name}-{identifier}", isDirectory: true, isDrive: false));
});
_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.
_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>())
.Returns(callInfo => Result.From(_fileSystemPathIdFixture.Create(Path.Combine(callInfo.Arg<FileSystemPathId>().Path, callInfo.Arg<string>()))));
_mockFileProviderService.GetFilePaths(Arg.Any<FileSystemPathId>(), true)
.Returns(Result.From<IEnumerable<FileSystemPathId>>([]));
}
/// <summary>
/// Builds the file system path of the directory that the artwork of the book is stored into.
/// </summary>
/// <param name="libraryId">The Id of the media library the book belongs to.</param>
/// <param name="bookId">The Id of the book.</param>
/// <param name="libraryName">The name of the media library the book belongs to.</param>
/// <param name="authorName">The name of the author of the book.</param>
/// <param name="bookTitle">The title of the book.</param>
/// <returns>The expected file system path of the book artwork directory.</returns>
private static string BuildArtworkDirectoryPath(Guid libraryId, Guid bookId, string libraryName, string authorName, string bookTitle)
{
return Path.Combine(
AppContext.BaseDirectory,
"media",
"books",
$"{libraryName}-{libraryId}",
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
{
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);
}
Process process = Process.Start(startInfo)!;
process.WaitForExit(5000);
return process.ExitCode == 0;
}
catch (Exception)
{
return false;
}
}
}
@@ -0,0 +1,783 @@
#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.IntegrationTests.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Reading;
/// <summary>
/// Contains integration 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 _libraryBookReaderConfigurationEntityFixture = 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>();
_mockUnitOfWork.SaveChangesAsync(Arg.Any<CancellationToken>()).Returns(Result.Success);
_mockConfigurationRepository = Substitute.For<ILibraryBookReaderConfigurationRepository>();
_mockUnitOfWork.LibraryBookReaderConfigurationRepository.Returns(_mockConfigurationRepository);
LibraryBookReaderConfigurationEntity enabledConfiguration = _libraryBookReaderConfigurationEntityFixture.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 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 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_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 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));
}
}
}