Implements tests for commit 4e13b23f16

Covers the normalized audio cache with integration tests for the cache paths, the coordinator, the reader lease, the reservation, the lease stream, the output size tracker and the startup initializer, and unit tests for the playback format catalog and the transcoding toolchain status, with fixtures for the index DTOs and the transcoding settings. Makes the array based asynchronous overloads of the lease stream adapt to the memory based overloads of the inner stream.
This commit is contained in:
BinaryAlley committed 2026-10-28 15:32:52 +02:00
1 parent cf3855ec12
commit d61a114d80
13 files changed
+3011 -2

No files matched your search

@@ -0,0 +1,66 @@
#region ========================================================================= USING =====================================================================================
using Bogus;
using Lumina.Infrastructure.Common.Models.DTO.Configuration;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
#endregion
namespace Lumina.Infrastructure.Fixtures.Common.Models.DTO.Configuration;
/// <summary>
/// Fixture class for the <see cref="TranscodingSettingsDto"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class TranscodingSettingsDtoFixture
{
private readonly Faker _faker = new();
/// <summary>
/// Creates a random valid <see cref="TranscodingSettingsDto"/>.
/// </summary>
/// <param name="ffmpegPath">Optional file name or path of the ffmpeg binary.</param>
/// <param name="maxConcurrentJobs">Optional maximum number of normalization jobs that may run at the same time.</param>
/// <param name="maxConcurrentJobsPerUser">Optional maximum number of normalization jobs a single user may have running at the same time.</param>
/// <param name="maxCacheBytes">Optional maximum total size of the normalized audio cache, in bytes.</param>
/// <param name="jobTimeoutSeconds">Optional maximum duration of a single normalization job, in seconds.</param>
/// <param name="evictionGraceSeconds">Optional period during which a cache entry is protected from eviction, in seconds.</param>
/// <param name="cacheDirectory">
/// Optional directory where normalized audio is cached. When it is not supplied, a generated directory is used. When
/// <paramref name="includeCacheDirectory"/> is <see langword="false"/>, the property stays <see langword="null"/>, which makes the pipeline use the
/// default temporary directory.
/// </param>
/// <param name="includeCacheDirectory">Whether to generate the optional cache directory, defaulting to <see langword="true"/>.</param>
/// <returns>A configured <see cref="TranscodingSettingsDto"/> instance.</returns>
public TranscodingSettingsDto Create(
string? ffmpegPath = null,
int? maxConcurrentJobs = null,
int? maxConcurrentJobsPerUser = null,
long? maxCacheBytes = null,
int? jobTimeoutSeconds = null,
int? evictionGraceSeconds = null,
string? cacheDirectory = null,
bool includeCacheDirectory = true)
{
return new TranscodingSettingsDto
{
FfmpegPath = ffmpegPath ?? _faker.System.FileName("exe"),
MaxConcurrentJobs = maxConcurrentJobs ?? _faker.Random.Int(1, 16),
MaxConcurrentJobsPerUser = maxConcurrentJobsPerUser ?? _faker.Random.Int(1, 8),
MaxCacheBytes = maxCacheBytes ?? _faker.Random.Long(1_000_000_000, 8_589_934_592),
JobTimeoutSeconds = jobTimeoutSeconds ?? _faker.Random.Int(60, 3600),
EvictionGraceSeconds = evictionGraceSeconds ?? _faker.Random.Int(0, 600),
CacheDirectory = includeCacheDirectory ? cacheDirectory ?? _faker.System.DirectoryPath() : null
};
}
/// <summary>
/// Creates a list of <see cref="TranscodingSettingsDto"/> instances with randomized test data.
/// </summary>
/// <param name="count">Number of instances to create.</param>
/// <returns>List of configured <see cref="TranscodingSettingsDto"/> instances.</returns>
public List<TranscodingSettingsDto> CreateMany(int count = 3)
{
return [.. Enumerable.Range(0, count).Select(_ => Create())];
}
}
@@ -0,0 +1,68 @@
#region ========================================================================= USING =====================================================================================
using Bogus;
using Lumina.Domain.SharedKernel.Common.Enums.Playback;
using Lumina.Infrastructure.Common.Models.DTO.MediaLibrary.AudioLibrary.MusicLibrary.Playback;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
#endregion
namespace Lumina.Infrastructure.Fixtures.Common.Models.DTO.MediaLibrary.AudioLibrary.MusicLibrary.Playback;
/// <summary>
/// Fixture class for the <see cref="NormalizedTrackIndexDto"/> record.
/// </summary>
[ExcludeFromCodeCoverage]
internal class NormalizedTrackIndexDtoFixture
{
private readonly Faker _faker = new();
private readonly NormalizedTrackSegmentIndexDtoFixture _normalizedTrackSegmentIndexDtoFixture = new();
/// <summary>
/// Creates a random valid <see cref="NormalizedTrackIndexDto"/>.
/// </summary>
/// <param name="version">Optional version of the index layout.</param>
/// <param name="trackId">Optional Id of the track the cached audio belongs to.</param>
/// <param name="mode">Optional way the audio is delivered.</param>
/// <param name="container">Optional container of the delivered audio.</param>
/// <param name="codec">Optional codec of the delivered audio.</param>
/// <param name="segmentDurationSeconds">Optional duration of each segment, in seconds.</param>
/// <param name="durationInSeconds">Optional duration of the produced and cached audio, in seconds.</param>
/// <param name="segments">
/// Optional segments that make up the delivered audio, in playback order. A caller can supply an explicit list, including an empty one; when it is not
/// supplied a random bounded list is generated.
/// </param>
/// <returns>The created <see cref="NormalizedTrackIndexDto"/>.</returns>
public NormalizedTrackIndexDto Create(
int? version = null,
Guid? trackId = null,
PlaybackDeliveryMode? mode = null,
string? container = null,
string? codec = null,
int? segmentDurationSeconds = null,
int? durationInSeconds = null,
IReadOnlyList<NormalizedTrackSegmentIndexDto>? segments = null)
{
return new NormalizedTrackIndexDto(
version ?? _faker.Random.Int(1, 10),
trackId ?? _faker.Random.Guid(),
mode ?? _faker.PickRandom(PlaybackDeliveryMode.DirectPlay, PlaybackDeliveryMode.Remux, PlaybackDeliveryMode.Transcode),
container ?? _faker.PickRandom("MP4", "OGG", "WAV", "FLAC"),
codec ?? _faker.PickRandom("AAC", "VORBIS", "PCM", "FLAC"),
segmentDurationSeconds ?? _faker.Random.Int(1, 60),
durationInSeconds ?? _faker.Random.Int(1, 100_000),
segments ?? [.. _normalizedTrackSegmentIndexDtoFixture.CreateMany(_faker.Random.Int(1, 5))]
);
}
/// <summary>
/// Creates a list of <see cref="NormalizedTrackIndexDto"/> instances with randomized test data.
/// </summary>
/// <param name="count">Number of instances to create.</param>
/// <returns>List of configured <see cref="NormalizedTrackIndexDto"/> instances.</returns>
public List<NormalizedTrackIndexDto> CreateMany(int count = 3)
{
return [.. Enumerable.Range(0, count).Select(_ => Create())];
}
}
@@ -0,0 +1,54 @@
#region ========================================================================= USING =====================================================================================
using Bogus;
using Lumina.Infrastructure.Common.Models.DTO.MediaLibrary.AudioLibrary.MusicLibrary.Playback;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
#endregion
namespace Lumina.Infrastructure.Fixtures.Common.Models.DTO.MediaLibrary.AudioLibrary.MusicLibrary.Playback;
/// <summary>
/// Fixture class for the <see cref="NormalizedTrackSegmentIndexDto"/> record.
/// </summary>
[ExcludeFromCodeCoverage]
internal class NormalizedTrackSegmentIndexDtoFixture
{
private readonly Faker _faker = new();
/// <summary>
/// Creates a random valid <see cref="NormalizedTrackSegmentIndexDto"/>.
/// </summary>
/// <param name="index">Optional zero based position of the segment in the delivered audio.</param>
/// <param name="startSeconds">Optional time, in seconds from the start of the track, at which the segment starts.</param>
/// <param name="durationSeconds">Optional duration of the segment, in seconds.</param>
/// <param name="fileName">Optional file name of the segment inside the cache entry.</param>
/// <param name="length">Optional length of the segment, in bytes.</param>
/// <returns>The created <see cref="NormalizedTrackSegmentIndexDto"/>.</returns>
public NormalizedTrackSegmentIndexDto Create(
int? index = null,
decimal? startSeconds = null,
decimal? durationSeconds = null,
string? fileName = null,
long? length = null)
{
return new NormalizedTrackSegmentIndexDto(
index ?? _faker.Random.Int(0, 10_000),
startSeconds ?? _faker.Random.Decimal(0m, 100_000m),
durationSeconds ?? _faker.Random.Decimal(1m, 600m),
fileName ?? $"segment{_faker.Random.Int(0, 10_000):D6}{_faker.PickRandom(".m4s", ".mp4", ".ts")}",
length ?? _faker.Random.Long(1, 100_000_000)
);
}
/// <summary>
/// Creates a list of <see cref="NormalizedTrackSegmentIndexDto"/> instances with randomized test data.
/// </summary>
/// <param name="count">Number of instances to create.</param>
/// <returns>List of configured <see cref="NormalizedTrackSegmentIndexDto"/> instances.</returns>
public List<NormalizedTrackSegmentIndexDto> CreateMany(int count = 3)
{
return [.. Enumerable.Range(0, count).Select(segmentIndex => Create(index: segmentIndex))];
}
}
@@ -0,0 +1,438 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Infrastructure.Common.Caching;
using System;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.IO;
using System.Threading;
#endregion
namespace Lumina.Infrastructure.IntegrationTests.Common.Caching;
/// <summary>
/// Contains integration tests for the <see cref="TranscodingCachePaths"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class TranscodingCachePathsTests : IDisposable
{
private readonly string _temporaryDirectory;
/// <summary>
/// Initializes a new instance of the <see cref="TranscodingCachePathsTests"/> class.
/// </summary>
public TranscodingCachePathsTests()
{
_temporaryDirectory = Path.Combine(Path.GetTempPath(), $"lumina-transcoding-cache-paths-{Guid.NewGuid():N}");
Directory.CreateDirectory(_temporaryDirectory);
}
[Theory]
[InlineData(null)] // no cache directory is configured
[InlineData("")] // an empty cache directory is configured
[InlineData(" ")] // a white space cache directory is configured
public void GetRootDirectory_WhenNoDirectoryIsConfigured_ShouldReturnTheDefaultDirectoryUnderTheTemporaryDirectory(string? configuredDirectory)
{
// Act
string result = TranscodingCachePaths.GetRootDirectory(configuredDirectory);
// Assert
string directoryName = Path.GetFileName(result);
Assert.Equal(Path.Combine(Path.GetTempPath(), directoryName), result);
Assert.StartsWith(TranscodingCachePaths.DEFAULT_DIRECTORY_NAME + "-", directoryName, StringComparison.Ordinal);
string accountSuffix = directoryName[(TranscodingCachePaths.DEFAULT_DIRECTORY_NAME.Length + 1)..];
Assert.Matches("^[0-9a-f]{16}$", accountSuffix);
}
[Fact]
public void GetRootDirectory_WhenCalledRepeatedly_ShouldReturnTheSamePath()
{
// Act
string firstResult = TranscodingCachePaths.GetRootDirectory(null);
string secondResult = TranscodingCachePaths.GetRootDirectory(null);
// Assert
Assert.Equal(firstResult, secondResult);
}
[Fact]
public void GetRootDirectory_WhenTheConfiguredDirectoryIsRooted_ShouldReturnItsFullPath()
{
// Arrange
string configuredDirectory = Path.Combine(_temporaryDirectory, "configured-cache");
// Act
string result = TranscodingCachePaths.GetRootDirectory($" {configuredDirectory} ");
// Assert
Assert.Equal(Path.GetFullPath(configuredDirectory), result);
}
[Fact]
public void GetRootDirectory_WhenTheConfiguredDirectoryIsRelative_ShouldResolveItAgainstTheBaseDirectory()
{
// Arrange
string configuredDirectory = Path.Combine("relative", "cache");
// Act
string result = TranscodingCachePaths.GetRootDirectory(configuredDirectory);
// Assert
Assert.Equal(Path.GetFullPath(Path.Combine(AppContext.BaseDirectory, configuredDirectory)), result);
}
[Fact]
public void HasCacheMarker_WhenTheDirectoryHasNoMarker_ShouldReturnFalse()
{
// Arrange
string directoryPath = Path.Combine(_temporaryDirectory, "unmarked");
Directory.CreateDirectory(directoryPath);
// Act
bool result = TranscodingCachePaths.HasCacheMarker(directoryPath);
// Assert
Assert.False(result);
}
[Fact]
public void WriteCacheMarker_WhenTheDirectoryHasNoMarker_ShouldWriteTheDocumentedMarkerFile()
{
// Arrange
string directoryPath = Path.Combine(_temporaryDirectory, "marked");
Directory.CreateDirectory(directoryPath);
// Act
TranscodingCachePaths.WriteCacheMarker(directoryPath);
// Assert
Assert.Equal(".lumina-transcoding-cache", TranscodingCachePaths.CACHE_MARKER_FILE_NAME);
Assert.True(TranscodingCachePaths.HasCacheMarker(directoryPath));
Assert.True(File.Exists(Path.Combine(directoryPath, TranscodingCachePaths.CACHE_MARKER_FILE_NAME)));
}
[Fact]
public void WriteCacheMarker_WhenCalledTwice_ShouldNotRewriteTheMarker()
{
// Arrange
string directoryPath = Path.Combine(_temporaryDirectory, "already-marked");
Directory.CreateDirectory(directoryPath);
TranscodingCachePaths.WriteCacheMarker(directoryPath);
string markerPath = Path.Combine(directoryPath, TranscodingCachePaths.CACHE_MARKER_FILE_NAME);
File.WriteAllText(markerPath, "operator content");
// Act
TranscodingCachePaths.WriteCacheMarker(directoryPath);
// Assert
Assert.Equal("operator content", File.ReadAllText(markerPath));
}
[Theory]
[InlineData(null)] // no identifier
[InlineData("")] // an empty identifier
[InlineData("0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcde")] // 63 characters
[InlineData("0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0")] // 65 characters
[InlineData("0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF")] // uppercase hexadecimal characters
[InlineData("0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdeg")] // a character that is not hexadecimal
[InlineData("0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcde/")] // a directory separator
public void IsValidCacheId_WhenTheValueIsNotAWellFormedIdentifier_ShouldReturnFalse(string? cacheId)
{
// Act
bool result = TranscodingCachePaths.IsValidCacheId(cacheId!);
// Assert
Assert.False(result);
}
[Fact]
public void IsValidCacheId_WhenTheValueIsA64CharacterLowercaseHexIdentifier_ShouldReturnTrue()
{
// Arrange
string cacheId = "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef";
// Act
bool result = TranscodingCachePaths.IsValidCacheId(cacheId);
// Assert
Assert.True(result);
}
[Theory]
[InlineData(null)] // no name
[InlineData("")] // an empty name
[InlineData("segment.m4s")] // an ordinary file name
[InlineData("not-a-cache-entry")] // an ordinary directory name
public void IsCacheEntryName_WhenTheNameIsNotInTheCacheNamespace_ShouldReturnFalse(string? entryName)
{
// Act
bool result = TranscodingCachePaths.IsCacheEntryName(entryName!);
// Assert
Assert.False(result);
}
[Theory]
[InlineData("0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef")] // a cache identifier
[InlineData("tmp-0123456789abcdef")] // a temporary directory
[InlineData("del-0123456789abcdef")] // a deletion tombstone
public void IsCacheEntryName_WhenTheNameIsInTheCacheNamespace_ShouldReturnTrue(string entryName)
{
// Act
bool result = TranscodingCachePaths.IsCacheEntryName(entryName);
// Assert
Assert.True(result);
}
[Fact]
public void ClearCacheEntries_WhenCalled_ShouldRemoveOnlyCacheEntriesAndKeepTheRoot()
{
// Arrange
string cacheRoot = Path.Combine(_temporaryDirectory, "clear-cache");
Directory.CreateDirectory(cacheRoot);
string cacheEntryPath = Path.Combine(cacheRoot, CreateCacheId());
Directory.CreateDirectory(Path.Combine(cacheEntryPath, "nested"));
File.WriteAllText(Path.Combine(cacheEntryPath, "nested", "segment.m4s"), "data");
string temporaryEntryPath = Path.Combine(cacheRoot, "tmp-0123456789abcdef");
Directory.CreateDirectory(temporaryEntryPath);
string deletionEntryPath = Path.Combine(cacheRoot, "del-0123456789abcdef");
Directory.CreateDirectory(deletionEntryPath);
string unrelatedDirectoryPath = Path.Combine(cacheRoot, "unrelated");
Directory.CreateDirectory(unrelatedDirectoryPath);
File.WriteAllText(Path.Combine(unrelatedDirectoryPath, "keep.txt"), "keep");
string unrelatedFilePath = Path.Combine(cacheRoot, "unrelated.txt");
File.WriteAllText(unrelatedFilePath, "keep");
// Act
TranscodingCachePaths.ClearCacheEntries(cacheRoot, CancellationToken.None);
// Assert
Assert.True(Directory.Exists(cacheRoot));
Assert.False(Directory.Exists(cacheEntryPath));
Assert.False(Directory.Exists(temporaryEntryPath));
Assert.False(Directory.Exists(deletionEntryPath));
Assert.True(Directory.Exists(unrelatedDirectoryPath));
Assert.True(File.Exists(Path.Combine(unrelatedDirectoryPath, "keep.txt")));
Assert.True(File.Exists(unrelatedFilePath));
}
[Fact]
public void ClearCacheEntries_WhenACacheEntryIsASymbolicLink_ShouldDeleteTheLinkAndKeepItsTarget()
{
// Arrange
string targetPath = Path.Combine(_temporaryDirectory, "link-target");
Directory.CreateDirectory(targetPath);
File.WriteAllText(Path.Combine(targetPath, "keep.txt"), "keep");
string cacheRoot = Path.Combine(_temporaryDirectory, "link-cache");
Directory.CreateDirectory(cacheRoot);
string linkPath = Path.Combine(cacheRoot, CreateCacheId());
if (!TryCreateJunction(linkPath, targetPath))
{
// The environment does not support creating reparse points.
return;
}
Assert.NotNull(new DirectoryInfo(linkPath).LinkTarget);
// Act
TranscodingCachePaths.ClearCacheEntries(cacheRoot, CancellationToken.None);
// Assert
Assert.False(Directory.Exists(linkPath));
Assert.True(Directory.Exists(targetPath));
Assert.True(File.Exists(Path.Combine(targetPath, "keep.txt")));
}
[Fact]
public void EnsureDirectoryExists_WhenTheDirectoryDoesNotExist_ShouldCreateItAndMarkIt()
{
// Arrange
string directoryPath = Path.Combine(_temporaryDirectory, "created-cache");
// Act
TranscodingCachePaths.EnsureDirectoryExists(directoryPath);
// Assert
Assert.True(Directory.Exists(directoryPath));
Assert.True(TranscodingCachePaths.HasCacheMarker(directoryPath));
}
[Fact]
public void EnsureDirectoryExists_WhenTheDirectoryExistsWithoutAMarker_ShouldNotMarkIt()
{
// Arrange
string directoryPath = Path.Combine(_temporaryDirectory, "existing-cache");
Directory.CreateDirectory(directoryPath);
// Act
TranscodingCachePaths.EnsureDirectoryExists(directoryPath);
// Assert
Assert.True(Directory.Exists(directoryPath));
Assert.False(TranscodingCachePaths.HasCacheMarker(directoryPath));
}
[Fact]
public void TryDeleteDirectory_WhenTheDirectoryExists_ShouldDeleteItAndReturnTrue()
{
// Arrange
string directoryPath = Path.Combine(_temporaryDirectory, "deletable-cache");
Directory.CreateDirectory(Path.Combine(directoryPath, "nested"));
File.WriteAllBytes(Path.Combine(directoryPath, "nested", "segment.m4s"), new byte[8]);
// Act
bool result = TranscodingCachePaths.TryDeleteDirectory(directoryPath);
// Assert
Assert.True(result);
Assert.False(Directory.Exists(directoryPath));
}
[Fact]
public void TryDeleteDirectory_WhenTheDirectoryDoesNotExist_ShouldReturnTrue()
{
// Arrange
string directoryPath = Path.Combine(_temporaryDirectory, "absent-cache");
// Act
bool result = TranscodingCachePaths.TryDeleteDirectory(directoryPath);
// Assert
Assert.True(result);
}
[Fact]
public void TryDeleteDirectory_WhenTheDirectoryContainsAnOpenFile_ShouldReportWhetherThePlatformDeletedIt()
{
// Arrange
string directoryPath = Path.Combine(_temporaryDirectory, "open-file-cache");
Directory.CreateDirectory(directoryPath);
string openFilePath = Path.Combine(directoryPath, "open.bin");
File.WriteAllBytes(openFilePath, new byte[8]);
// Act
bool result;
using (FileStream openStream = new(openFilePath, FileMode.Open, FileAccess.Read, FileShare.None))
result = TranscodingCachePaths.TryDeleteDirectory(directoryPath);
// Assert
if (OperatingSystem.IsWindows())
{
// Windows refuses to delete a file that another handle holds without delete sharing.
Assert.False(result);
Assert.True(Directory.Exists(directoryPath));
Assert.True(File.Exists(openFilePath));
}
else
{
// Unix-like platforms allow deleting a file that is still open.
Assert.True(result);
Assert.False(Directory.Exists(directoryPath));
}
}
[Fact]
public void RestrictPermissions_WhenTheDirectoryIsASymbolicLink_ShouldThrowIOException()
{
// Arrange
string targetPath = Path.Combine(_temporaryDirectory, "permissions-target");
Directory.CreateDirectory(targetPath);
string linkPath = Path.Combine(_temporaryDirectory, "permissions-link");
if (!TryCreateJunction(linkPath, targetPath))
{
// The environment does not support creating reparse points.
return;
}
Assert.NotNull(new DirectoryInfo(linkPath).LinkTarget);
// Act
IOException exception = Assert.Throws<IOException>(() => TranscodingCachePaths.RestrictPermissions(linkPath));
// Assert
Assert.Contains("symbolic link", exception.Message, StringComparison.OrdinalIgnoreCase);
}
[Fact]
public void RestrictPermissions_WhenTheDirectoryIsNotASymbolicLink_ShouldNotThrow()
{
// Arrange
string directoryPath = Path.Combine(_temporaryDirectory, "plain-cache");
Directory.CreateDirectory(directoryPath);
// Act
Exception? exception = Record.Exception(() => TranscodingCachePaths.RestrictPermissions(directoryPath));
// Assert
Assert.Null(exception);
}
/// <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(_temporaryDirectory))
Directory.Delete(_temporaryDirectory, recursive: true);
}
catch (Exception exception) when (exception is IOException or UnauthorizedAccessException)
{
// A symbolic link may keep a target alive on some platforms; the directory is under the process temporary directory.
}
GC.SuppressFinalize(this);
}
}
@@ -0,0 +1,738 @@
#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);
Thread.Sleep(200);
// Act
_sut.Touch(cacheId, TimeSpan.Zero);
bool result = _sut.TryReserve(80, 100, TimeSpan.FromMilliseconds(100), 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,255 @@
#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>>();
_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_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,199 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Infrastructure.Common.Models.DTO.MediaLibrary.AudioLibrary.MusicLibrary.Playback;
using Lumina.Infrastructure.Core.MediaLibrary.AudioLibrary.MusicLibrary.Playback;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
#endregion
namespace Lumina.Infrastructure.UnitTests.Core.MediaLibrary.AudioLibrary.MusicLibrary.Playback;
/// <summary>
/// Contains unit tests for the <see cref="PlaybackFormatCatalog"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class PlaybackFormatCatalogTests
{
[Fact]
public void Formats_WhenRead_ShouldExposeTheDocumentedCanonicalContainerAndCodecPairsInPreferenceOrder()
{
// Arrange
(string Container, string Codec)[] expectedPairs =
[
("MP4", "AAC"), // the preferred container of the preferred codec
("AAC", "AAC"), // the second container of the preferred codec
("OGG", "OPUS"), // the preferred lossy codec after AAC
("MP3", "MP3"), // the compatibility codec
("OGG", "VORBIS"), // the second lossy codec in OGG
("FLAC", "FLAC"), // the lossless codec
("WAV", "PCM") // the uncompressed codec
];
// Act
IReadOnlyList<NormalizedAudioFormatDto> result = PlaybackFormatCatalog.Formats;
// Assert
Assert.Equal(expectedPairs, result.Select(format => (format.Container, format.Codec)));
}
[Fact]
public void TranscodeCodecPreference_WhenRead_ShouldListEachCodecOnceInOrderOfFirstAppearanceInFormats()
{
// Arrange
List<string> expectedCodecs = [];
foreach (NormalizedAudioFormatDto format in PlaybackFormatCatalog.Formats)
if (!expectedCodecs.Contains(format.Codec, StringComparer.OrdinalIgnoreCase))
expectedCodecs.Add(format.Codec);
// Act
IReadOnlyList<string> result = PlaybackFormatCatalog.TranscodeCodecPreference;
// Assert
Assert.Equal(expectedCodecs, result);
Assert.Equal(["AAC", "OPUS", "MP3", "VORBIS", "FLAC", "PCM"], result);
Assert.Equal(result.Count, result.Distinct(StringComparer.OrdinalIgnoreCase).Count());
}
[Fact]
public void ProducibleContainersByCodec_WhenRead_ShouldGroupTheContainersPerCodecInCatalogOrder()
{
// Arrange
Dictionary<string, List<string>> expectedContainersByCodec = new(StringComparer.OrdinalIgnoreCase);
foreach (NormalizedAudioFormatDto format in PlaybackFormatCatalog.Formats)
{
if (!expectedContainersByCodec.TryGetValue(format.Codec, out List<string>? containers))
{
containers = [];
expectedContainersByCodec[format.Codec] = containers;
}
containers.Add(format.Container);
}
// Act
IReadOnlyDictionary<string, IReadOnlyList<string>> result = PlaybackFormatCatalog.ProducibleContainersByCodec;
// Assert
Assert.Equal(expectedContainersByCodec.Count, result.Count);
foreach (KeyValuePair<string, List<string>> expectedEntry in expectedContainersByCodec)
{
Assert.True(result.TryGetValue(expectedEntry.Key, out IReadOnlyList<string>? containers));
Assert.Equal(expectedEntry.Value, containers);
}
Assert.Equal(["MP4", "AAC"], result["AAC"]); // the preferred codec has two producible containers, in preference order
Assert.Equal(["OGG"], result["OPUS"]);
Assert.Equal(["OGG"], result["VORBIS"]);
Assert.Equal(["MP3"], result["MP3"]);
Assert.Equal(["FLAC"], result["FLAC"]);
Assert.Equal(["WAV"], result["PCM"]);
}
[Fact]
public void ProducibleContainersByCodec_WhenRead_ShouldNotRepeatAContainerWithinACodec()
{
// Act
IReadOnlyDictionary<string, IReadOnlyList<string>> result = PlaybackFormatCatalog.ProducibleContainersByCodec;
// Assert
foreach (IReadOnlyList<string> containers in result.Values)
Assert.Equal(containers.Count, containers.Distinct(StringComparer.OrdinalIgnoreCase).Count());
}
[Fact]
public void ProducibleContainersByCodec_WhenRead_ShouldOnlyContainPairsThatExistInTheCatalog()
{
// Act
IReadOnlyDictionary<string, IReadOnlyList<string>> result = PlaybackFormatCatalog.ProducibleContainersByCodec;
// Assert
foreach (KeyValuePair<string, IReadOnlyList<string>> entry in result)
foreach (string container in entry.Value)
Assert.Contains(PlaybackFormatCatalog.Formats, format =>
string.Equals(format.Codec, entry.Key, StringComparison.OrdinalIgnoreCase) &&
string.Equals(format.Container, container, StringComparison.OrdinalIgnoreCase));
}
[Fact]
public void FormatsByPair_WhenRead_ShouldContainExactlyOneEntryPerCatalogFormat()
{
// Act
IReadOnlyDictionary<string, NormalizedAudioFormatDto> result = PlaybackFormatCatalog.FormatsByPair;
// Assert
Assert.Equal(PlaybackFormatCatalog.Formats.Count, result.Count);
Assert.All(PlaybackFormatCatalog.Formats, format =>
{
string pairKey = PlaybackFormatCatalog.BuildPairKey(format.Container, format.Codec);
Assert.True(result.TryGetValue(pairKey, out NormalizedAudioFormatDto? indexedFormat));
Assert.Equal(format, indexedFormat);
});
}
[Theory]
[InlineData("mp4/aac", "MP4", "AAC")] // the canonical pair in lower case
[InlineData("Mp4/Aac", "MP4", "AAC")] // the canonical pair in mixed case
[InlineData("aac/aac", "AAC", "AAC")] // the second format in the catalog, in lower case
public void FormatsByPair_WhenLookedUpWithDifferentCasing_ShouldReturnTheCatalogFormat(string pairKey, string expectedContainer, string expectedCodec)
{
// Act
bool found = PlaybackFormatCatalog.FormatsByPair.TryGetValue(pairKey, out NormalizedAudioFormatDto? result);
// Assert
Assert.True(found);
Assert.NotNull(result);
Assert.Equal(expectedContainer, result.Container);
Assert.Equal(expectedCodec, result.Codec);
}
[Fact]
public void BuildPairKey_WhenTheInputsArePaddedAndDifferentlyCased_ShouldTrimAndUppercaseThem()
{
// Act
string result = PlaybackFormatCatalog.BuildPairKey(" mp4 ", "\taAc ");
// Assert
Assert.Equal("MP4/AAC", result);
}
[Fact]
public void BuildPairKey_WhenTheInputsDifferOnlyInCasingAndPadding_ShouldProduceTheSameKey()
{
// Act
string firstResult = PlaybackFormatCatalog.BuildPairKey("mp4", "aac");
string secondResult = PlaybackFormatCatalog.BuildPairKey(" MP4 ", " AAC ");
// Assert
Assert.Equal(firstResult, secondResult);
}
[Theory]
[InlineData(null, null, "/")] // both parts are absent
[InlineData("", "", "/")] // both parts are empty
[InlineData(" ", " ", "/")] // both parts are white space
[InlineData(null, "aac", "/AAC")] // only the container is absent
[InlineData("mp4", null, "MP4/")] // only the codec is absent
public void BuildPairKey_WhenAContainerOrCodecIsNullOrEmpty_ShouldProduceTheSlashSeparatedFormWithoutThrowing(string? container, string? codec, string expectedKey)
{
// Act
string result = PlaybackFormatCatalog.BuildPairKey(container!, codec!);
// Assert
Assert.Equal(expectedKey, result);
}
[Fact]
public void Formats_WhenRead_ShouldExposeANonEmptyMuxerALeadingDotExtensionAndANonEmptyEncoderForEveryFormat()
{
// Act
IReadOnlyList<NormalizedAudioFormatDto> result = PlaybackFormatCatalog.Formats;
// Assert
Assert.All(result, format =>
{
Assert.False(string.IsNullOrWhiteSpace(format.MuxerName));
Assert.StartsWith(".", format.FileExtension, StringComparison.Ordinal);
Assert.True(format.FileExtension.Length > 1);
Assert.False(string.IsNullOrWhiteSpace(format.EncoderName));
});
}
}
@@ -0,0 +1,141 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Infrastructure.Core.MediaLibrary.AudioLibrary.MusicLibrary.Playback;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
#endregion
namespace Lumina.Infrastructure.UnitTests.Core.MediaLibrary.AudioLibrary.MusicLibrary.Playback;
/// <summary>
/// Contains unit tests for the <see cref="TranscodingToolchainStatus"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class TranscodingToolchainStatusTests
{
private readonly TranscodingToolchainStatus _sut;
private readonly IReadOnlyList<string> _catalogEncoderNames;
/// <summary>
/// Initializes a new instance of the <see cref="TranscodingToolchainStatusTests"/> class.
/// </summary>
public TranscodingToolchainStatusTests()
{
_sut = new TranscodingToolchainStatus();
_catalogEncoderNames = [.. PlaybackFormatCatalog.Formats.Select(format => format.EncoderName).Distinct(StringComparer.OrdinalIgnoreCase)];
}
[Fact]
public void IsTranscoderAvailable_WhenTheStatusIsFresh_ShouldReturnTrue()
{
// Act
bool result = _sut.IsTranscoderAvailable;
// Assert
Assert.True(result);
}
[Fact]
public void IsEncoderAvailable_WhenTheStatusIsFresh_ShouldReturnTrueForEveryCatalogEncoder()
{
// Act
IReadOnlyList<bool> results = [.. _catalogEncoderNames.Select(_sut.IsEncoderAvailable)];
// Assert
Assert.All(results, result => Assert.True(result));
}
[Fact]
public void RecordUnavailable_WhenCalled_ShouldReportTheTranscoderAndEveryCatalogEncoderUnavailable()
{
// Act
_sut.RecordUnavailable();
// Assert
Assert.False(_sut.IsTranscoderAvailable);
Assert.All(_catalogEncoderNames, encoderName => Assert.False(_sut.IsEncoderAvailable(encoderName)));
}
[Fact]
public void RecordMissingEncoders_WhenCalled_ShouldKeepTheTranscoderAvailableAndReportOnlyTheListedEncodersUnavailable()
{
// Arrange
string missingEncoderName = _catalogEncoderNames[0];
string availableEncoderName = _catalogEncoderNames[1];
// Act
_sut.RecordMissingEncoders([missingEncoderName]);
// Assert
Assert.True(_sut.IsTranscoderAvailable);
Assert.False(_sut.IsEncoderAvailable(missingEncoderName));
Assert.True(_sut.IsEncoderAvailable(availableEncoderName));
}
[Theory]
[InlineData("AAC")] // an encoder name in upper case
[InlineData("Aac")] // an encoder name in mixed case
public void RecordMissingEncoders_WhenTheNameDiffersInCase_ShouldReportTheEncoderUnavailable(string missingEncoderName)
{
// Act
_sut.RecordMissingEncoders([missingEncoderName]);
// Assert
Assert.True(_sut.IsTranscoderAvailable);
Assert.False(_sut.IsEncoderAvailable("aac"));
}
[Fact]
public void RecordMissingEncoders_WhenCalledTwice_ShouldReplaceThePreviousMissingSetInsteadOfAccumulatingIt()
{
// Act
_sut.RecordMissingEncoders(["aac"]);
_sut.RecordMissingEncoders(["libopus"]);
// Assert
Assert.True(_sut.IsTranscoderAvailable);
Assert.True(_sut.IsEncoderAvailable("aac"));
Assert.False(_sut.IsEncoderAvailable("libopus"));
}
[Fact]
public void RecordMissingEncoders_WhenTheListIsEmpty_ShouldKeepEveryCatalogEncoderAvailable()
{
// Act
_sut.RecordMissingEncoders([]);
// Assert
Assert.True(_sut.IsTranscoderAvailable);
Assert.All(_catalogEncoderNames, encoderName => Assert.True(_sut.IsEncoderAvailable(encoderName)));
}
[Fact]
public void RecordAvailable_WhenTheTranscoderWasUnavailable_ShouldRestoreTheTranscoderAndEveryCatalogEncoder()
{
// Arrange
_sut.RecordUnavailable();
// Act
_sut.RecordAvailable();
// Assert
Assert.True(_sut.IsTranscoderAvailable);
Assert.All(_catalogEncoderNames, encoderName => Assert.True(_sut.IsEncoderAvailable(encoderName)));
}
[Fact]
public void RecordAvailable_WhenEncodersWereMissing_ShouldClearTheMissingSet()
{
// Arrange
_sut.RecordMissingEncoders(["aac", "libopus"]);
// Act
_sut.RecordAvailable();
// Assert
Assert.True(_sut.IsTranscoderAvailable);
Assert.True(_sut.IsEncoderAvailable("aac"));
Assert.True(_sut.IsEncoderAvailable("libopus"));
}
}