Renames project paths from Lumina to Nemera

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

No files matched your search

@@ -0,0 +1,39 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Domain.Common.Events;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.Events;
using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate;
using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.Events;
using System;
using System.Diagnostics.CodeAnalysis;
#endregion
namespace Lumina.Domain.UnitTests.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.Events;
/// <summary>
/// Contains unit tests for the <see cref="LibraryDeletedDomainEvent"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class LibraryDeletedDomainEventTests
{
private readonly LibraryFixture _libraryFixture = new();
private readonly LibraryDeletedDomainEventFixture _libraryDeletedDomainEventFixture = new();
[Fact]
public void Constructor_WhenCalled_ShouldSetAllProperties()
{
// Arrange
Guid id = Guid.NewGuid();
Library library = _libraryFixture.Create();
DateTime occurredOnUtc = DateTime.UtcNow;
// Act
LibraryDeletedDomainEvent domainEvent = _libraryDeletedDomainEventFixture.Create(id, library, occurredOnUtc);
// Assert
Assert.Equal(id, domainEvent.Id);
Assert.Equal(library, domainEvent.Library);
Assert.Equal(occurredOnUtc, domainEvent.OccurredOnUtc);
Assert.IsType<IDomainEvent>(domainEvent, exactMatch: false);
}
}
@@ -0,0 +1,39 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Domain.Common.Events;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.Events;
using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate;
using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.Events;
using System;
using System.Diagnostics.CodeAnalysis;
#endregion
namespace Lumina.Domain.UnitTests.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.Events;
/// <summary>
/// Contains unit tests for the <see cref="LibrarySavedDomainEvent"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class LibrarySavedDomainEventTests
{
private readonly LibraryFixture _libraryFixture = new();
private readonly LibrarySavedDomainEventFixture _librarySavedDomainEventFixture = new();
[Fact]
public void Constructor_WhenCalled_ShouldSetAllProperties()
{
// Arrange
Guid id = Guid.NewGuid();
Library library = _libraryFixture.Create();
DateTime occurredOnUtc = DateTime.UtcNow;
// Act
LibrarySavedDomainEvent domainEvent = _librarySavedDomainEventFixture.Create(id, library, occurredOnUtc);
// Assert
Assert.Equal(id, domainEvent.Id);
Assert.Equal(library, domainEvent.Library);
Assert.Equal(occurredOnUtc, domainEvent.OccurredOnUtc);
Assert.IsType<IDomainEvent>(domainEvent, exactMatch: false);
}
}
@@ -0,0 +1,295 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Domain.Common.Events;
using Lumina.Domain.Common.Primitives;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.Events;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects;
using Lumina.Domain.Core.BoundedContexts.UserManagementBoundedContext.UserAggregate.ValueObjects;
using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate;
using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects;
using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects;
using Lumina.Domain.Fixtures.Core.BoundedContexts.UserManagementBoundedContext.UserAggregate.ValueObjects;
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
#endregion
namespace Lumina.Domain.UnitTests.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate;
/// <summary>
/// Contains unit tests for the <see cref="Library"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class LibraryTests
{
private readonly LibraryFixture _libraryFixture = new();
private readonly UserIdFixture _userIdFixture = new();
private readonly ScanIdFixture _scanIdFixture = new();
private readonly LibraryIdFixture _libraryIdFixture = new();
private readonly LibraryConsumptionSettingsFixture _libraryConsumptionSettingsFixture = new();
[Fact]
public void Create_WhenCalledWithValidData_ShouldCreateLibraryWithAllPropertiesSet()
{
// Arrange
UserId userId = _userIdFixture.Create();
string title = "My Books";
LibraryType libraryType = LibraryType.Book;
List<string> contentLocations = ["C:/Media/Books", "D:/Books"];
string coverImageSourcePath = "C:/Cover/cover.jpg";
List<ScanId> scanIds = [_scanIdFixture.Create(), _scanIdFixture.Create()];
LibraryConsumptionSettings consumptionSettings = _libraryConsumptionSettingsFixture.Create(
shouldTrackConsumptionProgress: true,
completionThresholdPercentage: 75);
// Act
Result<Library> result = Library.Create(
userId,
title,
libraryType,
contentLocations,
coverImageSourcePath,
isEnabled: false,
isLocked: true,
canDownloadMetadataFromWeb: false,
shouldSaveMetadataInMediaDirectories: true,
shouldSkipUnchangedDirectoriesDuringScan: true,
shouldSkipHiddenFilesAndDirectoriesDuringScan: true,
isContentOnSsd: true,
consumptionSettings,
LibraryPathTemplate.Empty(),
scanIds);
// Assert
Assert.False(result.IsFailure);
Assert.Equal(userId, result.Value.UserId);
Assert.Equal(title, result.Value.Title);
Assert.Equal(libraryType, result.Value.LibraryType);
Assert.Equal(2, result.Value.ContentLocations.Count);
Assert.True(result.Value.CoverImage.HasValue);
Assert.Equal(coverImageSourcePath, result.Value.CoverImage.Value);
Assert.False(result.Value.IsEnabled);
Assert.True(result.Value.IsLocked);
Assert.False(result.Value.CanDownloadMetadataFromWeb);
Assert.True(result.Value.ShouldSaveMetadataInMediaDirectories);
Assert.True(result.Value.ShouldSkipUnchangedDirectoriesDuringScan);
Assert.True(result.Value.ShouldSkipHiddenFilesAndDirectoriesDuringScan);
Assert.True(result.Value.IsContentOnSsd);
Assert.Equal(consumptionSettings, result.Value.ConsumptionSettings);
Assert.Equal(scanIds, result.Value.ScanIds);
}
[Fact]
public void Create_WhenCalledWithPreExistingId_ShouldCreateLibraryWithThatId()
{
// Arrange
Guid id = Guid.NewGuid();
List<ScanId> scanIds = [_scanIdFixture.Create()];
// Act
Result<Library> result = Library.Create(
_libraryIdFixture.Create(id),
_userIdFixture.Create(),
"My Library",
LibraryType.Movie,
["C:/Media"],
Optional<string>.None(),
isEnabled: true,
isLocked: false,
canDownloadMetadataFromWeb: true,
shouldSaveMetadataInMediaDirectories: false,
shouldSkipUnchangedDirectoriesDuringScan: false,
shouldSkipHiddenFilesAndDirectoriesDuringScan: false,
isContentOnSsd: false,
_libraryConsumptionSettingsFixture.Create(),
LibraryPathTemplate.Empty(),
scanIds);
// Assert
Assert.False(result.IsFailure);
Assert.Equal(id, result.Value.Id.Value);
}
[Fact]
public void Create_WhenGivenPreExistingIdAndInvalidContentLocation_ShouldReturnError()
{
// Arrange
Guid id = Guid.NewGuid();
// Act
Result<Library> result = Library.Create(
_libraryIdFixture.Create(id),
_userIdFixture.Create(),
"My Library",
LibraryType.Book,
[""],
Optional<string>.None(),
isEnabled: true,
isLocked: false,
canDownloadMetadataFromWeb: true,
shouldSaveMetadataInMediaDirectories: false,
shouldSkipUnchangedDirectoriesDuringScan: false,
shouldSkipHiddenFilesAndDirectoriesDuringScan: false,
isContentOnSsd: false,
_libraryConsumptionSettingsFixture.Create(),
LibraryPathTemplate.Empty(),
[]);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(Lumina.Domain.Common.Errors.Errors.FileSystemManagement.InvalidPath, result.FirstError);
}
[Fact]
public void Create_WhenCalledWithValidData_ShouldLeaveCoverImageSourcePathUnset()
{
// Arrange
Library library = _libraryFixture.Create();
// Act
Optional<string> coverImageSourcePath = library.CoverImageSourcePath;
// Assert
Assert.False(coverImageSourcePath.HasValue);
}
[Fact]
public void Create_WhenCalledWithContentLocations_ShouldCreateFileSystemPathIdForEachLocation()
{
// Act
Result<Library> result = Library.Create(
_userIdFixture.Create(),
"My Library",
LibraryType.Book,
["C:/Media/Books", "D:/Books"],
Optional<string>.None(),
isEnabled: true,
isLocked: false,
canDownloadMetadataFromWeb: true,
shouldSaveMetadataInMediaDirectories: false,
shouldSkipUnchangedDirectoriesDuringScan: false,
shouldSkipHiddenFilesAndDirectoriesDuringScan: false,
isContentOnSsd: false,
_libraryConsumptionSettingsFixture.Create(),
LibraryPathTemplate.Empty(),
[]);
// Assert
Assert.False(result.IsFailure);
Assert.Equal(2, result.Value.ContentLocations.Count);
Assert.Contains(result.Value.ContentLocations, location => location.Path == "C:/Media/Books");
Assert.Contains(result.Value.ContentLocations, location => location.Path == "D:/Books");
}
[Theory]
[InlineData(null)] // Null content location.
[InlineData("")] // Empty content location.
[InlineData(" ")] // Whitespace content location.
public void Create_WhenContentLocationIsInvalid_ShouldReturnError(string? contentLocation)
{
// Act
Result<Library> result = Library.Create(
_userIdFixture.Create(),
"My Library",
LibraryType.Book,
[contentLocation!],
Optional<string>.None(),
isEnabled: true,
isLocked: false,
canDownloadMetadataFromWeb: true,
shouldSaveMetadataInMediaDirectories: false,
shouldSkipUnchangedDirectoriesDuringScan: false,
shouldSkipHiddenFilesAndDirectoriesDuringScan: false,
isContentOnSsd: false,
_libraryConsumptionSettingsFixture.Create(),
LibraryPathTemplate.Empty(),
[]);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(Lumina.Domain.Common.Errors.Errors.FileSystemManagement.InvalidPath, result.FirstError);
}
[Fact]
public void Save_WhenCalled_ShouldRaiseLibrarySavedDomainEvent()
{
// Arrange
Library library = _libraryFixture.Create();
// Act
library.Save();
// Assert
List<IDomainEvent> domainEvents = library.GetDomainEvents();
LibrarySavedDomainEvent savedEvent = Assert.IsType<LibrarySavedDomainEvent>(Assert.Single(domainEvents));
Assert.Equal(library, savedEvent.Library);
Assert.NotEqual(default, savedEvent.Id);
Assert.NotEqual(default, savedEvent.OccurredOnUtc);
}
[Fact]
public void Delete_WhenCalled_ShouldRaiseLibraryDeletedDomainEvent()
{
// Arrange
Library library = _libraryFixture.Create();
// Act
Result<Deleted> result = library.Delete();
// Assert
Assert.False(result.IsFailure);
Assert.Equal(Result.Deleted, result.Value);
List<IDomainEvent> domainEvents = library.GetDomainEvents();
LibraryDeletedDomainEvent deletedEvent = Assert.IsType<LibraryDeletedDomainEvent>(Assert.Single(domainEvents));
Assert.Equal(library, deletedEvent.Library);
}
[Fact]
public void Delete_WhenCalledAfterSave_ShouldClearPreviousEventsAndRaiseOnlyDeletedEvent()
{
// Arrange
Library library = _libraryFixture.Create();
library.Save();
// Act
library.Delete();
// Assert
List<IDomainEvent> domainEvents = library.GetDomainEvents();
Assert.Single(domainEvents);
Assert.IsType<LibraryDeletedDomainEvent>(domainEvents[0]);
}
[Fact]
public void Delete_WhenCalledMultipleTimes_ShouldRaiseOnlyOneDeletedEvent()
{
// Arrange
Library library = _libraryFixture.Create();
// Act
library.Delete();
library.Delete();
// Assert
List<IDomainEvent> domainEvents = library.GetDomainEvents();
Assert.Single(domainEvents);
Assert.IsType<LibraryDeletedDomainEvent>(domainEvents[0]);
}
[Fact]
public void SetInternalLibraryCoverImagePath_WhenCalled_ShouldUpdateCoverImage()
{
// Arrange
Library library = _libraryFixture.Create();
string internalPath = "C:/Internal/Covers/cover.jpg";
// Act
library.SetInternalLibraryCoverImagePath(internalPath);
// Assert
Assert.True(library.CoverImage.HasValue);
Assert.Equal(internalPath, library.CoverImage.Value);
}
}
@@ -0,0 +1,296 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects;
using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects;
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
using System.Diagnostics.CodeAnalysis;
#endregion
namespace Lumina.Domain.UnitTests.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects;
/// <summary>
/// Contains unit tests for the <see cref="LibraryConsumptionSettings"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class LibraryConsumptionSettingsTests
{
private readonly LibraryConsumptionSettingsFixture _libraryConsumptionSettingsFixture = new();
[Fact]
public void Create_WhenProgressTrackingIsEnabledAndThresholdIsSupplied_ShouldRetainThreshold()
{
// Act
LibraryConsumptionSettings settings = _libraryConsumptionSettingsFixture.Create(
shouldTrackConsumptionProgress: true,
completionThresholdPercentage: 65);
// Assert
Assert.True(settings.ShouldTrackConsumptionProgress);
Assert.True(settings.CompletionThresholdPercentage.HasValue);
Assert.Equal(65, settings.CompletionThresholdPercentage.Value);
}
[Fact]
public void Create_WhenProgressTrackingIsEnabledAndThresholdIsAbsent_ShouldHaveNoThreshold()
{
// Act
LibraryConsumptionSettings settings = _libraryConsumptionSettingsFixture.Create(
shouldTrackConsumptionProgress: true,
includeCompletionThreshold: false);
// Assert
Assert.True(settings.ShouldTrackConsumptionProgress);
Assert.False(settings.CompletionThresholdPercentage.HasValue);
}
[Fact]
public void Create_WhenProgressTrackingIsDisabledAndThresholdIsSupplied_ShouldNotRetainThreshold()
{
// Act
LibraryConsumptionSettings settings = _libraryConsumptionSettingsFixture.Create(
shouldTrackConsumptionProgress: false,
completionThresholdPercentage: 65);
// Assert
Assert.False(settings.ShouldTrackConsumptionProgress);
Assert.False(settings.CompletionThresholdPercentage.HasValue);
}
[Fact]
public void Create_WhenProgressTrackingIsDisabledAndThresholdIsAbsent_ShouldHaveNoThreshold()
{
// Act
LibraryConsumptionSettings settings = _libraryConsumptionSettingsFixture.Create(
shouldTrackConsumptionProgress: false,
includeCompletionThreshold: false);
// Assert
Assert.False(settings.ShouldTrackConsumptionProgress);
Assert.False(settings.CompletionThresholdPercentage.HasValue);
}
[Fact]
public void Equals_WhenSettingsHaveSameValues_ShouldReturnTrue()
{
// Arrange
LibraryConsumptionSettings firstSettings = _libraryConsumptionSettingsFixture.Create(
shouldTrackConsumptionProgress: true,
completionThresholdPercentage: 65);
LibraryConsumptionSettings secondSettings = _libraryConsumptionSettingsFixture.Create(
shouldTrackConsumptionProgress: true,
completionThresholdPercentage: 65);
// Act
bool areEqual = firstSettings.Equals(secondSettings);
// Assert
Assert.True(areEqual);
}
[Fact]
public void Equals_WhenProgressTrackingDiffers_ShouldReturnFalse()
{
// Arrange
LibraryConsumptionSettings trackingSettings = _libraryConsumptionSettingsFixture.Create(
shouldTrackConsumptionProgress: true,
completionThresholdPercentage: 65);
LibraryConsumptionSettings notTrackingSettings = _libraryConsumptionSettingsFixture.Create(
shouldTrackConsumptionProgress: false,
completionThresholdPercentage: 65);
// Act
bool areEqual = trackingSettings.Equals(notTrackingSettings);
// Assert
Assert.False(areEqual);
}
[Fact]
public void Equals_WhenThresholdsDiffer_ShouldReturnFalse()
{
// Arrange
LibraryConsumptionSettings firstSettings = _libraryConsumptionSettingsFixture.Create(
shouldTrackConsumptionProgress: true,
completionThresholdPercentage: 40);
LibraryConsumptionSettings secondSettings = _libraryConsumptionSettingsFixture.Create(
shouldTrackConsumptionProgress: true,
completionThresholdPercentage: 60);
// Act
bool areEqual = firstSettings.Equals(secondSettings);
// Assert
Assert.False(areEqual);
}
[Fact]
public void Equals_WhenProgressTrackingIsDisabled_ShouldIgnoreAnySuppliedThreshold()
{
// Arrange
LibraryConsumptionSettings settingsWithThreshold = _libraryConsumptionSettingsFixture.Create(
shouldTrackConsumptionProgress: false,
completionThresholdPercentage: 40);
LibraryConsumptionSettings settingsWithoutThreshold = _libraryConsumptionSettingsFixture.Create(
shouldTrackConsumptionProgress: false,
includeCompletionThreshold: false);
// Act
bool areEqual = settingsWithThreshold.Equals(settingsWithoutThreshold);
// Assert
Assert.False(settingsWithThreshold.CompletionThresholdPercentage.HasValue);
Assert.False(settingsWithoutThreshold.CompletionThresholdPercentage.HasValue);
Assert.True(areEqual);
}
[Fact]
public void Equals_WhenComparedWithNull_ShouldReturnFalse()
{
// Arrange
LibraryConsumptionSettings settings = _libraryConsumptionSettingsFixture.Create(
shouldTrackConsumptionProgress: true,
completionThresholdPercentage: 65);
// Act
bool areEqual = settings.Equals((object?)null);
// Assert
Assert.False(areEqual);
}
[Fact]
public void GetHashCode_WhenSettingsAreEqual_ShouldReturnSameHashCode()
{
// Arrange
LibraryConsumptionSettings firstSettings = _libraryConsumptionSettingsFixture.Create(
shouldTrackConsumptionProgress: true,
completionThresholdPercentage: 65);
LibraryConsumptionSettings secondSettings = _libraryConsumptionSettingsFixture.Create(
shouldTrackConsumptionProgress: true,
completionThresholdPercentage: 65);
// Act
int firstHashCode = firstSettings.GetHashCode();
int secondHashCode = secondSettings.GetHashCode();
// Assert
Assert.Equal(firstHashCode, secondHashCode);
}
[Theory]
[InlineData(LibraryType.Book, true, 100)] // Written content.
[InlineData(LibraryType.EBook, true, 100)] // Written content.
[InlineData(LibraryType.ComicBook, true, 100)] // Written content.
[InlineData(LibraryType.Magazine, true, 100)] // Written content.
[InlineData(LibraryType.Newspaper, true, 100)] // Written content.
[InlineData(LibraryType.Manga, true, 100)] // Written content.
[InlineData(LibraryType.GraphicNovel, true, 100)] // Written content.
[InlineData(LibraryType.AcademicPaper, true, 100)] // Written content.
[InlineData(LibraryType.SheetMusic, true, 100)] // Written content.
[InlineData(LibraryType.TvShow, true, 90)] // Video.
[InlineData(LibraryType.Movie, true, 90)] // Video.
[InlineData(LibraryType.Documentary, true, 90)] // Video.
[InlineData(LibraryType.Anime, true, 90)] // Video.
[InlineData(LibraryType.ConcertVideo, true, 90)] // Video.
[InlineData(LibraryType.TutorialVideo, true, 90)] // Video.
[InlineData(LibraryType.HomeVideo, true, 90)] // Video.
[InlineData(LibraryType.YouTubeVideo, true, 90)] // Video.
[InlineData(LibraryType.MusicVideo, true, 90)] // Video.
[InlineData(LibraryType.LiveRecordingVideo, true, 90)] // Video.
[InlineData(LibraryType.InterviewVideo, true, 90)] // Video.
[InlineData(LibraryType.CoverSongVideo, true, 90)] // Video.
[InlineData(LibraryType.Audiobook, true, 95)] // Audiobooks and podcasts.
[InlineData(LibraryType.PodcastAudio, true, 95)] // Audiobooks and podcasts.
[InlineData(LibraryType.PodcastVideo, true, 95)] // Audiobooks and podcasts.
[InlineData(LibraryType.Music, false, null)] // Music audio and photos.
[InlineData(LibraryType.Remix, false, null)] // Music audio and photos.
[InlineData(LibraryType.SoundEffect, false, null)] // Music audio and photos.
[InlineData(LibraryType.LiveRecordingAudio, false, null)] // Music audio and photos.
[InlineData(LibraryType.InterviewAudio, false, null)] // Music audio and photos.
[InlineData(LibraryType.CoverSongAudio, false, null)] // Music audio and photos.
[InlineData(LibraryType.Photo, false, null)] // Music audio and photos.
[InlineData(LibraryType.Playlist, false, null)] // Library types that are not media libraries.
[InlineData(LibraryType.Collection, false, null)] // Library types that are not media libraries.
[InlineData(LibraryType.Subtitles, false, null)] // Library types that are not media libraries.
[InlineData(LibraryType.Lyrics, false, null)] // Library types that are not media libraries.
[InlineData(LibraryType.Other, false, null)] // Library types that are not media libraries.
public void CreateDefault_WhenLibraryTypeIsKnown_ShouldReturnTheTypeDefaults(
LibraryType libraryType,
bool expectedShouldTrackConsumptionProgress,
int? expectedCompletionThresholdPercentage)
{
// Act
LibraryConsumptionSettings settings = LibraryConsumptionSettings.CreateDefault(libraryType);
// Assert
Assert.Equal(expectedShouldTrackConsumptionProgress, settings.ShouldTrackConsumptionProgress);
if (expectedCompletionThresholdPercentage is null)
Assert.False(settings.CompletionThresholdPercentage.HasValue);
else
{
Assert.True(settings.CompletionThresholdPercentage.HasValue);
Assert.Equal(expectedCompletionThresholdPercentage.Value, settings.CompletionThresholdPercentage.Value);
}
}
[Fact]
public void CreateDefault_WhenLibraryTypeIsNotClassified_ShouldReturnTrackingOffWithoutThreshold()
{
// Act
LibraryConsumptionSettings settings = LibraryConsumptionSettings.CreateDefault((LibraryType)999);
// Assert
Assert.False(settings.ShouldTrackConsumptionProgress);
Assert.False(settings.CompletionThresholdPercentage.HasValue);
}
[Theory]
[InlineData(MediaKind.None, false, null)] // No media kind.
[InlineData(MediaKind.MusicTrack, false, null)] // Music tracks.
[InlineData(MediaKind.PodcastEpisode, true, 95)] // Audiobooks and podcast episodes.
[InlineData(MediaKind.Audiobook, true, 95)] // Audiobooks and podcast episodes.
[InlineData(MediaKind.Movie, true, 90)] // Video.
[InlineData(MediaKind.TvEpisode, true, 90)] // Video.
[InlineData(MediaKind.Book, true, 100)] // Written content.
[InlineData(MediaKind.Photo, false, null)] // Photos.
[InlineData(MediaKind.Video, true, 90)] // Video.
public void CreateDefault_WhenMediaKindIsKnown_ShouldReturnTheKindDefaults(
MediaKind mediaKind,
bool expectedShouldTrackConsumptionProgress,
int? expectedCompletionThresholdPercentage)
{
// Act
LibraryConsumptionSettings settings = LibraryConsumptionSettings.CreateDefault(mediaKind);
// Assert
Assert.Equal(expectedShouldTrackConsumptionProgress, settings.ShouldTrackConsumptionProgress);
if (expectedCompletionThresholdPercentage is null)
Assert.False(settings.CompletionThresholdPercentage.HasValue);
else
{
Assert.True(settings.CompletionThresholdPercentage.HasValue);
Assert.Equal(expectedCompletionThresholdPercentage.Value, settings.CompletionThresholdPercentage.Value);
}
}
[Fact]
public void CreateDefault_WhenMediaKindIsNotClassified_ShouldReturnTrackingOffWithoutThreshold()
{
// Act
LibraryConsumptionSettings settings = LibraryConsumptionSettings.CreateDefault((MediaKind)999);
// Assert
Assert.False(settings.ShouldTrackConsumptionProgress);
Assert.False(settings.CompletionThresholdPercentage.HasValue);
}
[Fact]
public void CreateDefault_WhenReturnedSettingsAreTrackingOff_ShouldNotRetainAThreshold()
{
// Act
LibraryConsumptionSettings settings = LibraryConsumptionSettings.CreateDefault(LibraryType.Music);
// Assert
Assert.False(settings.ShouldTrackConsumptionProgress);
Assert.False(settings.CompletionThresholdPercentage.HasValue);
}
}
@@ -0,0 +1,155 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Domain.Common.Primitives;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects;
using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects;
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
using System.Diagnostics.CodeAnalysis;
#endregion
namespace Lumina.Domain.UnitTests.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects;
/// <summary>
/// Contains unit tests for the <see cref="LibraryPathPart"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class LibraryPathPartTests
{
private readonly LibraryPathPartFixture _libraryPathPartFixture = new();
[Fact]
public void Create_WhenKindIsSeparator_ShouldCreateSeparatorWithoutRepresentation()
{
// Act
Result<LibraryPathPart> result = LibraryPathPart.Create(LibraryPathPartKind.Separator, "/", isOptional: false);
// Assert
Assert.False(result.IsFailure);
Assert.Equal(LibraryPathPartKind.Separator, result.Value.Kind);
Assert.Equal(string.Empty, result.Value.Representation);
}
[Fact]
public void Create_WhenKindIsLiteralWithText_ShouldCreateLiteralWithThatRepresentation()
{
// Act
Result<LibraryPathPart> result = LibraryPathPart.Create(LibraryPathPartKind.Literal, " - ", isOptional: false);
// Assert
Assert.False(result.IsFailure);
Assert.Equal(LibraryPathPartKind.Literal, result.Value.Kind);
Assert.Equal(" - ", result.Value.Representation);
}
[Theory]
[InlineData(null)] // The representation is absent.
[InlineData("")] // The representation is empty.
[InlineData(" ")] // The representation is whitespace.
public void Create_WhenKindIsNotSeparatorAndRepresentationIsEmpty_ShouldReturnLiteralCannotBeEmptyError(string? representation)
{
// Act
Result<LibraryPathPart> result = LibraryPathPart.Create(LibraryPathPartKind.Literal, representation, isOptional: false);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(Lumina.Domain.Common.Errors.Errors.Library.PathTemplateLiteralCannotBeEmpty, result.FirstError);
}
[Fact]
public void Create_WhenTypedPartContainsSinglePlaceholder_ShouldCreateThePart()
{
// Act
Result<LibraryPathPart> result = LibraryPathPart.Create(LibraryPathPartKind.Artist, "{0}", isOptional: false);
// Assert
Assert.False(result.IsFailure);
Assert.Equal("{0}", result.Value.Representation);
}
[Fact]
public void Create_WhenTypedPartContainsFixedWidthPlaceholder_ShouldCreateThePart()
{
// Act
Result<LibraryPathPart> result = LibraryPathPart.Create(LibraryPathPartKind.TrackNumber, "Disc {0:00}", isOptional: true);
// Assert
Assert.False(result.IsFailure);
Assert.Equal("Disc {0:00}", result.Value.Representation);
Assert.True(result.Value.IsOptional);
}
[Theory]
[InlineData("no placeholder")] // The mask carries no value placeholder.
[InlineData("{0} {0}")] // The mask carries more than one value placeholder.
public void Create_WhenTypedPartDoesNotContainExactlyOnePlaceholder_ShouldReturnError(string representation)
{
// Act
Result<LibraryPathPart> result = LibraryPathPart.Create(LibraryPathPartKind.Artist, representation, isOptional: false);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(Lumina.Domain.Common.Errors.Errors.Library.PathTemplateValuePartMustContainSinglePlaceholder, result.FirstError);
}
[Fact]
public void Create_WhenLiteralContainsNoPlaceholder_ShouldCreateThePart()
{
// Act
Result<LibraryPathPart> result = LibraryPathPart.Create(LibraryPathPartKind.Literal, "Disk ", isOptional: false);
// Assert
Assert.False(result.IsFailure);
Assert.Equal("Disk ", result.Value.Representation);
}
[Fact]
public void Equals_WithSameValues_ShouldReturnTrue()
{
// Arrange
LibraryPathPart firstPart = _libraryPathPartFixture.Create(kind: LibraryPathPartKind.Artist, representation: "{0}", isOptional: true);
// Act
LibraryPathPart secondPart = _libraryPathPartFixture.Create(kind: LibraryPathPartKind.Artist, representation: "{0}", isOptional: true);
// Assert
Assert.Equal(firstPart, secondPart);
}
[Fact]
public void Equals_WithDifferentKind_ShouldReturnFalse()
{
// Arrange
LibraryPathPart firstPart = _libraryPathPartFixture.Create(kind: LibraryPathPartKind.Artist, representation: "{0}", isOptional: false);
// Act
LibraryPathPart secondPart = _libraryPathPartFixture.Create(kind: LibraryPathPartKind.ReleaseName, representation: "{0}", isOptional: false);
// Assert
Assert.NotEqual(firstPart, secondPart);
}
[Fact]
public void Equals_WithDifferentRepresentation_ShouldReturnFalse()
{
// Arrange
LibraryPathPart firstPart = _libraryPathPartFixture.Create(kind: LibraryPathPartKind.Artist, representation: "{0}", isOptional: false);
// Act
LibraryPathPart secondPart = _libraryPathPartFixture.Create(kind: LibraryPathPartKind.Artist, representation: "Artist: {0}", isOptional: false);
// Assert
Assert.NotEqual(firstPart, secondPart);
}
[Fact]
public void Equals_WithDifferentIsOptional_ShouldReturnFalse()
{
// Arrange
LibraryPathPart firstPart = _libraryPathPartFixture.Create(kind: LibraryPathPartKind.DiscNumber, representation: "{0:00}", isOptional: false);
// Act
LibraryPathPart secondPart = _libraryPathPartFixture.Create(kind: LibraryPathPartKind.DiscNumber, representation: "{0:00}", isOptional: true);
// Assert
Assert.NotEqual(firstPart, secondPart);
}
}
@@ -0,0 +1,96 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects;
using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
#endregion
namespace Lumina.Domain.UnitTests.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects;
/// <summary>
/// Contains unit tests for the <see cref="LibraryPathTemplate"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class LibraryPathTemplateTests
{
private readonly LibraryPathTemplateFixture _libraryPathTemplateFixture = new();
private readonly LibraryPathPartFixture _libraryPathPartFixture = new();
[Fact]
public void Create_WhenCalledWithParts_ShouldCreateTemplateWithThoseParts()
{
// Arrange
LibraryPathTemplate template = _libraryPathTemplateFixture.Create();
// Act
LibraryPathTemplate result = LibraryPathTemplate.Create(template.Parts);
// Assert
Assert.Equal(template.Parts, result.Parts);
Assert.False(result.IsEmpty);
}
[Fact]
public void Empty_WhenCalled_ShouldCreateTemplateWithoutParts()
{
// Act
LibraryPathTemplate result = LibraryPathTemplate.Empty();
// Assert
Assert.Empty(result.Parts);
Assert.True(result.IsEmpty);
}
[Fact]
public void Create_WhenSourceCollectionIsLaterModified_ShouldNotAffectTheTemplate()
{
// Arrange
List<LibraryPathPart> sourceParts = [.. _libraryPathTemplateFixture.Create().Parts];
int originalCount = sourceParts.Count;
// Act
LibraryPathTemplate template = LibraryPathTemplate.Create(sourceParts);
sourceParts.Clear();
// Assert
Assert.Equal(originalCount, template.Parts.Count);
}
[Fact]
public void Equals_WithSameValues_ShouldReturnTrue()
{
// Arrange
LibraryPathTemplate firstTemplate = _libraryPathTemplateFixture.Create();
// Act
LibraryPathTemplate secondTemplate = LibraryPathTemplate.Create(firstTemplate.Parts);
// Assert
Assert.Equal(firstTemplate, secondTemplate);
}
[Fact]
public void Equals_WithDifferentParts_ShouldReturnFalse()
{
// Arrange
LibraryPathTemplate firstTemplate = _libraryPathTemplateFixture.Create();
// Act
// The second template extends the first one, because two random templates can be identical (a single typed part of the same kind).
LibraryPathTemplate secondTemplate = LibraryPathTemplate.Create([.. firstTemplate.Parts, _libraryPathPartFixture.Create()]);
// Assert
Assert.NotEqual(firstTemplate, secondTemplate);
}
[Fact]
public void Equals_WhenBothTemplatesAreEmpty_ShouldReturnTrue()
{
// Act
LibraryPathTemplate firstTemplate = LibraryPathTemplate.Empty();
LibraryPathTemplate secondTemplate = LibraryPathTemplate.Empty();
// Assert
Assert.Equal(firstTemplate, secondTemplate);
}
}
@@ -0,0 +1,46 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Domain.Common.Events;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Events;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects;
using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects;
using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Events;
using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects;
using System;
using System.Diagnostics.CodeAnalysis;
#endregion
namespace Lumina.Domain.UnitTests.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Events;
/// <summary>
/// Contains unit tests for the <see cref="LibraryMediaItemDeletedDomainEvent"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class LibraryMediaItemDeletedDomainEventTests
{
private readonly LibraryIdFixture _libraryIdFixture = new();
private readonly MediaLibraryScanCompositeIdFixture _mediaLibraryScanCompositeIdFixture = new();
private readonly LibraryMediaItemDeletedDomainEventFixture _libraryMediaItemDeletedDomainEventFixture = new();
[Fact]
public void Constructor_WhenCalled_ShouldSetAllProperties()
{
// Arrange
Guid id = Guid.NewGuid();
LibraryId libraryId = _libraryIdFixture.Create();
MediaLibraryScanCompositeId compositeId = _mediaLibraryScanCompositeIdFixture.Create();
string path = "C:/Media/Books/old-book.pdf";
DateTime occurredOnUtc = DateTime.UtcNow;
// Act
LibraryMediaItemDeletedDomainEvent domainEvent = _libraryMediaItemDeletedDomainEventFixture.Create(id, libraryId, compositeId, path, occurredOnUtc);
// Assert
Assert.Equal(id, domainEvent.Id);
Assert.Equal(libraryId, domainEvent.LibraryId);
Assert.Equal(compositeId, domainEvent.MediaLibraryScanCompositeId);
Assert.Equal(path, domainEvent.Path);
Assert.Equal(occurredOnUtc, domainEvent.OccurredOnUtc);
Assert.IsAssignableFrom<IDomainEvent>(domainEvent);
}
}
@@ -0,0 +1,44 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Domain.Common.Events;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Events;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects;
using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects;
using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Events;
using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects;
using System;
using System.Diagnostics.CodeAnalysis;
#endregion
namespace Lumina.Domain.UnitTests.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Events;
/// <summary>
/// Contains unit tests for the <see cref="LibraryScanCancelledDomainEvent"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class LibraryScanCancelledDomainEventTests
{
private readonly ScanIdFixture _scanIdFixture = new();
private readonly LibraryIdFixture _libraryIdFixture = new();
private readonly LibraryScanCancelledDomainEventFixture _libraryScanCancelledDomainEventFixture = new();
[Fact]
public void Constructor_WhenCalled_ShouldSetAllProperties()
{
// Arrange
Guid id = Guid.NewGuid();
ScanId scanId = _scanIdFixture.Create();
LibraryId libraryId = _libraryIdFixture.Create();
DateTime occurredOnUtc = DateTime.UtcNow;
// Act
LibraryScanCancelledDomainEvent domainEvent = _libraryScanCancelledDomainEventFixture.Create(id, scanId, libraryId, occurredOnUtc);
// Assert
Assert.Equal(id, domainEvent.Id);
Assert.Equal(scanId, domainEvent.ScanId);
Assert.Equal(libraryId, domainEvent.LibraryId);
Assert.Equal(occurredOnUtc, domainEvent.OccurredOnUtc);
Assert.IsAssignableFrom<IDomainEvent>(domainEvent);
}
}
@@ -0,0 +1,63 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Domain.Common.Events;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Events;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects;
using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects;
using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Events;
using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects;
using System;
using System.Diagnostics.CodeAnalysis;
#endregion
namespace Lumina.Domain.UnitTests.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Events;
/// <summary>
/// Contains unit tests for the <see cref="LibraryScanFailedDomainEvent"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class LibraryScanFailedDomainEventTests
{
private readonly LibraryIdFixture _libraryIdFixture = new();
private readonly MediaLibraryScanCompositeIdFixture _mediaLibraryScanCompositeIdFixture = new();
private readonly LibraryScanFailedDomainEventFixture _libraryScanFailedDomainEventFixture = new();
[Fact]
public void Constructor_WhenCalledWithErrorMessage_ShouldSetAllProperties()
{
// Arrange
Guid id = Guid.NewGuid();
LibraryId libraryId = _libraryIdFixture.Create();
MediaLibraryScanCompositeId compositeId = _mediaLibraryScanCompositeIdFixture.Create();
DateTime occurredOnUtc = DateTime.UtcNow;
string errorMessage = "Scan failed unexpectedly.";
// Act
LibraryScanFailedDomainEvent domainEvent = _libraryScanFailedDomainEventFixture.Create(
id: id,
libraryId: libraryId,
mediaLibraryScanCompositeId: compositeId,
occurredOnUtc: occurredOnUtc,
errorMessage: errorMessage);
// Assert
Assert.Equal(id, domainEvent.Id);
Assert.Equal(libraryId, domainEvent.LibraryId);
Assert.Equal(compositeId, domainEvent.MediaLibraryScanCompositeId);
Assert.Equal(occurredOnUtc, domainEvent.OccurredOnUtc);
Assert.True(domainEvent.ErrorMessage.HasValue);
Assert.Equal(errorMessage, domainEvent.ErrorMessage.Value);
Assert.IsType<IDomainEvent>(domainEvent, exactMatch: false);
}
[Fact]
public void Constructor_WhenCalledWithoutErrorMessage_ShouldLeaveErrorMessageUnset()
{
// Act
LibraryScanFailedDomainEvent domainEvent = _libraryScanFailedDomainEventFixture.Create(includeErrorMessage: false);
// Assert
Assert.False(domainEvent.ErrorMessage.HasValue);
Assert.IsType<IDomainEvent>(domainEvent, exactMatch: false);
}
}
@@ -0,0 +1,39 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Domain.Common.Events;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Events;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects;
using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Events;
using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects;
using System;
using System.Diagnostics.CodeAnalysis;
#endregion
namespace Lumina.Domain.UnitTests.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Events;
/// <summary>
/// Contains unit tests for the <see cref="LibraryScanFinishedDomainEvent"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class LibraryScanFinishedDomainEventTests
{
private readonly MediaLibraryScanCompositeIdFixture _mediaLibraryScanCompositeIdFixture = new();
private readonly LibraryScanFinishedDomainEventFixture _libraryScanFinishedDomainEventFixture = new();
[Fact]
public void Constructor_WhenCalled_ShouldSetAllProperties()
{
// Arrange
Guid id = Guid.NewGuid();
MediaLibraryScanCompositeId compositeId = _mediaLibraryScanCompositeIdFixture.Create();
DateTime occurredOnUtc = DateTime.UtcNow;
// Act
LibraryScanFinishedDomainEvent domainEvent = _libraryScanFinishedDomainEventFixture.Create(id, compositeId, occurredOnUtc);
// Assert
Assert.Equal(id, domainEvent.Id);
Assert.Equal(compositeId, domainEvent.MediaLibraryScanCompositeId);
Assert.Equal(occurredOnUtc, domainEvent.OccurredOnUtc);
Assert.IsType<IDomainEvent>(domainEvent, exactMatch: false);
}
}
@@ -0,0 +1,47 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Domain.Common.Events;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Events;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects;
using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects;
using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Events;
using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects;
using System;
using System.Diagnostics.CodeAnalysis;
#endregion
namespace Lumina.Domain.UnitTests.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Events;
/// <summary>
/// Contains unit tests for the <see cref="LibraryScanJobProgressChangedDomainEvent"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class LibraryScanJobProgressChangedDomainEventTests
{
private readonly LibraryIdFixture _libraryIdFixture = new();
private readonly MediaLibraryScanCompositeIdFixture _mediaLibraryScanCompositeIdFixture = new();
private readonly MediaLibraryScanJobProgressFixture _mediaLibraryScanJobProgressFixture = new();
private readonly LibraryScanJobProgressChangedDomainEventFixture _libraryScanJobProgressChangedDomainEventFixture = new();
[Fact]
public void Constructor_WhenCalled_ShouldSetAllProperties()
{
// Arrange
Guid id = Guid.NewGuid();
LibraryId libraryId = _libraryIdFixture.Create();
MediaLibraryScanCompositeId compositeId = _mediaLibraryScanCompositeIdFixture.Create();
MediaLibraryScanJobProgress progress = _mediaLibraryScanJobProgressFixture.Create();
DateTime occurredOnUtc = DateTime.UtcNow;
// Act
LibraryScanJobProgressChangedDomainEvent domainEvent = _libraryScanJobProgressChangedDomainEventFixture.Create(id, libraryId, compositeId, progress, occurredOnUtc);
// Assert
Assert.Equal(id, domainEvent.Id);
Assert.Equal(libraryId, domainEvent.LibraryId);
Assert.Equal(compositeId, domainEvent.MediaLibraryScanCompositeId);
Assert.Equal(progress, domainEvent.Progress);
Assert.Equal(occurredOnUtc, domainEvent.OccurredOnUtc);
Assert.IsType<IDomainEvent>(domainEvent, exactMatch: false);
}
}
@@ -0,0 +1,44 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Domain.Common.Events;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Events;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects;
using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects;
using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Events;
using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects;
using System;
using System.Diagnostics.CodeAnalysis;
#endregion
namespace Lumina.Domain.UnitTests.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Events;
/// <summary>
/// Contains unit tests for the <see cref="LibraryScanProgressChangedDomainEvent"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class LibraryScanProgressChangedDomainEventTests
{
private readonly LibraryIdFixture _libraryIdFixture = new();
private readonly MediaLibraryScanCompositeIdFixture _mediaLibraryScanCompositeIdFixture = new();
private readonly LibraryScanProgressChangedDomainEventFixture _libraryScanProgressChangedDomainEventFixture = new();
[Fact]
public void Constructor_WhenCalled_ShouldSetAllProperties()
{
// Arrange
Guid id = Guid.NewGuid();
LibraryId libraryId = _libraryIdFixture.Create();
MediaLibraryScanCompositeId compositeId = _mediaLibraryScanCompositeIdFixture.Create();
DateTime occurredOnUtc = DateTime.UtcNow;
// Act
LibraryScanProgressChangedDomainEvent domainEvent = _libraryScanProgressChangedDomainEventFixture.Create(id, libraryId, compositeId, occurredOnUtc);
// Assert
Assert.Equal(id, domainEvent.Id);
Assert.Equal(libraryId, domainEvent.LibraryId);
Assert.Equal(compositeId, domainEvent.MediaLibraryScanCompositeId);
Assert.Equal(occurredOnUtc, domainEvent.OccurredOnUtc);
Assert.IsType<IDomainEvent>(domainEvent, exactMatch: false);
}
}
@@ -0,0 +1,49 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Domain.Common.Events;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Events;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects;
using Lumina.Domain.Core.BoundedContexts.UserManagementBoundedContext.UserAggregate.ValueObjects;
using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects;
using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Events;
using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects;
using Lumina.Domain.Fixtures.Core.BoundedContexts.UserManagementBoundedContext.UserAggregate.ValueObjects;
using System;
using System.Diagnostics.CodeAnalysis;
#endregion
namespace Lumina.Domain.UnitTests.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Events;
/// <summary>
/// Contains unit tests for the <see cref="LibraryScanQueuedDomainEvent"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class LibraryScanQueuedDomainEventTests
{
private readonly ScanIdFixture _scanIdFixture = new();
private readonly UserIdFixture _userIdFixture = new();
private readonly LibraryIdFixture _libraryIdFixture = new();
private readonly LibraryScanQueuedDomainEventFixture _libraryScanQueuedDomainEventFixture = new();
[Fact]
public void Constructor_WhenCalled_ShouldSetAllProperties()
{
// Arrange
Guid id = Guid.NewGuid();
ScanId scanId = _scanIdFixture.Create();
UserId userId = _userIdFixture.Create();
LibraryId libraryId = _libraryIdFixture.Create();
DateTime occurredOnUtc = DateTime.UtcNow;
// Act
LibraryScanQueuedDomainEvent domainEvent = _libraryScanQueuedDomainEventFixture.Create(id, scanId, userId, libraryId, occurredOnUtc);
// Assert
Assert.Equal(id, domainEvent.Id);
Assert.Equal(scanId, domainEvent.ScanId);
Assert.Equal(userId, domainEvent.UserId);
Assert.Equal(libraryId, domainEvent.LibraryId);
Assert.Equal(occurredOnUtc, domainEvent.OccurredOnUtc);
Assert.IsType<IDomainEvent>(domainEvent, exactMatch: false);
}
}
@@ -0,0 +1,39 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Domain.Common.Events;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Events;
using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate;
using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Events;
using System;
using System.Diagnostics.CodeAnalysis;
#endregion
namespace Lumina.Domain.UnitTests.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Events;
/// <summary>
/// Contains unit tests for the <see cref="LibraryScanStartedDomainEvent"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class LibraryScanStartedDomainEventTests
{
private readonly LibraryScanFixture _libraryScanFixture = new();
private readonly LibraryScanStartedDomainEventFixture _libraryScanStartedDomainEventFixture = new();
[Fact]
public void Constructor_WhenCalled_ShouldSetAllProperties()
{
// Arrange
Guid id = Guid.NewGuid();
LibraryScan scan = _libraryScanFixture.Create();
DateTime occurredOnUtc = DateTime.UtcNow;
// Act
LibraryScanStartedDomainEvent domainEvent = _libraryScanStartedDomainEventFixture.Create(id, scan, occurredOnUtc);
// Assert
Assert.Equal(id, domainEvent.Id);
Assert.Equal(scan, domainEvent.LibraryScan);
Assert.Equal(occurredOnUtc, domainEvent.OccurredOnUtc);
Assert.IsType<IDomainEvent>(domainEvent, exactMatch: false);
}
}
@@ -0,0 +1,295 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Domain.Common.Errors;
using Lumina.Domain.Common.Events;
using Lumina.Domain.Common.Primitives;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Events;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects;
using Lumina.Domain.Core.BoundedContexts.UserManagementBoundedContext.UserAggregate.ValueObjects;
using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects;
using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate;
using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects;
using Lumina.Domain.Fixtures.Core.BoundedContexts.UserManagementBoundedContext.UserAggregate.ValueObjects;
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
#endregion
namespace Lumina.Domain.UnitTests.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate;
/// <summary>
/// Contains unit tests for the <see cref="LibraryScan"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class LibraryScanTests
{
private readonly LibraryScanFixture _libraryScanFixture = new();
private readonly ScanIdFixture _scanIdFixture = new();
private readonly LibraryIdFixture _libraryIdFixture = new();
private readonly UserIdFixture _userIdFixture = new();
[Fact]
public void Create_WhenCalledWithValidData_ShouldCreateScanWithPendingStatus()
{
// Arrange
LibraryId libraryId = _libraryIdFixture.Create();
UserId userId = _userIdFixture.Create();
// Act
Result<LibraryScan> result = LibraryScan.Create(libraryId, userId, []);
// Assert
Assert.False(result.IsFailure);
Assert.Equal(libraryId, result.Value.LibraryId);
Assert.Equal(userId, result.Value.UserId);
Assert.Equal(LibraryScanJobStatus.Pending, result.Value.Status);
Assert.NotEqual(default, result.Value.Id.Value);
}
[Fact]
public void Create_WhenCalledWithPreExistingIdAndStatus_ShouldCreateScanWithThoseValues()
{
// Arrange
Guid id = Guid.NewGuid();
LibraryId libraryId = _libraryIdFixture.Create();
UserId userId = _userIdFixture.Create();
// Act
Result<LibraryScan> result = LibraryScan.Create(_scanIdFixture.Create(id), libraryId, userId, LibraryScanJobStatus.Running, []);
// Assert
Assert.False(result.IsFailure);
Assert.Equal(id, result.Value.Id.Value);
Assert.Equal(libraryId, result.Value.LibraryId);
Assert.Equal(userId, result.Value.UserId);
Assert.Equal(LibraryScanJobStatus.Running, result.Value.Status);
}
[Fact]
public void Create_WhenCalledTwice_ShouldGenerateDistinctIds()
{
// Act
Result<LibraryScan> firstResult = LibraryScan.Create(_libraryIdFixture.Create(), _userIdFixture.Create(), []);
Result<LibraryScan> secondResult = LibraryScan.Create(_libraryIdFixture.Create(), _userIdFixture.Create(), []);
// Assert
Assert.False(firstResult.IsFailure);
Assert.False(secondResult.IsFailure);
Assert.NotEqual(firstResult.Value.Id.Value, secondResult.Value.Id.Value);
}
[Fact]
public void QueueScan_WhenNoActivePastScanExists_ShouldSucceedAndRaiseQueuedEvent()
{
// Arrange
LibraryScan scan = _libraryScanFixture.Create();
// Act
Result<Success> result = scan.QueueScan();
// Assert
Assert.False(result.IsFailure);
Assert.Equal(Result.Success, result.Value);
Assert.Equal(LibraryScanJobStatus.Pending, scan.Status);
LibraryScanQueuedDomainEvent queuedEvent = Assert.IsType<LibraryScanQueuedDomainEvent>(Assert.Single(scan.GetDomainEvents()));
Assert.Equal(scan.Id, queuedEvent.ScanId);
Assert.Equal(scan.UserId, queuedEvent.UserId);
Assert.Equal(scan.LibraryId, queuedEvent.LibraryId);
}
[Fact]
public void QueueScan_WhenPastScanIsRunning_ShouldReturnError()
{
// Arrange
LibraryScan pastScan = _libraryScanFixture.Create(status: LibraryScanJobStatus.Running);
LibraryScan scan = _libraryScanFixture.Create(pastScans: [pastScan]);
// Act
Result<Success> result = scan.QueueScan();
// Assert
Assert.True(result.IsFailure);
Assert.Equal(Errors.LibraryScanning.LibraryAlreadyBeingScanned, result.FirstError);
Assert.Empty(scan.GetDomainEvents());
}
[Fact]
public void QueueScan_WhenPastScanIsPending_ShouldReturnError()
{
// Arrange
LibraryScan pastScan = _libraryScanFixture.Create(status: LibraryScanJobStatus.Pending);
LibraryScan scan = _libraryScanFixture.Create(pastScans: [pastScan]);
// Act
Result<Success> result = scan.QueueScan();
// Assert
Assert.True(result.IsFailure);
Assert.Equal(Errors.LibraryScanning.LibraryAlreadyBeingScanned, result.FirstError);
Assert.Empty(scan.GetDomainEvents());
}
[Fact]
public void StartScan_WhenPending_ShouldTransitionToRunningAndRaiseStartedEvent()
{
// Arrange
LibraryScan scan = _libraryScanFixture.Create();
// Act
Result<Success> result = scan.StartScan();
// Assert
Assert.False(result.IsFailure);
Assert.Equal(Result.Success, result.Value);
Assert.Equal(LibraryScanJobStatus.Running, scan.Status);
LibraryScanStartedDomainEvent startedEvent = Assert.IsType<LibraryScanStartedDomainEvent>(Assert.Single(scan.GetDomainEvents()));
Assert.Equal(scan, startedEvent.LibraryScan);
}
[Theory]
[InlineData(LibraryScanJobStatus.Running)] // Cannot start an already running scan.
[InlineData(LibraryScanJobStatus.Completed)] // Cannot start a completed scan.
[InlineData(LibraryScanJobStatus.Canceled)] // Cannot start a canceled scan.
[InlineData(LibraryScanJobStatus.Failed)] // Cannot start a failed scan.
public void StartScan_WhenNotPending_ShouldReturnError(LibraryScanJobStatus status)
{
// Arrange
LibraryScan scan = _libraryScanFixture.Create(status: status);
// Act
Result<Success> result = scan.StartScan();
// Assert
Assert.True(result.IsFailure);
Assert.Equal(Errors.LibraryScanning.CanOnlyStartPendingScans, result.FirstError);
Assert.Equal(status, scan.Status);
Assert.Empty(scan.GetDomainEvents());
}
[Fact]
public void StartScan_WhenPastScanIsActive_ShouldReturnError()
{
// Arrange
LibraryScan pastScan = _libraryScanFixture.Create(status: LibraryScanJobStatus.Running);
LibraryScan scan = _libraryScanFixture.Create(pastScans: [pastScan]);
// Act
Result<Success> result = scan.StartScan();
// Assert
Assert.True(result.IsFailure);
Assert.Equal(Errors.LibraryScanning.LibraryAlreadyBeingScanned, result.FirstError);
Assert.Empty(scan.GetDomainEvents());
}
[Fact]
public void FinishScan_WhenRunning_ShouldTransitionToCompleted()
{
// Arrange
LibraryScan scan = _libraryScanFixture.Create(status: LibraryScanJobStatus.Running);
// Act
Result<Success> result = scan.FinishScan();
// Assert
Assert.False(result.IsFailure);
Assert.Equal(Result.Success, result.Value);
Assert.Equal(LibraryScanJobStatus.Completed, scan.Status);
}
[Theory]
[InlineData(LibraryScanJobStatus.Pending)] // Cannot complete a pending scan.
[InlineData(LibraryScanJobStatus.Completed)] // Cannot complete an already completed scan.
[InlineData(LibraryScanJobStatus.Canceled)] // Cannot complete a canceled scan.
[InlineData(LibraryScanJobStatus.Failed)] // Cannot complete a failed scan.
public void FinishScan_WhenNotRunning_ShouldReturnError(LibraryScanJobStatus status)
{
// Arrange
LibraryScan scan = _libraryScanFixture.Create(status: status);
// Act
Result<Success> result = scan.FinishScan();
// Assert
Assert.True(result.IsFailure);
Assert.Equal(Errors.LibraryScanning.CanOnlyCompleteRunningScans, result.FirstError);
Assert.Equal(status, scan.Status);
}
[Theory]
[InlineData(LibraryScanJobStatus.Pending)] // A scan waiting in the scan queue can be canceled too.
[InlineData(LibraryScanJobStatus.Running)] // A scan that is already executing can be canceled.
public void CancelScan_WhenPendingOrRunning_ShouldTransitionToCanceledAndRaiseCancelledEvent(LibraryScanJobStatus status)
{
// Arrange
LibraryScan scan = _libraryScanFixture.Create(status: status);
// Act
Result<Success> result = scan.CancelScan();
// Assert
Assert.False(result.IsFailure);
Assert.Equal(Result.Success, result.Value);
Assert.Equal(LibraryScanJobStatus.Canceled, scan.Status);
LibraryScanCancelledDomainEvent cancelledEvent = Assert.IsType<LibraryScanCancelledDomainEvent>(Assert.Single(scan.GetDomainEvents()));
Assert.Equal(scan.Id, cancelledEvent.ScanId);
Assert.Equal(scan.LibraryId, cancelledEvent.LibraryId);
}
[Theory]
[InlineData(LibraryScanJobStatus.Completed)] // Cannot cancel a completed scan.
[InlineData(LibraryScanJobStatus.Canceled)] // Cannot cancel an already canceled scan.
[InlineData(LibraryScanJobStatus.Failed)] // Cannot cancel a failed scan.
public void CancelScan_WhenInATerminalState_ShouldReturnError(LibraryScanJobStatus status)
{
// Arrange
LibraryScan scan = _libraryScanFixture.Create(status: status);
// Act
Result<Success> result = scan.CancelScan();
// Assert
Assert.True(result.IsFailure);
Assert.Equal(Errors.LibraryScanning.CanOnlyCancelPendingOrRunningScans, result.FirstError);
Assert.Equal(status, scan.Status);
Assert.Empty(scan.GetDomainEvents());
}
[Theory]
[InlineData(LibraryScanJobStatus.Pending)] // A scan that has no scanner yet fails before it starts executing.
[InlineData(LibraryScanJobStatus.Running)] // A scan that is executing can fail too.
public void FailScan_WhenPendingOrRunning_ShouldTransitionToFailed(LibraryScanJobStatus status)
{
// Arrange
LibraryScan scan = _libraryScanFixture.Create(status: status);
// Act
Result<Success> result = scan.FailScan();
// Assert
Assert.False(result.IsFailure);
Assert.Equal(Result.Success, result.Value);
Assert.Equal(LibraryScanJobStatus.Failed, scan.Status);
}
[Theory]
[InlineData(LibraryScanJobStatus.Completed)] // Cannot fail a completed scan.
[InlineData(LibraryScanJobStatus.Canceled)] // Cannot fail a canceled scan.
[InlineData(LibraryScanJobStatus.Failed)] // Cannot fail an already failed scan.
public void FailScan_WhenInATerminalState_ShouldReturnError(LibraryScanJobStatus status)
{
// Arrange
LibraryScan scan = _libraryScanFixture.Create(status: status);
// Act
Result<Success> result = scan.FailScan();
// Assert
Assert.True(result.IsFailure);
Assert.Equal(Errors.LibraryScanning.CanOnlyFailPendingOrRunningScans, result.FirstError);
Assert.Equal(status, scan.Status);
}
}
@@ -0,0 +1,78 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Jobs;
using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects;
using Microsoft.Extensions.DependencyInjection;
using NSubstitute;
using System;
using System.Diagnostics.CodeAnalysis;
#endregion
namespace Lumina.Domain.UnitTests.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Jobs;
/// <summary>
/// Contains unit tests for the <see cref="MediaLibraryScanJobFactory"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class MediaLibraryScanJobFactoryTests
{
private readonly LibraryIdFixture _libraryIdFixture = new();
[Fact]
public void CreateJob_WhenJobTypeIsRegistered_ShouldResolveJobAndSetLibraryId()
{
// Arrange
LibraryId libraryId = _libraryIdFixture.Create();
IMediaLibraryScanJob expectedJob = Substitute.For<IMediaLibraryScanJob>();
ServiceCollection services = new();
services.AddSingleton(expectedJob);
using ServiceProvider serviceProvider = services.BuildServiceProvider();
MediaLibraryScanJobFactory sut = new(serviceProvider);
// Act
IMediaLibraryScanJob job = sut.CreateJob<IMediaLibraryScanJob>(libraryId);
// Assert
Assert.Same(expectedJob, job);
Assert.Equal(libraryId, job.LibraryId);
}
[Fact]
public void CreateJob_WhenJobTypeIsNotRegistered_ShouldThrowInvalidOperationException()
{
// Arrange
ServiceCollection services = new();
using ServiceProvider serviceProvider = services.BuildServiceProvider();
MediaLibraryScanJobFactory sut = new(serviceProvider);
// Act & Assert
Assert.Throws<InvalidOperationException>(() => sut.CreateJob<IMediaLibraryScanJob>(_libraryIdFixture.Create()));
}
[Fact]
public void CreateJob_WhenServiceProviderReturnsNull_ShouldThrowInvalidOperationException()
{
// Arrange
MediaLibraryScanJobFactory sut = new(new NullServiceProvider());
// Act & Assert
InvalidOperationException exception = Assert.Throws<InvalidOperationException>(() => sut.CreateJob<IMediaLibraryScanJob>(_libraryIdFixture.Create()));
Assert.Contains("IMediaLibraryScanJob", exception.Message);
}
/// <summary>
/// Test service provider that returns <see langword="null"/> for every requested service.
/// </summary>
private sealed class NullServiceProvider : IServiceProvider
{
/// <summary>
/// Gets the service object of the specified type.
/// </summary>
/// <param name="serviceType">The type of service to get.</param>
/// <returns><see langword="null"/>.</returns>
public object? GetService(Type serviceType)
{
return null;
}
}
}
@@ -0,0 +1,175 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Jobs;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects;
using Lumina.Domain.Core.BoundedContexts.UserManagementBoundedContext.UserAggregate.ValueObjects;
using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects;
using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects;
using Lumina.Domain.Fixtures.Core.BoundedContexts.UserManagementBoundedContext.UserAggregate.ValueObjects;
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
using System;
using System.Diagnostics.CodeAnalysis;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Domain.UnitTests.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Jobs;
/// <summary>
/// Contains unit tests for the <see cref="MediaLibraryScanJob"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class MediaLibraryScanJobTests
{
private readonly ScanIdFixture _scanIdFixture = new();
private readonly UserIdFixture _userIdFixture = new();
private readonly LibraryIdFixture _libraryIdFixture = new();
[Fact]
public void Status_WhenCreated_ShouldBePending()
{
// Act
TestMediaLibraryScanJob job = CreateJob();
// Assert
Assert.Equal(LibraryScanJobStatus.Pending, job.Status);
Assert.Empty(job.Children);
Assert.Empty(job.Parents);
}
[Fact]
public void AddChild_WhenCalledWithNewJob_ShouldAddChild()
{
// Arrange
TestMediaLibraryScanJob job = CreateJob();
TestMediaLibraryScanJob child = CreateJob();
// Act
job.AddChild(child);
// Assert
Assert.Single(job.Children);
Assert.Contains(child, job.Children);
}
[Fact]
public void AddChild_WhenJobIsAlreadyChild_ShouldNotAddDuplicate()
{
// Arrange
TestMediaLibraryScanJob job = CreateJob();
TestMediaLibraryScanJob child = CreateJob();
// Act
job.AddChild(child);
job.AddChild(child);
// Assert
Assert.Single(job.Children);
}
[Fact]
public void AddChild_WhenJobIsParent_ShouldNotAddChild()
{
// Arrange
TestMediaLibraryScanJob job = CreateJob();
TestMediaLibraryScanJob parent = CreateJob();
job.AddParent(parent);
// Act
job.AddChild(parent);
// Assert
Assert.Empty(job.Children);
Assert.Single(job.Parents);
}
[Fact]
public void AddParent_WhenCalledWithNewJob_ShouldAddParent()
{
// Arrange
TestMediaLibraryScanJob job = CreateJob();
TestMediaLibraryScanJob parent = CreateJob();
// Act
job.AddParent(parent);
// Assert
Assert.Single(job.Parents);
Assert.Contains(parent, job.Parents);
}
[Fact]
public void AddParent_WhenJobIsAlreadyParent_ShouldNotAddDuplicate()
{
// Arrange
TestMediaLibraryScanJob job = CreateJob();
TestMediaLibraryScanJob parent = CreateJob();
// Act
job.AddParent(parent);
job.AddParent(parent);
// Assert
Assert.Single(job.Parents);
}
[Fact]
public void AddParent_WhenJobIsChild_ShouldNotAddParent()
{
// Arrange
TestMediaLibraryScanJob job = CreateJob();
TestMediaLibraryScanJob child = CreateJob();
job.AddChild(child);
// Act
job.AddParent(child);
// Assert
Assert.Single(job.Children);
Assert.Empty(job.Parents);
}
[Fact]
public async Task ExecuteAsync_WhenCalled_ShouldCompleteWithoutChangingJobState()
{
// Arrange
TestMediaLibraryScanJob job = CreateJob();
// Act
await job.ExecuteAsync(Guid.NewGuid(), "input", CancellationToken.None);
// Assert
Assert.Equal(LibraryScanJobStatus.Pending, job.Status);
Assert.Empty(job.Children);
Assert.Empty(job.Parents);
}
private TestMediaLibraryScanJob CreateJob()
{
return new TestMediaLibraryScanJob
{
ScanId = _scanIdFixture.Create(),
UserId = _userIdFixture.Create(),
LibraryId = _libraryIdFixture.Create()
};
}
/// <summary>
/// Concrete test implementation of the abstract <see cref="MediaLibraryScanJob"/> class.
/// </summary>
private sealed class TestMediaLibraryScanJob : MediaLibraryScanJob
{
/// <summary>
/// Executes the payload of the media library scan job.
/// </summary>
/// <typeparam name="TInput">The type of the input parameter.</typeparam>
/// <param name="id">The unique identifier of the media library scan job.</param>
/// <param name="input">The input data to be processed.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>A task that represents the asynchronous operation.</returns>
public override Task ExecuteAsync<TInput>(Guid id, TInput input, CancellationToken cancellationToken)
{
return Task.CompletedTask;
}
}
}
@@ -0,0 +1,299 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Domain.Common.Errors;
using Lumina.Domain.Common.Events;
using Lumina.Domain.Common.Primitives;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Events;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Cancellation;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Jobs;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Progress;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Scanners;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects;
using Lumina.Domain.Core.BoundedContexts.UserManagementBoundedContext.UserAggregate.ValueObjects;
using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects;
using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate;
using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Jobs;
using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects;
using Lumina.Domain.Fixtures.Core.BoundedContexts.UserManagementBoundedContext.UserAggregate.ValueObjects;
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
using NSubstitute;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Domain.UnitTests.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services;
/// <summary>
/// Contains unit tests for the <see cref="MediaLibraryScanningService"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class MediaLibraryScanningServiceTests
{
private readonly IMediaLibraryScannerFactory _mockScannerFactory;
private readonly IMediaLibrariesScanCancellationTracker _mockCancellationTracker;
private readonly IMediaLibrariesScanProgressTracker _mockProgressTracker;
private readonly IDomainEventPublisher _mockDomainEventPublisher;
private readonly MediaLibraryScanningService _sut;
private readonly LibraryScanFixture _libraryScanFixture = new();
private readonly ScanIdFixture _scanIdFixture = new();
private readonly UserIdFixture _userIdFixture = new();
private readonly LibraryIdFixture _libraryIdFixture = new();
private readonly MediaLibraryScanDiscoveryJobFixture _mediaLibraryScanDiscoveryJobFixture = new();
/// <summary>
/// Initializes a new instance of the <see cref="MediaLibraryScanningServiceTests"/> class.
/// </summary>
public MediaLibraryScanningServiceTests()
{
_mockScannerFactory = Substitute.For<IMediaLibraryScannerFactory>();
_mockCancellationTracker = Substitute.For<IMediaLibrariesScanCancellationTracker>();
_mockProgressTracker = Substitute.For<IMediaLibrariesScanProgressTracker>();
_mockProgressTracker.InitializeScanProgress(Arg.Any<LibraryId>(), Arg.Any<MediaLibraryScanCompositeId>(), Arg.Any<int>())
.Returns(Result.Created);
_mockDomainEventPublisher = Substitute.For<IDomainEventPublisher>();
_sut = new MediaLibraryScanningService(_mockScannerFactory, _mockCancellationTracker, _mockProgressTracker, _mockDomainEventPublisher);
}
[Fact]
public async Task StartScanAsync_WhenScanStartsSuccessfully_ShouldReturnTheDiscoveryRootJob()
{
// Arrange
LibraryScan scan = _libraryScanFixture.Create();
FakeMediaLibraryScanDiscoveryJob rootJob = _mediaLibraryScanDiscoveryJobFixture.Create();
RegisterScanner(LibraryType.Book, rootJob);
// Act
Result<IMediaLibraryScanDiscoveryJob> result = await _sut.StartScanAsync(scan, LibraryType.Book, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
Assert.Same(rootJob, result.Value);
Assert.Equal(LibraryScanJobStatus.Running, scan.Status);
}
[Fact]
public async Task StartScanAsync_WhenScanStartsSuccessfully_ShouldPublishTheStartedEvent()
{
// Arrange
LibraryScan scan = _libraryScanFixture.Create();
RegisterScanner(LibraryType.Book, _mediaLibraryScanDiscoveryJobFixture.Create());
// Act
await _sut.StartScanAsync(scan, LibraryType.Book, CancellationToken.None);
// Assert
await _mockDomainEventPublisher.Received(1).PublishAsync(
Arg.Is<IDomainEvent>(domainEvent => domainEvent.GetType() == typeof(LibraryScanStartedDomainEvent)
&& ((LibraryScanStartedDomainEvent)domainEvent).LibraryScan == scan),
Arg.Any<CancellationToken>());
}
[Fact]
public async Task StartScanAsync_WhenScanStartsSuccessfully_ShouldRegisterTheScanForCancellation()
{
// Arrange
LibraryScan scan = _libraryScanFixture.Create();
RegisterScanner(LibraryType.Book, _mediaLibraryScanDiscoveryJobFixture.Create());
// Act
await _sut.StartScanAsync(scan, LibraryType.Book, CancellationToken.None);
// Assert
_mockCancellationTracker.Received(1).RegisterScan(
Arg.Is<MediaLibraryScanCompositeId>(compositeId => compositeId.ScanId == scan.Id && compositeId.UserId == scan.UserId));
}
[Fact]
public async Task StartScanAsync_WhenScanStartsSuccessfully_ShouldInitializeProgressWithTheRealJobCount()
{
// Arrange
LibraryScan scan = _libraryScanFixture.Create();
FakeMediaLibraryScanDiscoveryJob leafJob = _mediaLibraryScanDiscoveryJobFixture.Create();
FakeMediaLibraryScanDiscoveryJob middleJob = _mediaLibraryScanDiscoveryJobFixture.Create(children: [leafJob]);
FakeMediaLibraryScanDiscoveryJob rootJob = _mediaLibraryScanDiscoveryJobFixture.Create(children: [middleJob]);
RegisterScanner(LibraryType.Book, rootJob);
// Act
await _sut.StartScanAsync(scan, LibraryType.Book, CancellationToken.None);
// Assert
_mockProgressTracker.Received(1).InitializeScanProgress(
scan.LibraryId,
Arg.Is<MediaLibraryScanCompositeId>(compositeId => compositeId.ScanId == scan.Id && compositeId.UserId == scan.UserId),
totalJobs: 3);
}
[Fact]
public async Task StartScanAsync_WhenScanStartsSuccessfully_ShouldSetScanPropertiesOnTheWholeJobChain()
{
// Arrange
LibraryScan scan = _libraryScanFixture.Create();
FakeMediaLibraryScanDiscoveryJob leafJob = _mediaLibraryScanDiscoveryJobFixture.Create();
FakeMediaLibraryScanDiscoveryJob middleJob = _mediaLibraryScanDiscoveryJobFixture.Create(children: [leafJob]);
FakeMediaLibraryScanDiscoveryJob rootJob = _mediaLibraryScanDiscoveryJobFixture.Create(children: [middleJob]);
RegisterScanner(LibraryType.Book, rootJob);
// Act
await _sut.StartScanAsync(scan, LibraryType.Book, CancellationToken.None);
// Assert
AssertScanProperties(rootJob, scan);
AssertScanProperties(middleJob, scan);
AssertScanProperties(leafJob, scan);
}
[Fact]
public async Task StartScanAsync_WhenScannerIsUnavailable_ShouldReturnErrorAndChangeNothing()
{
// Arrange
LibraryScan scan = _libraryScanFixture.Create();
_mockScannerFactory.CreateLibraryScanner(LibraryType.Movie).Returns(Errors.LibraryScanning.NoScannerForLibraryType);
// Act
Result<IMediaLibraryScanDiscoveryJob> result = await _sut.StartScanAsync(scan, LibraryType.Movie, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(Errors.LibraryScanning.NoScannerForLibraryType, result.FirstError);
Assert.Equal(LibraryScanJobStatus.Pending, scan.Status);
Assert.Empty(scan.GetDomainEvents());
_mockCancellationTracker.DidNotReceive().RegisterScan(Arg.Any<MediaLibraryScanCompositeId>());
_mockProgressTracker.DidNotReceive().InitializeScanProgress(Arg.Any<LibraryId>(), Arg.Any<MediaLibraryScanCompositeId>(), Arg.Any<int>());
await _mockDomainEventPublisher.DidNotReceive().PublishAsync(Arg.Any<IDomainEvent>(), Arg.Any<CancellationToken>());
}
[Fact]
public async Task StartScanAsync_WhenScanIsNotPending_ShouldReturnErrorWithoutRegisteringOrPublishing()
{
// Arrange
LibraryScan scan = _libraryScanFixture.Create(status: LibraryScanJobStatus.Running);
RegisterScanner(LibraryType.Book, _mediaLibraryScanDiscoveryJobFixture.Create());
// Act
Result<IMediaLibraryScanDiscoveryJob> result = await _sut.StartScanAsync(scan, LibraryType.Book, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(Errors.LibraryScanning.CanOnlyStartPendingScans, result.FirstError);
Assert.Equal(LibraryScanJobStatus.Running, scan.Status);
Assert.Empty(scan.GetDomainEvents());
_mockCancellationTracker.DidNotReceive().RegisterScan(Arg.Any<MediaLibraryScanCompositeId>());
_mockProgressTracker.DidNotReceive().InitializeScanProgress(Arg.Any<LibraryId>(), Arg.Any<MediaLibraryScanCompositeId>(), Arg.Any<int>());
await _mockDomainEventPublisher.DidNotReceive().PublishAsync(Arg.Any<IDomainEvent>(), Arg.Any<CancellationToken>());
}
[Fact]
public async Task StartScanAsync_WhenProgressInitializationFails_ShouldReturnErrorWithoutPublishingEvents()
{
// Arrange
LibraryScan scan = _libraryScanFixture.Create();
RegisterScanner(LibraryType.Book, _mediaLibraryScanDiscoveryJobFixture.Create());
Error error = Error.Failure(description: "Failed to initialize the media library scan progress");
_mockProgressTracker.InitializeScanProgress(Arg.Any<LibraryId>(), Arg.Any<MediaLibraryScanCompositeId>(), Arg.Any<int>())
.Returns(error);
// Act
Result<IMediaLibraryScanDiscoveryJob> result = await _sut.StartScanAsync(scan, LibraryType.Book, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(error, result.FirstError);
await _mockDomainEventPublisher.DidNotReceive().PublishAsync(Arg.Any<IDomainEvent>(), Arg.Any<CancellationToken>());
}
[Fact]
public async Task StartScanAsync_WhenJobGraphHasSharedChild_ShouldCountOnlyUniqueJobs()
{
// Arrange
LibraryScan scan = _libraryScanFixture.Create();
IMediaLibraryScanJob sharedChild = CreateJob(children: []);
IMediaLibraryScanJob firstChild = CreateJob(children: [sharedChild]);
IMediaLibraryScanJob secondChild = CreateJob(children: [sharedChild]);
FakeMediaLibraryScanDiscoveryJob rootJob = _mediaLibraryScanDiscoveryJobFixture.Create(children: [firstChild, secondChild]);
RegisterScanner(LibraryType.Book, rootJob);
// Act
await _sut.StartScanAsync(scan, LibraryType.Book, CancellationToken.None);
// Assert
_mockProgressTracker.Received(1).InitializeScanProgress(scan.LibraryId, Arg.Any<MediaLibraryScanCompositeId>(), totalJobs: 4);
}
[Fact]
public void CancelScan_WhenCalled_ShouldCancelScanInTracker()
{
// Arrange
LibraryScan scan = _libraryScanFixture.Create();
// Act
Result<Success> result = _sut.CancelScan(scan);
// Assert
Assert.False(result.IsFailure);
Assert.Equal(Result.Success, result.Value);
_mockCancellationTracker.Received(1).CancelScan(Arg.Is<MediaLibraryScanCompositeId>(compositeId => compositeId.ScanId == scan.Id && compositeId.UserId == scan.UserId));
}
[Fact]
public void SetScanPropertiesForJobChain_WhenCalled_ShouldSetScanPropertiesRecursively()
{
// Arrange
ScanId scanId = _scanIdFixture.Create();
UserId userId = _userIdFixture.Create();
IMediaLibraryScanJob leafJob = CreateJob(children: []);
IMediaLibraryScanJob middleJob = CreateJob(children: [leafJob]);
IMediaLibraryScanJob rootJob = CreateJob(children: [middleJob]);
// Act
MediaLibraryScanningService.SetScanPropertiesForJobChain(rootJob, scanId, userId);
// Assert
Assert.Equal(scanId, rootJob.ScanId);
Assert.Equal(userId, rootJob.UserId);
Assert.Equal(scanId, middleJob.ScanId);
Assert.Equal(userId, middleJob.UserId);
Assert.Equal(scanId, leafJob.ScanId);
Assert.Equal(userId, leafJob.UserId);
}
/// <summary>
/// Registers a mocked media library scanner that returns <paramref name="rootJob"/> with the mocked scanner factory.
/// </summary>
/// <param name="libraryType">The media library type that the scanner is registered for.</param>
/// <param name="rootJob">The file system discovery job returned by the scanner.</param>
/// <returns>The created mocked scanner.</returns>
private IMediaTypeScanner RegisterScanner(LibraryType libraryType, IMediaLibraryScanDiscoveryJob rootJob)
{
IMediaTypeScanner scanner = Substitute.For<IMediaTypeScanner>();
scanner.CreateScanJobsForLibrary(Arg.Any<LibraryId>()).Returns(rootJob);
_mockScannerFactory.CreateLibraryScanner(libraryType).Returns(Result.From(scanner));
return scanner;
}
/// <summary>
/// Creates a mocked scan job with the given children.
/// </summary>
/// <param name="children">The child scan jobs of the created job.</param>
/// <returns>The created mocked scan job.</returns>
private static IMediaLibraryScanJob CreateJob(List<IMediaLibraryScanJob> children)
{
IMediaLibraryScanJob job = Substitute.For<IMediaLibraryScanJob>();
job.Children.Returns(children);
return job;
}
/// <summary>
/// Asserts that the scan identity of the scan was propagated to <paramref name="job"/>.
/// </summary>
/// <param name="job">The job whose scan properties are asserted.</param>
/// <param name="scan">The media library scan that owns the job.</param>
private static void AssertScanProperties(IMediaLibraryScanJob job, LibraryScan scan)
{
Assert.Equal(scan.Id, job.ScanId);
Assert.Equal(scan.UserId, job.UserId);
}
}
@@ -0,0 +1,497 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Domain.Common.Errors;
using Lumina.Domain.Common.Primitives;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.PathTemplate;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects;
using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects;
using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects;
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
using NSubstitute;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
#endregion
namespace Lumina.Domain.UnitTests.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.PathTemplate;
/// <summary>
/// Contains unit tests for the <see cref="LibraryPathTemplateService"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class LibraryPathTemplateServiceTests
{
private readonly ILibraryPathPartCatalog _mockCatalog = Substitute.For<ILibraryPathPartCatalog>();
private readonly LibraryPathTemplateService _sut;
private readonly LibraryPathPartFixture _libraryPathPartFixture = new();
private readonly LibraryPathTemplateFixture _libraryPathTemplateFixture = new();
private readonly LibraryPathPartDefinitionFixture _libraryPathPartDefinitionFixture = new();
/// <summary>
/// Initializes a new instance of the <see cref="LibraryPathTemplateServiceTests"/> class.
/// </summary>
public LibraryPathTemplateServiceTests()
{
_mockCatalog.SupportedLibraryType.Returns(LibraryType.Music);
_sut = new LibraryPathTemplateService([_mockCatalog]);
}
[Fact]
public void GetDefaultTemplate_WhenCatalogExists_ShouldReturnTheCatalogDefaultTemplate()
{
// Arrange
LibraryPathTemplate defaultTemplate = _libraryPathTemplateFixture.Create();
_mockCatalog.GetDefaultTemplate().Returns(defaultTemplate);
// Act
LibraryPathTemplate result = _sut.GetDefaultTemplate(LibraryType.Music);
// Assert
Assert.Equal(defaultTemplate, result);
}
[Fact]
public void GetDefaultTemplate_WhenNoCatalogExistsForTheLibraryType_ShouldReturnAnEmptyTemplate()
{
// Act
LibraryPathTemplate result = _sut.GetDefaultTemplate(LibraryType.Book);
// Assert
Assert.True(result.IsEmpty);
}
[Fact]
public void ResolveTemplate_WhenProvidedPartsAreEmpty_ShouldReturnTheCatalogDefaultTemplate()
{
// Arrange
SetupCatalog();
LibraryPathTemplate defaultTemplate = CreateMusicTemplate();
_mockCatalog.GetDefaultTemplate().Returns(defaultTemplate);
// Act
Result<LibraryPathTemplate> result = _sut.ResolveTemplate(LibraryType.Music, []);
// Assert
Assert.False(result.IsFailure);
Assert.Equal(defaultTemplate, result.Value);
_mockCatalog.Received(1).GetDefaultTemplate();
}
[Fact]
public void ResolveTemplate_WhenProvidedPartsAreEmptyAndNoCatalogExists_ShouldReturnAnEmptyTemplate()
{
// Act
Result<LibraryPathTemplate> result = _sut.ResolveTemplate(LibraryType.Book, []);
// Assert
Assert.False(result.IsFailure);
Assert.True(result.Value.IsEmpty);
}
[Fact]
public void ResolveTemplate_WhenProvidedPartsAreNotEmpty_ShouldReturnATemplateWithThoseParts()
{
// Arrange
SetupCatalog();
LibraryPathPart providedPart = _libraryPathPartFixture.Create(
kind: LibraryPathPartKind.Artist,
representation: "{0}",
isOptional: false);
// Act
Result<LibraryPathTemplate> result = _sut.ResolveTemplate(LibraryType.Music, [providedPart]);
// Assert
Assert.False(result.IsFailure);
LibraryPathPart pathPart = Assert.Single(result.Value.Parts);
Assert.Equal(LibraryPathPartKind.Artist, pathPart.Kind);
Assert.Equal("{0}", pathPart.Representation);
Assert.False(pathPart.IsOptional);
_mockCatalog.DidNotReceive().GetDefaultTemplate();
}
[Fact]
public void ResolveTemplate_WhenProvidedPartsAreNotSupportedByTheCatalog_ShouldReturnError()
{
// Arrange
SetupCatalog(
[
_libraryPathPartDefinitionFixture.Create(kind: LibraryPathPartKind.Artist, valueType: LibraryPathValueType.Text, defaultRepresentation: "{0}"),
_libraryPathPartDefinitionFixture.Create(kind: LibraryPathPartKind.Separator, valueType: LibraryPathValueType.None, defaultRepresentation: string.Empty)
]);
LibraryPathPart releaseNamePart = _libraryPathPartFixture.Create(
kind: LibraryPathPartKind.ReleaseName,
representation: "{0}",
isOptional: false);
// Act
Result<LibraryPathTemplate> result = _sut.ResolveTemplate(LibraryType.Music, [releaseNamePart]);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(Errors.Library.PathTemplatePartKindNotSupportedForLibraryType, result.FirstError);
}
[Fact]
public void ResolveTemplate_WhenNoCatalogExistsForTheLibraryTypeAndPartsAreProvided_ShouldReturnNotSupportedError()
{
// Arrange
LibraryPathPart artistPart = _libraryPathPartFixture.Create(
kind: LibraryPathPartKind.Artist,
representation: "{0}",
isOptional: false);
// Act
Result<LibraryPathTemplate> result = _sut.ResolveTemplate(LibraryType.Book, [artistPart]);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(Errors.Library.PathTemplateIsNotSupportedForLibraryType, result.FirstError);
}
[Fact]
public void Validate_WhenTemplateIsEmpty_ShouldReturnSuccess()
{
// Act
Result<Success> result = _sut.Validate(LibraryType.Music, LibraryPathTemplate.Empty());
// Assert
Assert.False(result.IsFailure);
}
[Fact]
public void Validate_WhenTemplateIsEmptyAndNoCatalogExists_ShouldReturnSuccess()
{
// Act
Result<Success> result = _sut.Validate(LibraryType.Book, LibraryPathTemplate.Empty());
// Assert
Assert.False(result.IsFailure);
}
[Fact]
public void Validate_WhenNoCatalogExistsForTheLibraryType_ShouldReturnNotSupportedError()
{
// Act
Result<Success> result = _sut.Validate(LibraryType.Book, CreateMusicTemplate());
// Assert
Assert.True(result.IsFailure);
Assert.Equal(Errors.Library.PathTemplateIsNotSupportedForLibraryType, result.FirstError);
}
[Fact]
public void Validate_WhenPartKindIsNotSupportedByTheCatalog_ShouldReturnError()
{
// Arrange
SetupCatalog(definitions:
[
_libraryPathPartDefinitionFixture.Create(kind: LibraryPathPartKind.Artist, valueType: LibraryPathValueType.Text, defaultRepresentation: "{0}"),
_libraryPathPartDefinitionFixture.Create(kind: LibraryPathPartKind.Separator, valueType: LibraryPathValueType.None, defaultRepresentation: string.Empty),
_libraryPathPartDefinitionFixture.Create(kind: LibraryPathPartKind.TrackName, valueType: LibraryPathValueType.Text, defaultRepresentation: "{0}")
]);
LibraryPathTemplate template = _libraryPathTemplateFixture.Create(
[
_libraryPathPartFixture.Create(kind: LibraryPathPartKind.Artist, representation: "{0}"),
_libraryPathPartFixture.Create(kind: LibraryPathPartKind.Separator, representation: string.Empty),
_libraryPathPartFixture.Create(kind: LibraryPathPartKind.ReleaseName, representation: "{0}")
]);
// Act
Result<Success> result = _sut.Validate(LibraryType.Music, template);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(Errors.Library.PathTemplatePartKindNotSupportedForLibraryType, result.FirstError);
}
[Fact]
public void Validate_WhenAllPartKindsAreSupportedByTheCatalog_ShouldReturnSuccess()
{
// Arrange
SetupCatalog();
LibraryPathTemplate template = CreateMusicTemplate();
// Act
Result<Success> result = _sut.Validate(LibraryType.Music, template);
// Assert
Assert.False(result.IsFailure);
}
[Theory]
[InlineData("")] // The relative path is empty.
[InlineData(" ")] // The relative path is whitespace.
public void Parse_WhenRelativePathIsEmpty_ShouldReturnNull(string relativePath)
{
// Act
Result<Optional<ParsedLibraryPath>> result = _sut.Parse(LibraryType.Music, CreateMusicTemplate(), relativePath, '/');
// Assert
Assert.False(result.IsFailure);
Assert.False(result.Value.HasValue);
}
[Fact]
public void Parse_WhenTemplateIsEmpty_ShouldReturnNull()
{
// Act
Result<Optional<ParsedLibraryPath>> result = _sut.Parse(LibraryType.Music, LibraryPathTemplate.Empty(), "Pink Floyd/1973 - Time.mp3", '/');
// Assert
Assert.False(result.IsFailure);
Assert.False(result.Value.HasValue);
}
[Fact]
public void Parse_WhenTemplateIsNotSupportedForTheLibraryType_ShouldReturnError()
{
// Act
Result<Optional<ParsedLibraryPath>> result = _sut.Parse(LibraryType.Book, CreateMusicTemplate(), "Pink Floyd/1973 - Time.mp3", '/');
// Assert
Assert.True(result.IsFailure);
Assert.Equal(Errors.Library.PathTemplateIsNotSupportedForLibraryType, result.FirstError);
}
[Fact]
public void Parse_WhenPathMatchesTheTemplate_ShouldReturnTheCapturedValues()
{
// Arrange
SetupCatalog();
LibraryPathTemplate template = CreateMusicTemplate();
// Act
Result<Optional<ParsedLibraryPath>> result = _sut.Parse(LibraryType.Music, template, "Pink Floyd/1973 - Time.mp3", '/');
// Assert
Assert.False(result.IsFailure);
ParsedLibraryPath parsedPath = result.Value.Value;
Assert.Equal("Pink Floyd", parsedPath.GetString(LibraryPathPartKind.Artist).Value);
Assert.Equal(1973, parsedPath.GetInt(LibraryPathPartKind.ReleaseYear).Value);
Assert.Equal("Time", parsedPath.GetString(LibraryPathPartKind.TrackName).Value);
Assert.Equal("mp3", parsedPath.GetString(LibraryPathPartKind.Extension).Value);
}
[Fact]
public void Parse_WhenPathDoesNotMatchTheTemplate_ShouldReturnNull()
{
// Arrange
SetupCatalog();
LibraryPathTemplate template = CreateMusicTemplate();
// Act
Result<Optional<ParsedLibraryPath>> result = _sut.Parse(LibraryType.Music, template, "Pink Floyd/no year/Time.mp3", '/');
// Assert
Assert.False(result.IsFailure);
Assert.False(result.Value.HasValue);
}
[Fact]
public void Parse_WhenIntegerPartHasAFixedWidth_ShouldCaptureIt()
{
// Arrange
SetupCatalog(
[
_libraryPathPartDefinitionFixture.Create(kind: LibraryPathPartKind.Artist, valueType: LibraryPathValueType.Text, defaultRepresentation: "{0}"),
_libraryPathPartDefinitionFixture.Create(kind: LibraryPathPartKind.Separator, valueType: LibraryPathValueType.None, defaultRepresentation: string.Empty),
_libraryPathPartDefinitionFixture.Create(kind: LibraryPathPartKind.TrackNumber, valueType: LibraryPathValueType.Integer, defaultRepresentation: "{0:00}")
]);
LibraryPathTemplate template = _libraryPathTemplateFixture.Create(
[
_libraryPathPartFixture.Create(kind: LibraryPathPartKind.Artist, representation: "{0}"),
_libraryPathPartFixture.Create(kind: LibraryPathPartKind.Separator, representation: string.Empty),
_libraryPathPartFixture.Create(kind: LibraryPathPartKind.TrackNumber, representation: "{0:00}")
]);
// Act
Result<Optional<ParsedLibraryPath>> result = _sut.Parse(LibraryType.Music, template, "Pink Floyd/07", '/');
// Assert
Assert.False(result.IsFailure);
Assert.Equal(7, result.Value.Value.GetInt(LibraryPathPartKind.TrackNumber).Value);
}
[Fact]
public void Parse_WhenIntegerPartDoesNotMatchTheFixedWidth_ShouldReturnNull()
{
// Arrange
SetupCatalog(
[
_libraryPathPartDefinitionFixture.Create(kind: LibraryPathPartKind.Artist, valueType: LibraryPathValueType.Text, defaultRepresentation: "{0}"),
_libraryPathPartDefinitionFixture.Create(kind: LibraryPathPartKind.Separator, valueType: LibraryPathValueType.None, defaultRepresentation: string.Empty),
_libraryPathPartDefinitionFixture.Create(kind: LibraryPathPartKind.TrackNumber, valueType: LibraryPathValueType.Integer, defaultRepresentation: "{0:00}")
]);
LibraryPathTemplate template = _libraryPathTemplateFixture.Create(
[
_libraryPathPartFixture.Create(kind: LibraryPathPartKind.Artist, representation: "{0}"),
_libraryPathPartFixture.Create(kind: LibraryPathPartKind.Separator, representation: string.Empty),
_libraryPathPartFixture.Create(kind: LibraryPathPartKind.TrackNumber, representation: "{0:00}")
]);
// Act
Result<Optional<ParsedLibraryPath>> result = _sut.Parse(LibraryType.Music, template, "Pink Floyd/007", '/');
// Assert
Assert.False(result.IsFailure);
Assert.False(result.Value.HasValue);
}
[Fact]
public void Parse_WhenYearPartHasAFourDigitValue_ShouldCaptureIt()
{
// Arrange
SetupCatalog(
[
_libraryPathPartDefinitionFixture.Create(kind: LibraryPathPartKind.ReleaseYear, valueType: LibraryPathValueType.Year, defaultRepresentation: "{0}")
]);
LibraryPathTemplate template = _libraryPathTemplateFixture.Create(
[
_libraryPathPartFixture.Create(kind: LibraryPathPartKind.ReleaseYear, representation: "{0}")
]);
// Act
Result<Optional<ParsedLibraryPath>> result = _sut.Parse(LibraryType.Music, template, "1973", '/');
// Assert
Assert.False(result.IsFailure);
Assert.Equal(1973, result.Value.Value.GetInt(LibraryPathPartKind.ReleaseYear).Value);
}
[Fact]
public void Parse_WhenYearPartDoesNotHaveAFourDigitValue_ShouldReturnNull()
{
// Arrange
SetupCatalog(
[
_libraryPathPartDefinitionFixture.Create(kind: LibraryPathPartKind.ReleaseYear, valueType: LibraryPathValueType.Year, defaultRepresentation: "{0}")
]);
LibraryPathTemplate template = _libraryPathTemplateFixture.Create(
[
_libraryPathPartFixture.Create(kind: LibraryPathPartKind.ReleaseYear, representation: "{0}")
]);
// Act
Result<Optional<ParsedLibraryPath>> result = _sut.Parse(LibraryType.Music, template, "73", '/');
// Assert
Assert.False(result.IsFailure);
Assert.False(result.Value.HasValue);
}
[Fact]
public void Parse_WhenAnOptionalRunIsAbsent_ShouldStillMatchThePath()
{
// Arrange
SetupCatalog(
[
_libraryPathPartDefinitionFixture.Create(kind: LibraryPathPartKind.Artist, valueType: LibraryPathValueType.Text, defaultRepresentation: "{0}"),
_libraryPathPartDefinitionFixture.Create(kind: LibraryPathPartKind.Separator, valueType: LibraryPathValueType.None, defaultRepresentation: string.Empty),
_libraryPathPartDefinitionFixture.Create(kind: LibraryPathPartKind.DiscNumber, valueType: LibraryPathValueType.Integer, defaultRepresentation: "{0:00}")
]);
LibraryPathTemplate template = _libraryPathTemplateFixture.Create(
[
_libraryPathPartFixture.Create(kind: LibraryPathPartKind.Artist, representation: "{0}"),
_libraryPathPartFixture.Create(kind: LibraryPathPartKind.Separator, representation: string.Empty),
_libraryPathPartFixture.Create(kind: LibraryPathPartKind.DiscNumber, representation: "{0:00}", isOptional: true)
]);
// Act
Result<Optional<ParsedLibraryPath>> result = _sut.Parse(LibraryType.Music, template, "Pink Floyd/", '/');
// Assert
Assert.False(result.IsFailure);
Assert.Equal("Pink Floyd", result.Value.Value.GetString(LibraryPathPartKind.Artist).Value);
Assert.False(result.Value.Value.GetInt(LibraryPathPartKind.DiscNumber).HasValue);
}
[Fact]
public void Parse_WhenAnOptionalRunIsPresent_ShouldCaptureIt()
{
// Arrange
SetupCatalog(
[
_libraryPathPartDefinitionFixture.Create(kind: LibraryPathPartKind.Artist, valueType: LibraryPathValueType.Text, defaultRepresentation: "{0}"),
_libraryPathPartDefinitionFixture.Create(kind: LibraryPathPartKind.Separator, valueType: LibraryPathValueType.None, defaultRepresentation: string.Empty),
_libraryPathPartDefinitionFixture.Create(kind: LibraryPathPartKind.DiscNumber, valueType: LibraryPathValueType.Integer, defaultRepresentation: "{0:00}")
]);
LibraryPathTemplate template = _libraryPathTemplateFixture.Create(
[
_libraryPathPartFixture.Create(kind: LibraryPathPartKind.Artist, representation: "{0}"),
_libraryPathPartFixture.Create(kind: LibraryPathPartKind.Separator, representation: string.Empty),
_libraryPathPartFixture.Create(kind: LibraryPathPartKind.DiscNumber, representation: "{0:00}", isOptional: true)
]);
// Act
Result<Optional<ParsedLibraryPath>> result = _sut.Parse(LibraryType.Music, template, "Pink Floyd/02", '/');
// Assert
Assert.False(result.IsFailure);
Assert.Equal("Pink Floyd", result.Value.Value.GetString(LibraryPathPartKind.Artist).Value);
Assert.Equal(2, result.Value.Value.GetInt(LibraryPathPartKind.DiscNumber).Value);
}
[Fact]
public void Parse_WhenTheSameKindAppearsMoreThanOnce_ShouldKeepTheFirstCapture()
{
// Arrange
SetupCatalog(
[
_libraryPathPartDefinitionFixture.Create(kind: LibraryPathPartKind.Author, valueType: LibraryPathValueType.Text, defaultRepresentation: "{0}"),
_libraryPathPartDefinitionFixture.Create(kind: LibraryPathPartKind.Separator, valueType: LibraryPathValueType.None, defaultRepresentation: string.Empty),
_libraryPathPartDefinitionFixture.Create(kind: LibraryPathPartKind.Title, valueType: LibraryPathValueType.Text, defaultRepresentation: "{0}"),
_libraryPathPartDefinitionFixture.Create(kind: LibraryPathPartKind.Literal, valueType: LibraryPathValueType.None, defaultRepresentation: string.Empty)
]);
LibraryPathTemplate template = _libraryPathTemplateFixture.Create(
[
_libraryPathPartFixture.Create(kind: LibraryPathPartKind.Author, representation: "{0}"),
_libraryPathPartFixture.Create(kind: LibraryPathPartKind.Separator, representation: string.Empty),
_libraryPathPartFixture.Create(kind: LibraryPathPartKind.Title, representation: "{0}"),
_libraryPathPartFixture.Create(kind: LibraryPathPartKind.Literal, representation: " - "),
_libraryPathPartFixture.Create(kind: LibraryPathPartKind.Author, representation: "{0}")
]);
// Act
Result<Optional<ParsedLibraryPath>> result = _sut.Parse(LibraryType.Music, template, "Tolkien/The Lord of the Rings - J.R.R. Tolkien", '/');
// Assert
Assert.False(result.IsFailure);
Assert.Equal("Tolkien", result.Value.Value.GetString(LibraryPathPartKind.Author).Value);
}
/// <summary>
/// Sets up the mock catalog to return a music-like set of part definitions and a default template.
/// </summary>
/// <param name="definitions">Optional. The part definitions the catalog returns. When omitted, a standard music set is used.</param>
private void SetupCatalog(IReadOnlyList<LibraryPathPartDefinition>? definitions = null)
{
_mockCatalog.GetPartDefinitions().Returns(definitions ??
[
_libraryPathPartDefinitionFixture.Create(kind: LibraryPathPartKind.Literal, valueType: LibraryPathValueType.None, defaultRepresentation: string.Empty),
_libraryPathPartDefinitionFixture.Create(kind: LibraryPathPartKind.Artist, valueType: LibraryPathValueType.Text, defaultRepresentation: "{0}"),
_libraryPathPartDefinitionFixture.Create(kind: LibraryPathPartKind.Separator, valueType: LibraryPathValueType.None, defaultRepresentation: string.Empty),
_libraryPathPartDefinitionFixture.Create(kind: LibraryPathPartKind.ReleaseYear, valueType: LibraryPathValueType.Year, defaultRepresentation: "{0}"),
_libraryPathPartDefinitionFixture.Create(kind: LibraryPathPartKind.TrackNumber, valueType: LibraryPathValueType.Integer, defaultRepresentation: "{0:00}"),
_libraryPathPartDefinitionFixture.Create(kind: LibraryPathPartKind.TrackName, valueType: LibraryPathValueType.Text, defaultRepresentation: "{0}"),
_libraryPathPartDefinitionFixture.Create(kind: LibraryPathPartKind.Extension, valueType: LibraryPathValueType.Text, defaultRepresentation: "{0}")
]);
}
/// <summary>
/// Creates a music-like path template whose parts are all supported by the standard music set of definitions.
/// </summary>
/// <returns>The created path template.</returns>
private LibraryPathTemplate CreateMusicTemplate()
{
return _libraryPathTemplateFixture.Create(
[
_libraryPathPartFixture.Create(kind: LibraryPathPartKind.Artist, representation: "{0}"),
_libraryPathPartFixture.Create(kind: LibraryPathPartKind.Separator, representation: string.Empty),
_libraryPathPartFixture.Create(kind: LibraryPathPartKind.ReleaseYear, representation: "{0}"),
_libraryPathPartFixture.Create(kind: LibraryPathPartKind.Literal, representation: " - "),
_libraryPathPartFixture.Create(kind: LibraryPathPartKind.TrackName, representation: "{0}"),
_libraryPathPartFixture.Create(kind: LibraryPathPartKind.Literal, representation: "."),
_libraryPathPartFixture.Create(kind: LibraryPathPartKind.Extension, representation: "{0}")
]);
}
}
@@ -0,0 +1,259 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Domain.Common.Errors;
using Lumina.Domain.Common.Primitives;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Progress;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects;
using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects;
using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects;
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
using System.Diagnostics.CodeAnalysis;
#endregion
namespace Lumina.Domain.UnitTests.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Progress;
/// <summary>
/// Contains unit tests for the <see cref="MediaLibrariesScanProgressTracker"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class MediaLibrariesScanProgressTrackerTests
{
private readonly MediaLibrariesScanProgressTracker _sut = new();
private readonly LibraryIdFixture _libraryIdFixture = new();
private readonly MediaLibraryScanCompositeIdFixture _mediaLibraryScanCompositeIdFixture = new();
private readonly MediaLibraryScanJobProgressFixture _mediaLibraryScanJobProgressFixture = new();
[Fact]
public void InitializeQueuedScanProgress_WhenCalled_ShouldCreatePendingProgressWithZeroTotalJobs()
{
// Arrange
LibraryId libraryId = _libraryIdFixture.Create();
MediaLibraryScanCompositeId compositeId = _mediaLibraryScanCompositeIdFixture.Create();
// Act
Result<Created> result = _sut.InitializeQueuedScanProgress(libraryId, compositeId);
// Assert
Assert.False(result.IsFailure);
Assert.Equal(Result.Created, result.Value);
Result<MediaLibraryScanProgress> progressResult = _sut.GetScanProgress(compositeId);
Assert.False(progressResult.IsFailure);
Assert.Equal(compositeId.ScanId, progressResult.Value.ScanId);
Assert.Equal(compositeId.UserId, progressResult.Value.UserId);
Assert.Equal(libraryId, progressResult.Value.LibraryId);
Assert.Equal(0, progressResult.Value.CompletedJobs);
Assert.Equal(0, progressResult.Value.TotalJobs);
Assert.Equal(LibraryScanJobStatus.Pending, progressResult.Value.Status);
Assert.True(progressResult.Value.CurrentJobProgress.HasValue);
Assert.Equal("Queued", progressResult.Value.CurrentJobProgress.Value.CurrentOperation);
}
[Fact]
public void InitializeQueuedScanProgress_WhenCalledTwice_ShouldReplaceThePreviousProgress()
{
// Arrange
LibraryId libraryId = _libraryIdFixture.Create();
MediaLibraryScanCompositeId compositeId = _mediaLibraryScanCompositeIdFixture.Create();
// Act
_sut.InitializeQueuedScanProgress(libraryId, compositeId);
Result<Created> result = _sut.InitializeQueuedScanProgress(libraryId, compositeId);
// Assert
Assert.False(result.IsFailure);
Result<MediaLibraryScanProgress> progressResult = _sut.GetScanProgress(compositeId);
Assert.False(progressResult.IsFailure);
Assert.Equal(0, progressResult.Value.CompletedJobs);
Assert.Equal(0, progressResult.Value.TotalJobs);
Assert.Equal("Queued", progressResult.Value.CurrentJobProgress.Value.CurrentOperation);
}
[Fact]
public void InitializeScanProgress_WhenCalled_ShouldCreateProgressWithZeroCompletedJobs()
{
// Arrange
LibraryId libraryId = _libraryIdFixture.Create();
MediaLibraryScanCompositeId compositeId = _mediaLibraryScanCompositeIdFixture.Create();
// Act
Result<Created> result = _sut.InitializeScanProgress(libraryId, compositeId, totalJobs: 5);
// Assert
Assert.False(result.IsFailure);
Assert.Equal(Result.Created, result.Value);
Result<MediaLibraryScanProgress> progressResult = _sut.GetScanProgress(compositeId);
Assert.False(progressResult.IsFailure);
Assert.Equal(0, progressResult.Value.CompletedJobs);
Assert.Equal(5, progressResult.Value.TotalJobs);
Assert.Equal(LibraryScanJobStatus.Pending, progressResult.Value.Status);
Assert.True(progressResult.Value.CurrentJobProgress.HasValue);
Assert.Equal("Initializing", progressResult.Value.CurrentJobProgress.Value.CurrentOperation);
}
[Fact]
public void InitializeScanProgress_WhenTotalJobsIsNegative_ShouldReturnError()
{
// Arrange
LibraryId libraryId = _libraryIdFixture.Create();
MediaLibraryScanCompositeId compositeId = _mediaLibraryScanCompositeIdFixture.Create();
// Act
Result<Created> result = _sut.InitializeScanProgress(libraryId, compositeId, totalJobs: -1);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(Errors.LibraryScanning.TotalScanJobsCountMustBePositive, result.FirstError);
}
[Fact]
public void UpdateScanProgress_WhenScanExists_ShouldIncrementCompletedJobs()
{
// Arrange
LibraryId libraryId = _libraryIdFixture.Create();
MediaLibraryScanCompositeId compositeId = _mediaLibraryScanCompositeIdFixture.Create();
_sut.InitializeScanProgress(libraryId, compositeId, totalJobs: 2);
// Act
Result<Updated> result = _sut.UpdateScanProgress(libraryId, compositeId);
// Assert
Assert.False(result.IsFailure);
Assert.Equal(Result.Updated, result.Value);
Result<MediaLibraryScanProgress> progressResult = _sut.GetScanProgress(compositeId);
Assert.False(progressResult.IsFailure);
Assert.Equal(1, progressResult.Value.CompletedJobs);
Assert.Equal(LibraryScanJobStatus.Running, progressResult.Value.Status);
}
[Fact]
public void UpdateScanProgress_WhenLastJobIsCompleted_ShouldSetStatusCompleted()
{
// Arrange
LibraryId libraryId = _libraryIdFixture.Create();
MediaLibraryScanCompositeId compositeId = _mediaLibraryScanCompositeIdFixture.Create();
_sut.InitializeScanProgress(libraryId, compositeId, totalJobs: 1);
// Act
Result<Updated> result = _sut.UpdateScanProgress(libraryId, compositeId);
// Assert
Assert.False(result.IsFailure);
Result<MediaLibraryScanProgress> progressResult = _sut.GetScanProgress(compositeId);
Assert.False(progressResult.IsFailure);
Assert.Equal(1, progressResult.Value.CompletedJobs);
Assert.Equal(LibraryScanJobStatus.Completed, progressResult.Value.Status);
Assert.Equal(100, progressResult.Value.OverallProgressPercentage);
}
[Fact]
public void UpdateScanProgress_WhenScanIsAlreadyCompleted_ShouldReturnError()
{
// Arrange
LibraryId libraryId = _libraryIdFixture.Create();
MediaLibraryScanCompositeId compositeId = _mediaLibraryScanCompositeIdFixture.Create();
_sut.InitializeScanProgress(libraryId, compositeId, totalJobs: 1);
_sut.UpdateScanProgress(libraryId, compositeId);
// Act
Result<Updated> result = _sut.UpdateScanProgress(libraryId, compositeId);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(Errors.LibraryScanning.CompletedScanJobsCountCantExceedTotalScanJobsCount, result.FirstError);
}
[Fact]
public void UpdateScanJobProgress_WhenScanExists_ShouldUpdateCurrentJobProgress()
{
// Arrange
LibraryId libraryId = _libraryIdFixture.Create();
MediaLibraryScanCompositeId compositeId = _mediaLibraryScanCompositeIdFixture.Create();
_sut.InitializeScanProgress(libraryId, compositeId, totalJobs: 2);
MediaLibraryScanJobProgress jobProgress = _mediaLibraryScanJobProgressFixture.Create(completedItems: 3, totalItems: 10, currentOperation: "Hashing files");
// Act
Result<Updated> result = _sut.UpdateScanJobProgress(libraryId, compositeId, jobProgress);
// Assert
Assert.False(result.IsFailure);
Assert.Equal(Result.Updated, result.Value);
Result<MediaLibraryScanProgress> progressResult = _sut.GetScanProgress(compositeId);
Assert.False(progressResult.IsFailure);
Assert.True(progressResult.Value.CurrentJobProgress.HasValue);
Assert.Equal(3, progressResult.Value.CurrentJobProgress.Value.CompletedItems);
Assert.Equal("Hashing files", progressResult.Value.CurrentJobProgress.Value.CurrentOperation);
}
[Fact]
public void UpdateScanJobProgress_WhenScanDoesNotExist_ShouldReturnNotFoundError()
{
// Arrange
LibraryId libraryId = _libraryIdFixture.Create();
MediaLibraryScanCompositeId compositeId = _mediaLibraryScanCompositeIdFixture.Create();
MediaLibraryScanJobProgress jobProgress = _mediaLibraryScanJobProgressFixture.Create(completedItems: 1, totalItems: 10, currentOperation: "Hashing files");
// Act
Result<Updated> result = _sut.UpdateScanJobProgress(libraryId, compositeId, jobProgress);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(Errors.LibraryScanning.LibraryScanNotFound, result.FirstError);
}
[Fact]
public void GetScanProgress_WhenScanExists_ShouldReturnProgress()
{
// Arrange
LibraryId libraryId = _libraryIdFixture.Create();
MediaLibraryScanCompositeId compositeId = _mediaLibraryScanCompositeIdFixture.Create();
_sut.InitializeScanProgress(libraryId, compositeId, totalJobs: 3);
// Act
Result<MediaLibraryScanProgress> result = _sut.GetScanProgress(compositeId);
// Assert
Assert.False(result.IsFailure);
Assert.Equal(compositeId.ScanId, result.Value.ScanId);
Assert.Equal(compositeId.UserId, result.Value.UserId);
Assert.Equal(libraryId, result.Value.LibraryId);
}
[Fact]
public void GetScanProgress_WhenScanDoesNotExist_ShouldReturnNotFoundError()
{
// Act
Result<MediaLibraryScanProgress> result = _sut.GetScanProgress(_mediaLibraryScanCompositeIdFixture.Create());
// Assert
Assert.True(result.IsFailure);
Assert.Equal(Errors.LibraryScanning.LibraryScanNotFound, result.FirstError);
}
[Fact]
public void RemoveScanProgress_WhenScanExists_ShouldRemoveAndReturnProgress()
{
// Arrange
LibraryId libraryId = _libraryIdFixture.Create();
MediaLibraryScanCompositeId compositeId = _mediaLibraryScanCompositeIdFixture.Create();
_sut.InitializeScanProgress(libraryId, compositeId, totalJobs: 3);
// Act
Result<MediaLibraryScanProgress> result = _sut.RemoveScanProgress(compositeId);
// Assert
Assert.False(result.IsFailure);
Assert.Equal(compositeId.ScanId, result.Value.ScanId);
Assert.True(_sut.GetScanProgress(compositeId).IsFailure);
}
[Fact]
public void RemoveScanProgress_WhenScanDoesNotExist_ShouldReturnNotFoundError()
{
// Act
Result<MediaLibraryScanProgress> result = _sut.RemoveScanProgress(_mediaLibraryScanCompositeIdFixture.Create());
// Assert
Assert.True(result.IsFailure);
Assert.Equal(Errors.LibraryScanning.LibraryScanNotFound, result.FirstError);
}
}
@@ -0,0 +1,138 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Domain.Common.Errors;
using Lumina.Domain.Common.Primitives;
using Lumina.Domain.Core.BoundedContexts.AudioLibraryBoundedContext.MusicLibraryAggregate.Services.Scanners;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Scanners;
using Lumina.Domain.Core.BoundedContexts.WrittenContentLibraryBoundedContext.BookLibraryAggregate.Services.Scanners;
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
using Microsoft.Extensions.DependencyInjection;
using NSubstitute;
using System;
using System.Diagnostics.CodeAnalysis;
#endregion
namespace Lumina.Domain.UnitTests.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Scanners;
/// <summary>
/// Contains unit tests for the <see cref="MediaLibraryScannerFactory"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class MediaLibraryScannerFactoryTests : IDisposable
{
private readonly IBookLibraryTypeScanner _mockBookLibraryTypeScanner;
private readonly IMusicLibraryTypeScanner _mockMusicLibraryTypeScanner;
private readonly ServiceProvider _serviceProvider;
private readonly MediaLibraryScannerFactory _sut;
/// <summary>
/// Initializes a new instance of the <see cref="MediaLibraryScannerFactoryTests"/> class.
/// </summary>
public MediaLibraryScannerFactoryTests()
{
_mockBookLibraryTypeScanner = Substitute.For<IBookLibraryTypeScanner>();
_mockMusicLibraryTypeScanner = Substitute.For<IMusicLibraryTypeScanner>();
ServiceCollection services = new();
services.AddSingleton(_mockBookLibraryTypeScanner);
services.AddSingleton(_mockMusicLibraryTypeScanner);
_serviceProvider = services.BuildServiceProvider();
_sut = new MediaLibraryScannerFactory(_serviceProvider);
}
[Fact]
public void CreateLibraryScanner_WhenLibraryTypeIsBook_ShouldReturnBookLibraryTypeScanner()
{
// Act
Result<IMediaTypeScanner> result = _sut.CreateLibraryScanner(LibraryType.Book);
// Assert
Assert.False(result.IsFailure);
Assert.Same(_mockBookLibraryTypeScanner, result.Value);
}
[Fact]
public void CreateLibraryScanner_WhenLibraryTypeIsMusic_ShouldReturnMusicLibraryTypeScanner()
{
// Act
Result<IMediaTypeScanner> result = _sut.CreateLibraryScanner(LibraryType.Music);
// Assert
Assert.False(result.IsFailure);
Assert.Same(_mockMusicLibraryTypeScanner, result.Value);
}
[Theory]
[InlineData(LibraryType.EBook)] // EBook scanner is not implemented.
[InlineData(LibraryType.ComicBook)] // Comic book scanner is not implemented.
[InlineData(LibraryType.Magazine)] // Magazine scanner is not implemented.
[InlineData(LibraryType.Newspaper)] // Newspaper scanner is not implemented.
[InlineData(LibraryType.Manga)] // Manga scanner is not implemented.
[InlineData(LibraryType.GraphicNovel)] // Graphic novel scanner is not implemented.
[InlineData(LibraryType.AcademicPaper)] // Academic paper scanner is not implemented.
[InlineData(LibraryType.SheetMusic)] // Sheet music scanner is not implemented.
[InlineData(LibraryType.Movie)] // Movie scanner is not implemented.
[InlineData(LibraryType.TvShow)] // TV show scanner is not implemented.
[InlineData(LibraryType.Documentary)] // Documentary scanner is not implemented.
[InlineData(LibraryType.Anime)] // Anime scanner is not implemented.
[InlineData(LibraryType.ConcertVideo)] // Concert video scanner is not implemented.
[InlineData(LibraryType.TutorialVideo)] // Tutorial video scanner is not implemented.
[InlineData(LibraryType.HomeVideo)] // Home video scanner is not implemented.
[InlineData(LibraryType.YouTubeVideo)] // YouTube video scanner is not implemented.
[InlineData(LibraryType.MusicVideo)] // Music video scanner is not implemented.
[InlineData(LibraryType.LiveRecordingVideo)] // Live recording video scanner is not implemented.
[InlineData(LibraryType.InterviewVideo)] // Interview video scanner is not implemented.
[InlineData(LibraryType.CoverSongVideo)] // Cover song video scanner is not implemented.
[InlineData(LibraryType.PodcastVideo)] // Podcast video scanner is not implemented.
[InlineData(LibraryType.Audiobook)] // Audiobook scanner is not implemented.
[InlineData(LibraryType.LiveRecordingAudio)] // Live recording audio scanner is not implemented.
[InlineData(LibraryType.InterviewAudio)] // Interview audio scanner is not implemented.
[InlineData(LibraryType.CoverSongAudio)] // Cover song audio scanner is not implemented.
[InlineData(LibraryType.Remix)] // Remix scanner is not implemented.
[InlineData(LibraryType.SoundEffect)] // Sound effect scanner is not implemented.
[InlineData(LibraryType.PodcastAudio)] // Podcast audio scanner is not implemented.
[InlineData(LibraryType.Photo)] // Photo scanner is not implemented.
[InlineData(LibraryType.Playlist)] // Playlist scanner is not implemented.
[InlineData(LibraryType.Collection)] // Collection scanner is not implemented.
[InlineData(LibraryType.Subtitles)] // Subtitles scanner is not implemented.
[InlineData(LibraryType.Lyrics)] // Lyrics scanner is not implemented.
public void CreateLibraryScanner_WhenLibraryTypeIsNotImplemented_ShouldReturnNoScannerError(LibraryType libraryType)
{
// Act
Result<IMediaTypeScanner> result = _sut.CreateLibraryScanner(libraryType);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(Errors.LibraryScanning.NoScannerForLibraryType, result.FirstError);
Assert.IsType<NotImplementedError>(result.FirstError);
}
[Fact]
public void CreateLibraryScanner_WhenLibraryTypeIsNotImplemented_ShouldNotThrow()
{
// Act
Exception? exception = Record.Exception(() => _sut.CreateLibraryScanner(LibraryType.Movie));
// Assert
Assert.Null(exception);
}
[Fact]
public void CreateLibraryScanner_WhenLibraryTypeIsUnknown_ShouldReturnNoScannerError()
{
// Act
Result<IMediaTypeScanner> result = _sut.CreateLibraryScanner((LibraryType)999);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(Errors.LibraryScanning.NoScannerForLibraryType, result.FirstError);
Assert.IsType<NotImplementedError>(result.FirstError);
}
/// <summary>
/// Disposes the test dependencies.
/// </summary>
public void Dispose()
{
_serviceProvider.Dispose();
}
}
@@ -0,0 +1,129 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects;
using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects;
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
using System.Diagnostics.CodeAnalysis;
#endregion
namespace Lumina.Domain.UnitTests.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects;
/// <summary>
/// Contains unit tests for the <see cref="LibraryPathPartDefinition"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class LibraryPathPartDefinitionTests
{
private readonly LibraryPathPartDefinitionFixture _libraryPathPartDefinitionFixture = new();
[Fact]
public void Constructor_WhenCalled_ShouldSetAllProperties()
{
// Act
LibraryPathPartDefinition definition = new(LibraryPathPartKind.TrackNumber, LibraryPathValueType.Integer, "{0:00}", isOptionalByDefault: true);
// Assert
Assert.Equal(LibraryPathPartKind.TrackNumber, definition.Kind);
Assert.Equal(LibraryPathValueType.Integer, definition.ValueType);
Assert.Equal("{0:00}", definition.DefaultRepresentation);
Assert.True(definition.IsOptionalByDefault);
}
[Fact]
public void Equals_WithSameValues_ShouldReturnTrue()
{
// Arrange
LibraryPathPartDefinition firstDefinition = _libraryPathPartDefinitionFixture.Create(
kind: LibraryPathPartKind.Artist,
valueType: LibraryPathValueType.Text,
defaultRepresentation: "{0}",
isOptionalByDefault: false);
// Act
LibraryPathPartDefinition secondDefinition = _libraryPathPartDefinitionFixture.Create(
kind: LibraryPathPartKind.Artist,
valueType: LibraryPathValueType.Text,
defaultRepresentation: "{0}",
isOptionalByDefault: false);
// Assert
Assert.Equal(firstDefinition, secondDefinition);
}
[Fact]
public void Equals_WithDifferentKind_ShouldReturnFalse()
{
// Arrange
LibraryPathPartDefinition firstDefinition = _libraryPathPartDefinitionFixture.Create(
kind: LibraryPathPartKind.Artist,
valueType: LibraryPathValueType.Text,
defaultRepresentation: "{0}");
// Act
LibraryPathPartDefinition secondDefinition = _libraryPathPartDefinitionFixture.Create(
kind: LibraryPathPartKind.ReleaseName,
valueType: LibraryPathValueType.Text,
defaultRepresentation: "{0}");
// Assert
Assert.NotEqual(firstDefinition, secondDefinition);
}
[Fact]
public void Equals_WithDifferentValueType_ShouldReturnFalse()
{
// Arrange
LibraryPathPartDefinition firstDefinition = _libraryPathPartDefinitionFixture.Create(
kind: LibraryPathPartKind.TrackNumber,
valueType: LibraryPathValueType.Integer,
defaultRepresentation: "{0}");
// Act
LibraryPathPartDefinition secondDefinition = _libraryPathPartDefinitionFixture.Create(
kind: LibraryPathPartKind.TrackNumber,
valueType: LibraryPathValueType.Text,
defaultRepresentation: "{0}");
// Assert
Assert.NotEqual(firstDefinition, secondDefinition);
}
[Fact]
public void Equals_WithDifferentDefaultRepresentation_ShouldReturnFalse()
{
// Arrange
LibraryPathPartDefinition firstDefinition = _libraryPathPartDefinitionFixture.Create(
kind: LibraryPathPartKind.ReleaseYear,
valueType: LibraryPathValueType.Year,
defaultRepresentation: "{0}");
// Act
LibraryPathPartDefinition secondDefinition = _libraryPathPartDefinitionFixture.Create(
kind: LibraryPathPartKind.ReleaseYear,
valueType: LibraryPathValueType.Year,
defaultRepresentation: "Year {0}");
// Assert
Assert.NotEqual(firstDefinition, secondDefinition);
}
[Fact]
public void Equals_WithDifferentIsOptionalByDefault_ShouldReturnFalse()
{
// Arrange
LibraryPathPartDefinition firstDefinition = _libraryPathPartDefinitionFixture.Create(
kind: LibraryPathPartKind.DiscNumber,
valueType: LibraryPathValueType.Integer,
defaultRepresentation: "{0:00}",
isOptionalByDefault: false);
// Act
LibraryPathPartDefinition secondDefinition = _libraryPathPartDefinitionFixture.Create(
kind: LibraryPathPartKind.DiscNumber,
valueType: LibraryPathValueType.Integer,
defaultRepresentation: "{0:00}",
isOptionalByDefault: true);
// Assert
Assert.NotEqual(firstDefinition, secondDefinition);
}
}
@@ -0,0 +1,94 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects;
using Lumina.Domain.Core.BoundedContexts.UserManagementBoundedContext.UserAggregate.ValueObjects;
using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects;
using Lumina.Domain.Fixtures.Core.BoundedContexts.UserManagementBoundedContext.UserAggregate.ValueObjects;
using System.Diagnostics.CodeAnalysis;
#endregion
namespace Lumina.Domain.UnitTests.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects;
/// <summary>
/// Contains unit tests for the <see cref="MediaLibraryScanCompositeId"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class MediaLibraryScanCompositeIdTests
{
private readonly ScanIdFixture _scanIdFixture = new();
private readonly UserIdFixture _userIdFixture = new();
private readonly MediaLibraryScanCompositeIdFixture _mediaLibraryScanCompositeIdFixture = new();
[Fact]
public void Create_WhenCalledWithScanIdAndUserId_ShouldCreateCompositeIdWithThoseValues()
{
// Arrange
ScanId scanId = _scanIdFixture.Create();
UserId userId = _userIdFixture.Create();
// Act
MediaLibraryScanCompositeId compositeId = MediaLibraryScanCompositeId.Create(scanId, userId);
// Assert
Assert.Equal(scanId, compositeId.ScanId);
Assert.Equal(userId, compositeId.UserId);
}
[Fact]
public void Equals_WithSameValues_ShouldReturnTrue()
{
// Arrange
ScanId scanId = _scanIdFixture.Create();
UserId userId = _userIdFixture.Create();
// Act
MediaLibraryScanCompositeId firstId = _mediaLibraryScanCompositeIdFixture.Create(scanId: scanId, userId: userId);
MediaLibraryScanCompositeId secondId = _mediaLibraryScanCompositeIdFixture.Create(scanId: scanId, userId: userId);
// Assert
Assert.Equal(firstId, secondId);
}
[Fact]
public void Equals_WithDifferentScanId_ShouldReturnFalse()
{
// Arrange
UserId userId = _userIdFixture.Create();
// Act
MediaLibraryScanCompositeId firstId = _mediaLibraryScanCompositeIdFixture.Create(userId: userId);
MediaLibraryScanCompositeId secondId = _mediaLibraryScanCompositeIdFixture.Create(userId: userId);
// Assert
Assert.NotEqual(firstId, secondId);
}
[Fact]
public void GetHashCode_WithSameValues_ShouldReturnSameHashCode()
{
// Arrange
ScanId scanId = _scanIdFixture.Create();
UserId userId = _userIdFixture.Create();
// Act
MediaLibraryScanCompositeId firstId = _mediaLibraryScanCompositeIdFixture.Create(scanId: scanId, userId: userId);
MediaLibraryScanCompositeId secondId = _mediaLibraryScanCompositeIdFixture.Create(scanId: scanId, userId: userId);
// Assert
Assert.Equal(firstId.GetHashCode(), secondId.GetHashCode());
}
[Fact]
public void ToString_WhenCalled_ShouldReturnFormattedString()
{
// Arrange
ScanId scanId = _scanIdFixture.Create();
UserId userId = _userIdFixture.Create();
MediaLibraryScanCompositeId compositeId = _mediaLibraryScanCompositeIdFixture.Create(scanId: scanId, userId: userId);
// Act
string result = compositeId.ToString();
// Assert
Assert.Equal($"{scanId}-{userId}", result);
}
}
@@ -0,0 +1,132 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Domain.Common.Errors;
using Lumina.Domain.Common.Primitives;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects;
using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects;
using System;
using System.Diagnostics.CodeAnalysis;
#endregion
namespace Lumina.Domain.UnitTests.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects;
/// <summary>
/// Contains unit tests for the <see cref="MediaLibraryScanJobProgress"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class MediaLibraryScanJobProgressTests
{
private readonly MediaLibraryScanJobProgressFixture _mediaLibraryScanJobProgressFixture = new();
[Fact]
public void Create_WhenCalledWithValidValues_ShouldCreateJobProgressWithExpectedValues()
{
// Act
Result<MediaLibraryScanJobProgress> result = MediaLibraryScanJobProgress.Create(completedItems: 2, totalItems: 10, "Scanning files");
// Assert
Assert.False(result.IsFailure);
Assert.Equal(2, result.Value.CompletedItems);
Assert.Equal(10, result.Value.TotalItems);
Assert.Equal("Scanning files", result.Value.CurrentOperation);
Assert.Equal(20, result.Value.ProgressPercentage);
}
[Fact]
public void Create_WhenTotalItemsIsZero_ShouldCreateJobProgressWithZeroPercentage()
{
// Act
Result<MediaLibraryScanJobProgress> result = MediaLibraryScanJobProgress.Create(completedItems: 0, totalItems: 0, "Scanning files");
// Assert
Assert.False(result.IsFailure);
Assert.Equal(0, result.Value.ProgressPercentage);
}
[Fact]
public void Create_WhenTotalItemsIsNegative_ShouldReturnError()
{
// Act
Result<MediaLibraryScanJobProgress> result = MediaLibraryScanJobProgress.Create(completedItems: 0, totalItems: -1, "Scanning files");
// Assert
Assert.True(result.IsFailure);
Assert.Equal(Errors.LibraryScanning.TotalScanJobItemsCountMustBePositive, result.FirstError);
}
[Fact]
public void Create_WhenCompletedItemsIsNegative_ShouldReturnError()
{
// Act
Result<MediaLibraryScanJobProgress> result = MediaLibraryScanJobProgress.Create(completedItems: -1, totalItems: 10, "Scanning files");
// Assert
Assert.True(result.IsFailure);
Assert.Equal(Errors.LibraryScanning.CompletedScanJobItemsCountMustBePositive, result.FirstError);
}
[Fact]
public void Create_WhenCompletedItemsExceedsTotalItems_ShouldReturnError()
{
// Act
Result<MediaLibraryScanJobProgress> result = MediaLibraryScanJobProgress.Create(completedItems: 11, totalItems: 10, "Scanning files");
// Assert
Assert.True(result.IsFailure);
Assert.Equal(Errors.LibraryScanning.CompletedScanJobItemsCountCantExceedTotalScanJobItemsCount, result.FirstError);
}
[Theory]
[InlineData(null)] // Null current operation.
[InlineData("")] // Empty current operation.
[InlineData(" ")] // Whitespace current operation.
public void Create_WhenCurrentOperationIsEmpty_ShouldReturnError(string? currentOperation)
{
// Act
Result<MediaLibraryScanJobProgress> result = MediaLibraryScanJobProgress.Create(completedItems: 1, totalItems: 10, currentOperation!);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(Errors.LibraryScanning.ScanJobCurrentOperationCannotBeEmpty, result.FirstError);
}
[Fact]
public void Equals_WithSameValues_ShouldReturnTrue()
{
// Arrange
MediaLibraryScanJobProgress firstProgress = _mediaLibraryScanJobProgressFixture.Create(completedItems: 2, totalItems: 10, currentOperation: "Scanning files");
MediaLibraryScanJobProgress secondProgress = _mediaLibraryScanJobProgressFixture.Create(completedItems: 2, totalItems: 10, currentOperation: "Scanning files");
// Act
bool result = firstProgress.Equals(secondProgress);
// Assert
Assert.True(result);
}
[Fact]
public void Equals_WithDifferentCurrentOperation_ShouldReturnFalse()
{
// Arrange
MediaLibraryScanJobProgress firstProgress = _mediaLibraryScanJobProgressFixture.Create(completedItems: 2, totalItems: 10, currentOperation: "Scanning files");
MediaLibraryScanJobProgress secondProgress = _mediaLibraryScanJobProgressFixture.Create(completedItems: 2, totalItems: 10, currentOperation: "Hashing files");
// Act
bool result = firstProgress.Equals(secondProgress);
// Assert
Assert.False(result);
}
[Fact]
public void ToString_WhenCalled_ShouldReturnFormattedString()
{
// Arrange
MediaLibraryScanJobProgress jobProgress = _mediaLibraryScanJobProgressFixture.Create(completedItems: 2, totalItems: 10, currentOperation: "Scanning files");
// Act
string result = jobProgress.ToString();
// Assert
Assert.Equal("CompletedItems: 2; TotalItems: 10; CurrentOperation: Scanning files", result);
}
}
@@ -0,0 +1,258 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Domain.Common.Errors;
using Lumina.Domain.Common.Primitives;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects;
using Lumina.Domain.Core.BoundedContexts.UserManagementBoundedContext.UserAggregate.ValueObjects;
using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects;
using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects;
using Lumina.Domain.Fixtures.Core.BoundedContexts.UserManagementBoundedContext.UserAggregate.ValueObjects;
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
using System;
using System.Diagnostics.CodeAnalysis;
#endregion
namespace Lumina.Domain.UnitTests.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects;
/// <summary>
/// Contains unit tests for the <see cref="MediaLibraryScanProgress"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class MediaLibraryScanProgressTests
{
private readonly ScanIdFixture _scanIdFixture = new();
private readonly UserIdFixture _userIdFixture = new();
private readonly LibraryIdFixture _libraryIdFixture = new();
private readonly MediaLibraryScanJobProgressFixture _mediaLibraryScanJobProgressFixture = new();
private readonly MediaLibraryScanProgressFixture _mediaLibraryScanProgressFixture = new();
[Fact]
public void Create_WhenCalledWithValidValues_ShouldCreateProgressWithExpectedValues()
{
// Arrange
ScanId scanId = _scanIdFixture.Create();
UserId userId = _userIdFixture.Create();
LibraryId libraryId = _libraryIdFixture.Create();
Optional<MediaLibraryScanJobProgress> currentJobProgress = Optional<MediaLibraryScanJobProgress>.Some(_mediaLibraryScanJobProgressFixture.Create());
// Act
Result<MediaLibraryScanProgress> result = MediaLibraryScanProgress.Create(scanId, userId, libraryId, completedJobs: 2, totalJobs: 5, LibraryScanJobStatus.Running, currentJobProgress);
// Assert
Assert.False(result.IsFailure);
Assert.Equal(scanId, result.Value.ScanId);
Assert.Equal(userId, result.Value.UserId);
Assert.Equal(libraryId, result.Value.LibraryId);
Assert.Equal(2, result.Value.CompletedJobs);
Assert.Equal(5, result.Value.TotalJobs);
Assert.Equal(LibraryScanJobStatus.Running, result.Value.Status);
Assert.True(result.Value.CurrentJobProgress.HasValue);
Assert.Equal(40, result.Value.OverallProgressPercentage);
}
[Fact]
public void Create_WhenCalledWithDefaults_ShouldUsePendingStatusAndNoCurrentJobProgress()
{
// Act
Result<MediaLibraryScanProgress> result = MediaLibraryScanProgress.Create(
_scanIdFixture.Create(),
_userIdFixture.Create(),
_libraryIdFixture.Create(),
completedJobs: 0,
totalJobs: 1,
LibraryScanJobStatus.Pending,
Optional<MediaLibraryScanJobProgress>.None());
// Assert
Assert.False(result.IsFailure);
Assert.Equal(LibraryScanJobStatus.Pending, result.Value.Status);
Assert.False(result.Value.CurrentJobProgress.HasValue);
}
[Fact]
public void Create_WhenTotalJobsIsZeroAndStatusIsPending_ShouldCreateQueuedProgress()
{
// Act
Result<MediaLibraryScanProgress> result = MediaLibraryScanProgress.Create(
_scanIdFixture.Create(),
_userIdFixture.Create(),
_libraryIdFixture.Create(),
completedJobs: 0,
totalJobs: 0,
LibraryScanJobStatus.Pending,
Optional<MediaLibraryScanJobProgress>.None());
// Assert
Assert.False(result.IsFailure);
Assert.Equal(0, result.Value.TotalJobs);
Assert.Equal(LibraryScanJobStatus.Pending, result.Value.Status);
Assert.Equal(0, result.Value.OverallProgressPercentage);
}
[Fact]
public void Create_WhenTotalJobsIsNegative_ShouldReturnError()
{
// Act
Result<MediaLibraryScanProgress> result = MediaLibraryScanProgress.Create(
_scanIdFixture.Create(),
_userIdFixture.Create(),
_libraryIdFixture.Create(),
completedJobs: 0,
totalJobs: -1,
LibraryScanJobStatus.Pending,
Optional<MediaLibraryScanJobProgress>.None());
// Assert
Assert.True(result.IsFailure);
Assert.Equal(Errors.LibraryScanning.TotalScanJobsCountMustBePositive, result.FirstError);
}
[Theory]
[InlineData(LibraryScanJobStatus.Running)] // Only a scan that is still queued may have no jobs yet.
[InlineData(LibraryScanJobStatus.Completed)] // A completed scan must have had at least one job.
[InlineData(LibraryScanJobStatus.Canceled)] // A canceled scan must have had at least one job.
[InlineData(LibraryScanJobStatus.Failed)] // A failed scan must have had at least one job.
public void Create_WhenTotalJobsIsZeroAndStatusIsNotPending_ShouldReturnError(LibraryScanJobStatus status)
{
// Act
Result<MediaLibraryScanProgress> result = MediaLibraryScanProgress.Create(
_scanIdFixture.Create(),
_userIdFixture.Create(),
_libraryIdFixture.Create(),
completedJobs: 0,
totalJobs: 0,
status,
Optional<MediaLibraryScanJobProgress>.None());
// Assert
Assert.True(result.IsFailure);
Assert.Equal(Errors.LibraryScanning.TotalScanJobsCountMustBePositive, result.FirstError);
}
[Fact]
public void Create_WhenCompletedJobsIsNegative_ShouldReturnError()
{
// Act
Result<MediaLibraryScanProgress> result = MediaLibraryScanProgress.Create(
_scanIdFixture.Create(),
_userIdFixture.Create(),
_libraryIdFixture.Create(),
completedJobs: -1,
totalJobs: 5,
LibraryScanJobStatus.Pending,
Optional<MediaLibraryScanJobProgress>.None());
// Assert
Assert.True(result.IsFailure);
Assert.Equal(Errors.LibraryScanning.CompletedScanJobsCountMustBePositive, result.FirstError);
}
[Fact]
public void Create_WhenCompletedJobsExceedsTotalJobs_ShouldReturnError()
{
// Act
Result<MediaLibraryScanProgress> result = MediaLibraryScanProgress.Create(
_scanIdFixture.Create(),
_userIdFixture.Create(),
_libraryIdFixture.Create(),
completedJobs: 6,
totalJobs: 5,
LibraryScanJobStatus.Pending,
Optional<MediaLibraryScanJobProgress>.None());
// Assert
Assert.True(result.IsFailure);
Assert.Equal(Errors.LibraryScanning.CompletedScanJobsCountCantExceedTotalScanJobsCount, result.FirstError);
}
[Fact]
public void OverallProgressPercentage_WhenNoJobsCompleted_ShouldReturnZero()
{
// Arrange
MediaLibraryScanProgress scanProgress = _mediaLibraryScanProgressFixture.Create(completedJobs: 0, totalJobs: 5);
// Act
decimal result = scanProgress.OverallProgressPercentage;
// Assert
Assert.Equal(0, result);
}
[Fact]
public void Equals_WithSameValues_ShouldReturnTrue()
{
// Arrange
ScanId scanId = _scanIdFixture.Create();
UserId userId = _userIdFixture.Create();
LibraryId libraryId = _libraryIdFixture.Create();
// Act
MediaLibraryScanProgress firstResult = _mediaLibraryScanProgressFixture.Create(
scanId: scanId,
userId: userId,
libraryId: libraryId,
completedJobs: 2,
totalJobs: 5,
status: LibraryScanJobStatus.Running,
currentJobProgress: Optional<MediaLibraryScanJobProgress>.None());
MediaLibraryScanProgress secondResult = _mediaLibraryScanProgressFixture.Create(
scanId: scanId,
userId: userId,
libraryId: libraryId,
completedJobs: 2,
totalJobs: 5,
status: LibraryScanJobStatus.Running,
currentJobProgress: Optional<MediaLibraryScanJobProgress>.None());
// Assert
Assert.Equal(firstResult, secondResult);
}
[Fact]
public void Equals_WithDifferentCompletedJobs_ShouldReturnFalse()
{
// Arrange
ScanId scanId = _scanIdFixture.Create();
UserId userId = _userIdFixture.Create();
LibraryId libraryId = _libraryIdFixture.Create();
// Act
MediaLibraryScanProgress firstResult = _mediaLibraryScanProgressFixture.Create(
scanId: scanId,
userId: userId,
libraryId: libraryId,
completedJobs: 2,
totalJobs: 5,
status: LibraryScanJobStatus.Running,
currentJobProgress: Optional<MediaLibraryScanJobProgress>.None());
MediaLibraryScanProgress secondResult = _mediaLibraryScanProgressFixture.Create(
scanId: scanId,
userId: userId,
libraryId: libraryId,
completedJobs: 3,
totalJobs: 5,
status: LibraryScanJobStatus.Running,
currentJobProgress: Optional<MediaLibraryScanJobProgress>.None());
// Assert
Assert.NotEqual(firstResult, secondResult);
}
[Fact]
public void ToString_WhenCalled_ShouldReturnFormattedProgressString()
{
// Arrange
MediaLibraryScanJobProgress currentJobProgress = _mediaLibraryScanJobProgressFixture.Create(completedItems: 3, totalItems: 10, currentOperation: "Hashing files");
MediaLibraryScanProgress scanProgress = _mediaLibraryScanProgressFixture.Create(
completedJobs: 2,
totalJobs: 5,
status: LibraryScanJobStatus.Running,
currentJobProgress: Optional<MediaLibraryScanJobProgress>.Some(currentJobProgress));
// Act
string result = scanProgress.ToString();
// Assert
Assert.Equal("CompletedJobs: 2; TotalJobs: 5; CurrentJobProgress: CompletedItems: 3; TotalItems: 10; CurrentOperation: Hashing files", result);
}
}
@@ -0,0 +1,230 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Domain.Common.Primitives;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects;
using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects;
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
#endregion
namespace Lumina.Domain.UnitTests.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects;
/// <summary>
/// Contains unit tests for the <see cref="ParsedLibraryPath"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class ParsedLibraryPathTests
{
private readonly ParsedLibraryPathFixture _parsedLibraryPathFixture = new();
[Fact]
public void Create_WhenCalledWithValues_ShouldExposeThoseValues()
{
// Arrange
Dictionary<LibraryPathPartKind, string> values = new()
{
[LibraryPathPartKind.Artist] = "Pink Floyd",
[LibraryPathPartKind.TrackName] = "Time"
};
// Act
ParsedLibraryPath result = ParsedLibraryPath.Create(values);
// Assert
Assert.Equal(2, result.Values.Count);
Assert.Equal("Pink Floyd", result.Values[LibraryPathPartKind.Artist]);
Assert.Equal("Time", result.Values[LibraryPathPartKind.TrackName]);
}
[Fact]
public void GetString_WhenKindIsCaptured_ShouldReturnTheTrimmedValue()
{
// Arrange
ParsedLibraryPath parsedPath = _parsedLibraryPathFixture.Create(new Dictionary<LibraryPathPartKind, string>
{
[LibraryPathPartKind.Artist] = " Pink Floyd "
});
// Act
Optional<string> result = parsedPath.GetString(LibraryPathPartKind.Artist);
// Assert
Assert.True(result.HasValue);
Assert.Equal("Pink Floyd", result.Value);
}
[Fact]
public void GetString_WhenKindIsNotCaptured_ShouldReturnNoValue()
{
// Arrange
ParsedLibraryPath parsedPath = _parsedLibraryPathFixture.Create(new Dictionary<LibraryPathPartKind, string>
{
[LibraryPathPartKind.Artist] = "Pink Floyd"
});
// Act
Optional<string> result = parsedPath.GetString(LibraryPathPartKind.TrackName);
// Assert
Assert.False(result.HasValue);
}
[Fact]
public void GetString_WhenCapturedValueIsWhitespace_ShouldReturnNoValue()
{
// Arrange
ParsedLibraryPath parsedPath = _parsedLibraryPathFixture.Create(new Dictionary<LibraryPathPartKind, string>
{
[LibraryPathPartKind.Artist] = " "
});
// Act
Optional<string> result = parsedPath.GetString(LibraryPathPartKind.Artist);
// Assert
Assert.False(result.HasValue);
}
[Fact]
public void GetInt_WhenKindIsCapturedWithAnInteger_ShouldReturnTheValue()
{
// Arrange
ParsedLibraryPath parsedPath = _parsedLibraryPathFixture.Create(new Dictionary<LibraryPathPartKind, string>
{
[LibraryPathPartKind.ReleaseYear] = "1973"
});
// Act
Optional<int> result = parsedPath.GetInt(LibraryPathPartKind.ReleaseYear);
// Assert
Assert.True(result.HasValue);
Assert.Equal(1973, result.Value);
}
[Fact]
public void GetInt_WhenKindIsNotCaptured_ShouldReturnNoValue()
{
// Arrange
ParsedLibraryPath parsedPath = _parsedLibraryPathFixture.Create(new Dictionary<LibraryPathPartKind, string>
{
[LibraryPathPartKind.Artist] = "Pink Floyd"
});
// Act
Optional<int> result = parsedPath.GetInt(LibraryPathPartKind.ReleaseYear);
// Assert
Assert.False(result.HasValue);
}
[Fact]
public void GetInt_WhenCapturedValueIsNotAnInteger_ShouldReturnNoValue()
{
// Arrange
ParsedLibraryPath parsedPath = _parsedLibraryPathFixture.Create(new Dictionary<LibraryPathPartKind, string>
{
[LibraryPathPartKind.ReleaseYear] = "not a year"
});
// Act
Optional<int> result = parsedPath.GetInt(LibraryPathPartKind.ReleaseYear);
// Assert
Assert.False(result.HasValue);
}
[Fact]
public void ToDictionary_WhenCalled_ShouldReturnAllCapturedValues()
{
// Arrange
Dictionary<LibraryPathPartKind, string> values = new()
{
[LibraryPathPartKind.Artist] = "Pink Floyd",
[LibraryPathPartKind.TrackName] = "Time"
};
ParsedLibraryPath parsedPath = _parsedLibraryPathFixture.Create(values);
// Act
IReadOnlyDictionary<LibraryPathPartKind, string> result = parsedPath.ToDictionary();
// Assert
Assert.Equal(values, result);
}
[Fact]
public void ToDictionary_WhenCalled_ShouldReturnACopy()
{
// Arrange
Dictionary<LibraryPathPartKind, string> values = new()
{
[LibraryPathPartKind.Artist] = "Pink Floyd"
};
ParsedLibraryPath parsedPath = _parsedLibraryPathFixture.Create(values);
// Act
IReadOnlyDictionary<LibraryPathPartKind, string> result = parsedPath.ToDictionary();
// Assert
Assert.NotSame(values, result);
}
[Fact]
public void Equals_WithSameValuesInDifferentOrder_ShouldReturnTrue()
{
// Arrange
ParsedLibraryPath firstPath = _parsedLibraryPathFixture.Create(new Dictionary<LibraryPathPartKind, string>
{
[LibraryPathPartKind.Artist] = "Pink Floyd",
[LibraryPathPartKind.TrackName] = "Time"
});
// Act
ParsedLibraryPath secondPath = _parsedLibraryPathFixture.Create(new Dictionary<LibraryPathPartKind, string>
{
[LibraryPathPartKind.TrackName] = "Time",
[LibraryPathPartKind.Artist] = "Pink Floyd"
});
// Assert
Assert.Equal(firstPath, secondPath);
}
[Fact]
public void Equals_WithDifferentValues_ShouldReturnFalse()
{
// Arrange
ParsedLibraryPath firstPath = _parsedLibraryPathFixture.Create(new Dictionary<LibraryPathPartKind, string>
{
[LibraryPathPartKind.Artist] = "Pink Floyd"
});
// Act
ParsedLibraryPath secondPath = _parsedLibraryPathFixture.Create(new Dictionary<LibraryPathPartKind, string>
{
[LibraryPathPartKind.Artist] = "Queen"
});
// Assert
Assert.NotEqual(firstPath, secondPath);
}
[Fact]
public void Equals_WithDifferentKeys_ShouldReturnFalse()
{
// Arrange
ParsedLibraryPath firstPath = _parsedLibraryPathFixture.Create(new Dictionary<LibraryPathPartKind, string>
{
[LibraryPathPartKind.Artist] = "Pink Floyd"
});
// Act
ParsedLibraryPath secondPath = _parsedLibraryPathFixture.Create(new Dictionary<LibraryPathPartKind, string>
{
[LibraryPathPartKind.Title] = "Pink Floyd"
});
// Assert
Assert.NotEqual(firstPath, secondPath);
}
}
@@ -0,0 +1,81 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects;
using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects;
using System;
using System.Diagnostics.CodeAnalysis;
#endregion
namespace Lumina.Domain.UnitTests.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects;
/// <summary>
/// Contains unit tests for the <see cref="ScanId"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class ScanIdTests
{
private readonly ScanIdFixture _scanIdFixture = new();
[Fact]
public void CreateUnique_WhenCalled_ShouldReturnIdWithNonEmptyValue()
{
// Act
ScanId scanId = ScanId.CreateUnique();
// Assert
Assert.NotNull(scanId);
Assert.NotEqual(default, scanId.Value);
}
[Fact]
public void CreateUnique_WhenCalledTwice_ShouldReturnDistinctIds()
{
// Act
ScanId firstId = ScanId.CreateUnique();
ScanId secondId = ScanId.CreateUnique();
// Assert
Assert.NotEqual(firstId.Value, secondId.Value);
}
[Fact]
public void Create_WhenCalledWithValue_ShouldReturnIdWithThatValue()
{
// Arrange
Guid value = Guid.NewGuid();
// Act
ScanId scanId = ScanId.Create(value);
// Assert
Assert.Equal(value, scanId.Value);
}
[Fact]
public void Equals_WithSameValue_ShouldReturnTrue()
{
// Arrange
Guid value = Guid.NewGuid();
ScanId firstId = _scanIdFixture.Create(value);
ScanId secondId = _scanIdFixture.Create(value);
// Act
bool result = firstId.Equals(secondId);
// Assert
Assert.True(result);
}
[Fact]
public void Equals_WithDifferentValue_ShouldReturnFalse()
{
// Arrange
ScanId firstId = _scanIdFixture.Create();
ScanId secondId = _scanIdFixture.Create();
// Act
bool result = firstId.Equals(secondId);
// Assert
Assert.False(result);
}
}