Covers the SSD content setting with tests

Adds domain, mapping, endpoint, persistence, discovery, and hashing coverage, including parallel and sequential read behavior.
This commit is contained in:
BinaryAlley committed 2026-10-30 22:40:41 +02:00
1 parent fc800afe03
commit 45c1d1bd44
21 files changed
+354 -22

No files matched your search

@@ -33,6 +33,7 @@ public class LibraryEntityFixture
/// <param name="canDownloadMetadataFromWeb">Whether the media library should download metadata from the web or not.</param>
/// <param name="shouldSaveMetadataInMediaDirectories">Whether the metadata should be saved in the media directories or not.</param>
/// <param name="shouldSkipUnchangedDirectoriesDuringScan">Whether unchanged directories should be skipped during a scan or not.</param>
/// <param name="isContentOnSsd">Whether the content of the media library is stored on a solid state drive.</param>
/// <param name="shouldTrackConsumptionProgress">Whether the consumption progress of the media library items is tracked.</param>
/// <param name="completionThresholdPercentage">The percentage of a media library item that must be consumed for its session to be considered completed.</param>
/// <param name="metadataProvidersConfigurationFingerprint">Optional. The fingerprint of the metadata provider configuration of the media library.</param>
@@ -52,6 +53,7 @@ public class LibraryEntityFixture
bool canDownloadMetadataFromWeb = true,
bool shouldSaveMetadataInMediaDirectories = true,
bool shouldSkipUnchangedDirectoriesDuringScan = false,
bool isContentOnSsd = false,
bool shouldTrackConsumptionProgress = false,
int? completionThresholdPercentage = null,
string? metadataProvidersConfigurationFingerprint = null,
@@ -75,6 +77,7 @@ public class LibraryEntityFixture
CanDownloadMetadataFromWeb = canDownloadMetadataFromWeb,
ShouldSaveMetadataInMediaDirectories = shouldSaveMetadataInMediaDirectories,
ShouldSkipUnchangedDirectoriesDuringScan = shouldSkipUnchangedDirectoriesDuringScan,
IsContentOnSsd = isContentOnSsd,
ShouldTrackConsumptionProgress = shouldTrackConsumptionProgress,
CompletionThresholdPercentage = completionThresholdPercentage,
MetadataProvidersConfigurationFingerprint = metadataProvidersConfigurationFingerprint,
@@ -28,6 +28,7 @@ public class AddLibraryCommandFixture
/// <param name="canDownloadMetadataFromWeb">Whether the media library should download metadata from the web or not.</param>
/// <param name="shouldSaveMetadataInMediaDirectories">Whether the metadata should be saved in the media directories or not.</param>
/// <param name="shouldSkipUnchangedDirectoriesDuringScan">Whether unchanged directories should be skipped during a scan or not.</param>
/// <param name="isContentOnSsd">Whether the content of the media library is stored on a solid state drive.</param>
/// <param name="shouldTrackConsumptionProgress">Optional. Whether the consumption progress of the media library items should be tracked, or not.</param>
/// <param name="completionThresholdPercentage">Optional. The percentage of a media library item that must be consumed for its session to be considered completed.</param>
/// <param name="pathTemplateParts">Optional. The ordered parts of the path template of the media library.</param>
@@ -42,6 +43,7 @@ public class AddLibraryCommandFixture
bool canDownloadMetadataFromWeb = true,
bool shouldSaveMetadataInMediaDirectories = true,
bool shouldSkipUnchangedDirectoriesDuringScan = false,
bool isContentOnSsd = false,
bool? shouldTrackConsumptionProgress = null,
int? completionThresholdPercentage = null,
LibraryPathTemplatePartDto[]? pathTemplateParts = null)
@@ -57,6 +59,7 @@ public class AddLibraryCommandFixture
true,
true,
false,
false,
shouldTrackConsumptionProgress,
completionThresholdPercentage,
null
@@ -70,6 +73,7 @@ public class AddLibraryCommandFixture
.RuleFor(x => x.CanDownloadMetadataFromWeb, canDownloadMetadataFromWeb)
.RuleFor(x => x.ShouldSaveMetadataInMediaDirectories, shouldSaveMetadataInMediaDirectories)
.RuleFor(x => x.ShouldSkipUnchangedDirectoriesDuringScan, shouldSkipUnchangedDirectoriesDuringScan)
.RuleFor(x => x.IsContentOnSsd, isContentOnSsd)
.RuleFor(x => x.PathTemplateParts, pathTemplateParts)
.Generate();
}
@@ -31,6 +31,7 @@ public class UpdateLibraryCommandFixture
/// <param name="canDownloadMetadataFromWeb">Whether the media library should download metadata from the web or not.</param>
/// <param name="shouldSaveMetadataInMediaDirectories">Whether the metadata should be saved in the media directories or not.</param>
/// <param name="shouldSkipUnchangedDirectoriesDuringScan">Whether unchanged directories should be skipped during a scan or not.</param>
/// <param name="isContentOnSsd">Whether the content of the media library is stored on a solid state drive.</param>
/// <param name="shouldTrackConsumptionProgress">Optional. Whether the consumption progress of the media library items should be tracked, or not.</param>
/// <param name="completionThresholdPercentage">Optional. The percentage of a media library item that must be consumed for its session to be considered completed.</param>
/// <param name="pathTemplateParts">Optional. The ordered parts of the path template of the media library.</param>
@@ -47,6 +48,7 @@ public class UpdateLibraryCommandFixture
bool canDownloadMetadataFromWeb = true,
bool shouldSaveMetadataInMediaDirectories = true,
bool shouldSkipUnchangedDirectoriesDuringScan = false,
bool isContentOnSsd = false,
bool? shouldTrackConsumptionProgress = null,
int? completionThresholdPercentage = null,
LibraryPathTemplatePartDto[]? pathTemplateParts = null)
@@ -64,6 +66,7 @@ public class UpdateLibraryCommandFixture
true,
true,
false,
false,
shouldTrackConsumptionProgress,
completionThresholdPercentage,
null
@@ -79,6 +82,7 @@ public class UpdateLibraryCommandFixture
.RuleFor(x => x.CanDownloadMetadataFromWeb, canDownloadMetadataFromWeb)
.RuleFor(x => x.ShouldSaveMetadataInMediaDirectories, shouldSaveMetadataInMediaDirectories)
.RuleFor(x => x.ShouldSkipUnchangedDirectoriesDuringScan, shouldSkipUnchangedDirectoriesDuringScan)
.RuleFor(x => x.IsContentOnSsd, isContentOnSsd)
.RuleFor(x => x.PathTemplateParts, pathTemplateParts)
.Generate();
}
@@ -28,6 +28,7 @@ public class AddLibraryRequestFixture
/// <param name="canDownloadMetadataFromWeb">Optional. Whether metadata should be downloaded from the web.</param>
/// <param name="shouldSaveMetadataInMediaDirectories">Optional. Whether metadata should be saved in the media directories.</param>
/// <param name="shouldSkipUnchangedDirectoriesDuringScan">Optional. Whether unchanged directories should be skipped during scan.</param>
/// <param name="isContentOnSsd">Optional. Whether the content of the media library is stored on a solid state drive.</param>
/// <param name="shouldTrackConsumptionProgress">Optional. Whether the consumption progress of the media library items should be tracked, or not.</param>
/// <param name="completionThresholdPercentage">Optional. The percentage of a media library item that must be consumed for its session to be considered completed.</param>
/// <param name="pathTemplateParts">Optional. The ordered parts of the path template of the media library.</param>
@@ -42,6 +43,7 @@ public class AddLibraryRequestFixture
bool? canDownloadMetadataFromWeb = null,
bool? shouldSaveMetadataInMediaDirectories = null,
bool? shouldSkipUnchangedDirectoriesDuringScan = null,
bool? isContentOnSsd = null,
bool? shouldTrackConsumptionProgress = null,
int? completionThresholdPercentage = null,
LibraryPathTemplatePartRequest[]? pathTemplateParts = null)
@@ -56,6 +58,7 @@ public class AddLibraryRequestFixture
canDownloadMetadataFromWeb ?? _faker.Random.Bool(),
shouldSaveMetadataInMediaDirectories ?? _faker.Random.Bool(),
shouldSkipUnchangedDirectoriesDuringScan ?? _faker.Random.Bool(),
isContentOnSsd ?? false,
shouldTrackConsumptionProgress,
completionThresholdPercentage,
pathTemplateParts
@@ -31,6 +31,7 @@ public class UpdateLibraryRequestFixture
/// <param name="canDownloadMetadataFromWeb">Optional. Whether metadata should be downloaded from the web.</param>
/// <param name="shouldSaveMetadataInMediaDirectories">Optional. Whether metadata should be saved in the media directories.</param>
/// <param name="shouldSkipUnchangedDirectoriesDuringScan">Optional. Whether unchanged directories should be skipped during scan.</param>
/// <param name="isContentOnSsd">Optional. Whether the content of the media library is stored on a solid state drive.</param>
/// <param name="shouldTrackConsumptionProgress">Optional. Whether the consumption progress of the media library items should be tracked, or not.</param>
/// <param name="completionThresholdPercentage">Optional. The percentage of a media library item that must be consumed for its session to be considered completed.</param>
/// <param name="pathTemplateParts">Optional. The ordered parts of the path template of the media library.</param>
@@ -47,6 +48,7 @@ public class UpdateLibraryRequestFixture
bool? canDownloadMetadataFromWeb = null,
bool? shouldSaveMetadataInMediaDirectories = null,
bool? shouldSkipUnchangedDirectoriesDuringScan = null,
bool? isContentOnSsd = null,
bool? shouldTrackConsumptionProgress = null,
int? completionThresholdPercentage = null,
LibraryPathTemplatePartRequest[]? pathTemplateParts = null)
@@ -63,6 +65,7 @@ public class UpdateLibraryRequestFixture
canDownloadMetadataFromWeb ?? _faker.Random.Bool(),
shouldSaveMetadataInMediaDirectories ?? _faker.Random.Bool(),
shouldSkipUnchangedDirectoriesDuringScan ?? _faker.Random.Bool(),
isContentOnSsd ?? false,
shouldTrackConsumptionProgress,
completionThresholdPercentage,
pathTemplateParts
@@ -32,6 +32,7 @@ public class LibraryResponseFixture
/// <param name="canDownloadMetadataFromWeb">Optional. Whether metadata should be downloaded from the web.</param>
/// <param name="shouldSaveMetadataInMediaDirectories">Optional. Whether metadata should be saved in the media directories.</param>
/// <param name="shouldSkipUnchangedDirectoriesDuringScan">Optional. Whether unchanged directories should be skipped during scan.</param>
/// <param name="isContentOnSsd">Optional. Whether the content of the media library is stored on a solid state drive.</param>
/// <param name="shouldTrackConsumptionProgress">Optional. Whether the consumption progress of the media library items is tracked.</param>
/// <param name="completionThresholdPercentage">Optional. The percentage of a media library item that must be consumed for its session to be considered completed.</param>
/// <param name="pathTemplateParts">Optional. The ordered parts of the path template of the media library.</param>
@@ -50,6 +51,7 @@ public class LibraryResponseFixture
bool? canDownloadMetadataFromWeb = null,
bool? shouldSaveMetadataInMediaDirectories = null,
bool? shouldSkipUnchangedDirectoriesDuringScan = null,
bool? isContentOnSsd = null,
bool? shouldTrackConsumptionProgress = null,
int? completionThresholdPercentage = null,
List<LibraryPathTemplatePartResponse>? pathTemplateParts = null,
@@ -70,6 +72,7 @@ public class LibraryResponseFixture
canDownloadMetadataFromWeb ?? _faker.Random.Bool(),
shouldSaveMetadataInMediaDirectories ?? _faker.Random.Bool(),
shouldSkipUnchangedDirectoriesDuringScan ?? _faker.Random.Bool(),
isContentOnSsd ?? false,
resolvedShouldTrackConsumptionProgress,
resolvedCompletionThresholdPercentage,
pathTemplateParts ?? [],
@@ -43,6 +43,7 @@ public class LibraryFixture
/// <param name="canDownloadMetadataFromWeb">Whether metadata download from the web is enabled.</param>
/// <param name="shouldSaveMetadataInMediaDirectories">Whether metadata should be saved in the media directories.</param>
/// <param name="shouldSkipUnchangedDirectoriesDuringScan">Whether unchanged directories should be skipped during scan.</param>
/// <param name="isContentOnSsd">Whether the content of the library is stored on a solid state drive.</param>
/// <param name="consumptionSettings">Optional. The consumption settings of the library.</param>
/// <param name="scanIds">Optional. The scan Ids associated with the library.</param>
/// <param name="pathTemplate">Optional. The path template of the library.</param>
@@ -60,6 +61,7 @@ public class LibraryFixture
bool canDownloadMetadataFromWeb = true,
bool shouldSaveMetadataInMediaDirectories = false,
bool shouldSkipUnchangedDirectoriesDuringScan = false,
bool isContentOnSsd = false,
LibraryConsumptionSettings? consumptionSettings = null,
IEnumerable<Guid>? scanIds = null,
LibraryPathTemplate? pathTemplate = null,
@@ -91,6 +93,7 @@ public class LibraryFixture
canDownloadMetadataFromWeb,
shouldSaveMetadataInMediaDirectories,
shouldSkipUnchangedDirectoriesDuringScan,
isContentOnSsd,
resolvedConsumptionSettings,
pathTemplate ?? LibraryPathTemplate.Empty(),
resolvedScanIds
@@ -107,6 +110,7 @@ public class LibraryFixture
canDownloadMetadataFromWeb,
shouldSaveMetadataInMediaDirectories,
shouldSkipUnchangedDirectoriesDuringScan,
isContentOnSsd,
resolvedConsumptionSettings,
pathTemplate ?? LibraryPathTemplate.Empty(),
resolvedScanIds
@@ -148,6 +148,31 @@ public class LibraryRepositoryTests
Assert.Null(storedLibrary.CompletionThresholdPercentage);
}
[Fact]
public async Task InsertAsync_WhenLibraryContentIsOnSsd_ShouldPersistTheSetting()
{
// Arrange
using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-libraryrepo-insert-ssd-{Guid.NewGuid()};Mode=Memory;Cache=Shared");
anchorConnection.Open();
Guid userId = Guid.NewGuid();
DateTime utcNow = new(2025, 1, 1, 12, 0, 0, DateTimeKind.Utc);
using LuminaDbContext context = CreateAuditedContext(anchorConnection, userId, utcNow);
LibraryRepository sut = new(context);
context.Users.Add(_userEntityFixture.Create(id: userId));
LibraryEntity library = _libraryEntityFixture.Create(userId: userId, isContentOnSsd: true, contentLocations: []);
// Act
Result<Created> result = await sut.InsertAsync(library, CancellationToken.None);
await context.SaveChangesAsync();
// Assert
Assert.False(result.IsFailure);
Assert.Equal(Result.Created, result.Value);
LibraryEntity? storedLibrary = await context.Libraries.AsNoTracking().FirstOrDefaultAsync(candidate => candidate.Id == library.Id);
Assert.NotNull(storedLibrary);
Assert.True(storedLibrary!.IsContentOnSsd);
}
[Fact]
public async Task UpdateAsync_WhenConsumptionSettingsAreEnabled_ShouldPersistTheTrackingAndThreshold()
{
@@ -81,7 +81,7 @@ public class BooksFileSystemDiscoveryJobTests
_scanId = _scanIdFixture.Create();
_userId = _userIdFixture.Create();
_libraryId = _libraryIdFixture.Create();
_sut = new BooksFileSystemDiscoveryJob(_mockServiceScopeFactory)
_sut = new BooksFileSystemDiscoveryJob(_mockServiceScopeFactory, Substitute.For<Microsoft.Extensions.Logging.ILogger<BooksFileSystemDiscoveryJob>>())
{
ScanId = _scanId,
UserId = _userId,
@@ -105,7 +105,8 @@ public class BooksFileSystemDiscoveryJobTests
title: "Test Library",
libraryType: LibraryType.Book,
contentLocations: [temporaryLibraryDirectory.Path],
shouldSkipUnchangedDirectoriesDuringScan: false);
shouldSkipUnchangedDirectoriesDuringScan: false,
isContentOnSsd: true);
_mockLibraryRepository.GetByIdAsync(_libraryId.Value, cancellationToken: Arg.Any<CancellationToken>())
.Returns(Result.From<LibraryEntity?>(libraryEntity));
_mockStagingResultsRepository.InsertRangeAsync(Arg.Any<IReadOnlyCollection<LibraryScanStagingResultsEntity>>(), Arg.Any<CancellationToken>())
@@ -40,6 +40,7 @@ public class FileHashServiceTests
// Act
List<HashedFileSystemFileDto> result = await _sut.HashFilesAsync(
inputFiles,
shouldParallelizeReads: true,
() =>
{
callbackInvocationCount++;
@@ -66,7 +67,7 @@ public class FileHashServiceTests
List<HashedFileSystemFileDto> inputFiles = [_hashedFileSystemFileDtoFixture.Create(path: filePath, size: new FileInfo(filePath).Length, currentHash: 0, oldHash: 0, ticks: 0)];
// Act
List<HashedFileSystemFileDto> result = await _sut.HashFilesAsync(inputFiles, () => Task.CompletedTask, CancellationToken.None);
List<HashedFileSystemFileDto> result = await _sut.HashFilesAsync(inputFiles, shouldParallelizeReads: true, () => Task.CompletedTask, CancellationToken.None);
// Assert
HashedFileSystemFileDto hashedFile = Assert.Single(result);
@@ -83,10 +84,10 @@ public class FileHashServiceTests
List<HashedFileSystemFileDto> firstInputFiles = [_hashedFileSystemFileDtoFixture.Create(path: filePath, size: new FileInfo(filePath).Length, currentHash: 0, oldHash: 0, ticks: 0)];
// Act
List<HashedFileSystemFileDto> firstResult = await _sut.HashFilesAsync(firstInputFiles, () => Task.CompletedTask, CancellationToken.None);
List<HashedFileSystemFileDto> firstResult = await _sut.HashFilesAsync(firstInputFiles, shouldParallelizeReads: true, () => Task.CompletedTask, CancellationToken.None);
await File.WriteAllTextAsync(filePath, "changed content");
List<HashedFileSystemFileDto> secondInputFiles = [_hashedFileSystemFileDtoFixture.Create(path: filePath, size: new FileInfo(filePath).Length, currentHash: 0, oldHash: 0, ticks: 0)];
List<HashedFileSystemFileDto> secondResult = await _sut.HashFilesAsync(secondInputFiles, () => Task.CompletedTask, CancellationToken.None);
List<HashedFileSystemFileDto> secondResult = await _sut.HashFilesAsync(secondInputFiles, shouldParallelizeReads: true, () => Task.CompletedTask, CancellationToken.None);
// Assert
Assert.NotEqual(firstResult[0].CurrentHash, secondResult[0].CurrentHash);
@@ -100,7 +101,7 @@ public class FileHashServiceTests
List<HashedFileSystemFileDto> inputFiles = [_hashedFileSystemFileDtoFixture.Create(path: nonExistentFilePath, size: 100, currentHash: 0, oldHash: 0, ticks: 0)];
// Act
List<HashedFileSystemFileDto> result = await _sut.HashFilesAsync(inputFiles, () => Task.CompletedTask, CancellationToken.None);
List<HashedFileSystemFileDto> result = await _sut.HashFilesAsync(inputFiles, shouldParallelizeReads: true, () => Task.CompletedTask, CancellationToken.None);
// Assert
Assert.Empty(result);
@@ -119,7 +120,7 @@ public class FileHashServiceTests
];
// Act
List<HashedFileSystemFileDto> result = await _sut.HashFilesAsync(inputFiles, () => Task.CompletedTask, CancellationToken.None);
List<HashedFileSystemFileDto> result = await _sut.HashFilesAsync(inputFiles, shouldParallelizeReads: true, () => Task.CompletedTask, CancellationToken.None);
// Assert
HashedFileSystemFileDto hashedFile = Assert.Single(result);
@@ -127,6 +128,37 @@ public class FileHashServiceTests
Assert.NotEqual(0UL, hashedFile.CurrentHash);
}
[Fact]
public async Task HashFilesAsync_WhenReadsAreNotParallelized_ShouldHashAllFilesSequentially()
{
// Arrange
using TemporaryTestDirectory temporaryTestDirectory = new();
string filePath1 = temporaryTestDirectory.CreateFile("book1.pdf", "content of the first book");
string filePath2 = temporaryTestDirectory.CreateFile("book2.pdf", "content of the second book");
List<HashedFileSystemFileDto> inputFiles =
[
_hashedFileSystemFileDtoFixture.Create(path: filePath1, size: new FileInfo(filePath1).Length, currentHash: 0, oldHash: 0, ticks: 0),
_hashedFileSystemFileDtoFixture.Create(path: filePath2, size: new FileInfo(filePath2).Length, currentHash: 0, oldHash: 0, ticks: 0)
];
int callbackInvocationCount = 0;
// Act
List<HashedFileSystemFileDto> result = await _sut.HashFilesAsync(
inputFiles,
shouldParallelizeReads: false,
() =>
{
callbackInvocationCount++;
return Task.CompletedTask;
},
CancellationToken.None);
// Assert
Assert.Equal(2, result.Count);
Assert.Equal(2, callbackInvocationCount);
Assert.All(result, file => Assert.NotEqual(0UL, file.CurrentHash));
}
[Fact]
public async Task HashFilesAsync_WhenCancellationRequested_ShouldCancelOperation()
{
@@ -138,7 +170,7 @@ public class FileHashServiceTests
cancellationTokenSource.Cancel();
// Act
Task<List<HashedFileSystemFileDto>> operation = _sut.HashFilesAsync(inputFiles, () => Task.CompletedTask, cancellationTokenSource.Token);
Task<List<HashedFileSystemFileDto>> operation = _sut.HashFilesAsync(inputFiles, shouldParallelizeReads: true, () => Task.CompletedTask, cancellationTokenSource.Token);
// Assert
await Assert.ThrowsAnyAsync<OperationCanceledException>(() => operation);
@@ -182,7 +214,7 @@ public class FileHashServiceTests
List<HashedFileSystemFileDto> inputFiles = [_hashedFileSystemFileDtoFixture.Create(path: filePath, size: new FileInfo(filePath).Length, currentHash: 0, oldHash: 0, ticks: 0)];
// Act
List<HashedFileSystemFileDto> result = await _sut.HashFilesAsync(inputFiles, () => Task.CompletedTask, CancellationToken.None);
List<HashedFileSystemFileDto> result = await _sut.HashFilesAsync(inputFiles, shouldParallelizeReads: true, () => Task.CompletedTask, CancellationToken.None);
// Assert
HashedFileSystemFileDto hashedFile = Assert.Single(result);
@@ -32,6 +32,7 @@ public class AddMediaLibraryRequestMappingTests
canDownloadMetadataFromWeb: true,
shouldSaveMetadataInMediaDirectories: false,
shouldSkipUnchangedDirectoriesDuringScan: false,
isContentOnSsd: true,
shouldTrackConsumptionProgress: true,
completionThresholdPercentage: 90
);
@@ -49,6 +50,7 @@ public class AddMediaLibraryRequestMappingTests
Assert.Equal(request.IsLocked, result.IsLocked);
Assert.Equal(request.CanDownloadMetadataFromWeb, result.CanDownloadMetadataFromWeb);
Assert.Equal(request.ShouldSaveMetadataInMediaDirectories, result.ShouldSaveMetadataInMediaDirectories);
Assert.Equal(request.IsContentOnSsd, result.IsContentOnSsd);
Assert.Equal(request.ShouldTrackConsumptionProgress, result.ShouldTrackConsumptionProgress);
Assert.Equal(request.CompletionThresholdPercentage, result.CompletionThresholdPercentage);
}
@@ -32,7 +32,8 @@ public class LibraryEntityMappingTests
title: "My Library",
libraryType: LibraryType.Book,
contentLocations: ["C:/Books", "D:/Media/Books"],
coverImage: "D:/myPoster.jpg");
coverImage: "D:/myPoster.jpg",
isContentOnSsd: true);
// Act
LibraryResponse result = entity.ToResponse();
@@ -45,6 +46,7 @@ public class LibraryEntityMappingTests
Assert.Equal(entity.LibraryType, result.LibraryType);
Assert.Equal(entity.ContentLocations.Select(l => l.Path), result.ContentLocations);
Assert.Equal(entity.CoverImage, result.CoverImage);
Assert.Equal(entity.IsContentOnSsd, result.IsContentOnSsd);
Assert.Equal(entity.ShouldTrackConsumptionProgress, result.ShouldTrackConsumptionProgress);
Assert.Equal(entity.CompletionThresholdPercentage, result.CompletionThresholdPercentage);
Assert.Equal(entity.CreatedOnUtc, result.CreatedOnUtc);
@@ -188,6 +190,7 @@ public class LibraryEntityMappingTests
libraryType: LibraryType.Book,
contentLocations: ["C:/Books"],
coverImage: "D:/cover.jpg",
isContentOnSsd: true,
pathTemplateParts: [firstPart, secondPart]);
// Act
@@ -200,6 +203,7 @@ public class LibraryEntityMappingTests
Assert.Equal(entity.Title, result.Value.Title);
Assert.Equal(entity.LibraryType, result.Value.LibraryType);
Assert.Equal("D:/cover.jpg", result.Value.CoverImage.Value);
Assert.Equal(entity.IsContentOnSsd, result.Value.IsContentOnSsd);
Assert.Equal(entity.ShouldTrackConsumptionProgress, result.Value.ConsumptionSettings.ShouldTrackConsumptionProgress);
Assert.Equal(entity.CompletionThresholdPercentage, result.Value.ConsumptionSettings.CompletionThresholdPercentage.HasValue ? result.Value.ConsumptionSettings.CompletionThresholdPercentage.Value : null);
Assert.Equal(2, result.Value.PathTemplate.Parts.Count);
@@ -60,6 +60,7 @@ public class LibraryMappingTests
Assert.False(result.IsLocked);
Assert.True(result.CanDownloadMetadataFromWeb);
Assert.False(result.ShouldSaveMetadataInMediaDirectories);
Assert.Equal(library.IsContentOnSsd, result.IsContentOnSsd);
Assert.Equal(library.ConsumptionSettings.ShouldTrackConsumptionProgress, result.ShouldTrackConsumptionProgress);
Assert.Equal(library.ConsumptionSettings.CompletionThresholdPercentage.HasValue ? library.ConsumptionSettings.CompletionThresholdPercentage.Value : null, result.CompletionThresholdPercentage);
Assert.Equal(library.ScanIds.Select(scanId => scanId.Value), result.LibraryScans.Select(libraryScan => libraryScan.Id));
@@ -32,6 +32,7 @@ public class UpdateLibraryRequestMappingTests
canDownloadMetadataFromWeb: true,
shouldSaveMetadataInMediaDirectories: false,
shouldSkipUnchangedDirectoriesDuringScan: false,
isContentOnSsd: true,
shouldTrackConsumptionProgress: true,
completionThresholdPercentage: 90);
@@ -49,6 +50,7 @@ public class UpdateLibraryRequestMappingTests
Assert.Equal(request.CanDownloadMetadataFromWeb, result.CanDownloadMetadataFromWeb);
Assert.Equal(request.ShouldSaveMetadataInMediaDirectories, result.ShouldSaveMetadataInMediaDirectories);
Assert.Equal(request.ShouldSkipUnchangedDirectoriesDuringScan, result.ShouldSkipUnchangedDirectoriesDuringScan);
Assert.Equal(request.IsContentOnSsd, result.IsContentOnSsd);
Assert.Equal(request.ShouldTrackConsumptionProgress, result.ShouldTrackConsumptionProgress);
Assert.Equal(request.CompletionThresholdPercentage, result.CompletionThresholdPercentage);
}
@@ -62,6 +62,7 @@ public class LibraryConfigurationTests
IProperty downloadMetadataProperty = entityType.GetProperty(nameof(LibraryEntity.CanDownloadMetadataFromWeb));
IProperty shouldTrackConsumptionProgressProperty = entityType.GetProperty(nameof(LibraryEntity.ShouldTrackConsumptionProgress));
IProperty completionThresholdPercentageProperty = entityType.GetProperty(nameof(LibraryEntity.CompletionThresholdPercentage));
IProperty isContentOnSsdProperty = entityType.GetProperty(nameof(LibraryEntity.IsContentOnSsd));
// Assert
Assert.False(titleProperty.IsNullable);
@@ -76,6 +77,23 @@ public class LibraryConfigurationTests
Assert.Equal(typeof(int?), completionThresholdPercentageProperty.ClrType);
Assert.True(completionThresholdPercentageProperty.IsNullable);
Assert.Null(completionThresholdPercentageProperty.GetDefaultValue());
Assert.Equal(typeof(bool), isContentOnSsdProperty.ClrType);
Assert.False(isContentOnSsdProperty.IsNullable);
Assert.Equal(false, isContentOnSsdProperty.GetDefaultValue());
}
[Fact]
public void Configure_WhenApplied_ShouldConfigureSsdContentColumnOrder()
{
// Arrange
IEntityType entityType = DesignTimeModel.FindEntityType(typeof(LibraryEntity))!;
// Act
IProperty isContentOnSsdProperty = entityType.GetProperty(nameof(LibraryEntity.IsContentOnSsd));
// Assert
Assert.Equal(18, isContentOnSsdProperty.GetColumnOrder());
Assert.Equal(nameof(LibraryEntity.IsContentOnSsd), isContentOnSsdProperty.GetColumnName());
}
[Fact]
@@ -56,6 +56,7 @@ public class LibraryTests
canDownloadMetadataFromWeb: false,
shouldSaveMetadataInMediaDirectories: true,
shouldSkipUnchangedDirectoriesDuringScan: true,
isContentOnSsd: true,
consumptionSettings,
LibraryPathTemplate.Empty(),
scanIds);
@@ -73,6 +74,7 @@ public class LibraryTests
Assert.False(result.Value.CanDownloadMetadataFromWeb);
Assert.True(result.Value.ShouldSaveMetadataInMediaDirectories);
Assert.True(result.Value.ShouldSkipUnchangedDirectoriesDuringScan);
Assert.True(result.Value.IsContentOnSsd);
Assert.Equal(consumptionSettings, result.Value.ConsumptionSettings);
Assert.Equal(scanIds, result.Value.ScanIds);
}
@@ -97,6 +99,7 @@ public class LibraryTests
canDownloadMetadataFromWeb: true,
shouldSaveMetadataInMediaDirectories: false,
shouldSkipUnchangedDirectoriesDuringScan: false,
isContentOnSsd: false,
_libraryConsumptionSettingsFixture.Create(),
LibraryPathTemplate.Empty(),
scanIds);
@@ -125,6 +128,7 @@ public class LibraryTests
canDownloadMetadataFromWeb: true,
shouldSaveMetadataInMediaDirectories: false,
shouldSkipUnchangedDirectoriesDuringScan: false,
isContentOnSsd: false,
_libraryConsumptionSettingsFixture.Create(),
LibraryPathTemplate.Empty(),
[]);
@@ -162,6 +166,7 @@ public class LibraryTests
canDownloadMetadataFromWeb: true,
shouldSaveMetadataInMediaDirectories: false,
shouldSkipUnchangedDirectoriesDuringScan: false,
isContentOnSsd: false,
_libraryConsumptionSettingsFixture.Create(),
LibraryPathTemplate.Empty(),
[]);
@@ -191,6 +196,7 @@ public class LibraryTests
canDownloadMetadataFromWeb: true,
shouldSaveMetadataInMediaDirectories: false,
shouldSkipUnchangedDirectoriesDuringScan: false,
isContentOnSsd: false,
_libraryConsumptionSettingsFixture.Create(),
LibraryPathTemplate.Empty(),
[]);
@@ -19,10 +19,12 @@ using Lumina.Domain.Fixtures.Core.BoundedContexts.UserManagementBoundedContext.U
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
using Lumina.Infrastructure.Core.MediaLibrary.Management.Scanning.Jobs.Audio.Music;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using NSubstitute;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.IO;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
@@ -38,6 +40,7 @@ public class MusicFileSystemDiscoveryJobTests
{
private const string ROOT_PATH = @"C:\Music";
private const string AUDIO_FILE_PATH = @"C:\Music\song.mp3";
private const string SECOND_AUDIO_FILE_PATH = @"C:\Music\other.mp3";
private const string IMAGE_FILE_PATH = @"C:\Music\cover.jpg";
private readonly IServiceScopeFactory _mockServiceScopeFactory;
@@ -50,6 +53,7 @@ public class MusicFileSystemDiscoveryJobTests
private readonly IFileProviderService _mockFileProviderService;
private readonly IDirectoryProviderService _mockDirectoryProviderService;
private readonly IDomainEventPublisher _mockDomainEventPublisher;
private readonly ILogger<MusicFileSystemDiscoveryJob> _mockLogger;
private readonly MusicFileSystemDiscoveryJob _sut;
private readonly LibraryEntityFixture _libraryEntityFixture = new();
private readonly DirectoryScanFingerprintEntityFixture _directoryScanFingerprintEntityFixture = new();
@@ -101,7 +105,9 @@ public class MusicFileSystemDiscoveryJobTests
_libraryId = _libraryIdFixture.Create();
_scanId = _scanIdFixture.Create();
_userId = _userIdFixture.Create();
_sut = new MusicFileSystemDiscoveryJob(_mockServiceScopeFactory)
_mockLogger = Substitute.For<ILogger<MusicFileSystemDiscoveryJob>>();
_mockLogger.IsEnabled(Arg.Any<LogLevel>()).Returns(true);
_sut = new MusicFileSystemDiscoveryJob(_mockServiceScopeFactory, _mockLogger)
{
ScanId = _scanId,
UserId = _userId,
@@ -182,6 +188,45 @@ public class MusicFileSystemDiscoveryJobTests
Arg.Any<CancellationToken>());
}
[Fact]
public async Task ExecuteAsync_WhenTheLibraryIsOnSsd_ShouldReadInParallelAndSkipFilesThatBecomeInaccessible()
{
// Arrange
SetupLibrary(isContentOnSsd: true);
SetupDirectory(ROOT_PATH, files: [AUDIO_FILE_PATH, SECOND_AUDIO_FILE_PATH, IMAGE_FILE_PATH], subdirectories: []);
_mockFileProviderService.GetSize(Arg.Is<FileSystemPathId>(path => path.Path == AUDIO_FILE_PATH))
.Returns(_ => throw new IOException("The file vanished between enumeration and processing"));
_mockFileProviderService.GetSize(Arg.Is<FileSystemPathId>(path => path.Path == SECOND_AUDIO_FILE_PATH)).Returns(Result.From<long?>(1234L));
_mockFileProviderService.GetLastWriteTime(Arg.Is<FileSystemPathId>(path => path.Path == SECOND_AUDIO_FILE_PATH))
.Returns(Result.From(Optional<DateTime>.Some(new DateTime(2020, 1, 1, 0, 0, 0, DateTimeKind.Utc))));
// Act
await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None);
// Assert
// The sequential path does not catch per-file IO exceptions, so completing here proves the parallel path was taken.
Assert.Equal(LibraryScanJobStatus.Completed, _sut.Status);
await _mockStagingResultsRepository.Received(1).InsertRangeAsync(
Arg.Is<IReadOnlyCollection<LibraryScanStagingResultsEntity>>(entities => entities.Count == 1
&& entities.First().Path == SECOND_AUDIO_FILE_PATH
&& entities.First().Size == 1234
&& entities.First().LibraryScanId == _scanId.Value
&& entities.First().NeedsRehash),
Arg.Any<CancellationToken>());
_mockLogger.Received(1).Log(
LogLevel.Debug,
Arg.Any<EventId>(),
Arg.Is<object>(state => state.ToString()!.Contains("solid state drive", StringComparison.Ordinal)),
Arg.Any<Exception?>(),
Arg.Any<Func<object, Exception?, string>>());
_mockLogger.Received(1).Log(
LogLevel.Warning,
Arg.Any<EventId>(),
Arg.Is<object>(state => state.ToString()!.Contains(AUDIO_FILE_PATH, StringComparison.Ordinal)),
Arg.Any<IOException>(),
Arg.Any<Func<object, Exception?, string>>());
}
[Fact]
public async Task ExecuteAsync_WhenTheSubdirectoryHasAudioFiles_ShouldTraverseIntoIt()
{
@@ -301,6 +346,22 @@ public class MusicFileSystemDiscoveryJobTests
await _mockDomainEventPublisher.Received(1).PublishAsync(Arg.Is<LibraryScanFailedDomainEvent>(domainEvent => domainEvent.LibraryId == _libraryId), Arg.Any<CancellationToken>());
}
[Fact]
public async Task ExecuteAsync_WhenAFileMetadataReadThrowsAnUnexpectedException_ShouldMarkJobAsFailed()
{
// Arrange
SetupLibrary(isContentOnSsd: true);
SetupDirectory(ROOT_PATH, files: [AUDIO_FILE_PATH], subdirectories: []);
_mockFileProviderService.GetSize(Arg.Any<FileSystemPathId>()).Returns(_ => throw new InvalidOperationException("Unexpected defect"));
// Act
await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None);
// Assert
Assert.Equal(LibraryScanJobStatus.Failed, _sut.Status);
await _mockDomainEventPublisher.Received(1).PublishAsync(Arg.Is<LibraryScanFailedDomainEvent>(domainEvent => domainEvent.LibraryId == _libraryId), Arg.Any<CancellationToken>());
}
[Fact]
public async Task ExecuteAsync_WhenTheFingerprintUpsertFails_ShouldMarkJobAsFailed()
{
@@ -342,13 +403,15 @@ public class MusicFileSystemDiscoveryJobTests
/// Stubs the media library reader with a library whose single content location is the test root path.
/// </summary>
/// <param name="shouldSkipUnchangedDirectoriesDuringScan">Whether the library skips the directories that have not changed since the last scan.</param>
private void SetupLibrary(bool shouldSkipUnchangedDirectoriesDuringScan = false)
/// <param name="isContentOnSsd">Whether the content of the library is stored on a solid state drive.</param>
private void SetupLibrary(bool shouldSkipUnchangedDirectoriesDuringScan = false, bool isContentOnSsd = false)
{
LibraryEntity library = _libraryEntityFixture.Create(
id: _libraryId.Value,
libraryType: LibraryType.Music,
contentLocations: [ROOT_PATH],
shouldSkipUnchangedDirectoriesDuringScan: shouldSkipUnchangedDirectoriesDuringScan);
shouldSkipUnchangedDirectoriesDuringScan: shouldSkipUnchangedDirectoriesDuringScan,
isContentOnSsd: isContentOnSsd);
_mockLibraryRepository.GetByIdAsync(Arg.Any<Guid>(), cancellationToken: Arg.Any<CancellationToken>())
.Returns(Result.From<LibraryEntity?>(library));
}
@@ -1,4 +1,5 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management;
using Lumina.Application.Common.DataAccess.Repositories.MediaLibrary;
using Lumina.Application.Common.DataAccess.UoW;
using Lumina.Application.Common.Infrastructure.Models.DTO.MediaLibraryScanJobPayloads;
@@ -13,6 +14,7 @@ using Lumina.Domain.Core.BoundedContexts.UserManagementBoundedContext.UserAggreg
using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects;
using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects;
using Lumina.Domain.Fixtures.Core.BoundedContexts.UserManagementBoundedContext.UserAggregate.ValueObjects;
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management;
using Lumina.Application.Fixtures.Common.Infrastructure.Models.DTO.MediaLibraryScanJobPayloads;
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
using Lumina.Infrastructure.Core.MediaLibrary.Management.Scanning.Jobs.Common;
@@ -38,6 +40,7 @@ public class MediaLibraryScanHashJobTests
private readonly IServiceScope _mockServiceScope;
private readonly IServiceProvider _mockServiceProvider;
private readonly IUnitOfWork _mockUnitOfWork;
private readonly ILibraryRepository _mockLibraryRepository;
private readonly ILibraryScanStagingResultsRepository _mockStagingResultsRepository;
private readonly IDomainEventPublisher _mockDomainEventPublisher;
private readonly IFileHashService _mockFileHashService;
@@ -46,6 +49,7 @@ public class MediaLibraryScanHashJobTests
private readonly UserIdFixture _userIdFixture = new();
private readonly LibraryIdFixture _libraryIdFixture = new();
private readonly HashedFileSystemFileDtoFixture _hashedFileSystemFileDtoFixture = new();
private readonly LibraryEntityFixture _libraryEntityFixture = new();
private readonly ScanId _scanId;
private readonly UserId _userId;
private readonly LibraryId _libraryId;
@@ -63,7 +67,9 @@ public class MediaLibraryScanHashJobTests
_mockUnitOfWork = Substitute.For<IUnitOfWork>();
_mockUnitOfWork.SaveChangesAsync(Arg.Any<CancellationToken>()).Returns(Result.Success);
_mockLibraryRepository = Substitute.For<ILibraryRepository>();
_mockStagingResultsRepository = Substitute.For<ILibraryScanStagingResultsRepository>();
_mockUnitOfWork.LibraryRepository.Returns(_mockLibraryRepository);
_mockUnitOfWork.LibraryScanStagingResultsRepository.Returns(_mockStagingResultsRepository);
_mockServiceProvider.GetService(typeof(IUnitOfWork)).Returns(_mockUnitOfWork);
@@ -84,6 +90,9 @@ public class MediaLibraryScanHashJobTests
UserId = _userId,
LibraryId = _libraryId
};
_mockLibraryRepository.GetByIdAsync(_libraryId.Value, Arg.Any<bool>(), Arg.Any<bool>(), Arg.Any<CancellationToken>())
.Returns(Result.From<LibraryEntity?>(_libraryEntityFixture.Create(id: _libraryId.Value, userId: _userId.Value, isContentOnSsd: true)));
}
[Fact]
@@ -97,7 +106,7 @@ public class MediaLibraryScanHashJobTests
.Returns(
Result.From<IReadOnlyList<HashedFileSystemFileDto>>(filesToHash),
Result.From<IReadOnlyList<HashedFileSystemFileDto>>([]));
_mockFileHashService.HashFilesAsync(Arg.Any<IReadOnlyCollection<HashedFileSystemFileDto>>(), Arg.Any<Func<Task>>(), Arg.Any<CancellationToken>())
_mockFileHashService.HashFilesAsync(Arg.Any<IReadOnlyCollection<HashedFileSystemFileDto>>(), Arg.Any<bool>(), Arg.Any<Func<Task>>(), Arg.Any<CancellationToken>())
.Returns(callInfo => Task.FromResult(callInfo.Arg<IReadOnlyCollection<HashedFileSystemFileDto>>()
.Select(file => file with { CurrentHash = 42UL })
.ToList()));
@@ -111,6 +120,7 @@ public class MediaLibraryScanHashJobTests
Assert.Equal(LibraryScanJobStatus.Completed, _sut.Status);
await _mockFileHashService.Received(1).HashFilesAsync(
Arg.Any<IReadOnlyCollection<HashedFileSystemFileDto>>(),
Arg.Is<bool>(shouldParallelizeReads => shouldParallelizeReads),
Arg.Any<Func<Task>>(),
Arg.Any<CancellationToken>());
await _mockStagingResultsRepository.Received(1).UpdateFileHashesAsync(
@@ -120,6 +130,59 @@ public class MediaLibraryScanHashJobTests
await _mockDomainEventPublisher.Received(1).PublishAsync(Arg.Is<LibraryScanProgressChangedDomainEvent>(domainEvent => domainEvent.LibraryId == _libraryId), Arg.Any<CancellationToken>());
}
[Fact]
public async Task ExecuteAsync_WhenLibraryIsNotOnSsd_ShouldHashTheFilesSequentially()
{
// Arrange
_mockLibraryRepository.GetByIdAsync(_libraryId.Value, Arg.Any<bool>(), Arg.Any<bool>(), Arg.Any<CancellationToken>())
.Returns(Result.From<LibraryEntity?>(_libraryEntityFixture.Create(id: _libraryId.Value, userId: _userId.Value, isContentOnSsd: false)));
List<HashedFileSystemFileDto> filesToHash = [_hashedFileSystemFileDtoFixture.Create(path: "/books/book1.pdf")];
_mockStagingResultsRepository.GetFilesToHashCountAsync(_scanId.Value, Arg.Any<CancellationToken>())
.Returns(Result.From(1));
_mockStagingResultsRepository.GetFilesToHashPageAsync(_scanId.Value, Arg.Any<string?>(), Arg.Any<int>(), Arg.Any<CancellationToken>())
.Returns(
Result.From<IReadOnlyList<HashedFileSystemFileDto>>(filesToHash),
Result.From<IReadOnlyList<HashedFileSystemFileDto>>([]));
_mockFileHashService.HashFilesAsync(Arg.Any<IReadOnlyCollection<HashedFileSystemFileDto>>(), Arg.Any<bool>(), Arg.Any<Func<Task>>(), Arg.Any<CancellationToken>())
.Returns(callInfo => Task.FromResult(callInfo.Arg<IReadOnlyCollection<HashedFileSystemFileDto>>()
.Select(file => file with { CurrentHash = 42UL })
.ToList()));
_mockStagingResultsRepository.UpdateFileHashesAsync(_scanId.Value, Arg.Any<IReadOnlyCollection<HashedFileSystemFileDto>>(), Arg.Any<CancellationToken>())
.Returns(Result.From(Result.Updated));
// Act
await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None);
// Assert
Assert.Equal(LibraryScanJobStatus.Completed, _sut.Status);
await _mockFileHashService.Received(1).HashFilesAsync(
Arg.Any<IReadOnlyCollection<HashedFileSystemFileDto>>(),
Arg.Is<bool>(shouldParallelizeReads => !shouldParallelizeReads),
Arg.Any<Func<Task>>(),
Arg.Any<CancellationToken>());
}
[Fact]
public async Task ExecuteAsync_WhenGettingTheLibraryFails_ShouldMarkJobAsFailedAndPublishFailureEvent()
{
// Arrange
_mockStagingResultsRepository.GetFilesToHashCountAsync(_scanId.Value, Arg.Any<CancellationToken>())
.Returns(Result.From(1));
_mockLibraryRepository.GetByIdAsync(_libraryId.Value, Arg.Any<bool>(), Arg.Any<bool>(), Arg.Any<CancellationToken>())
.Returns(Error.Failure("Database.Error", "Failed to retrieve the library"));
// Act
await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None);
// Assert
Assert.Equal(LibraryScanJobStatus.Failed, _sut.Status);
await _mockFileHashService.DidNotReceive().HashFilesAsync(Arg.Any<IReadOnlyCollection<HashedFileSystemFileDto>>(), Arg.Any<bool>(), Arg.Any<Func<Task>>(), Arg.Any<CancellationToken>());
await _mockDomainEventPublisher.Received(1).PublishAsync(Arg.Is<LibraryScanFailedDomainEvent>(domainEvent =>
domainEvent.LibraryId == _libraryId
&& domainEvent.MediaLibraryScanCompositeId.ScanId == _scanId
&& domainEvent.MediaLibraryScanCompositeId.UserId == _userId), Arg.Any<CancellationToken>());
}
[Fact]
public async Task ExecuteAsync_WhenNoFilesNeedHashing_ShouldCompleteWithoutHashing()
{
@@ -134,7 +197,8 @@ public class MediaLibraryScanHashJobTests
// Assert
Assert.Equal(LibraryScanJobStatus.Completed, _sut.Status);
await _mockFileHashService.DidNotReceive().HashFilesAsync(Arg.Any<IReadOnlyCollection<HashedFileSystemFileDto>>(), Arg.Any<Func<Task>>(), Arg.Any<CancellationToken>());
await _mockLibraryRepository.DidNotReceive().GetByIdAsync(Arg.Any<Guid>(), Arg.Any<bool>(), Arg.Any<bool>(), Arg.Any<CancellationToken>());
await _mockFileHashService.DidNotReceive().HashFilesAsync(Arg.Any<IReadOnlyCollection<HashedFileSystemFileDto>>(), Arg.Any<bool>(), Arg.Any<Func<Task>>(), Arg.Any<CancellationToken>());
await _mockStagingResultsRepository.DidNotReceive().UpdateFileHashesAsync(Arg.Any<Guid>(), Arg.Any<IReadOnlyCollection<HashedFileSystemFileDto>>(), Arg.Any<CancellationToken>());
await _mockDomainEventPublisher.Received(1).PublishAsync(Arg.Is<LibraryScanProgressChangedDomainEvent>(domainEvent => domainEvent.LibraryId == _libraryId), Arg.Any<CancellationToken>());
}
@@ -151,7 +215,7 @@ public class MediaLibraryScanHashJobTests
// Assert
Assert.Equal(LibraryScanJobStatus.Failed, _sut.Status);
await _mockFileHashService.DidNotReceive().HashFilesAsync(Arg.Any<IReadOnlyCollection<HashedFileSystemFileDto>>(), Arg.Any<Func<Task>>(), Arg.Any<CancellationToken>());
await _mockFileHashService.DidNotReceive().HashFilesAsync(Arg.Any<IReadOnlyCollection<HashedFileSystemFileDto>>(), Arg.Any<bool>(), Arg.Any<Func<Task>>(), Arg.Any<CancellationToken>());
await _mockDomainEventPublisher.Received(1).PublishAsync(Arg.Is<LibraryScanFailedDomainEvent>(domainEvent =>
domainEvent.LibraryId == _libraryId
&& domainEvent.MediaLibraryScanCompositeId.ScanId == _scanId
@@ -187,7 +251,7 @@ public class MediaLibraryScanHashJobTests
// Assert
Assert.Equal(LibraryScanJobStatus.Failed, _sut.Status);
await _mockFileHashService.DidNotReceive().HashFilesAsync(Arg.Any<IReadOnlyCollection<HashedFileSystemFileDto>>(), Arg.Any<Func<Task>>(), Arg.Any<CancellationToken>());
await _mockFileHashService.DidNotReceive().HashFilesAsync(Arg.Any<IReadOnlyCollection<HashedFileSystemFileDto>>(), Arg.Any<bool>(), Arg.Any<Func<Task>>(), Arg.Any<CancellationToken>());
await _mockDomainEventPublisher.Received(1).PublishAsync(Arg.Is<LibraryScanFailedDomainEvent>(domainEvent =>
domainEvent.LibraryId == _libraryId
&& domainEvent.MediaLibraryScanCompositeId.ScanId == _scanId
@@ -205,7 +269,7 @@ public class MediaLibraryScanHashJobTests
.Returns(
Result.From<IReadOnlyList<HashedFileSystemFileDto>>(filesToHash),
Result.From<IReadOnlyList<HashedFileSystemFileDto>>([]));
_mockFileHashService.HashFilesAsync(Arg.Any<IReadOnlyCollection<HashedFileSystemFileDto>>(), Arg.Any<Func<Task>>(), Arg.Any<CancellationToken>())
_mockFileHashService.HashFilesAsync(Arg.Any<IReadOnlyCollection<HashedFileSystemFileDto>>(), Arg.Any<bool>(), Arg.Any<Func<Task>>(), Arg.Any<CancellationToken>())
.Returns(callInfo => Task.FromResult(callInfo.Arg<IReadOnlyCollection<HashedFileSystemFileDto>>()
.Select(file => file with { CurrentHash = 42UL })
.ToList()));
@@ -217,7 +281,7 @@ public class MediaLibraryScanHashJobTests
// Assert
Assert.Equal(LibraryScanJobStatus.Failed, _sut.Status);
await _mockFileHashService.Received(1).HashFilesAsync(Arg.Any<IReadOnlyCollection<HashedFileSystemFileDto>>(), Arg.Any<Func<Task>>(), Arg.Any<CancellationToken>());
await _mockFileHashService.Received(1).HashFilesAsync(Arg.Any<IReadOnlyCollection<HashedFileSystemFileDto>>(), Arg.Any<bool>(), Arg.Any<Func<Task>>(), Arg.Any<CancellationToken>());
await _mockDomainEventPublisher.Received(1).PublishAsync(Arg.Is<LibraryScanFailedDomainEvent>(domainEvent =>
domainEvent.LibraryId == _libraryId
&& domainEvent.MediaLibraryScanCompositeId.ScanId == _scanId
@@ -235,7 +299,7 @@ public class MediaLibraryScanHashJobTests
.Returns(
Result.From<IReadOnlyList<HashedFileSystemFileDto>>(filesToHash),
Result.From<IReadOnlyList<HashedFileSystemFileDto>>([]));
_mockFileHashService.HashFilesAsync(Arg.Any<IReadOnlyCollection<HashedFileSystemFileDto>>(), Arg.Any<Func<Task>>(), Arg.Any<CancellationToken>())
_mockFileHashService.HashFilesAsync(Arg.Any<IReadOnlyCollection<HashedFileSystemFileDto>>(), Arg.Any<bool>(), Arg.Any<Func<Task>>(), Arg.Any<CancellationToken>())
.Returns(async callInfo =>
{
await callInfo.Arg<Func<Task>>()();
@@ -268,7 +332,7 @@ public class MediaLibraryScanHashJobTests
.Returns(
Result.From<IReadOnlyList<HashedFileSystemFileDto>>(filesToHash),
Result.From<IReadOnlyList<HashedFileSystemFileDto>>([]));
_mockFileHashService.HashFilesAsync(Arg.Any<IReadOnlyCollection<HashedFileSystemFileDto>>(), Arg.Any<Func<Task>>(), Arg.Any<CancellationToken>())
_mockFileHashService.HashFilesAsync(Arg.Any<IReadOnlyCollection<HashedFileSystemFileDto>>(), Arg.Any<bool>(), Arg.Any<Func<Task>>(), Arg.Any<CancellationToken>())
.Returns(async callInfo =>
{
await Task.Delay(150);
@@ -2,6 +2,7 @@
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management;
using Lumina.Application.Common.DataAccess.Repositories.MediaLibrary;
using Lumina.Application.Common.DataAccess.UoW;
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management;
using Lumina.Domain.Common.Errors;
using Lumina.Domain.Common.Events;
using Lumina.Domain.Common.Primitives;
@@ -15,10 +16,13 @@ using Lumina.Domain.Fixtures.Core.BoundedContexts.UserManagementBoundedContext.U
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
using Lumina.Infrastructure.Core.MediaLibrary.Management.Scanning.Jobs.WrittenContent.Books;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using NSubstitute;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.IO;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
#endregion
@@ -38,7 +42,9 @@ public class BooksFileSystemDiscoveryJobTests
private readonly ILibraryRepository _mockLibraryRepository;
private readonly ILibraryScanStagingResultsRepository _mockStagingResultsRepository;
private readonly IDomainEventPublisher _mockDomainEventPublisher;
private readonly ILogger<BooksFileSystemDiscoveryJob> _mockLogger;
private readonly BooksFileSystemDiscoveryJob _sut;
private readonly LibraryEntityFixture _libraryEntityFixture = new();
private readonly ScanIdFixture _scanIdFixture = new();
private readonly UserIdFixture _userIdFixture = new();
private readonly LibraryIdFixture _libraryIdFixture = new();
@@ -73,7 +79,9 @@ public class BooksFileSystemDiscoveryJobTests
_scanId = _scanIdFixture.Create();
_userId = _userIdFixture.Create();
_libraryId = _libraryIdFixture.Create();
_sut = new BooksFileSystemDiscoveryJob(_mockServiceScopeFactory)
_mockLogger = Substitute.For<ILogger<BooksFileSystemDiscoveryJob>>();
_mockLogger.IsEnabled(Arg.Any<LogLevel>()).Returns(true);
_sut = new BooksFileSystemDiscoveryJob(_mockServiceScopeFactory, _mockLogger)
{
ScanId = _scanId,
UserId = _userId,
@@ -130,4 +138,82 @@ public class BooksFileSystemDiscoveryJobTests
await Assert.ThrowsAnyAsync<OperationCanceledException>(() => operation);
Assert.Equal(LibraryScanJobStatus.Canceled, _sut.Status);
}
[Fact]
public async Task ExecuteAsync_WhenTheLibraryIsOnSsd_ShouldLogThatTheFileSystemReadsRunInParallel()
{
// Arrange
string temporaryDirectoryPath = Path.Combine(Path.GetTempPath(), $"lumina-books-ssd-{Guid.NewGuid()}");
Directory.CreateDirectory(temporaryDirectoryPath);
File.WriteAllText(Path.Combine(temporaryDirectoryPath, "book.pdf"), "book content");
try
{
LibraryEntity libraryEntity = _libraryEntityFixture.Create(
id: _libraryId.Value,
userId: _userId.Value,
libraryType: LibraryType.Book,
contentLocations: [temporaryDirectoryPath],
isContentOnSsd: true);
_mockLibraryRepository.GetByIdAsync(_libraryId.Value, cancellationToken: Arg.Any<CancellationToken>())
.Returns(Result.From<LibraryEntity?>(libraryEntity));
_mockStagingResultsRepository.InsertRangeAsync(Arg.Any<IReadOnlyCollection<LibraryScanStagingResultsEntity>>(), Arg.Any<CancellationToken>())
.Returns(Result.From(Result.Created));
// Act
await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None);
// Assert
Assert.Equal(LibraryScanJobStatus.Completed, _sut.Status);
await _mockStagingResultsRepository.Received(1).InsertRangeAsync(
Arg.Is<IReadOnlyCollection<LibraryScanStagingResultsEntity>>(entities => entities.Count == 1 && Path.GetFileName(entities.First().Path) == "book.pdf"),
Arg.Any<CancellationToken>());
_mockLogger.Received(1).Log(
LogLevel.Debug,
Arg.Any<EventId>(),
Arg.Is<object>(state => state.ToString()!.Contains("solid state drive", StringComparison.Ordinal)),
Arg.Any<Exception?>(),
Arg.Any<Func<object, Exception?, string>>());
}
finally
{
Directory.Delete(temporaryDirectoryPath, recursive: true);
}
}
[Fact]
public async Task StageFilesInParallelAsync_WhenAFileVanishesBeforeItsMetadataIsRead_ShouldSkipItAndLogAWarning()
{
// Arrange
FileInfo vanishedFile = new(Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString(), "vanished.pdf"));
List<LibraryScanStagingResultsEntity> stagingBatch = [];
// Act
await _sut.StageFilesInParallelAsync([vanishedFile], stagingBatch, _mockStagingResultsRepository, CancellationToken.None);
// Assert
Assert.Empty(stagingBatch);
await _mockStagingResultsRepository.DidNotReceive().InsertRangeAsync(Arg.Any<IReadOnlyCollection<LibraryScanStagingResultsEntity>>(), Arg.Any<CancellationToken>());
_mockLogger.Received(1).Log(
LogLevel.Warning,
Arg.Any<EventId>(),
Arg.Is<object>(state => state.ToString()!.Contains("vanished.pdf", StringComparison.Ordinal)),
Arg.Any<IOException>(),
Arg.Any<Func<object, Exception?, string>>());
}
[Fact]
public async Task StageFilesInParallelAsync_WhenAFileReadThrowsAnUnexpectedException_ShouldRethrowTheRealCause()
{
// Arrange
List<LibraryScanStagingResultsEntity> stagingBatch = [];
List<FileInfo> files = [null!];
// Act
Exception exception = await Assert.ThrowsAsync<NullReferenceException>(() =>
_sut.StageFilesInParallelAsync(files, stagingBatch, _mockStagingResultsRepository, CancellationToken.None));
// Assert
// Parallel.For wraps the body exception in an AggregateException, which would otherwise be reported as "One or more errors occurred.".
Assert.IsType<NullReferenceException>(exception);
}
}
@@ -87,6 +87,7 @@ public class AddLibraryEndpointTests
{
// Arrange
AddLibraryRequest request = _addLibraryRequestFixture.Create(
isContentOnSsd: true,
shouldTrackConsumptionProgress: true,
completionThresholdPercentage: 65);
CancellationToken cancellationToken = CancellationToken.None;
@@ -108,6 +109,7 @@ public class AddLibraryEndpointTests
command.CanDownloadMetadataFromWeb == request.CanDownloadMetadataFromWeb &&
command.ShouldSaveMetadataInMediaDirectories == request.ShouldSaveMetadataInMediaDirectories &&
command.ShouldSkipUnchangedDirectoriesDuringScan == request.ShouldSkipUnchangedDirectoriesDuringScan &&
command.IsContentOnSsd == request.IsContentOnSsd &&
command.ShouldTrackConsumptionProgress == request.ShouldTrackConsumptionProgress &&
command.CompletionThresholdPercentage == request.CompletionThresholdPercentage),
Arg.Is(cancellationToken));
@@ -87,6 +87,7 @@ public class UpdateLibraryEndpointTests
{
// Arrange
UpdateLibraryRequest request = _updateLibraryRequestFixture.Create(
isContentOnSsd: true,
shouldTrackConsumptionProgress: true,
completionThresholdPercentage: 65);
CancellationToken cancellationToken = CancellationToken.None;
@@ -110,6 +111,7 @@ public class UpdateLibraryEndpointTests
command.CanDownloadMetadataFromWeb == request.CanDownloadMetadataFromWeb &&
command.ShouldSaveMetadataInMediaDirectories == request.ShouldSaveMetadataInMediaDirectories &&
command.ShouldSkipUnchangedDirectoriesDuringScan == request.ShouldSkipUnchangedDirectoriesDuringScan &&
command.IsContentOnSsd == request.IsContentOnSsd &&
command.ShouldTrackConsumptionProgress == request.ShouldTrackConsumptionProgress &&
command.CompletionThresholdPercentage == request.CompletionThresholdPercentage),
Arg.Is(cancellationToken));