Adds unit tests improving domain project code coverage

This commit is contained in:
BinaryAlley committed 2026-09-02 06:56:36 -07:00
1 parent 208f102070
commit 0ec6eb7ab4
25 files changed
+1577 -12

No files matched your search

@@ -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;
/// <summary>
/// Fixture class for the <see cref="UserSettingsId"/> value object.
/// </summary>
[ExcludeFromCodeCoverage]
public class UserSettingsIdFixture
{
/// <summary>
/// Creates a random valid <see cref="UserSettingsId"/>.
/// </summary>
/// <param name="value">Optional. The raw value of the user settings Id.</param>
/// <returns>The created <see cref="UserSettingsId"/>.</returns>
public UserSettingsId Create(Guid? value = null)
{
return UserSettingsId.Create(value ?? Guid.NewGuid());
}
/// <summary>
/// Creates a list of <see cref="UserSettingsId"/> instances with randomized test data.
/// </summary>
/// <param name="count">Number of instances to create.</param>
/// <returns>List of configured <see cref="UserSettingsId"/> instances.</returns>
public List<UserSettingsId> CreateMany(int count = 3)
{
return [.. Enumerable.Range(0, count).Select(_ => Create())];
}
}
@@ -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;
/// <summary>
/// Fixture class for the <see cref="LibraryId"/> value object.
/// </summary>
[ExcludeFromCodeCoverage]
public class LibraryIdFixture
{
/// <summary>
/// Creates a random valid <see cref="LibraryId"/>.
/// </summary>
/// <param name="value">Optional. The raw value of the library Id.</param>
/// <returns>The created <see cref="LibraryId"/>.</returns>
public LibraryId Create(Guid? value = null)
{
return LibraryId.Create(value ?? Guid.NewGuid());
}
/// <summary>
/// Creates a list of <see cref="LibraryId"/> instances with randomized test data.
/// </summary>
/// <param name="count">Number of instances to create.</param>
/// <returns>List of configured <see cref="LibraryId"/> instances.</returns>
public List<LibraryId> CreateMany(int count = 3)
{
return [.. Enumerable.Range(0, count).Select(_ => Create())];
}
}
@@ -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)
@@ -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<object?> 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);
}
/// <summary>
/// Concrete test implementation of the abstract <see cref="EntityId{TId}"/> class.
/// </summary>
@@ -107,4 +132,25 @@ public class EntityIdTests
yield return Value;
}
}
/// <summary>
/// Concrete test implementation of the abstract <see cref="EntityId{TId}"/> class that relies on the base equality components.
/// </summary>
private sealed class DefaultEntityId : EntityId<Guid>
{
/// <summary>
/// Initializes a new instance of the <see cref="DefaultEntityId"/> class.
/// </summary>
/// <param name="value">The value representing this object.</param>
public DefaultEntityId(Guid value) : base(value)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="DefaultEntityId"/> class.
/// </summary>
public DefaultEntityId() : base()
{
}
}
}
@@ -295,6 +295,39 @@ public class ResultTests
Assert.True(firstResult.Equals(secondResult));
}
[Fact]
public void Equals_WhenOneResultIsSuccessfulAndTheOtherIsFailed_ShouldReturnFalse()
{
// Act
Result<string> successResult = Result<string>.Success("test");
Result<string> failureResult = Result<string>.Failure(Error.Validation("Code", "Description"));
// Assert
Assert.False(successResult.Equals(failureResult));
}
[Fact]
public void Equals_WhenCalledWithBoxedResult_ShouldReturnTrue()
{
// Act
Result<string> firstResult = Result<string>.Success("test");
object boxedResult = Result<string>.Success("test");
// Assert
Assert.True(firstResult.Equals(boxedResult));
}
[Fact]
public void Equals_WhenCalledWithNonResultObject_ShouldReturnFalse()
{
// Act
Result<string> result = Result<string>.Success("test");
object nonResultObject = new();
// Assert
Assert.False(result.Equals(nonResultObject));
}
[Fact]
public void EqualityOperator_WhenResultsAreEqual_ShouldReturnTrue()
{
@@ -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<string>.Some("English"));
LanguageInfo secondLanguageInfo = _languageInfoFixture.Create(
languageCode: "en",
languageName: "English",
nativeName: Optional<string>.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<string>.Some("English"));
LanguageInfo secondLanguageInfo = _languageInfoFixture.Create(
languageCode: "en",
languageName: "English",
nativeName: Optional<string>.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<string>.None());
LanguageInfo secondLanguageInfo = _languageInfoFixture.Create(
languageCode: "en",
languageName: "French",
nativeName: Optional<string>.None());
// Act
bool result = firstLanguageInfo.Equals(secondLanguageInfo);
// Assert
Assert.False(result);
}
}
@@ -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<string>()).Returns(callInfo =>
{
IDirectoryInfo mockDirInfo = Substitute.For<IDirectoryInfo>();
mockDirInfo.FullName.Returns(callInfo.Arg<string>());
return mockDirInfo;
});
IDirectoryInfo invalidNestedDir = Substitute.For<IDirectoryInfo>();
invalidNestedDir.FullName.Returns(" ");
IDirectoryInfo nestedDirInfo = Substitute.For<IDirectoryInfo>();
nestedDirInfo.GetFiles().Returns([]);
nestedDirInfo.GetDirectories().Returns([invalidNestedDir]);
_mockFileSystem.DirectoryInfo.New(_pathSourceSubDir).Returns(nestedDirInfo);
IDirectoryInfo subDirInfo = Substitute.For<IDirectoryInfo>();
subDirInfo.Name.Returns("SubDir");
subDirInfo.FullName.Returns(_pathSourceSubDir);
IDirectoryInfo sourceDirectoryInfo = Substitute.For<IDirectoryInfo>();
sourceDirectoryInfo.GetFiles().Returns([]);
sourceDirectoryInfo.GetDirectories().Returns([subDirInfo]);
_mockFileSystem.DirectoryInfo.New(_pathSource).Returns(sourceDirectoryInfo);
_mockFileSystem.Path.Combine(Arg.Any<string>(), Arg.Any<string>())
.Returns(callInfo => Path.Combine(callInfo.ArgAt<string>(0), callInfo.ArgAt<string>(1)));
// Act
Result<FileSystemPathId> 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<string>()).Returns(callInfo =>
{
IDirectoryInfo mockDirInfo = Substitute.For<IDirectoryInfo>();
mockDirInfo.FullName.Returns(callInfo.Arg<string>());
return mockDirInfo;
});
IDirectoryInfo subDirInfo = Substitute.For<IDirectoryInfo>();
subDirInfo.Name.Returns("SubDir");
subDirInfo.FullName.Returns(_pathSourceSubDir);
IDirectoryInfo sourceDirectoryInfo = Substitute.For<IDirectoryInfo>();
sourceDirectoryInfo.GetFiles().Returns([]);
sourceDirectoryInfo.GetDirectories().Returns([subDirInfo]);
_mockFileSystem.DirectoryInfo.New(_pathSource).Returns(sourceDirectoryInfo);
_mockFileSystem.Path.Combine(Arg.Any<string>(), Arg.Any<string>()).Returns(" ");
// Act
Result<FileSystemPathId> 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<string>(), Arg.Any<string>());
}
[Fact]
public void RenameDirectory_WhenParentDirectoryPathIsWhitespace_ShouldReturnInvalidPathError()
{
// Arrange
FileSystemPathId path = _fileSystemPathIdFixture.Create(
s_isUnix ? "/OldName" : @"C:\OldName"
);
string newName = "NewName";
IDirectoryInfo parentDirectoryInfo = Substitute.For<IDirectoryInfo>();
parentDirectoryInfo.FullName.Returns(" ");
_mockFileSystem.Directory.GetParent(path.Path).Returns(parentDirectoryInfo);
// Act
Result<FileSystemPathId> result = _sut.RenameDirectory(path, newName);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(Errors.FileSystemManagement.InvalidPath, result.FirstError);
_mockFileSystem.Directory.DidNotReceive().Move(Arg.Any<string>(), Arg.Any<string>());
}
[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<IDirectoryInfo>();
parentDirectoryInfo.FullName.Returns(parentPath);
_mockFileSystem.Directory.GetParent(path.Path).Returns(parentDirectoryInfo);
_mockFileSystem.Path.Combine(parentPath, newName).Returns(" ");
// Act
Result<FileSystemPathId> result = _sut.RenameDirectory(path, newName);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(Errors.FileSystemManagement.InvalidPath, result.FirstError);
_mockFileSystem.Directory.DidNotReceive().Move(Arg.Any<string>(), Arg.Any<string>());
}
[Fact]
public void DeleteDirectory_WhenDirectoryExistsAndHasDeletePermission_ShouldDeleteSuccessfully()
{
@@ -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 ? '/' : '\\';
/// <summary>
/// Initializes a new instance of the <see cref="DirectoryServiceTests"/> class.
@@ -497,6 +498,150 @@ public class DirectoryServiceTests
_mockEnvironmentContext.DirectoryProviderService.DidNotReceive().CreateDirectory(Arg.Any<FileSystemPathId>(), Arg.Any<string>());
}
[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<FileSystemPathId>())
.Returns(Result.From(false));
// Act
Result<Directory> 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<FileSystemPathId>())
.Returns(Result.From(false));
// Act
Result<Directory> 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<FileSystemPathId>())
.Returns(Errors.Permission.UnauthorizedAccess);
// Act
Result<Directory> 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<FileSystemPathId>())
.Returns(Result.From(true));
// Act & Assert
Assert.Throws<NotImplementedException>(() => _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<FileSystemPathId>())
.Returns(Result.From(false));
// Act
Result<Directory> 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<FileSystemPathId>())
.Returns(Result.From(false));
// Act
Result<Directory> 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<FileSystemPathId>())
.Returns(Errors.Permission.UnauthorizedAccess);
// Act
Result<Directory> 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<FileSystemPathId>())
.Returns(Result.From(true));
// Act & Assert
Assert.Throws<NotImplementedException>(() => _sut.MoveDirectory(sourcePath, destinationPath, overrideExisting));
}
[Fact]
public void RenameDirectory_WithValidStringPath_ShouldReturnRenamedDirectory()
{
@@ -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<IEnumerable<FileSystemItem>> 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<IDriveInfo>();
@@ -858,6 +858,52 @@ public class FileProviderServiceTests
_mockFileSystem.File.DidNotReceive().Move(Arg.Any<string>(), Arg.Any<string>());
}
[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<IFileInfo>();
fileInfo.DirectoryName.Returns(" ");
_mockFileSystem.FileInfo.New(path.Path).Returns(fileInfo);
// Act
Result<FileSystemPathId> result = _sut.RenameFile(path, newName);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(Errors.FileSystemManagement.InvalidPath, result.FirstError);
_mockFileSystem.File.DidNotReceive().Move(Arg.Any<string>(), Arg.Any<string>());
}
[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<IFileInfo>();
fileInfo.DirectoryName.Returns(parentPath);
_mockFileSystem.FileInfo.New(path.Path).Returns(fileInfo);
_mockFileSystem.Path.Combine(parentPath, newName).Returns(" ");
// Act
Result<FileSystemPathId> result = _sut.RenameFile(path, newName);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(Errors.FileSystemManagement.InvalidPath, result.FirstError);
_mockFileSystem.File.DidNotReceive().Move(Arg.Any<string>(), Arg.Any<string>());
}
[Fact]
public void RenameFile_WhenParentDirectoryExistsButNotWritable_ShouldReturnUnauthorizedAccessError()
{
@@ -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<DateTime>.FromNullable(DateTime.Now)));
_mockEnvironmentContext.FileProviderService.GetCreationTime(filePath)
.Returns(Result.From(Optional<DateTime>.FromNullable(DateTime.Now.AddDays(-1))));
_mockEnvironmentContext.FileProviderService.GetSize(filePath)
.Returns(Errors.Permission.UnauthorizedAccess);
// Act
Result<IEnumerable<File>> 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<File> 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<File> 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<DateTime>.FromNullable(DateTime.Now));
_mockEnvironmentContext.FileProviderService.GetCreationTime(copiedFilePathId)
.Returns(Optional<DateTime>.FromNullable(DateTime.Now.AddDays(-1)));
_mockEnvironmentContext.FileProviderService.GetSize(copiedFilePathId)
.Returns(Errors.Permission.UnauthorizedAccess);
// Act
Result<File> 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<DateTime>.FromNullable(DateTime.Now));
_mockEnvironmentContext.FileProviderService.GetCreationTime(movedFilePathId)
.Returns(Optional<DateTime>.FromNullable(DateTime.Now.AddDays(-1)));
_mockEnvironmentContext.FileProviderService.GetSize(movedFilePathId)
.Returns(Errors.Permission.UnauthorizedAccess);
// Act
Result<File> 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<FileSystemPathId>(), 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<DateTime>.FromNullable(DateTime.Now)));
_mockEnvironmentContext.FileProviderService.GetCreationTime(newPathId)
.Returns(Result.From(Optional<DateTime>.FromNullable(DateTime.Now.AddDays(-1))));
_mockEnvironmentContext.FileProviderService.GetSize(newPathId)
.Returns(Errors.Permission.UnauthorizedAccess);
// Act
Result<File> 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<bool> result = _sut.ReadFile(pathId);
// Assert
Assert.False(result.IsFailure);
Assert.True(result.Value);
}
}
@@ -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;
/// <summary>
/// Contains unit tests for the <see cref="FileSystemStructureSeedService"/> class.
/// </summary>
[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";
/// <summary>
/// Initializes a new instance of the <see cref="FileSystemStructureSeedServiceTests"/> class.
/// </summary>
public FileSystemStructureSeedServiceTests()
{
_mockEnvironmentContext = Substitute.For<IEnvironmentContext>();
_mockDirectoryProviderService = Substitute.For<IDirectoryProviderService>();
_mockPathService = Substitute.For<IPathService>();
_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<FileSystemPathId>()).Returns(false);
_mockDirectoryProviderService.CreateDirectory(Arg.Any<FileSystemPathId>(), Arg.Any<string>())
.Returns(callInfo => Result<FileSystemPathId>.Success(FileSystemPathId.Create(Path.Combine(_rootPath, callInfo.ArgAt<string>(1))).Value));
// Act
Result<Created> result = _sut.SetDefaultDirectories(_rootPath);
// Assert
Assert.True(result.IsSuccess);
_mockDirectoryProviderService.Received(2).DirectoryExists(Arg.Any<FileSystemPathId>());
_mockDirectoryProviderService.Received(2).CreateDirectory(Arg.Any<FileSystemPathId>(), Arg.Any<string>());
}
[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<FileSystemPathId>()).Returns(true);
// Act
Result<Created> result = _sut.SetDefaultDirectories(_rootPath);
// Assert
Assert.True(result.IsSuccess);
_mockDirectoryProviderService.Received(2).DirectoryExists(Arg.Any<FileSystemPathId>());
_mockDirectoryProviderService.DidNotReceive().CreateDirectory(Arg.Any<FileSystemPathId>(), Arg.Any<string>());
}
[Fact]
public void SetDefaultDirectories_WhenRootPathIsInvalid_ShouldReturnInvalidPathError()
{
// Act
Result<Created> result = _sut.SetDefaultDirectories(" ");
// Assert
Assert.True(result.IsFailure);
Assert.Equal(Errors.FileSystemManagement.InvalidPath, result.FirstError);
_mockPathService.DidNotReceive().CombinePath(Arg.Any<string>(), Arg.Any<string>());
_mockDirectoryProviderService.DidNotReceive().DirectoryExists(Arg.Any<FileSystemPathId>());
}
[Fact]
public void SetDefaultDirectories_WhenCombiningPathFails_ShouldReturnTheError()
{
// Arrange
_mockPathService.CombinePath(_rootPath, "libraries").Returns(Errors.FileSystemManagement.InvalidPath);
// Act
Result<Created> result = _sut.SetDefaultDirectories(_rootPath);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(Errors.FileSystemManagement.InvalidPath, result.FirstError);
_mockDirectoryProviderService.DidNotReceive().DirectoryExists(Arg.Any<FileSystemPathId>());
}
[Fact]
public void SetDefaultDirectories_WhenCheckingDirectoryExistenceFails_ShouldReturnTheError()
{
// Arrange
_mockPathService.CombinePath(_rootPath, "libraries").Returns(Path.Combine(_rootPath, "libraries"));
_mockDirectoryProviderService.DirectoryExists(Arg.Any<FileSystemPathId>()).Returns(Errors.FileSystemManagement.DirectoryNotFound);
// Act
Result<Created> result = _sut.SetDefaultDirectories(_rootPath);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(Errors.FileSystemManagement.DirectoryNotFound, result.FirstError);
_mockDirectoryProviderService.DidNotReceive().CreateDirectory(Arg.Any<FileSystemPathId>(), Arg.Any<string>());
}
[Fact]
public void SetDefaultDirectories_WhenCreatingDirectoryFails_ShouldReturnTheError()
{
// Arrange
_mockPathService.CombinePath(_rootPath, "libraries").Returns(Path.Combine(_rootPath, "libraries"));
_mockDirectoryProviderService.DirectoryExists(Arg.Any<FileSystemPathId>()).Returns(false);
_mockDirectoryProviderService.CreateDirectory(Arg.Any<FileSystemPathId>(), Arg.Any<string>())
.Returns(Errors.FileSystemManagement.DirectoryAlreadyExists);
// Act
Result<Created> result = _sut.SetDefaultDirectories(_rootPath);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(Errors.FileSystemManagement.DirectoryAlreadyExists, result.FirstError);
}
}
@@ -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()
{
@@ -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<CancellationToken>())
.Returns(Result.From(imageType));
_mockEnvironmentContext.FileProviderService.GetFileAsync(pathId)
.Returns(Result.From(imageBytes));
// Act
Result<Thumbnail> 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<CancellationToken>())
.Returns(Result.From(imageType));
_mockEnvironmentContext.FileProviderService.GetFileAsync(pathId)
.Returns(Result.From(imageBytes));
// Act
Result<Thumbnail> 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<TaskCanceledException>(() =>
_sut.GetThumbnailAsync(pathId, quality, cts.Token));
}
/// <summary>
/// Creates the bytes of a small image encoded with the specified encoder.
/// </summary>
/// <param name="encoder">The encoder used to encode the image.</param>
/// <returns>The bytes of the created image.</returns>
private static byte[] CreateImageBytes(IImageEncoder encoder)
{
using Image<Rgba32> image = new(10, 10);
using MemoryStream memoryStream = new();
image.Save(memoryStream, encoder);
return memoryStream.ToArray();
}
}
@@ -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<IEnumerable<PathSegment>> result = _sut.ParsePath(path);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(Errors.FileSystemManagement.NameCannotBeEmpty, result.FirstError);
}
[Fact]
public void ParsePath_WithPathContainingDots_ShouldParseCorrectly()
{
@@ -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<IEnumerable<PathSegment>> result = _sut.ParsePath(path);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(Errors.FileSystemManagement.NameCannotBeEmpty, result.FirstError);
}
[Fact]
public void ParsePath_WithPathContainingDots_ShouldParseCorrectly()
{
@@ -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<Library> 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()
{
@@ -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<Updated> result = _sut.UpdateScanProgress(libraryId, compositeId);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(Errors.LibraryScanning.CompletedScanJobsCountCantExceedTotalScanJobsCount, result.FirstError);
}
[Fact]
public void UpdateScanJobProgress_WhenScanExists_ShouldUpdateCurrentJobProgress()
{
@@ -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
@@ -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<MediaLibraryScanJobProgress>.Some(currentJobProgress));
// Act
string result = scanProgress.ToString();
// Assert
Assert.Equal("CompletedJobs: 2; TotalJobs: 5; CurrentJobProgress: CompletedItems: 3; TotalItems: 10; CurrentOperation: Hashing files", result);
}
}
@@ -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<MediaContributorName> result = MediaContributorName.Create(displayName!, Optional<string>.None());
// Assert
Assert.True(result.IsFailure);
Assert.Equal(Errors.MediaContributors.MediaContributorNameCannotBeEmpty, result.FirstError);
}
[Fact]
public void Equals_WithSameValues_ShouldReturnTrue()
{
@@ -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<UserSettings> 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<UserSettings> 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()
{
@@ -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;
/// <summary>
/// Contains unit tests for the <see cref="UserSettingsId"/> class.
/// </summary>
[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);
}
}
@@ -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<Book> 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<DateTime>.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()
{
@@ -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;
/// <summary>
/// Contains unit tests for the <see cref="LibraryId"/> class.
/// </summary>
[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);
}
}