diff --git a/tests/Common/Lumina.Domain.Fixtures/Core/BoundedContexts/UserManagementBoundedContext/UserSettingsAggregate/ValueObjects/UserSettingsIdFixture.cs b/tests/Common/Lumina.Domain.Fixtures/Core/BoundedContexts/UserManagementBoundedContext/UserSettingsAggregate/ValueObjects/UserSettingsIdFixture.cs new file mode 100644 index 00000000..a1f52ae8 --- /dev/null +++ b/tests/Common/Lumina.Domain.Fixtures/Core/BoundedContexts/UserManagementBoundedContext/UserSettingsAggregate/ValueObjects/UserSettingsIdFixture.cs @@ -0,0 +1,36 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Domain.Core.BoundedContexts.UserManagementBoundedContext.UserSettingsAggregate.ValueObjects; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Domain.Fixtures.Core.BoundedContexts.UserManagementBoundedContext.UserSettingsAggregate.ValueObjects; + +/// +/// Fixture class for the value object. +/// +[ExcludeFromCodeCoverage] +public class UserSettingsIdFixture +{ + /// + /// Creates a random valid . + /// + /// Optional. The raw value of the user settings Id. + /// The created . + public UserSettingsId Create(Guid? value = null) + { + return UserSettingsId.Create(value ?? Guid.NewGuid()); + } + + /// + /// Creates a list of instances with randomized test data. + /// + /// Number of instances to create. + /// List of configured instances. + public List CreateMany(int count = 3) + { + return [.. Enumerable.Range(0, count).Select(_ => Create())]; + } +} diff --git a/tests/Common/Lumina.Domain.Fixtures/Core/BoundedContexts/WrittenContentLibraryBoundedContext/ExternalIdentifiers/LibraryManagementBoundedContext/LibraryAggregate/LibraryIdFixture.cs b/tests/Common/Lumina.Domain.Fixtures/Core/BoundedContexts/WrittenContentLibraryBoundedContext/ExternalIdentifiers/LibraryManagementBoundedContext/LibraryAggregate/LibraryIdFixture.cs new file mode 100644 index 00000000..82e5d030 --- /dev/null +++ b/tests/Common/Lumina.Domain.Fixtures/Core/BoundedContexts/WrittenContentLibraryBoundedContext/ExternalIdentifiers/LibraryManagementBoundedContext/LibraryAggregate/LibraryIdFixture.cs @@ -0,0 +1,36 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Domain.Core.BoundedContexts.WrittenContentLibraryBoundedContext.ExternalIdentifiers.LibraryManagementBoundedContext.LibraryAggregate; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Domain.Fixtures.Core.BoundedContexts.WrittenContentLibraryBoundedContext.ExternalIdentifiers.LibraryManagementBoundedContext.LibraryAggregate; + +/// +/// Fixture class for the value object. +/// +[ExcludeFromCodeCoverage] +public class LibraryIdFixture +{ + /// + /// Creates a random valid . + /// + /// Optional. The raw value of the library Id. + /// The created . + public LibraryId Create(Guid? value = null) + { + return LibraryId.Create(value ?? Guid.NewGuid()); + } + + /// + /// Creates a list of instances with randomized test data. + /// + /// Number of instances to create. + /// List of configured instances. + public List CreateMany(int count = 3) + { + return [.. Enumerable.Range(0, count).Select(_ => Create())]; + } +} diff --git a/tests/UnitTests/Lumina.Domain.UnitTests/Common/Errors/ErrorsTests.cs b/tests/UnitTests/Lumina.Domain.UnitTests/Common/Errors/ErrorsTests.cs index 2cc0c0af..986db136 100644 --- a/tests/UnitTests/Lumina.Domain.UnitTests/Common/Errors/ErrorsTests.cs +++ b/tests/UnitTests/Lumina.Domain.UnitTests/Common/Errors/ErrorsTests.cs @@ -82,62 +82,168 @@ public class ErrorsTests } [Fact] - public void Metadata_WhenAccessed_ShouldExposeRepresentativeErrorsWithExpectedTypes() + public void Metadata_WhenAccessed_ShouldExposeErrorsWithExpectedTypes() { // Assert + // The count assertion fails when an error is added or removed, reminding to update the assertions below. + Assert.Equal(31, typeof(DomainErrors.Metadata).GetProperties().Length); AssertError(DomainErrors.Metadata.MetadataCannotBeNull, ErrorType.Validation); AssertError(DomainErrors.Metadata.TitleCannotBeEmpty, ErrorType.Validation); + AssertError(DomainErrors.Metadata.TitleMustBeMaximum255CharactersLong, ErrorType.Validation); + AssertError(DomainErrors.Metadata.OriginalTitleMustBeMaximum255CharactersLong, ErrorType.Validation); + AssertError(DomainErrors.Metadata.DescriptionMustBeMaximum2000CharactersLong, ErrorType.Validation); + AssertError(DomainErrors.Metadata.GenresListCannotBeNull, ErrorType.Validation); + AssertError(DomainErrors.Metadata.GenreNameCannotBeEmpty, ErrorType.Validation); + AssertError(DomainErrors.Metadata.GenreNameMustBeMaximum50CharactersLong, ErrorType.Validation); + AssertError(DomainErrors.Metadata.TagsListCannotBeNull, ErrorType.Validation); + AssertError(DomainErrors.Metadata.TagNameCannotBeEmpty, ErrorType.Validation); + AssertError(DomainErrors.Metadata.TagNameMustBeMaximum50CharactersLong, ErrorType.Validation); + AssertError(DomainErrors.Metadata.LanguageCodeCannotBeEmpty, ErrorType.Validation); + AssertError(DomainErrors.Metadata.LanguageNameCannotBeEmpty, ErrorType.Validation); + AssertError(DomainErrors.Metadata.LanguageCodeMustBe2CharactersLong, ErrorType.Validation); + AssertError(DomainErrors.Metadata.LanguageNameMustBeMaximum50CharactersLong, ErrorType.Validation); + AssertError(DomainErrors.Metadata.LanguageNativeNameMustBeMaximum50CharactersLong, ErrorType.Validation); AssertError(DomainErrors.Metadata.OriginalReleaseYearMustBeBetween1And9999, ErrorType.Validation); + AssertError(DomainErrors.Metadata.ReReleaseYearMustBeBetween1And9999, ErrorType.Validation); AssertError(DomainErrors.Metadata.ReReleaseYearCannotBeEarlierThanOriginalReleaseYear, ErrorType.Validation); + AssertError(DomainErrors.Metadata.CountryCodeMustBe2CharactersLong, ErrorType.Validation); + AssertError(DomainErrors.Metadata.ReleaseVersionMustBeMaximum50CharactersLong, ErrorType.Validation); AssertError(DomainErrors.Metadata.OriginalReleaseDateAndYearMustMatch, ErrorType.Validation); + AssertError(DomainErrors.Metadata.ReReleaseDateAndYearMustMatch, ErrorType.Validation); + AssertError(DomainErrors.Metadata.ReReleaseDateCannotBeEarlierThanOriginalReleaseDate, ErrorType.Validation); + AssertError(DomainErrors.Metadata.ReleaseInfoCannotBeNull, ErrorType.Validation); AssertError(DomainErrors.Metadata.RatingValueMustBePositive, ErrorType.Validation); + AssertError(DomainErrors.Metadata.RatingMaxValueMustBePositive, ErrorType.Validation); AssertError(DomainErrors.Metadata.RatingValueCannotBeGreaterThanMaxValue, ErrorType.Validation); AssertError(DomainErrors.Metadata.RatingVoteCountMustBePositive, ErrorType.Validation); + AssertError(DomainErrors.Metadata.RatingsListCannotBeNull, ErrorType.Validation); AssertError(DomainErrors.Metadata.InvalidIsoCode, ErrorType.Validation); - AssertError(DomainErrors.Metadata.GenreNameCannotBeEmpty, ErrorType.Validation); - AssertError(DomainErrors.Metadata.TagNameCannotBeEmpty, ErrorType.Validation); - AssertError(DomainErrors.Metadata.LanguageCodeCannotBeEmpty, ErrorType.Validation); } [Fact] - public void WrittenContent_WhenAccessed_ShouldExposeRepresentativeErrorsWithExpectedTypes() + public void WrittenContent_WhenAccessed_ShouldExposeErrorsWithExpectedTypes() { // Assert + // The count assertion fails when an error is added or removed, reminding to update the assertions below. + Assert.Equal(27, typeof(DomainErrors.WrittenContent).GetProperties().Length); AssertError(DomainErrors.WrittenContent.BookAlreadyExists, ErrorType.Conflict); AssertError(DomainErrors.WrittenContent.IsbnValueCannotBeEmpty, ErrorType.Validation); + AssertError(DomainErrors.WrittenContent.IsbnListCannotBeNull, ErrorType.Validation); AssertError(DomainErrors.WrittenContent.InvalidIsbn10Format, ErrorType.Validation); AssertError(DomainErrors.WrittenContent.InvalidIsbn13Format, ErrorType.Validation); AssertError(DomainErrors.WrittenContent.UnknownIsbnFormat, ErrorType.Unexpected); AssertError(DomainErrors.WrittenContent.TheBookIsAlreadyInTheSeries, ErrorType.Forbidden); AssertError(DomainErrors.WrittenContent.TheBookIsNotInTheSeries, ErrorType.Forbidden); - AssertError(DomainErrors.WrittenContent.BookNotFound, ErrorType.NotFound); + AssertError(DomainErrors.WrittenContent.AsinMustBe10CharactersLong, ErrorType.Validation); + AssertError(DomainErrors.WrittenContent.GoodreadsIdMustBeNumeric, ErrorType.Validation); + AssertError(DomainErrors.WrittenContent.InvalidLccnFormat, ErrorType.Validation); + AssertError(DomainErrors.WrittenContent.InvalidOclcFormat, ErrorType.Validation); + AssertError(DomainErrors.WrittenContent.InvalidOpenLibraryId, ErrorType.Validation); + AssertError(DomainErrors.WrittenContent.LibraryThingIdMustBeMaximum50CharactersLong, ErrorType.Validation); + AssertError(DomainErrors.WrittenContent.GoogleBooksIdMustBe12CharactersLong, ErrorType.Validation); + AssertError(DomainErrors.WrittenContent.InvalidGoogleBooksIdFormat, ErrorType.Validation); + AssertError(DomainErrors.WrittenContent.BarnesAndNoblesIdMustBe10CharactersLong, ErrorType.Validation); + AssertError(DomainErrors.WrittenContent.InvalidBarnesAndNoblesIdFormat, ErrorType.Validation); + AssertError(DomainErrors.WrittenContent.InvalidAppleBooksIdFormat, ErrorType.Validation); + AssertError(DomainErrors.WrittenContent.PublisherMustBeMaximum100CharactersLong, ErrorType.Validation); AssertError(DomainErrors.WrittenContent.PageCountMustBeGreaterThanZero, ErrorType.Validation); + AssertError(DomainErrors.WrittenContent.UnknownBookFormat, ErrorType.Validation); + AssertError(DomainErrors.WrittenContent.EditionMustBeMaximum50CharactersLong, ErrorType.Validation); + AssertError(DomainErrors.WrittenContent.VolumeNumberMustBeGreaterThanZero, ErrorType.Validation); + AssertError(DomainErrors.WrittenContent.BookLibraryCannotBeNull, ErrorType.Validation); + AssertError(DomainErrors.WrittenContent.BookPathCannotBeEmpty, ErrorType.Validation); + AssertError(DomainErrors.WrittenContent.BookNotFound, ErrorType.NotFound); } [Fact] - public void MediaContributor_WhenAccessed_ShouldExposeRepresentativeErrorsWithExpectedTypes() + public void MediaContributor_WhenAccessed_ShouldExposeErrorsWithExpectedTypes() { // Assert + // The count assertion fails when an error is added or removed, reminding to update the assertions below. + Assert.Equal(9, typeof(DomainErrors.MediaContributor).GetProperties().Length); AssertError(DomainErrors.MediaContributor.ContributorsListCannotBeNull, ErrorType.Validation); AssertError(DomainErrors.MediaContributor.ContributorNameCannotBeEmpty, ErrorType.Validation); AssertError(DomainErrors.MediaContributor.ContributorDisplayNameCannotBeEmpty, ErrorType.Validation); AssertError(DomainErrors.MediaContributor.ContributorDisplayNameMustBeMaximum100CharactersLong, ErrorType.Validation); + AssertError(DomainErrors.MediaContributor.ContributorLegalNameMustBeMaximum100CharactersLong, ErrorType.Validation); AssertError(DomainErrors.MediaContributor.RoleNameCannotBeEmpty, ErrorType.Validation); + AssertError(DomainErrors.MediaContributor.RoleNameMustBeMaximum50CharactersLong, ErrorType.Validation); AssertError(DomainErrors.MediaContributor.RoleCategoryCannotBeEmpty, ErrorType.Validation); AssertError(DomainErrors.MediaContributor.ContributorRoleCannotBeNull, ErrorType.Validation); } [Fact] - public void FileSystemManagement_WhenAccessed_ShouldExposeRepresentativeErrorsWithExpectedTypes() + public void MediaContributors_WhenAccessed_ShouldExposeErrorsWithExpectedTypes() { // Assert + // The count assertion fails when an error is added or removed, reminding to update the assertions below. + Assert.Equal(2, typeof(DomainErrors.MediaContributors).GetProperties().Length); + AssertError(DomainErrors.MediaContributors.MediaContributorNameCannotBeEmpty, ErrorType.Validation); + AssertError(DomainErrors.MediaContributors.MediaContributorRoleNameCannotBeEmpty, ErrorType.Validation); + } + + [Fact] + public void FileSystemManagement_WhenAccessed_ShouldExposeErrorsWithExpectedTypes() + { + // Assert + // The count assertion fails when an error is added or removed, reminding to update the assertions below. + Assert.Equal(19, typeof(DomainErrors.FileSystemManagement).GetProperties().Length); AssertError(DomainErrors.FileSystemManagement.ParentNodeCannotBeNull, ErrorType.Failure); + AssertError(DomainErrors.FileSystemManagement.PathMustBeMaximum260CharactersLong, ErrorType.Failure); + AssertError(DomainErrors.FileSystemManagement.FileCopyError, ErrorType.Failure); + AssertError(DomainErrors.FileSystemManagement.FileMoveError, ErrorType.Failure); + AssertError(DomainErrors.FileSystemManagement.DirectoryCopyError, ErrorType.Failure); + AssertError(DomainErrors.FileSystemManagement.DirectoryMoveError, ErrorType.Failure); + AssertError(DomainErrors.FileSystemManagement.FileNotFound, ErrorType.NotFound); AssertError(DomainErrors.FileSystemManagement.InvalidPath, ErrorType.Validation); AssertError(DomainErrors.FileSystemManagement.PathCannotBeEmpty, ErrorType.Validation); - AssertError(DomainErrors.FileSystemManagement.FileNotFound, ErrorType.NotFound); - AssertError(DomainErrors.FileSystemManagement.FileAlreadyExists, ErrorType.Conflict); - AssertError(DomainErrors.FileSystemManagement.DirectoryAlreadyExists, ErrorType.Conflict); + AssertError(DomainErrors.FileSystemManagement.ExtensionCannotBeEmpty, ErrorType.Validation); + AssertError(DomainErrors.FileSystemManagement.StreamIdCannotBeEmpty, ErrorType.Validation); + AssertError(DomainErrors.FileSystemManagement.CodecCannotBeEmpty, ErrorType.Validation); + AssertError(DomainErrors.FileSystemManagement.BitrateMustBeAPositiveNumber, ErrorType.Validation); + AssertError(DomainErrors.FileSystemManagement.CannotNavigateUp, ErrorType.Failure); AssertError(DomainErrors.FileSystemManagement.NameCannotBeEmpty, ErrorType.Validation); + AssertError(DomainErrors.FileSystemManagement.FileAlreadyExists, ErrorType.Conflict); + AssertError(DomainErrors.FileSystemManagement.DirectoryNotFound, ErrorType.NotFound); + AssertError(DomainErrors.FileSystemManagement.DirectoryAlreadyExists, ErrorType.Conflict); + AssertError(DomainErrors.FileSystemManagement.FileTooLarge, ErrorType.Validation); + } + + [Fact] + public void Reading_WhenAccessed_ShouldExposeErrorsWithExpectedTypes() + { + // Assert + // The count assertion fails when an error is added or removed, reminding to update the assertions below. + Assert.Equal(9, typeof(DomainErrors.Reading).GetProperties().Length); + AssertError(DomainErrors.Reading.BookIdCannotBeEmpty, ErrorType.Validation); + AssertError(DomainErrors.Reading.LocationRefCannotBeEmpty, ErrorType.Validation); + AssertError(DomainErrors.Reading.ResourceKeyCannotBeEmpty, ErrorType.Validation); + AssertError(DomainErrors.Reading.BookNotFound, ErrorType.NotFound); + AssertError(DomainErrors.Reading.NoReaderAvailable, ErrorType.NotFound); + AssertError(DomainErrors.Reading.ReaderDisabled, ErrorType.NotFound); + AssertError(DomainErrors.Reading.BookFileNotFound, ErrorType.NotFound); + AssertError(DomainErrors.Reading.SectionNotFound, ErrorType.NotFound); + AssertError(DomainErrors.Reading.ResourceNotFound, ErrorType.NotFound); + } + + [Fact] + public void Themes_WhenAccessed_ShouldExposeErrorsWithExpectedTypes() + { + // Assert + // The count assertion fails when an error is added or removed, reminding to update the assertions below. + Assert.Equal(12, typeof(DomainErrors.Themes).GetProperties().Length); + AssertError(DomainErrors.Themes.ThemeNotFound, ErrorType.NotFound); + AssertError(DomainErrors.Themes.ThemeIdCannotBeEmpty, ErrorType.Validation); + AssertError(DomainErrors.Themes.PageKeyCannotBeEmpty, ErrorType.Validation); + AssertError(DomainErrors.Themes.ThemeAssetPathCannotBeEmpty, ErrorType.Validation); + AssertError(DomainErrors.Themes.ThemeArchiveCannotBeNull, ErrorType.Validation); + AssertError(DomainErrors.Themes.LastBundledThemeCannotBeDeleted, ErrorType.Forbidden); + AssertError(DomainErrors.Themes.ThemeCannotBeDeleted, ErrorType.Forbidden); + AssertError(DomainErrors.Themes.ThemeCannotBeRestored, ErrorType.Forbidden); + AssertError(DomainErrors.Themes.ThemeArchiveNotReadable, ErrorType.Failure); + AssertError(DomainErrors.Themes.ThemeFilesUnreadable, ErrorType.Failure); + AssertError(DomainErrors.Themes.ThemeTemplateNotFound, ErrorType.NotFound); + AssertError(DomainErrors.Themes.ThemeNotAvailable, ErrorType.Failure); } [Fact] @@ -160,14 +266,23 @@ public class ErrorsTests } [Fact] - public void Plugins_WhenAccessed_ShouldExposeRepresentativeErrorsWithExpectedTypes() + public void Plugins_WhenAccessed_ShouldExposeErrorsWithExpectedTypes() { // Assert + // The count assertion fails when an error is added or removed, reminding to update the assertions below. + Assert.Equal(12, typeof(DomainErrors.Plugins).GetProperties().Length); AssertError(DomainErrors.Plugins.PluginNotFound, ErrorType.NotFound); AssertError(DomainErrors.Plugins.PluginIdCannotBeEmpty, ErrorType.Validation); + AssertError(DomainErrors.Plugins.PluginSettingsCannotBeNull, ErrorType.Validation); + AssertError(DomainErrors.Plugins.LibraryIdCannotBeEmpty, ErrorType.Validation); AssertError(DomainErrors.Plugins.PluginIdsListCannotBeNull, ErrorType.Validation); AssertError(DomainErrors.Plugins.PluginIdsListCannotBeEmpty, ErrorType.Validation); AssertError(DomainErrors.Plugins.LibraryMetadataProviderConfigurationNotFound, ErrorType.NotFound); + AssertError(DomainErrors.Plugins.PluginArchiveCannotBeNull, ErrorType.Validation); + AssertError(DomainErrors.Plugins.PluginFileNameCannotBeEmpty, ErrorType.Validation); + AssertError(DomainErrors.Plugins.UnsupportedPluginFileType, ErrorType.Validation); + AssertError(DomainErrors.Plugins.PluginArchiveNotReadable, ErrorType.Failure); + AssertError(DomainErrors.Plugins.PluginArchiveContainsNoAssemblies, ErrorType.Failure); } private static void AssertError(Error error, ErrorType expectedType) diff --git a/tests/UnitTests/Lumina.Domain.UnitTests/Common/Models/Core/EntityIdTests.cs b/tests/UnitTests/Lumina.Domain.UnitTests/Common/Models/Core/EntityIdTests.cs index eb8794ac..a1dbba3e 100644 --- a/tests/UnitTests/Lumina.Domain.UnitTests/Common/Models/Core/EntityIdTests.cs +++ b/tests/UnitTests/Lumina.Domain.UnitTests/Common/Models/Core/EntityIdTests.cs @@ -85,6 +85,31 @@ public class EntityIdTests Assert.Equal(firstHashCode, secondHashCode); } + [Fact] + public void GetEqualityComponents_WhenNotOverridden_ShouldYieldOnlyTheValue() + { + // Arrange + Guid value = Guid.NewGuid(); + DefaultEntityId entityId = new(value); + + // Act + IEnumerable components = entityId.GetEqualityComponents(); + + // Assert + object? component = Assert.Single(components); + Assert.Equal(value, component); + } + + [Fact] + public void Constructor_WhenCalledWithoutArguments_ShouldLeaveValueAsDefault() + { + // Act + DefaultEntityId entityId = new(); + + // Assert + Assert.Equal(default, entityId.Value); + } + /// /// Concrete test implementation of the abstract class. /// @@ -107,4 +132,25 @@ public class EntityIdTests yield return Value; } } + + /// + /// Concrete test implementation of the abstract class that relies on the base equality components. + /// + private sealed class DefaultEntityId : EntityId + { + /// + /// Initializes a new instance of the class. + /// + /// The value representing this object. + public DefaultEntityId(Guid value) : base(value) + { + } + + /// + /// Initializes a new instance of the class. + /// + public DefaultEntityId() : base() + { + } + } } diff --git a/tests/UnitTests/Lumina.Domain.UnitTests/Common/Primitives/ResultTests.cs b/tests/UnitTests/Lumina.Domain.UnitTests/Common/Primitives/ResultTests.cs index 00d40cc9..47583c5e 100644 --- a/tests/UnitTests/Lumina.Domain.UnitTests/Common/Primitives/ResultTests.cs +++ b/tests/UnitTests/Lumina.Domain.UnitTests/Common/Primitives/ResultTests.cs @@ -295,6 +295,39 @@ public class ResultTests Assert.True(firstResult.Equals(secondResult)); } + [Fact] + public void Equals_WhenOneResultIsSuccessfulAndTheOtherIsFailed_ShouldReturnFalse() + { + // Act + Result successResult = Result.Success("test"); + Result failureResult = Result.Failure(Error.Validation("Code", "Description")); + + // Assert + Assert.False(successResult.Equals(failureResult)); + } + + [Fact] + public void Equals_WhenCalledWithBoxedResult_ShouldReturnTrue() + { + // Act + Result firstResult = Result.Success("test"); + object boxedResult = Result.Success("test"); + + // Assert + Assert.True(firstResult.Equals(boxedResult)); + } + + [Fact] + public void Equals_WhenCalledWithNonResultObject_ShouldReturnFalse() + { + // Act + Result result = Result.Success("test"); + object nonResultObject = new(); + + // Assert + Assert.False(result.Equals(nonResultObject)); + } + [Fact] public void EqualityOperator_WhenResultsAreEqual_ShouldReturnTrue() { diff --git a/tests/UnitTests/Lumina.Domain.UnitTests/Common/ValueObjects/Metadata/LanguageInfoTests.cs b/tests/UnitTests/Lumina.Domain.UnitTests/Common/ValueObjects/Metadata/LanguageInfoTests.cs index 61ac9093..12cd4adb 100644 --- a/tests/UnitTests/Lumina.Domain.UnitTests/Common/ValueObjects/Metadata/LanguageInfoTests.cs +++ b/tests/UnitTests/Lumina.Domain.UnitTests/Common/ValueObjects/Metadata/LanguageInfoTests.cs @@ -87,4 +87,65 @@ public class LanguageInfoTests // Assert Assert.Equal("en - English", result); } + + [Fact] + public void Equals_WithSameValues_ShouldReturnTrue() + { + // Arrange + LanguageInfo firstLanguageInfo = _languageInfoFixture.Create( + languageCode: "en", + languageName: "English", + nativeName: Optional.Some("English")); + LanguageInfo secondLanguageInfo = _languageInfoFixture.Create( + languageCode: "en", + languageName: "English", + nativeName: Optional.Some("English")); + + // Act + bool result = firstLanguageInfo.Equals(secondLanguageInfo); + + // Assert + Assert.True(result); + } + + [Fact] + public void GetHashCode_WithSameValues_ShouldReturnSameHashCode() + { + // Arrange + LanguageInfo firstLanguageInfo = _languageInfoFixture.Create( + languageCode: "en", + languageName: "English", + nativeName: Optional.Some("English")); + LanguageInfo secondLanguageInfo = _languageInfoFixture.Create( + languageCode: "en", + languageName: "English", + nativeName: Optional.Some("English")); + + // Act + int firstHashCode = firstLanguageInfo.GetHashCode(); + int secondHashCode = secondLanguageInfo.GetHashCode(); + + // Assert + Assert.Equal(firstHashCode, secondHashCode); + } + + [Fact] + public void Equals_WithDifferentLanguageName_ShouldReturnFalse() + { + // Arrange + LanguageInfo firstLanguageInfo = _languageInfoFixture.Create( + languageCode: "en", + languageName: "English", + nativeName: Optional.None()); + LanguageInfo secondLanguageInfo = _languageInfoFixture.Create( + languageCode: "en", + languageName: "French", + nativeName: Optional.None()); + + // Act + bool result = firstLanguageInfo.Equals(secondLanguageInfo); + + // Assert + Assert.False(result); + } } diff --git a/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Services/DirectoryProviderServiceTests.cs b/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Services/DirectoryProviderServiceTests.cs index 1d827fa3..b1d236ce 100644 --- a/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Services/DirectoryProviderServiceTests.cs +++ b/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Services/DirectoryProviderServiceTests.cs @@ -597,6 +597,90 @@ public class DirectoryProviderServiceTests Assert.Equal(Errors.FileSystemManagement.DirectoryCopyError, result.FirstError); } + [Fact] + public void CopyDirectory_WhenNestedSubdirectoryPathIsInvalid_ShouldReturnError() + { + // Arrange + FileSystemPathId sourcePath = _fileSystemPathIdFixture.Create(_pathSource); + FileSystemPathId destinationPath = _fileSystemPathIdFixture.Create(_pathDestination); + bool overrideExisting = false; + + _mockFileSystem.Directory.Exists(_pathSource).Returns(true); + _mockFileSystem.Directory.Exists(_pathSourceSubDir).Returns(true); + _mockFileSystem.Directory.Exists(_pathDestination).Returns(false); + + _mockFileSystem.Directory.CreateDirectory(Arg.Any()).Returns(callInfo => + { + IDirectoryInfo mockDirInfo = Substitute.For(); + mockDirInfo.FullName.Returns(callInfo.Arg()); + return mockDirInfo; + }); + + IDirectoryInfo invalidNestedDir = Substitute.For(); + invalidNestedDir.FullName.Returns(" "); + + IDirectoryInfo nestedDirInfo = Substitute.For(); + nestedDirInfo.GetFiles().Returns([]); + nestedDirInfo.GetDirectories().Returns([invalidNestedDir]); + _mockFileSystem.DirectoryInfo.New(_pathSourceSubDir).Returns(nestedDirInfo); + + IDirectoryInfo subDirInfo = Substitute.For(); + subDirInfo.Name.Returns("SubDir"); + subDirInfo.FullName.Returns(_pathSourceSubDir); + + IDirectoryInfo sourceDirectoryInfo = Substitute.For(); + sourceDirectoryInfo.GetFiles().Returns([]); + sourceDirectoryInfo.GetDirectories().Returns([subDirInfo]); + _mockFileSystem.DirectoryInfo.New(_pathSource).Returns(sourceDirectoryInfo); + + _mockFileSystem.Path.Combine(Arg.Any(), Arg.Any()) + .Returns(callInfo => Path.Combine(callInfo.ArgAt(0), callInfo.ArgAt(1))); + + // Act + Result result = _sut.CopyDirectory(sourcePath, destinationPath, overrideExisting); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.FileSystemManagement.InvalidPath, result.FirstError); + } + + [Fact] + public void CopyDirectory_WhenDestinationSubdirectoryPathIsInvalid_ShouldReturnError() + { + // Arrange + FileSystemPathId sourcePath = _fileSystemPathIdFixture.Create(_pathSource); + FileSystemPathId destinationPath = _fileSystemPathIdFixture.Create(_pathDestination); + bool overrideExisting = false; + + _mockFileSystem.Directory.Exists(_pathSource).Returns(true); + _mockFileSystem.Directory.Exists(_pathDestination).Returns(false); + + _mockFileSystem.Directory.CreateDirectory(Arg.Any()).Returns(callInfo => + { + IDirectoryInfo mockDirInfo = Substitute.For(); + mockDirInfo.FullName.Returns(callInfo.Arg()); + return mockDirInfo; + }); + + IDirectoryInfo subDirInfo = Substitute.For(); + subDirInfo.Name.Returns("SubDir"); + subDirInfo.FullName.Returns(_pathSourceSubDir); + + IDirectoryInfo sourceDirectoryInfo = Substitute.For(); + sourceDirectoryInfo.GetFiles().Returns([]); + sourceDirectoryInfo.GetDirectories().Returns([subDirInfo]); + _mockFileSystem.DirectoryInfo.New(_pathSource).Returns(sourceDirectoryInfo); + + _mockFileSystem.Path.Combine(Arg.Any(), Arg.Any()).Returns(" "); + + // Act + Result result = _sut.CopyDirectory(sourcePath, destinationPath, overrideExisting); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.FileSystemManagement.InvalidPath, result.FirstError); + } + [Fact] public void MoveDirectory_WhenSourceDirectoryDoesNotExist_ShouldReturnDirectoryNotFoundError() { @@ -969,6 +1053,52 @@ public class DirectoryProviderServiceTests _mockFileSystem.Directory.DidNotReceive().Move(Arg.Any(), Arg.Any()); } + [Fact] + public void RenameDirectory_WhenParentDirectoryPathIsWhitespace_ShouldReturnInvalidPathError() + { + // Arrange + FileSystemPathId path = _fileSystemPathIdFixture.Create( + s_isUnix ? "/OldName" : @"C:\OldName" + ); + string newName = "NewName"; + + IDirectoryInfo parentDirectoryInfo = Substitute.For(); + parentDirectoryInfo.FullName.Returns(" "); + _mockFileSystem.Directory.GetParent(path.Path).Returns(parentDirectoryInfo); + + // Act + Result result = _sut.RenameDirectory(path, newName); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.FileSystemManagement.InvalidPath, result.FirstError); + _mockFileSystem.Directory.DidNotReceive().Move(Arg.Any(), Arg.Any()); + } + + [Fact] + public void RenameDirectory_WhenNewPathIsWhitespace_ShouldReturnInvalidPathError() + { + // Arrange + FileSystemPathId path = _fileSystemPathIdFixture.Create( + s_isUnix ? "/OldName" : @"C:\OldName" + ); + string newName = "NewName"; + string parentPath = s_isUnix ? "/" : @"C:\"; + + IDirectoryInfo parentDirectoryInfo = Substitute.For(); + parentDirectoryInfo.FullName.Returns(parentPath); + _mockFileSystem.Directory.GetParent(path.Path).Returns(parentDirectoryInfo); + _mockFileSystem.Path.Combine(parentPath, newName).Returns(" "); + + // Act + Result result = _sut.RenameDirectory(path, newName); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.FileSystemManagement.InvalidPath, result.FirstError); + _mockFileSystem.Directory.DidNotReceive().Move(Arg.Any(), Arg.Any()); + } + [Fact] public void DeleteDirectory_WhenDirectoryExistsAndHasDeletePermission_ShouldDeleteSuccessfully() { diff --git a/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Services/DirectoryServiceTests.cs b/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Services/DirectoryServiceTests.cs index 1ec2e417..4cf8069e 100644 --- a/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Services/DirectoryServiceTests.cs +++ b/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Services/DirectoryServiceTests.cs @@ -36,6 +36,7 @@ public class DirectoryServiceTests private readonly string _pathDirTest = s_isUnix ? "/TestDir" : @"C:\TestDir"; private readonly string _pathDirTestSubDir1 = s_isUnix ? "/TestDir/Sub1" : @"C:\TestDir\Sub1"; private readonly string _pathDirTestSubDir2 = s_isUnix ? "/TestDir/Sub2" : @"C:\TestDir\Sub2"; + private readonly char _dirSeparator = s_isUnix ? '/' : '\\'; /// /// Initializes a new instance of the class. @@ -497,6 +498,150 @@ public class DirectoryServiceTests _mockEnvironmentContext.DirectoryProviderService.DidNotReceive().CreateDirectory(Arg.Any(), Arg.Any()); } + [Fact] + public void CopyDirectory_WhenSourceAndDestinationDoNotEndWithSeparator_ShouldAppendSeparatorAndReturnDirectoryNotFoundError() + { + // Arrange + string sourcePath = s_isUnix ? "/TestDir/Source" : @"C:\TestDir\Source"; + string destinationPath = s_isUnix ? "/TestDir/Destination" : @"C:\TestDir\Destination"; + bool overrideExisting = true; + _mockPlatformContext.PathStrategy.PathSeparator.Returns(_dirSeparator); + _mockEnvironmentContext.DirectoryProviderService.DirectoryExists(Arg.Any()) + .Returns(Result.From(false)); + + // Act + Result result = _sut.CopyDirectory(sourcePath, destinationPath, overrideExisting); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.FileSystemManagement.DirectoryNotFound, result.FirstError); + } + + [Fact] + public void CopyDirectory_WhenSourceAndDestinationEndWithSeparator_ShouldReturnDirectoryNotFoundError() + { + // Arrange + string sourcePath = s_isUnix ? "/TestDir/Source/" : @"C:\TestDir\Source\"; + string destinationPath = s_isUnix ? "/TestDir/Destination/" : @"C:\TestDir\Destination\"; + bool overrideExisting = true; + _mockPlatformContext.PathStrategy.PathSeparator.Returns(_dirSeparator); + _mockEnvironmentContext.DirectoryProviderService.DirectoryExists(Arg.Any()) + .Returns(Result.From(false)); + + // Act + Result result = _sut.CopyDirectory(sourcePath, destinationPath, overrideExisting); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.FileSystemManagement.DirectoryNotFound, result.FirstError); + } + + [Fact] + public void CopyDirectory_WhenDirectoryExistsReturnsError_ShouldPropagateError() + { + // Arrange + string sourcePath = s_isUnix ? "/TestDir/Source" : @"C:\TestDir\Source"; + string destinationPath = s_isUnix ? "/TestDir/Destination" : @"C:\TestDir\Destination"; + bool overrideExisting = true; + _mockPlatformContext.PathStrategy.PathSeparator.Returns(_dirSeparator); + _mockEnvironmentContext.DirectoryProviderService.DirectoryExists(Arg.Any()) + .Returns(Errors.Permission.UnauthorizedAccess); + + // Act + Result result = _sut.CopyDirectory(sourcePath, destinationPath, overrideExisting); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.Permission.UnauthorizedAccess, result.FirstError); + } + + [Fact] + public void CopyDirectory_WhenSourceDirectoryExists_ShouldThrowNotImplementedException() + { + // Arrange + string sourcePath = s_isUnix ? "/TestDir/Source" : @"C:\TestDir\Source"; + string destinationPath = s_isUnix ? "/TestDir/Destination" : @"C:\TestDir\Destination"; + bool overrideExisting = true; + _mockPlatformContext.PathStrategy.PathSeparator.Returns(_dirSeparator); + _mockEnvironmentContext.DirectoryProviderService.DirectoryExists(Arg.Any()) + .Returns(Result.From(true)); + + // Act & Assert + Assert.Throws(() => _sut.CopyDirectory(sourcePath, destinationPath, overrideExisting)); + } + + [Fact] + public void MoveDirectory_WhenSourceAndDestinationDoNotEndWithSeparator_ShouldAppendSeparatorAndReturnDirectoryNotFoundError() + { + // Arrange + string sourcePath = s_isUnix ? "/TestDir/Source" : @"C:\TestDir\Source"; + string destinationPath = s_isUnix ? "/TestDir/Destination" : @"C:\TestDir\Destination"; + bool overrideExisting = true; + _mockPlatformContext.PathStrategy.PathSeparator.Returns(_dirSeparator); + _mockEnvironmentContext.DirectoryProviderService.DirectoryExists(Arg.Any()) + .Returns(Result.From(false)); + + // Act + Result result = _sut.MoveDirectory(sourcePath, destinationPath, overrideExisting); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.FileSystemManagement.DirectoryNotFound, result.FirstError); + } + + [Fact] + public void MoveDirectory_WhenSourceAndDestinationEndWithSeparator_ShouldReturnDirectoryNotFoundError() + { + // Arrange + string sourcePath = s_isUnix ? "/TestDir/Source/" : @"C:\TestDir\Source\"; + string destinationPath = s_isUnix ? "/TestDir/Destination/" : @"C:\TestDir\Destination\"; + bool overrideExisting = true; + _mockPlatformContext.PathStrategy.PathSeparator.Returns(_dirSeparator); + _mockEnvironmentContext.DirectoryProviderService.DirectoryExists(Arg.Any()) + .Returns(Result.From(false)); + + // Act + Result result = _sut.MoveDirectory(sourcePath, destinationPath, overrideExisting); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.FileSystemManagement.DirectoryNotFound, result.FirstError); + } + + [Fact] + public void MoveDirectory_WhenDirectoryExistsReturnsError_ShouldPropagateError() + { + // Arrange + string sourcePath = s_isUnix ? "/TestDir/Source" : @"C:\TestDir\Source"; + string destinationPath = s_isUnix ? "/TestDir/Destination" : @"C:\TestDir\Destination"; + bool overrideExisting = true; + _mockPlatformContext.PathStrategy.PathSeparator.Returns(_dirSeparator); + _mockEnvironmentContext.DirectoryProviderService.DirectoryExists(Arg.Any()) + .Returns(Errors.Permission.UnauthorizedAccess); + + // Act + Result result = _sut.MoveDirectory(sourcePath, destinationPath, overrideExisting); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.Permission.UnauthorizedAccess, result.FirstError); + } + + [Fact] + public void MoveDirectory_WhenSourceDirectoryExists_ShouldThrowNotImplementedException() + { + // Arrange + string sourcePath = s_isUnix ? "/TestDir/Source" : @"C:\TestDir\Source"; + string destinationPath = s_isUnix ? "/TestDir/Destination" : @"C:\TestDir\Destination"; + bool overrideExisting = true; + _mockPlatformContext.PathStrategy.PathSeparator.Returns(_dirSeparator); + _mockEnvironmentContext.DirectoryProviderService.DirectoryExists(Arg.Any()) + .Returns(Result.From(true)); + + // Act & Assert + Assert.Throws(() => _sut.MoveDirectory(sourcePath, destinationPath, overrideExisting)); + } + [Fact] public void RenameDirectory_WithValidStringPath_ShouldReturnRenamedDirectory() { diff --git a/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Services/DriveServiceTests.cs b/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Services/DriveServiceTests.cs index 132aef7f..f5e78cc9 100644 --- a/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Services/DriveServiceTests.cs +++ b/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Services/DriveServiceTests.cs @@ -76,6 +76,27 @@ public class DriveServiceTests Assert.Equal(["C:\\", "D:\\"], result.Value.Select(d => d.Name)); } + [Fact] + public void GetDrives_OnWindowsPlatformWithDriveWithInvalidName_ShouldExcludeThatDrive() + { + // Arrange + _mockPlatformContext.Platform.Returns(PlatformType.Windows); + IDriveInfo[] mockDrives = + [ + CreateMockDriveInfo("C:\\", true), + CreateMockDriveInfo("", true) // drive whose name cannot be turned into a valid path + ]; + _mockFileSystem.DriveInfo.GetDrives().Returns(mockDrives); + + // Act + Result> result = _sut.GetDrives(); + + // Assert + Assert.False(result.IsFailure); + Assert.Single(result.Value); + Assert.Equal("C:\\", result.Value.First().Name); + } + private static IDriveInfo CreateMockDriveInfo(string name, bool isReady) { IDriveInfo mockDriveInfo = Substitute.For(); diff --git a/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Services/FileProviderServiceTests.cs b/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Services/FileProviderServiceTests.cs index 686ca380..cafb59a2 100644 --- a/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Services/FileProviderServiceTests.cs +++ b/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Services/FileProviderServiceTests.cs @@ -858,6 +858,52 @@ public class FileProviderServiceTests _mockFileSystem.File.DidNotReceive().Move(Arg.Any(), Arg.Any()); } + [Fact] + public void RenameFile_WhenParentDirectoryPathIsWhitespace_ShouldReturnInvalidPathError() + { + // Arrange + FileSystemPathId path = _fileSystemPathIdFixture.Create( + s_isUnix ? "/OldName.txt" : @"C:\OldName.txt" + ); + string newName = "NewName.txt"; + + IFileInfo fileInfo = Substitute.For(); + fileInfo.DirectoryName.Returns(" "); + _mockFileSystem.FileInfo.New(path.Path).Returns(fileInfo); + + // Act + Result result = _sut.RenameFile(path, newName); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.FileSystemManagement.InvalidPath, result.FirstError); + _mockFileSystem.File.DidNotReceive().Move(Arg.Any(), Arg.Any()); + } + + [Fact] + public void RenameFile_WhenNewPathIsWhitespace_ShouldReturnInvalidPathError() + { + // Arrange + FileSystemPathId path = _fileSystemPathIdFixture.Create( + s_isUnix ? "/OldName.txt" : @"C:\OldName.txt" + ); + string newName = "NewName.txt"; + string parentPath = s_isUnix ? "/" : @"C:\"; + + IFileInfo fileInfo = Substitute.For(); + fileInfo.DirectoryName.Returns(parentPath); + _mockFileSystem.FileInfo.New(path.Path).Returns(fileInfo); + _mockFileSystem.Path.Combine(parentPath, newName).Returns(" "); + + // Act + Result result = _sut.RenameFile(path, newName); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.FileSystemManagement.InvalidPath, result.FirstError); + _mockFileSystem.File.DidNotReceive().Move(Arg.Any(), Arg.Any()); + } + [Fact] public void RenameFile_WhenParentDirectoryExistsButNotWritable_ShouldReturnUnauthorizedAccessError() { diff --git a/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Services/FileServiceTests.cs b/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Services/FileServiceTests.cs index 1efdd9be..a2782531 100644 --- a/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Services/FileServiceTests.cs +++ b/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Services/FileServiceTests.cs @@ -326,6 +326,35 @@ public class FileServiceTests Assert.Equal(FileSystemItemStatus.Inaccessible, result.Value.First().Status); } + [Fact] + public void GetFilesWithFileSystemPathId_WhenSizeRetrievalFails_ShouldReturnInaccessibleFileWithZeroSize() + { + // Arrange + FileSystemPathId pathId = _fileSystemPathIdFixture.Create(_pathTestDir); + bool includeHiddenElements = false; + FileSystemPathId filePath = _fileSystemPathIdFixture.Create(_pathTestDirFile1); + + _mockEnvironmentContext.FileProviderService.GetFilePaths(pathId, includeHiddenElements) + .Returns(Result.From(new[] { filePath }.AsEnumerable())); + _mockEnvironmentContext.FileProviderService.GetFileName(filePath) + .Returns(Result.From("File1.txt")); + _mockEnvironmentContext.FileProviderService.GetLastWriteTime(filePath) + .Returns(Result.From(Optional.FromNullable(DateTime.Now))); + _mockEnvironmentContext.FileProviderService.GetCreationTime(filePath) + .Returns(Result.From(Optional.FromNullable(DateTime.Now.AddDays(-1)))); + _mockEnvironmentContext.FileProviderService.GetSize(filePath) + .Returns(Errors.Permission.UnauthorizedAccess); + + // Act + Result> result = _sut.GetFiles(pathId, includeHiddenElements); + + // Assert + Assert.False(result.IsFailure); + Assert.Single(result.Value); + Assert.Equal(FileSystemItemStatus.Inaccessible, result.Value.First().Status); + Assert.Equal(0, result.Value.First().Size); + } + [Fact] public void CopyFile_WithValidPaths_ShouldReturnCopiedFile() { @@ -432,6 +461,27 @@ public class FileServiceTests Assert.Equal(FileSystemItemStatus.Inaccessible, result.Value.Status); } + [Fact] + public void CopyFile_WhenFileExistsReturnsError_ShouldPropagateError() + { + // Arrange + string sourcePath = _pathSourceFile; + string destinationPath = _pathDestination1; + bool overrideExisting = true; + FileSystemPathId sourcePathId = _fileSystemPathIdFixture.Create(sourcePath); + + _mockPlatformContext.PathStrategy.PathSeparator.Returns(_dirSeparator); + _mockEnvironmentContext.FileProviderService.FileExists(sourcePathId) + .Returns(Errors.Permission.UnauthorizedAccess); + + // Act + Result result = _sut.CopyFile(sourcePath, destinationPath, overrideExisting); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.Permission.UnauthorizedAccess, result.FirstError); + } + [Fact] public void CopyFile_WithInvalidSourcePath_ShouldReturnError() { @@ -559,6 +609,55 @@ public class FileServiceTests Assert.Equal(FileSystemItemStatus.Inaccessible, result.Value.Status); } + [Fact] + public void CopyFileWithFileSystemPathIds_WhenFileExistsReturnsError_ShouldPropagateError() + { + // Arrange + FileSystemPathId sourcePathId = _fileSystemPathIdFixture.Create(_pathSourceFile); + FileSystemPathId destinationPathId = _fileSystemPathIdFixture.Create(_pathDestination2); + bool overrideExisting = true; + + _mockEnvironmentContext.FileProviderService.FileExists(sourcePathId) + .Returns(Errors.Permission.UnauthorizedAccess); + + // Act + Result result = _sut.CopyFile(sourcePathId, destinationPathId, overrideExisting); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.Permission.UnauthorizedAccess, result.FirstError); + } + + [Fact] + public void CopyFileWithFileSystemPathIds_WhenSizeRetrievalFails_ShouldReturnInaccessibleFileWithZeroSize() + { + // Arrange + FileSystemPathId sourcePathId = _fileSystemPathIdFixture.Create(_pathSourceFile); + FileSystemPathId destinationPathId = _fileSystemPathIdFixture.Create(_pathDestination2); + FileSystemPathId copiedFilePathId = _fileSystemPathIdFixture.Create(_pathDestinationFile); + bool overrideExisting = true; + + _mockEnvironmentContext.FileProviderService.FileExists(sourcePathId).Returns(true); + _mockEnvironmentContext.FileProviderService.CopyFile(sourcePathId, destinationPathId, overrideExisting) + .Returns(copiedFilePathId); + _mockEnvironmentContext.FileProviderService.GetFileName(copiedFilePathId).Returns("file.txt"); + _mockEnvironmentContext.FileProviderService.GetLastWriteTime(copiedFilePathId) + .Returns(Optional.FromNullable(DateTime.Now)); + _mockEnvironmentContext.FileProviderService.GetCreationTime(copiedFilePathId) + .Returns(Optional.FromNullable(DateTime.Now.AddDays(-1))); + _mockEnvironmentContext.FileProviderService.GetSize(copiedFilePathId) + .Returns(Errors.Permission.UnauthorizedAccess); + + // Act + Result result = _sut.CopyFile(sourcePathId, destinationPathId, overrideExisting); + + // Assert + Assert.False(result.IsFailure); + Assert.NotNull(result.Value); + Assert.Equal(FileSystemItemStatus.Inaccessible, result.Value.Status); + Assert.Equal(0, result.Value.Size); + } + [Fact] public void MoveFile_WithValidPaths_ShouldReturnMovedFile() { @@ -800,6 +899,36 @@ public class FileServiceTests Assert.Equal(FileSystemItemStatus.Inaccessible, result.Value.Status); } + [Fact] + public void MoveFileWithFileSystemPathIds_WhenSizeRetrievalFails_ShouldReturnInaccessibleFileWithZeroSize() + { + // Arrange + FileSystemPathId sourcePathId = _fileSystemPathIdFixture.Create(_pathSourceFile); + FileSystemPathId destinationPathId = _fileSystemPathIdFixture.Create(_pathDestination1); + FileSystemPathId movedFilePathId = _fileSystemPathIdFixture.Create(_pathDestinationFile); + bool overrideExisting = true; + + _mockEnvironmentContext.FileProviderService.FileExists(sourcePathId).Returns(true); + _mockEnvironmentContext.FileProviderService.MoveFile(sourcePathId, destinationPathId, overrideExisting) + .Returns(movedFilePathId); + _mockEnvironmentContext.FileProviderService.GetFileName(movedFilePathId).Returns("file.txt"); + _mockEnvironmentContext.FileProviderService.GetLastWriteTime(movedFilePathId) + .Returns(Optional.FromNullable(DateTime.Now)); + _mockEnvironmentContext.FileProviderService.GetCreationTime(movedFilePathId) + .Returns(Optional.FromNullable(DateTime.Now.AddDays(-1))); + _mockEnvironmentContext.FileProviderService.GetSize(movedFilePathId) + .Returns(Errors.Permission.UnauthorizedAccess); + + // Act + Result result = _sut.MoveFile(sourcePathId, destinationPathId, overrideExisting); + + // Assert + Assert.False(result.IsFailure); + Assert.NotNull(result.Value); + Assert.Equal(FileSystemItemStatus.Inaccessible, result.Value.Status); + Assert.Equal(0, result.Value.Size); + } + [Fact] public void MoveFile_WhenFileExistsReturnsError_ShouldPropagateError() { @@ -1045,6 +1174,37 @@ public class FileServiceTests Assert.Equal(FileSystemItemStatus.Inaccessible, result.Value.Status); } + [Fact] + public void RenameFileWithFileSystemPathId_WhenSizeRetrievalFails_ShouldReturnInaccessibleFileWithZeroSize() + { + // Arrange + FileSystemPathId pathId = _fileSystemPathIdFixture.Create(_pathSourceOldFile); + string newName = "newfile.txt"; + FileSystemPathId newPathId = _fileSystemPathIdFixture.Create(_pathSourceNewFile); + + _mockPlatformContext.PathStrategy.CombinePath(Arg.Any(), newName) + .Returns(Result.From(newPathId)); + _mockEnvironmentContext.FileProviderService.FileExists(newPathId).Returns(false); + _mockEnvironmentContext.FileProviderService.RenameFile(pathId, newName) + .Returns(Result.From(newPathId)); + _mockEnvironmentContext.FileProviderService.GetFileName(newPathId).Returns(Result.From(newName)); + _mockEnvironmentContext.FileProviderService.GetLastWriteTime(newPathId) + .Returns(Result.From(Optional.FromNullable(DateTime.Now))); + _mockEnvironmentContext.FileProviderService.GetCreationTime(newPathId) + .Returns(Result.From(Optional.FromNullable(DateTime.Now.AddDays(-1)))); + _mockEnvironmentContext.FileProviderService.GetSize(newPathId) + .Returns(Errors.Permission.UnauthorizedAccess); + + // Act + Result result = _sut.RenameFile(pathId, newName); + + // Assert + Assert.False(result.IsFailure); + Assert.NotNull(result.Value); + Assert.Equal(FileSystemItemStatus.Inaccessible, result.Value.Status); + Assert.Equal(0, result.Value.Size); + } + [Fact] public void RenameFile_WhenCombinePathReturnsError_ShouldPropagateError() { @@ -1208,4 +1368,18 @@ public class FileServiceTests Assert.True(result.IsFailure); Assert.Equal(Errors.Permission.UnauthorizedAccess, result.FirstError); } + + [Fact] + public void ReadFile_WithFileSystemPathId_ShouldReturnTrue() + { + // Arrange + FileSystemPathId pathId = _fileSystemPathIdFixture.Create(_pathSourceFile); + + // Act + Result result = _sut.ReadFile(pathId); + + // Assert + Assert.False(result.IsFailure); + Assert.True(result.Value); + } } diff --git a/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Services/FileSystemStructureSeedServiceTests.cs b/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Services/FileSystemStructureSeedServiceTests.cs new file mode 100644 index 00000000..8bf0cae6 --- /dev/null +++ b/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Services/FileSystemStructureSeedServiceTests.cs @@ -0,0 +1,137 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Domain.Common.Errors; +using Lumina.Domain.Common.Primitives; +using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Services; +using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Strategies.Environment; +using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.ValueObjects; +using NSubstitute; +using System; +using System.Diagnostics.CodeAnalysis; +using System.IO; +using System.Runtime.InteropServices; +#endregion + +namespace Lumina.Domain.UnitTests.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Services; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class FileSystemStructureSeedServiceTests +{ + private readonly IEnvironmentContext _mockEnvironmentContext; + private readonly IDirectoryProviderService _mockDirectoryProviderService; + private readonly IPathService _mockPathService; + private readonly FileSystemStructureSeedService _sut; + private static readonly bool s_isUnix = RuntimeInformation.IsOSPlatform(OSPlatform.Linux) || RuntimeInformation.IsOSPlatform(OSPlatform.OSX); + private readonly string _rootPath = s_isUnix ? "/Lumina" : @"C:\Lumina"; + + /// + /// Initializes a new instance of the class. + /// + public FileSystemStructureSeedServiceTests() + { + _mockEnvironmentContext = Substitute.For(); + _mockDirectoryProviderService = Substitute.For(); + _mockPathService = Substitute.For(); + _mockEnvironmentContext.DirectoryProviderService.Returns(_mockDirectoryProviderService); + _sut = new FileSystemStructureSeedService(_mockEnvironmentContext, _mockPathService); + } + + [Fact] + public void SetDefaultDirectories_WhenDirectoriesDoNotExist_ShouldCreateThem() + { + // Arrange + _mockPathService.CombinePath(_rootPath, "libraries").Returns(Path.Combine(_rootPath, "libraries")); + _mockPathService.CombinePath(_rootPath, "books").Returns(Path.Combine(_rootPath, "books")); + _mockDirectoryProviderService.DirectoryExists(Arg.Any()).Returns(false); + _mockDirectoryProviderService.CreateDirectory(Arg.Any(), Arg.Any()) + .Returns(callInfo => Result.Success(FileSystemPathId.Create(Path.Combine(_rootPath, callInfo.ArgAt(1))).Value)); + + // Act + Result result = _sut.SetDefaultDirectories(_rootPath); + + // Assert + Assert.True(result.IsSuccess); + _mockDirectoryProviderService.Received(2).DirectoryExists(Arg.Any()); + _mockDirectoryProviderService.Received(2).CreateDirectory(Arg.Any(), Arg.Any()); + } + + [Fact] + public void SetDefaultDirectories_WhenDirectoriesAlreadyExist_ShouldNotCreateThem() + { + // Arrange + _mockPathService.CombinePath(_rootPath, "libraries").Returns(Path.Combine(_rootPath, "libraries")); + _mockPathService.CombinePath(_rootPath, "books").Returns(Path.Combine(_rootPath, "books")); + _mockDirectoryProviderService.DirectoryExists(Arg.Any()).Returns(true); + + // Act + Result result = _sut.SetDefaultDirectories(_rootPath); + + // Assert + Assert.True(result.IsSuccess); + _mockDirectoryProviderService.Received(2).DirectoryExists(Arg.Any()); + _mockDirectoryProviderService.DidNotReceive().CreateDirectory(Arg.Any(), Arg.Any()); + } + + [Fact] + public void SetDefaultDirectories_WhenRootPathIsInvalid_ShouldReturnInvalidPathError() + { + // Act + Result result = _sut.SetDefaultDirectories(" "); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.FileSystemManagement.InvalidPath, result.FirstError); + _mockPathService.DidNotReceive().CombinePath(Arg.Any(), Arg.Any()); + _mockDirectoryProviderService.DidNotReceive().DirectoryExists(Arg.Any()); + } + + [Fact] + public void SetDefaultDirectories_WhenCombiningPathFails_ShouldReturnTheError() + { + // Arrange + _mockPathService.CombinePath(_rootPath, "libraries").Returns(Errors.FileSystemManagement.InvalidPath); + + // Act + Result result = _sut.SetDefaultDirectories(_rootPath); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.FileSystemManagement.InvalidPath, result.FirstError); + _mockDirectoryProviderService.DidNotReceive().DirectoryExists(Arg.Any()); + } + + [Fact] + public void SetDefaultDirectories_WhenCheckingDirectoryExistenceFails_ShouldReturnTheError() + { + // Arrange + _mockPathService.CombinePath(_rootPath, "libraries").Returns(Path.Combine(_rootPath, "libraries")); + _mockDirectoryProviderService.DirectoryExists(Arg.Any()).Returns(Errors.FileSystemManagement.DirectoryNotFound); + + // Act + Result result = _sut.SetDefaultDirectories(_rootPath); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.FileSystemManagement.DirectoryNotFound, result.FirstError); + _mockDirectoryProviderService.DidNotReceive().CreateDirectory(Arg.Any(), Arg.Any()); + } + + [Fact] + public void SetDefaultDirectories_WhenCreatingDirectoryFails_ShouldReturnTheError() + { + // Arrange + _mockPathService.CombinePath(_rootPath, "libraries").Returns(Path.Combine(_rootPath, "libraries")); + _mockDirectoryProviderService.DirectoryExists(Arg.Any()).Returns(false); + _mockDirectoryProviderService.CreateDirectory(Arg.Any(), Arg.Any()) + .Returns(Errors.FileSystemManagement.DirectoryAlreadyExists); + + // Act + Result result = _sut.SetDefaultDirectories(_rootPath); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.FileSystemManagement.DirectoryAlreadyExists, result.FirstError); + } +} diff --git a/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Services/PathServiceTests.cs b/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Services/PathServiceTests.cs index cf0803aa..f87eaacc 100644 --- a/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Services/PathServiceTests.cs +++ b/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Services/PathServiceTests.cs @@ -40,6 +40,20 @@ public class PathServiceTests _sut = new PathService(_mockPlatformContextManager); } + [Fact] + public void PathSeparator_WhenAccessed_ShouldReturnPathStrategySeparator() + { + // Arrange + char expectedSeparator = '\\'; + _mockPathStrategy.PathSeparator.Returns(expectedSeparator); + + // Act + char result = _sut.PathSeparator; + + // Assert + Assert.Equal(expectedSeparator, result); + } + [Fact] public void IsValidPath_WithValidPath_ShouldReturnTrue() { diff --git a/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Services/ThumbnailServiceTests.cs b/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Services/ThumbnailServiceTests.cs index 83d75cf0..fbf57350 100644 --- a/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Services/ThumbnailServiceTests.cs +++ b/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Services/ThumbnailServiceTests.cs @@ -9,6 +9,7 @@ using Lumina.Domain.Fixtures.Core.BoundedContexts.FileSystemManagementBoundedCon using Lumina.Domain.SharedKernel.Common.Enums.PhotoLibrary; using NSubstitute; using SixLabors.ImageSharp; +using SixLabors.ImageSharp.Formats; using SixLabors.ImageSharp.Formats.Jpeg; using SixLabors.ImageSharp.PixelFormats; using System.Diagnostics.CodeAnalysis; @@ -168,6 +169,67 @@ public class ThumbnailServiceTests } } + [Theory] + [InlineData(ImageType.JPEG2000)] // resolution adjustment switch branch for JPEG2000 + [InlineData(ImageType.JPEG_CANON)] // resolution adjustment switch branch for Canon JPEG + [InlineData(ImageType.JPEG_UNKNOWN)] // resolution adjustment switch branch for unknown JPEG + [InlineData(ImageType.TIFF)] // resolution adjustment switch branch for TIFF + [InlineData(ImageType.WEBP)] // resolution adjustment switch branch for WEBP + [InlineData(ImageType.TGA)] // resolution adjustment switch branch for TGA + public async Task GetThumbnailAsync_WithAdditionalSupportedImageTypes_ShouldReturnAdjustedThumbnail(ImageType imageType) + { + // Arrange + FileSystemPathId pathId = _fileSystemPathIdFixture.Create(@"C:\TestImage"); + int quality = 80; + byte[] imageBytes = CreateImageBytes(new JpegEncoder()); + + _mockEnvironmentContext.FileTypeService.GetImageTypeAsync(pathId, Arg.Any()) + .Returns(Result.From(imageType)); + _mockEnvironmentContext.FileProviderService.GetFileAsync(pathId) + .Returns(Result.From(imageBytes)); + + // Act + Result result = await _sut.GetThumbnailAsync(pathId, quality, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal(imageType, result.Value.Type); + Assert.NotEmpty(result.Value.Bytes); + + using (MemoryStream ms = new(result.Value.Bytes)) + { + Image loadedImage = Image.Load(ms); + Assert.NotNull(loadedImage); + } + } + + [Theory] + [InlineData(ImageType.SVG)] // SVG is not resized, original bytes are returned + [InlineData(ImageType.PICT)] // PICT is not resized, original bytes are returned + [InlineData(ImageType.ICO)] // ICO is not resized, original bytes are returned + [InlineData(ImageType.PSD)] // PSD is not resized, original bytes are returned + [InlineData(ImageType.AVIF)] // AVIF is not resized, original bytes are returned + public async Task GetThumbnailAsync_WithUnsupportedNonNoneImageType_ShouldReturnOriginalBytes(ImageType imageType) + { + // Arrange + FileSystemPathId pathId = _fileSystemPathIdFixture.Create(@"C:\TestImage"); + int quality = 80; + byte[] imageBytes = CreateImageBytes(new JpegEncoder()); + + _mockEnvironmentContext.FileTypeService.GetImageTypeAsync(pathId, Arg.Any()) + .Returns(Result.From(imageType)); + _mockEnvironmentContext.FileProviderService.GetFileAsync(pathId) + .Returns(Result.From(imageBytes)); + + // Act + Result result = await _sut.GetThumbnailAsync(pathId, quality, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal(imageType, result.Value.Type); + Assert.Equal(imageBytes, result.Value.Bytes); + } + [Fact] public async Task GetThumbnailAsync_WithCancellation_ShouldThrowTaskCanceledException() { @@ -184,4 +246,17 @@ public class ThumbnailServiceTests await Assert.ThrowsAsync(() => _sut.GetThumbnailAsync(pathId, quality, cts.Token)); } + + /// + /// Creates the bytes of a small image encoded with the specified encoder. + /// + /// The encoder used to encode the image. + /// The bytes of the created image. + private static byte[] CreateImageBytes(IImageEncoder encoder) + { + using Image image = new(10, 10); + using MemoryStream memoryStream = new(); + image.Save(memoryStream, encoder); + return memoryStream.ToArray(); + } } diff --git a/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Strategies/Path/UnixPathStrategyTests.cs b/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Strategies/Path/UnixPathStrategyTests.cs index c79f6fc3..ee30f141 100644 --- a/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Strategies/Path/UnixPathStrategyTests.cs +++ b/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Strategies/Path/UnixPathStrategyTests.cs @@ -376,6 +376,20 @@ public class UnixPathStrategyTests Assert.Equal(Errors.FileSystemManagement.InvalidPath, result.FirstError); } + [Fact] + public void ParsePath_WhenPathContainsWhitespaceSegment_ShouldReturnError() + { + // Arrange + FileSystemPathId path = _fileSystemPathIdFixture.Create("/home/ /user"); + + // Act + Result> result = _sut.ParsePath(path); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.FileSystemManagement.NameCannotBeEmpty, result.FirstError); + } + [Fact] public void ParsePath_WithPathContainingDots_ShouldParseCorrectly() { diff --git a/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Strategies/Path/WindowsPathStrategyTests.cs b/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Strategies/Path/WindowsPathStrategyTests.cs index a01a5f9b..1e915b96 100644 --- a/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Strategies/Path/WindowsPathStrategyTests.cs +++ b/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Strategies/Path/WindowsPathStrategyTests.cs @@ -419,6 +419,20 @@ public class WindowsPathStrategyTests Assert.Equal(Errors.FileSystemManagement.InvalidPath, result.FirstError); } + [Fact] + public void ParsePath_WhenPathContainsWhitespaceSegment_ShouldReturnError() + { + // Arrange + FileSystemPathId path = _fileSystemPathIdFixture.Create(@"C:\ \folder"); + + // Act + Result> result = _sut.ParsePath(path); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.FileSystemManagement.NameCannotBeEmpty, result.FirstError); + } + [Fact] public void ParsePath_WithPathContainingDots_ShouldParseCorrectly() { diff --git a/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryAggregate/LibraryTests.cs b/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryAggregate/LibraryTests.cs index ca069f9b..e6e9d88e 100644 --- a/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryAggregate/LibraryTests.cs +++ b/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryAggregate/LibraryTests.cs @@ -95,6 +95,45 @@ public class LibraryTests Assert.Equal(id, result.Value.Id.Value); } + [Fact] + public void Create_WhenGivenPreExistingIdAndInvalidContentLocation_ShouldReturnError() + { + // Arrange + Guid id = Guid.NewGuid(); + + // Act + Result result = Library.Create( + _libraryIdFixture.Create(id), + _userIdFixture.Create(), + "My Library", + LibraryType.Book, + [""], + null, + isEnabled: true, + isLocked: false, + canDownloadMetadataFromWeb: true, + shouldSaveMetadataInMediaDirectories: false, + shouldSkipUnchangedDirectoriesDuringScan: false, + []); + + // 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 + string? coverImageSourcePath = library.CoverImageSourcePath; + + // Assert + Assert.Null(coverImageSourcePath); + } + [Fact] public void Create_WhenCalledWithContentLocations_ShouldCreateFileSystemPathIdForEachLocation() { diff --git a/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Services/Progress/MediaLibrariesScanProgressTrackerTests.cs b/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Services/Progress/MediaLibrariesScanProgressTrackerTests.cs index 2f189b6b..ffa634d3 100644 --- a/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Services/Progress/MediaLibrariesScanProgressTrackerTests.cs +++ b/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Services/Progress/MediaLibrariesScanProgressTrackerTests.cs @@ -100,6 +100,23 @@ public class MediaLibrariesScanProgressTrackerTests 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 result = _sut.UpdateScanProgress(libraryId, compositeId); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.LibraryScanning.CompletedScanJobsCountCantExceedTotalScanJobsCount, result.FirstError); + } + [Fact] public void UpdateScanJobProgress_WhenScanExists_ShouldUpdateCurrentJobProgress() { diff --git a/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Services/Scanners/MediaLibraryScannerFactoryTests.cs b/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Services/Scanners/MediaLibraryScannerFactoryTests.cs index 33356182..9a3f743b 100644 --- a/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Services/Scanners/MediaLibraryScannerFactoryTests.cs +++ b/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Services/Scanners/MediaLibraryScannerFactoryTests.cs @@ -35,9 +35,39 @@ public class MediaLibraryScannerFactoryTests [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.Music)] // music 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_ShouldThrowNotImplementedException(LibraryType libraryType) { // Arrange diff --git a/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/ValueObjects/MediaLibraryScanProgressTests.cs b/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/ValueObjects/MediaLibraryScanProgressTests.cs index d271dab9..8a3c3ee7 100644 --- a/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/ValueObjects/MediaLibraryScanProgressTests.cs +++ b/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/ValueObjects/MediaLibraryScanProgressTests.cs @@ -197,4 +197,22 @@ public class MediaLibraryScanProgressTests // 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.Some(currentJobProgress)); + + // Act + string result = scanProgress.ToString(); + + // Assert + Assert.Equal("CompletedJobs: 2; TotalJobs: 5; CurrentJobProgress: CompletedItems: 3; TotalItems: 10; CurrentOperation: Hashing files", result); + } } diff --git a/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/MediaContributorBoundedContext/MediaContributorAggregate/ValueObjects/MediaContributorNameTests.cs b/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/MediaContributorBoundedContext/MediaContributorAggregate/ValueObjects/MediaContributorNameTests.cs index 5ff0c4d6..c1777268 100644 --- a/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/MediaContributorBoundedContext/MediaContributorAggregate/ValueObjects/MediaContributorNameTests.cs +++ b/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/MediaContributorBoundedContext/MediaContributorAggregate/ValueObjects/MediaContributorNameTests.cs @@ -1,4 +1,5 @@ #region ========================================================================= USING ===================================================================================== +using Lumina.Domain.Common.Errors; using Lumina.Domain.Common.Primitives; using Lumina.Domain.Core.BoundedContexts.MediaContributorBoundedContext.MediaContributorAggregate.ValueObjects; using Lumina.Domain.Fixtures.Core.BoundedContexts.MediaContributorBoundedContext.MediaContributorAggregate.ValueObjects; @@ -40,6 +41,20 @@ public class MediaContributorNameTests Assert.False(result.Value.LegalName.HasValue); } + [Theory] + [InlineData(null)] // null display name + [InlineData("")] // empty display name + [InlineData(" ")] // whitespace display name + public void Create_WhenDisplayNameIsNullOrWhitespace_ShouldReturnError(string? displayName) + { + // Act + Result result = MediaContributorName.Create(displayName!, Optional.None()); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.MediaContributors.MediaContributorNameCannotBeEmpty, result.FirstError); + } + [Fact] public void Equals_WithSameValues_ShouldReturnTrue() { diff --git a/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/UserManagementBoundedContext/UserSettingsAggregate/UserSettingsTests.cs b/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/UserManagementBoundedContext/UserSettingsAggregate/UserSettingsTests.cs index ba156551..27de1b25 100644 --- a/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/UserManagementBoundedContext/UserSettingsAggregate/UserSettingsTests.cs +++ b/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/UserManagementBoundedContext/UserSettingsAggregate/UserSettingsTests.cs @@ -3,8 +3,10 @@ using Lumina.Domain.Common.Errors; using Lumina.Domain.Common.Primitives; using Lumina.Domain.Core.BoundedContexts.UserManagementBoundedContext.UserAggregate.ValueObjects; using Lumina.Domain.Core.BoundedContexts.UserManagementBoundedContext.UserSettingsAggregate; +using Lumina.Domain.Core.BoundedContexts.UserManagementBoundedContext.UserSettingsAggregate.ValueObjects; using Lumina.Domain.Fixtures.Core.BoundedContexts.UserManagementBoundedContext.UserAggregate.ValueObjects; using Lumina.Domain.Fixtures.Core.BoundedContexts.UserManagementBoundedContext.UserSettingsAggregate; +using Lumina.Domain.Fixtures.Core.BoundedContexts.UserManagementBoundedContext.UserSettingsAggregate.ValueObjects; using System.Diagnostics.CodeAnalysis; #endregion @@ -18,6 +20,7 @@ public class UserSettingsTests { private readonly UserIdFixture _userIdFixture = new(); private readonly UserSettingsFixture _userSettingsFixture = new(); + private readonly UserSettingsIdFixture _userSettingsIdFixture = new(); [Fact] public void Create_WhenCalledWithoutValues_ShouldCreateSettingsWithDefaultValues() @@ -121,6 +124,38 @@ public class UserSettingsTests Assert.Equal(Errors.UserSettings.ItemsPerPageMustBeGreaterThanZero, result.FirstError); } + [Fact] + public void Create_WhenCalledWithPreExistingIdAndValidValues_ShouldCreateSettingsWithThatId() + { + // Arrange + UserId userId = _userIdFixture.Create(); + UserSettingsId id = _userSettingsIdFixture.Create(); + + // Act + Result result = UserSettings.Create(id, userId, isPaginationEnabled: true, itemsPerPage: 24, shouldIgnoreThePrefixForAlphaPicker: false, isThemeCachingEnabled: true, shouldAggregateMetadataWhenMissing: false, shouldRenderPdfAsImages: false, shouldPreserveBookStyles: true); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal(id, result.Value.Id); + Assert.Equal(userId, result.Value.UserId); + Assert.Equal(24, result.Value.ItemsPerPage); + } + + [Fact] + public void Create_WhenCalledWithPreExistingIdAndNonPositiveItemsPerPage_ShouldReturnError() + { + // Arrange + UserId userId = _userIdFixture.Create(); + UserSettingsId id = _userSettingsIdFixture.Create(); + + // Act + Result result = UserSettings.Create(id, userId, isPaginationEnabled: true, itemsPerPage: 0, shouldIgnoreThePrefixForAlphaPicker: false, isThemeCachingEnabled: true, shouldAggregateMetadataWhenMissing: false, shouldRenderPdfAsImages: false, shouldPreserveBookStyles: false); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.UserSettings.ItemsPerPageMustBeGreaterThanZero, result.FirstError); + } + [Fact] public void UpdateSettings_WhenCalledWithValidValues_ShouldUpdateSettings() { diff --git a/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/UserManagementBoundedContext/UserSettingsAggregate/ValueObjects/UserSettingsIdTests.cs b/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/UserManagementBoundedContext/UserSettingsAggregate/ValueObjects/UserSettingsIdTests.cs new file mode 100644 index 00000000..b26c901e --- /dev/null +++ b/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/UserManagementBoundedContext/UserSettingsAggregate/ValueObjects/UserSettingsIdTests.cs @@ -0,0 +1,86 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Domain.Core.BoundedContexts.UserManagementBoundedContext.UserSettingsAggregate.ValueObjects; +using Lumina.Domain.Fixtures.Core.BoundedContexts.UserManagementBoundedContext.UserSettingsAggregate.ValueObjects; +using System; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Domain.UnitTests.Core.BoundedContexts.UserManagementBoundedContext.UserSettingsAggregate.ValueObjects; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class UserSettingsIdTests +{ + private readonly UserSettingsIdFixture _userSettingsIdFixture = new(); + + [Fact] + public void CreateUnique_WhenCalled_ShouldReturnIdWithNonEmptyValue() + { + // Act + UserSettingsId userSettingsId = UserSettingsId.CreateUnique(); + + // Assert + Assert.NotNull(userSettingsId); + Assert.NotEqual(default, userSettingsId.Value); + } + + [Fact] + public void Create_WhenCalledWithValue_ShouldReturnIdWithThatValue() + { + // Arrange + Guid value = Guid.NewGuid(); + + // Act + UserSettingsId userSettingsId = UserSettingsId.Create(value); + + // Assert + Assert.Equal(value, userSettingsId.Value); + } + + [Fact] + public void Equals_WithSameValue_ShouldReturnTrue() + { + // Arrange + Guid value = Guid.NewGuid(); + UserSettingsId firstId = _userSettingsIdFixture.Create(value); + UserSettingsId secondId = _userSettingsIdFixture.Create(value); + + // Act + bool result = firstId.Equals(secondId); + + // Assert + Assert.True(result); + } + + [Fact] + public void GetHashCode_WithSameValue_ShouldReturnSameHashCode() + { + // Arrange + Guid value = Guid.NewGuid(); + UserSettingsId firstId = _userSettingsIdFixture.Create(value); + UserSettingsId secondId = _userSettingsIdFixture.Create(value); + + // Act + int firstHashCode = firstId.GetHashCode(); + int secondHashCode = secondId.GetHashCode(); + + // Assert + Assert.Equal(firstHashCode, secondHashCode); + } + + [Fact] + public void Equals_WithDifferentValue_ShouldReturnFalse() + { + // Arrange + UserSettingsId firstId = _userSettingsIdFixture.Create(); + UserSettingsId secondId = _userSettingsIdFixture.Create(); + + // Act + bool result = firstId.Equals(secondId); + + // Assert + Assert.False(result); + } +} diff --git a/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/WrittenContentLibraryBoundedContext/BookLibraryAggregate/BookTests.cs b/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/WrittenContentLibraryBoundedContext/BookLibraryAggregate/BookTests.cs index e90f14cf..6bb62492 100644 --- a/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/WrittenContentLibraryBoundedContext/BookLibraryAggregate/BookTests.cs +++ b/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/WrittenContentLibraryBoundedContext/BookLibraryAggregate/BookTests.cs @@ -67,6 +67,148 @@ public class BookTests Assert.Equal(replacementContributorId, contributorId); } + [Fact] + public void Create_WhenCalledWithPreExistingIdAndTimestamps_ShouldPreserveIdentityAndTimestamps() + { + // Arrange + Book sourceBook = _bookFixture.Create(); + DateTime createdOnUtc = DateTime.UtcNow.AddDays(-1); + DateTime updatedOnUtc = DateTime.UtcNow; + + // Act + Result result = Book.Create( + sourceBook.Id, + sourceBook.LibraryId, + sourceBook.Path, + sourceBook.Metadata, + sourceBook.Format, + sourceBook.Edition, + sourceBook.VolumeNumber, + sourceBook.Series, + sourceBook.ASIN, + sourceBook.GoodreadsId, + sourceBook.LCCN, + sourceBook.OCLCNumber, + sourceBook.OpenLibraryId, + sourceBook.LibraryThingId, + sourceBook.GoogleBooksId, + sourceBook.BarnesAndNobleId, + sourceBook.AppleBooksId, + createdOnUtc, + Optional.Some(updatedOnUtc), + [.. sourceBook.ISBNs], + [.. sourceBook.Contributors], + [.. sourceBook.Ratings]); + + // Assert + Book book = result.Value; + Assert.Equal(sourceBook.Id, book.Id); + Assert.Equal(sourceBook.LibraryId, book.LibraryId); + Assert.Equal(sourceBook.Path, book.Path); + Assert.Equal(sourceBook.Metadata, book.Metadata); + Assert.Equal(createdOnUtc, book.CreatedOnUtc); + Assert.Equal(updatedOnUtc, book.UpdatedOnUtc); + Assert.Equal(sourceBook.ISBNs, book.ISBNs); + Assert.Equal(sourceBook.Ratings, book.Ratings); + } + + [Fact] + public void ApplyEnrichedMetadata_WhenCalled_ShouldReplaceMetadataAndRelatedFields() + { + // Arrange + Book book = _bookFixture.Create(); + Book enrichedSource = _bookFixture.Create(); + + // Act + book.ApplyEnrichedMetadata( + enrichedSource.Metadata, + enrichedSource.Format, + enrichedSource.Edition, + enrichedSource.VolumeNumber, + enrichedSource.Series, + enrichedSource.ASIN, + enrichedSource.GoodreadsId, + enrichedSource.LCCN, + enrichedSource.OCLCNumber, + enrichedSource.OpenLibraryId, + enrichedSource.LibraryThingId, + enrichedSource.GoogleBooksId, + enrichedSource.BarnesAndNobleId, + enrichedSource.AppleBooksId, + [.. enrichedSource.ISBNs], + [.. enrichedSource.Ratings]); + + // Assert + // the metadata and related fields are replaced with the enriched values + Assert.Equal(enrichedSource.Metadata, book.Metadata); + Assert.Equal(enrichedSource.Format, book.Format); + Assert.Equal(enrichedSource.Edition, book.Edition); + Assert.Equal(enrichedSource.VolumeNumber, book.VolumeNumber); + Assert.Equal(enrichedSource.Series, book.Series); + Assert.Equal(enrichedSource.ASIN, book.ASIN); + Assert.Equal(enrichedSource.GoodreadsId, book.GoodreadsId); + Assert.Equal(enrichedSource.LCCN, book.LCCN); + Assert.Equal(enrichedSource.OCLCNumber, book.OCLCNumber); + Assert.Equal(enrichedSource.OpenLibraryId, book.OpenLibraryId); + Assert.Equal(enrichedSource.LibraryThingId, book.LibraryThingId); + Assert.Equal(enrichedSource.GoogleBooksId, book.GoogleBooksId); + Assert.Equal(enrichedSource.BarnesAndNobleId, book.BarnesAndNobleId); + Assert.Equal(enrichedSource.AppleBooksId, book.AppleBooksId); + Assert.Equal(enrichedSource.ISBNs, book.ISBNs); + Assert.Equal(enrichedSource.Ratings, book.Ratings); + } + + [Fact] + public void ApplyEnrichedMetadata_WhenCalledAgain_ShouldReplaceCollectionsWithoutAppending() + { + // Arrange + Book book = _bookFixture.Create(); + Book firstEnrichmentSource = _bookFixture.Create(); + Book secondEnrichmentSource = _bookFixture.Create(); + book.ApplyEnrichedMetadata( + firstEnrichmentSource.Metadata, + firstEnrichmentSource.Format, + firstEnrichmentSource.Edition, + firstEnrichmentSource.VolumeNumber, + firstEnrichmentSource.Series, + firstEnrichmentSource.ASIN, + firstEnrichmentSource.GoodreadsId, + firstEnrichmentSource.LCCN, + firstEnrichmentSource.OCLCNumber, + firstEnrichmentSource.OpenLibraryId, + firstEnrichmentSource.LibraryThingId, + firstEnrichmentSource.GoogleBooksId, + firstEnrichmentSource.BarnesAndNobleId, + firstEnrichmentSource.AppleBooksId, + [.. firstEnrichmentSource.ISBNs], + [.. firstEnrichmentSource.Ratings]); + + // Act + book.ApplyEnrichedMetadata( + secondEnrichmentSource.Metadata, + secondEnrichmentSource.Format, + secondEnrichmentSource.Edition, + secondEnrichmentSource.VolumeNumber, + secondEnrichmentSource.Series, + secondEnrichmentSource.ASIN, + secondEnrichmentSource.GoodreadsId, + secondEnrichmentSource.LCCN, + secondEnrichmentSource.OCLCNumber, + secondEnrichmentSource.OpenLibraryId, + secondEnrichmentSource.LibraryThingId, + secondEnrichmentSource.GoogleBooksId, + secondEnrichmentSource.BarnesAndNobleId, + secondEnrichmentSource.AppleBooksId, + [.. secondEnrichmentSource.ISBNs], + [.. secondEnrichmentSource.Ratings]); + + // Assert + // the second enrichment replaces the first, it is not appended to it + Assert.Equal(secondEnrichmentSource.ISBNs.Count, book.ISBNs.Count); + Assert.Equal(secondEnrichmentSource.ISBNs, book.ISBNs); + Assert.Equal(secondEnrichmentSource.Ratings, book.Ratings); + } + [Fact] public void Create_WhenCalled_ShouldNotExposeEnrichmentTracking() { diff --git a/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/WrittenContentLibraryBoundedContext/ExternalIdentifiers/LibraryManagementBoundedContext/LibraryAggregate/LibraryIdTests.cs b/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/WrittenContentLibraryBoundedContext/ExternalIdentifiers/LibraryManagementBoundedContext/LibraryAggregate/LibraryIdTests.cs new file mode 100644 index 00000000..4c93e1ab --- /dev/null +++ b/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/WrittenContentLibraryBoundedContext/ExternalIdentifiers/LibraryManagementBoundedContext/LibraryAggregate/LibraryIdTests.cs @@ -0,0 +1,86 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Domain.Core.BoundedContexts.WrittenContentLibraryBoundedContext.ExternalIdentifiers.LibraryManagementBoundedContext.LibraryAggregate; +using Lumina.Domain.Fixtures.Core.BoundedContexts.WrittenContentLibraryBoundedContext.ExternalIdentifiers.LibraryManagementBoundedContext.LibraryAggregate; +using System; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Domain.UnitTests.Core.BoundedContexts.WrittenContentLibraryBoundedContext.ExternalIdentifiers.LibraryManagementBoundedContext.LibraryAggregate; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class LibraryIdTests +{ + private readonly LibraryIdFixture _libraryIdFixture = new(); + + [Fact] + public void CreateUnique_WhenCalled_ShouldReturnIdWithNonEmptyValue() + { + // Act + LibraryId libraryId = LibraryId.CreateUnique(); + + // Assert + Assert.NotNull(libraryId); + Assert.NotEqual(default, libraryId.Value); + } + + [Fact] + public void Create_WhenCalledWithValue_ShouldReturnIdWithThatValue() + { + // Arrange + Guid value = Guid.NewGuid(); + + // Act + LibraryId libraryId = LibraryId.Create(value); + + // Assert + Assert.Equal(value, libraryId.Value); + } + + [Fact] + public void Equals_WithSameValue_ShouldReturnTrue() + { + // Arrange + Guid value = Guid.NewGuid(); + LibraryId firstId = _libraryIdFixture.Create(value); + LibraryId secondId = _libraryIdFixture.Create(value); + + // Act + bool result = firstId.Equals(secondId); + + // Assert + Assert.True(result); + } + + [Fact] + public void GetHashCode_WithSameValue_ShouldReturnSameHashCode() + { + // Arrange + Guid value = Guid.NewGuid(); + LibraryId firstId = _libraryIdFixture.Create(value); + LibraryId secondId = _libraryIdFixture.Create(value); + + // Act + int firstHashCode = firstId.GetHashCode(); + int secondHashCode = secondId.GetHashCode(); + + // Assert + Assert.Equal(firstHashCode, secondHashCode); + } + + [Fact] + public void Equals_WithDifferentValue_ShouldReturnFalse() + { + // Arrange + LibraryId firstId = _libraryIdFixture.Create(); + LibraryId secondId = _libraryIdFixture.Create(); + + // Act + bool result = firstId.Equals(secondId); + + // Assert + Assert.False(result); + } +}