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

@@ -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);
}
}